Esempio n. 1
0
 internal void SetValue(PSObject obj, object property, object value, ExecutionContext context)
 {
     if (!LanguagePrimitives.IsNull((object)obj))
     {
         if (!LanguagePrimitives.IsNull(property))
         {
             try
             {
                 if (PSObject.Base((object)obj) is IDictionary dictionary)
                 {
                     dictionary[property] = value;
                     return;
                 }
                 PSMemberInfo memberInfo = this.GetMemberInfo(obj, property, context);
                 if (memberInfo == null)
                 {
                     throw InterpreterError.NewInterpreterException(property, typeof(RuntimeException), this.NodeToken, "PropertyNotFound", property);
                 }
                 memberInfo.Value = value;
                 return;
             }
             catch (TerminateException ex)
             {
                 throw;
             }
             catch (Exception ex)
             {
                 CommandProcessorBase.CheckForSevereException(ex);
                 throw InterpreterError.NewInterpreterExceptionByMessage(typeof(RuntimeException), this.NodeToken, ex.Message, "PropertyAssignmentException", ex);
             }
         }
     }
     throw InterpreterError.NewInterpreterException(property, typeof(RuntimeException), this.NodeToken, "PropertyNotFound", property);
 }
Esempio n. 2
0
 internal void ReportEngineStartupError(string resourceString, params object[] arguments)
 {
     try
     {
         Cmdlet cmdlet;
         string str;
         if (this.IsModuleCommandCurrentlyRunning(out cmdlet, out str))
         {
             RuntimeException replaceParentContainsErrorRecordException = InterpreterError.NewInterpreterException(null, typeof(RuntimeException), null, str, resourceString, arguments);
             cmdlet.WriteError(new ErrorRecord(replaceParentContainsErrorRecordException.ErrorRecord, replaceParentContainsErrorRecordException));
         }
         else
         {
             PSHost engineHostInterface = this.EngineHostInterface;
             if (engineHostInterface != null)
             {
                 PSHostUserInterface uI = engineHostInterface.UI;
                 if (uI != null)
                 {
                     uI.WriteErrorLine(StringUtil.Format(resourceString, arguments));
                 }
             }
         }
     }
     catch (Exception exception2)
     {
         CommandProcessorBase.CheckForSevereException(exception2);
     }
 }
Esempio n. 3
0
        public FlagsExpression(object[] expression)
        {
            if (!typeof(T).IsEnum)
            {
                throw InterpreterError.NewInterpreterException(expression, typeof(RuntimeException), null, "InvalidGenericType", EnumExpressionEvaluatorStrings.InvalidGenericType, new object[0]);
            }
            this._underType = Enum.GetUnderlyingType(typeof(T));
            if (expression == null)
            {
                throw InterpreterError.NewInterpreterException(null, typeof(ArgumentNullException), null, "EmptyInputString", EnumExpressionEvaluatorStrings.EmptyInputString, new object[0]);
            }
            foreach (string str in expression)
            {
                if (string.IsNullOrWhiteSpace(str))
                {
                    throw InterpreterError.NewInterpreterException(expression, typeof(RuntimeException), null, "EmptyInputString", EnumExpressionEvaluatorStrings.EmptyInputString, new object[0]);
                }
            }
            List <Token> tokenList = new List <Token>();

            foreach (string str2 in expression)
            {
                tokenList.AddRange(this.TokenizeInput(str2));
                tokenList.Add(new Token(TokenKind.Or));
            }
            this.CheckSyntaxError(tokenList);
            this._root = this.ConstructExpressionTree(tokenList);
        }
Esempio n. 4
0
        internal static object GetVariableValue(VariablePath variablePath, ExecutionContext executionContext, VariableExpressionAst varAst)
        {
            if (!variablePath.IsVariable)
            {
                CmdletProviderContext contextOut;
                SessionStateScope     scopeOut;
                SessionStateInternal  ss = executionContext.EngineSessionState;
                return(ss.GetVariableValueFromProvider(variablePath, out contextOut, out scopeOut, ss.CurrentScope.ScopeOrigin));
            }

            SessionStateInternal sessionState = executionContext.EngineSessionState;
            CommandOrigin        origin       = sessionState.CurrentScope.ScopeOrigin;

            SessionStateScope scope;
            PSVariable        var = sessionState.GetVariableItem(variablePath, out scope, origin);

            if (var != null)
            {
                return(var.Value);
            }

            if (sessionState.ExecutionContext._debuggingMode > 0)
            {
                sessionState.ExecutionContext.Debugger.CheckVariableRead(variablePath.UnqualifiedPath);
            }

            if (ThrowStrictModeUndefinedVariable(executionContext, varAst))
            {
                throw InterpreterError.NewInterpreterException(variablePath.UserPath, typeof(RuntimeException),
                                                               varAst.Extent, "VariableIsUndefined", ParserStrings.VariableIsUndefined, variablePath.UserPath);
            }

            return(null);
        }
Esempio n. 5
0
        private static object SplitWithPattern(System.Management.Automation.ExecutionContext context, IScriptExtent errorPosition, IEnumerable <string> content, string separatorPattern, int limit, SplitOptions options)
        {
            if (((options & SplitOptions.SimpleMatch) == 0) && ((options & SplitOptions.RegexMatch) == 0))
            {
                options |= SplitOptions.RegexMatch;
            }
            if (((options & SplitOptions.SimpleMatch) != 0) && ((options & ~(SplitOptions.IgnoreCase | SplitOptions.SimpleMatch)) != 0))
            {
                throw InterpreterError.NewInterpreterException(null, typeof(ParseException), errorPosition, "InvalidSplitOptionCombination", ParserStrings.InvalidSplitOptionCombination, new object[0]);
            }
            if ((options & (SplitOptions.Singleline | SplitOptions.Multiline)) == (SplitOptions.Singleline | SplitOptions.Multiline))
            {
                throw InterpreterError.NewInterpreterException(null, typeof(ParseException), errorPosition, "InvalidSplitOptionCombination", ParserStrings.InvalidSplitOptionCombination, new object[0]);
            }
            if ((options & SplitOptions.SimpleMatch) != 0)
            {
                separatorPattern = Regex.Escape(separatorPattern);
            }
            if (limit < 0)
            {
                limit = 0;
            }
            RegexOptions  options2 = parseRegexOptions(options);
            Regex         regex    = NewRegex(separatorPattern, options2);
            List <string> list     = new List <string>();

            foreach (string str in content)
            {
                string[] items = regex.Split(str, limit, 0);
                ExtendList <string>(list, items);
            }
            return(list.ToArray());
        }
Esempio n. 6
0
        internal static object StringToNumber(string input)
        {
            if (string.IsNullOrEmpty(input))
            {
                return((object)null);
            }
            input = input.Trim();
            if (string.IsNullOrEmpty(input))
            {
                return((object)null);
            }
            string str1 = "";

            if (input[0] == '+' || SpecialCharacters.IsDash(input[0]))
            {
                str1  = input[0].ToString();
                input = input.Substring(1);
            }
            string str2 = NumberTokenReader.ScanForNumber(input, 0);

            if (str2 == null)
            {
                return((object)null);
            }
            if (str2.Length < input.Length)
            {
                throw InterpreterError.NewInterpreterException((object)input, typeof(RuntimeException), (Token)null, "BadNumericConstant", (object)input);
            }
            return(NumberTokenReader.ConvertToNumber(str1 + str2, (Tokenizer)null));
        }
Esempio n. 7
0
        internal object GetValue(object target, object index, ExecutionContext context)
        {
            if (LanguagePrimitives.IsNull(target))
            {
                throw InterpreterError.NewInterpreterException(index, typeof(RuntimeException), this.NodeToken, "NullArray");
            }
            if (LanguagePrimitives.IsNull(index))
            {
                throw InterpreterError.NewInterpreterException(index, typeof(RuntimeException), this.NodeToken, "NullArrayIndex");
            }
            switch (target)
            {
            case Array array:
                return(this.DoGetValue(array, index, context));

            case IDictionary dictionary:
                return(this.DoGetValue(dictionary, index, context));

            case string str:
                return(this.DoGetValue(str, index, context));

            default:
                return(this.GetItemPropertyValue(target, index, context));
            }
        }
Esempio n. 8
0
        private static object GetUsingValue(MutableTuple tuple, int index, ExecutionContext context)
        {
            UsingResult usingValueFromTuple = GetUsingValueFromTuple(tuple, index);

            if (usingValueFromTuple != null)
            {
                return(usingValueFromTuple.Value);
            }
            for (SessionStateScope scope = context.EngineSessionState.CurrentScope; scope != null; scope = scope.Parent)
            {
                usingValueFromTuple = GetUsingValueFromTuple(scope.LocalsTuple, index);
                if (usingValueFromTuple != null)
                {
                    return(usingValueFromTuple.Value);
                }
                foreach (MutableTuple tuple2 in scope.DottedScopes)
                {
                    usingValueFromTuple = GetUsingValueFromTuple(tuple2, index);
                    if (usingValueFromTuple != null)
                    {
                        return(usingValueFromTuple.Value);
                    }
                }
            }
            throw InterpreterError.NewInterpreterException(null, typeof(RuntimeException), null, "UsingWithoutInvokeCommand", ParserStrings.UsingWithoutInvokeCommand, new object[0]);
        }
Esempio n. 9
0
        private static PSReference GetVariableAsRef(VariablePath variablePath, ExecutionContext executionContext, Type staticType)
        {
            SessionStateScope    scope;
            SessionStateInternal engineSessionState = executionContext.EngineSessionState;
            CommandOrigin        scopeOrigin        = engineSessionState.CurrentScope.ScopeOrigin;
            PSVariable           variable           = engineSessionState.GetVariableItem(variablePath, out scope, scopeOrigin);

            if (variable == null)
            {
                throw InterpreterError.NewInterpreterException(variablePath, typeof(RuntimeException), null, "NonExistingVariableReference", ParserStrings.NonExistingVariableReference, new object[0]);
            }
            object obj2 = variable.Value;

            if ((staticType == null) && (obj2 != null))
            {
                obj2 = PSObject.Base(obj2);
                if (obj2 != null)
                {
                    staticType = obj2.GetType();
                }
            }
            if (staticType == null)
            {
                ArgumentTypeConverterAttribute attribute = variable.Attributes.OfType <ArgumentTypeConverterAttribute>().FirstOrDefault <ArgumentTypeConverterAttribute>();
                staticType = (attribute != null) ? attribute.TargetType : typeof(LanguagePrimitives.Null);
            }
            return(PSReference.CreateInstance(variable, staticType));
        }
Esempio n. 10
0
        internal static Type ResolveTypeName(ITypeName typeName)
        {
            Type reflectionType = typeName.GetReflectionType();

            if (reflectionType != null)
            {
                return(reflectionType);
            }
            GenericTypeName name = typeName as GenericTypeName;

            if (name != null)
            {
                Type   genericType   = name.GetGenericType(ResolveTypeName(name.TypeName));
                Type[] typeArguments = (from arg in name.GenericArguments select ResolveTypeName(arg)).ToArray <Type>();
                try
                {
                    if ((genericType != null) && genericType.ContainsGenericParameters)
                    {
                        genericType.MakeGenericType(typeArguments);
                    }
                }
                catch (Exception exception)
                {
                    CommandProcessorBase.CheckForSevereException(exception);
                    throw InterpreterError.NewInterpreterException(typeName, typeof(RuntimeException), null, "TypeNotFoundWithMessage", ParserStrings.TypeNotFoundWithMessage, new object[] { typeName.FullName, exception.Message });
                }
            }
            ArrayTypeName name2 = typeName as ArrayTypeName;

            if (name2 != null)
            {
                ResolveTypeName(name2.ElementType);
            }
            throw InterpreterError.NewInterpreterException(typeName, typeof(RuntimeException), null, "TypeNotFound", ParserStrings.TypeNotFound, new object[] { typeName.FullName });
        }
Esempio n. 11
0
        internal static object AsOperator(object left, Type type)
        {
            bool flag;

            if (type == null)
            {
                throw InterpreterError.NewInterpreterException(null, typeof(RuntimeException), null, "AsOperatorRequiresType", ParserStrings.AsOperatorRequiresType, new object[0]);
            }
            LanguagePrimitives.ConversionData data = LanguagePrimitives.FigureConversion(left, type, out flag);
            if (data.Rank == ConversionRank.None)
            {
                return(null);
            }
            try
            {
                if (flag)
                {
                    return(data.Invoke(PSObject.Base(left), type, false, (PSObject)left, NumberFormatInfo.InvariantInfo, null));
                }
                return(data.Invoke(left, type, false, null, NumberFormatInfo.InvariantInfo, null));
            }
            catch (PSInvalidCastException)
            {
                return(null);
            }
        }
        internal PSVariable GetVariable(ExecutionContext context)
        {
            if (this._useConstantValue)
            {
                return((PSVariable)null);
            }
            SessionStateInternal engineSessionState = context.EngineSessionState;
            CommandOrigin        scopeOrigin        = engineSessionState.currentScope.ScopeOrigin;

            if (!this._variablePath.IsScopedItem)
            {
                SessionStateScope scope = (SessionStateScope)null;
                return(engineSessionState.GetVariableItem(this._variablePath, out scope, scopeOrigin));
            }
            PSVariable variable = engineSessionState.CurrentActivationRecord.GetVariable(this._activationRecordSlot, scopeOrigin);

            if (variable == null)
            {
                SessionStateScope scope;
                variable = engineSessionState.GetVariableItem(this._variablePath, out scope, scopeOrigin);
                if (variable != null)
                {
                    engineSessionState.CurrentActivationRecord.SetVariable(variable, scope, this._activationRecordSlot);
                }
                else if ((context.IsStrictVersion(2) || !this._inExpandableString && context.IsStrictVersion(1)) && !this.IsInternalCode)
                {
                    throw InterpreterError.NewInterpreterException((object)this.NodeToken, typeof(RuntimeException), this.NodeToken, "VariableIsUndefined", (object)this.NodeToken);
                }
            }
            return(variable);
        }
Esempio n. 13
0
        internal static object GetNonIndexable(object target, object[] indices)
        {
            // We want to allow:
            //     $x[0]
            // and
            //     $x[-1]
            // to be the same as
            //     $x
            // But disallow anything else:
            //     if in the strict mode, throw exception
            //     otherwise, return AutomationNull.Value to signal no result

            if (indices.Length == 1)
            {
                var index = indices[0];
                if (index != null && (LanguagePrimitives.Equals(0, index) || LanguagePrimitives.Equals(-1, index)))
                {
                    return(target);
                }
            }

            var context = LocalPipeline.GetExecutionContextFromTLS();

            if (context == null || !context.IsStrictVersion(2))
            {
                return(AutomationNull.Value);
            }

            throw InterpreterError.NewInterpreterException(target, typeof(RuntimeException), null, "CannotIndex",
                                                           ParserStrings.CannotIndex, target.GetType());
        }
Esempio n. 14
0
        private Attribute GetCustomAttribute()
        {
            Attribute customAttributeObject = this.GetCustomAttributeObject();

            if (customAttributeObject != null && this._namedArguments != null)
            {
                Hashtable constValue = (Hashtable)this._namedArguments.GetConstValue();
                PSObject  psObject   = LanguagePrimitives.AsPSObjectOrNull((object)customAttributeObject);
                foreach (object key in (IEnumerable)constValue.Keys)
                {
                    object obj = constValue[key];
                    try
                    {
                        PSMemberInfo member = psObject.Members[key.ToString()];
                        if (member != null)
                        {
                            member.Value = obj;
                        }
                        else
                        {
                            throw InterpreterError.NewInterpreterException((object)this.NodeToken, typeof(RuntimeException), this.NodeToken, "PropertyNotFoundForType", (object)key.ToString(), (object)customAttributeObject.GetType().ToString());
                        }
                    }
                    catch (Exception ex)
                    {
                        CommandProcessorBase.CheckForSevereException(ex);
                        throw InterpreterError.NewInterpreterExceptionByMessage(typeof(RuntimeException), this.NodeToken, ex.Message, "PropertyAssignmentException", ex);
                    }
                }
            }
            return(customAttributeObject);
        }
Esempio n. 15
0
        private object BuildHashtable(
            ParseTreeNode.ParseTreeNodeExecutor parseTreeNodeExecutor)
        {
            Hashtable hashtable = new Hashtable((IEqualityComparer)StringComparer.CurrentCultureIgnoreCase);

            for (int index = 0; index < this._keys.Count; ++index)
            {
                object obj1 = this._keys[index];
                if (obj1 is ParseTreeNode)
                {
                    obj1 = parseTreeNodeExecutor((ParseTreeNode)obj1);
                }
                object obj2 = PSObject.Base(obj1);
                if (obj2 == null || obj2 == AutomationNull.Value)
                {
                    throw InterpreterError.NewInterpreterException(obj2, typeof(RuntimeException), this._tokens[index], "NullArrayIndex");
                }
                if (hashtable.ContainsKey(obj2))
                {
                    string str = PSObject.ToStringParser((ExecutionContext)null, obj2);
                    if (str.Length > 40)
                    {
                        str = str.Substring(0, 40) + "...";
                    }
                    throw InterpreterError.NewInterpreterException(obj2, typeof(RuntimeException), this._tokens[index], "DuplicateKeyInHashLiteral", (object)str);
                }
                hashtable[obj2] = parseTreeNodeExecutor(this._expressions[index]);
            }
            return((object)hashtable);
        }
Esempio n. 16
0
        internal static PSReference GetVariableAsRef(VariablePath variablePath, ExecutionContext executionContext, Type staticType)
        {
            Diagnostics.Assert(variablePath.IsVariable, "calller to verify varpath is a variable.");

            SessionStateInternal sessionState = executionContext.EngineSessionState;
            CommandOrigin        origin       = sessionState.CurrentScope.ScopeOrigin;

            SessionStateScope scope;
            PSVariable        var = sessionState.GetVariableItem(variablePath, out scope, origin);

            if (var == null)
            {
                throw InterpreterError.NewInterpreterException(variablePath, typeof(RuntimeException), null,
                                                               "NonExistingVariableReference",
                                                               ParserStrings.NonExistingVariableReference);
            }

            object value = var.Value;

            if (staticType == null && value != null)
            {
                value = PSObject.Base(value);
                if (value != null)
                {
                    staticType = value.GetType();
                }
            }
            if (staticType == null)
            {
                var declaredType = var.Attributes.OfType <ArgumentTypeConverterAttribute>().FirstOrDefault();
                staticType = declaredType != null ? declaredType.TargetType : typeof(LanguagePrimitives.Null);
            }

            return(PSReference.CreateInstance(var, staticType));
        }
Esempio n. 17
0
        internal void SetValue(object target, object index, object value)
        {
            if (LanguagePrimitives.IsNull(target))
            {
                throw InterpreterError.NewInterpreterException(index, typeof(RuntimeException), this.NodeToken, "NullArray");
            }
            if (LanguagePrimitives.IsNull(index))
            {
                throw InterpreterError.NewInterpreterException(target, typeof(RuntimeException), this.NodeToken, "NullArrayIndex");
            }
            switch (target)
            {
            case Array array:
                this.DoSetValue(array, index, value);
                break;

            case IDictionary dictionary:
                this.DoSetValue(dictionary, index, value);
                break;

            default:
                this.SetItemPropertyValue(target, index, value);
                break;
            }
        }
Esempio n. 18
0
        private void DoSetValue(Array array, object index, object value)
        {
            if (index is IList list)
            {
                if (array.Rank != 1)
                {
                    if (list.Count > 1)
                    {
                        if (!(list[0] is IList))
                        {
                            goto label_5;
                        }
                    }
                    else
                    {
                        goto label_5;
                    }
                }
                throw InterpreterError.NewInterpreterException(index, typeof(RuntimeException), this.NodeToken, "ArraySliceAssignmentFailed", (object)ArrayReferenceNode.IndexStringMessage(index));
            }
label_5:
            try
            {
                this.SetArrayElement(array, index, value);
            }
            catch (IndexOutOfRangeException ex)
            {
                throw InterpreterError.NewInterpreterExceptionWithInnerException(index, typeof(RuntimeException), this.NodeToken, "IndexOutOfRange", (Exception)ex, (object)ArrayReferenceNode.IndexStringMessage(index));
            }
            catch (Exception ex)
            {
                CommandProcessorBase.CheckForSevereException(ex);
                throw InterpreterError.NewInterpreterExceptionWithInnerException(value, typeof(RuntimeException), this.NodeToken, "ArrayAssignmentFailed", ex, (object)ArrayReferenceNode.IndexStringMessage(index), (object)ex.Message);
            }
        }
Esempio n. 19
0
        /// <summary>
        /// Construct the expression from a single string.
        /// </summary>
        /// <param name="expression">
        /// The specified flag attribute expression string.
        /// </param>
        public FlagsExpression(string expression)
        {
            if (!typeof(T).IsEnum)
            {
                throw InterpreterError.NewInterpreterException(expression, typeof(RuntimeException),
                                                               null, "InvalidGenericType", EnumExpressionEvaluatorStrings.InvalidGenericType);
            }

            _underType = Enum.GetUnderlyingType(typeof(T));

            if (String.IsNullOrWhiteSpace(expression))
            {
                throw InterpreterError.NewInterpreterException(expression, typeof(RuntimeException),
                                                               null, "EmptyInputString", EnumExpressionEvaluatorStrings.EmptyInputString);
            }

            List <Token> tokenList = TokenizeInput(expression);

            // Append an OR at the end of the list for construction
            tokenList.Add(new Token(TokenKind.Or));

            CheckSyntaxError(tokenList);

            Root = ConstructExpressionTree(tokenList);
        }
Esempio n. 20
0
        /// <summary>
        /// Efficiently multiplies collection by integer.
        /// </summary>
        /// <param name="array">Collection to multiply.</param>
        /// <param name="times">Number of times the collection is to be multiplied/copied.</param>
        /// <returns>Collection multiplied by integer.</returns>
        internal static T[] Multiply <T>(T[] array, uint times)
        {
            Diagnostics.Assert(array != null, "Caller should verify the arguments for array multiplication");

            if (times == 1)
            {
                return(array);
            }

            if (times == 0 || array.Length == 0)
            {
#pragma warning disable CA1825 // Avoid zero-length array allocations
                // Don't use Array.Empty<T>(); always return a new instance.
                return(new T[0]);

#pragma warning restore CA1825 // Avoid zero-length array allocations
            }

            var context = LocalPipeline.GetExecutionContextFromTLS();
            if (context != null &&
                context.LanguageMode == PSLanguageMode.RestrictedLanguage && (array.Length * times) > 1024)
            {
                throw InterpreterError.NewInterpreterException(times, typeof(RuntimeException),
                                                               null, "ArrayMultiplyToolongInDataSection", ParserStrings.ArrayMultiplyToolongInDataSection, 1024);
            }

            var uncheckedLength = array.Length * times;
            int elements        = -1;
            try
            {
                elements = checked ((int)uncheckedLength);
            }
            catch (OverflowException)
            {
                LanguagePrimitives.ThrowInvalidCastException(uncheckedLength, typeof(int));
            }

            // Make the minimum number of calls to Array.Copy by doubling the array up to
            // the most significant bit in times, then do one final Array.Copy to get the
            // remaining copies.

            T[] result       = new T[elements];
            int resultLength = array.Length;
            Array.Copy(array, 0, result, 0, resultLength);
            times >>= 1;
            while (times != 0)
            {
                Array.Copy(result, 0, result, resultLength, resultLength);
                resultLength *= 2;
                times       >>= 1;
            }

            if (result.Length != resultLength)
            {
                Array.Copy(result, 0, result, resultLength, (result.Length - resultLength));
            }

            return(result);
        }
Esempio n. 21
0
        private Token GetNextToken(string input, ref int _offset)
        {
            string        str;
            StringBuilder builder = new StringBuilder();

            for (bool flag = false; _offset < input.Length; flag = true)
            {
                char ch = input[_offset++];
                switch (ch)
                {
                case ',':
                case '+':
                case '!':
                    if (!flag)
                    {
                        builder.Append(ch);
                    }
                    else
                    {
                        _offset--;
                    }
                    goto Label_0054;
                }
                builder.Append(ch);
            }
Label_0054:
            str = builder.ToString().Trim();
            if ((str.Length >= 2) && (((str[0] == '\'') && (str[str.Length - 1] == '\'')) || ((str[0] == '"') && (str[str.Length - 1] == '"'))))
            {
                str = str.Substring(1, str.Length - 2);
            }
            str = str.Trim();
            if (string.IsNullOrWhiteSpace(str))
            {
                throw InterpreterError.NewInterpreterException(input, typeof(RuntimeException), null, "EmptyTokenString", EnumExpressionEvaluatorStrings.EmptyTokenString, new object[] { EnumMinimumDisambiguation.EnumAllValues(typeof(T)) });
            }
            if (str[0] == '(')
            {
                int index = input.IndexOf(')', _offset);
                if ((str[str.Length - 1] == ')') || (index >= 0))
                {
                    throw InterpreterError.NewInterpreterException(input, typeof(RuntimeException), null, "NoIdentifierGroupingAllowed", EnumExpressionEvaluatorStrings.NoIdentifierGroupingAllowed, new object[0]);
                }
            }
            if (str.Equals(","))
            {
                return(new Token(TokenKind.Or));
            }
            if (str.Equals("+"))
            {
                return(new Token(TokenKind.And));
            }
            if (str.Equals("!"))
            {
                return(new Token(TokenKind.Not));
            }
            return(new Token(str));
        }
        /// <summary>
        /// Get using values as dictionary for the Foreach-Object parallel cmdlet.
        /// Ignore any using expressions that are associated with inner nested Foreach-Object parallel calls,
        /// since they are only effective in the nested call scope and not the current outer scope.
        /// </summary>
        /// <param name = "scriptBlock">Scriptblock to search.</param>
        /// <param name = "isTrustedInput">True when input is trusted.</param>
        /// <param name = "context">Execution context.</param>
        /// <param name = "foreachNames">List of foreach command names and aliases.</param>
        /// <returns>Dictionary of using variable map.</returns>
        internal static Dictionary <string, object> GetUsingValuesForEachParallel(
            ScriptBlock scriptBlock,
            bool isTrustedInput,
            ExecutionContext context,
            string[] foreachNames)
        {
            // Using variables for Foreach-Object -Parallel use are restricted to be within the
            // Foreach-Object -Parallel call scope. This will filter the using variable map to variables
            // only within the current (outer) Foreach-Object -Parallel call scope.
            var usingAsts = UsingExpressionAstSearcher.FindAllUsingExpressions(scriptBlock.Ast).ToList();
            UsingExpressionAst usingAst = null;
            var     usingValueMap       = new Dictionary <string, object>(usingAsts.Count);
            Version oldStrictVersion    = null;

            try
            {
                if (context != null)
                {
                    oldStrictVersion = context.EngineSessionState.CurrentScope.StrictModeVersion;
                    context.EngineSessionState.CurrentScope.StrictModeVersion = PSVersionInfo.PSVersion;
                }

                for (int i = 0; i < usingAsts.Count; ++i)
                {
                    usingAst = (UsingExpressionAst)usingAsts[i];
                    if (IsInForeachParallelCallingScope(usingAst, foreachNames))
                    {
                        var    value       = Compiler.GetExpressionValue(usingAst.SubExpression, isTrustedInput, context);
                        string usingAstKey = PsUtils.GetUsingExpressionKey(usingAst);
                        usingValueMap.TryAdd(usingAstKey, value);
                    }
                }
            }
            catch (RuntimeException rte)
            {
                if (rte.ErrorRecord.FullyQualifiedErrorId.Equals("VariableIsUndefined", StringComparison.Ordinal))
                {
                    throw InterpreterError.NewInterpreterException(
                              targetObject: null,
                              exceptionType: typeof(RuntimeException),
                              errorPosition: usingAst.Extent,
                              resourceIdAndErrorId: "UsingVariableIsUndefined",
                              resourceString: AutomationExceptions.UsingVariableIsUndefined,
                              args: rte.ErrorRecord.TargetObject);
                }
            }
            finally
            {
                if (context != null)
                {
                    context.EngineSessionState.CurrentScope.StrictModeVersion = oldStrictVersion;
                }
            }

            return(usingValueMap);
        }
Esempio n. 23
0
        private static void ReportIndexingError(Array array, object index, Exception reason)
        {
            string str = IndexStringMessage(index);

            if (reason == null)
            {
                throw InterpreterError.NewInterpreterException(index, typeof(RuntimeException), null, "NeedMultidimensionalIndex", ParserStrings.NeedMultidimensionalIndex, new object[] { array.Rank, str });
            }
            throw InterpreterError.NewInterpreterExceptionWithInnerException(index, typeof(RuntimeException), null, "NeedMultidimensionalIndex", ParserStrings.NeedMultidimensionalIndex, reason, new object[] { array.Rank, str });
        }
Esempio n. 24
0
        internal void ReportIndexingError(Array array, object index, Exception reason)
        {
            string str = ArrayReferenceNode.IndexStringMessage(index);

            if (reason == null)
            {
                throw InterpreterError.NewInterpreterException(index, typeof(RuntimeException), this.NodeToken, "NeedMultidimensionalIndex", (object)array.Rank, (object)str);
            }
            throw InterpreterError.NewInterpreterExceptionWithInnerException(index, typeof(RuntimeException), this.NodeToken, "NeedMultidimensionalIndex", reason, (object)array.Rank, (object)str);
        }
Esempio n. 25
0
        private string GetLabel(object result, ExecutionContext context)
        {
            string stringParser = PSObject.ToStringParser(context, result);

            for (int index = 0; index < stringParser.Length; ++index)
            {
                if (!char.IsLetterOrDigit(stringParser[index]) && stringParser[index] != '_')
                {
                    throw InterpreterError.NewInterpreterException((object)stringParser, typeof(RuntimeException), this.NodeToken, "InvalidLabelCharacter", (object)stringParser[index]);
                }
            }
            return(stringParser);
        }
 internal override void Visit(CommandNode node)
 {
     if (this._allowedCommands != null && node.Expression == null && node.Elements[0] is Token element)
     {
         foreach (string allowedCommand in this._allowedCommands)
         {
             if (allowedCommand.Equals(element.TokenText, StringComparison.OrdinalIgnoreCase))
             {
                 return;
             }
         }
         throw InterpreterError.NewInterpreterException((object)element, typeof(RuntimeException), element, "CmdletNotInAllowedListForDataSection", (object)element.TokenText);
     }
 }
Esempio n. 27
0
        private static void ReportIndexingError(Array array, object index, Exception reason)
        {
            // Convert this index into something printable (we hope)...
            string msgString = IndexStringMessage(index);

            if (reason == null)
            {
                throw InterpreterError.NewInterpreterException(index, typeof(RuntimeException), null,
                                                               "NeedMultidimensionalIndex", ParserStrings.NeedMultidimensionalIndex, array.Rank, msgString);
            }

            throw InterpreterError.NewInterpreterExceptionWithInnerException(index, typeof(RuntimeException), null,
                                                                             "NeedMultidimensionalIndex", ParserStrings.NeedMultidimensionalIndex, reason, array.Rank, msgString);
        }
 internal void CheckTypeConversionViolation()
 {
     if (this._typeConstraint == null || this._typeConstraint.Count <= 1)
     {
         return;
     }
     for (int index = 0; index < this._typeConstraint.Count - 1; ++index)
     {
         if (this._typeConstraint[index].IsRef)
         {
             throw InterpreterError.NewInterpreterException((object)this.NodeToken, typeof(RuntimeException), this.NodeToken, "ReferenceNeedsToBeLastTypeInTypeConversion");
         }
     }
 }
Esempio n. 29
0
        private static object SplitOperatorImpl(System.Management.Automation.ExecutionContext context, IScriptExtent errorPosition, object lval, object rval, SplitImplOptions implOptions, bool ignoreCase)
        {
            IEnumerable <string> content   = enumerateContent(context, errorPosition, implOptions, lval);
            ScriptBlock          predicate = null;
            string       separatorPattern  = null;
            int          limit             = 0;
            SplitOptions options           = 0;

            object[] objArray = unfoldTuple(context, errorPosition, rval);
            if (objArray.Length < 1)
            {
                throw InterpreterError.NewInterpreterException(rval, typeof(RuntimeException), errorPosition, "BadOperatorArgument", ParserStrings.BadOperatorArgument, new object[] { "-split", rval });
            }
            object obj1 = objArray[0];

            predicate = objArray[0] as ScriptBlock;
            if (predicate == null)
            {
                separatorPattern = PSObject.ToStringParser(context, objArray[0]);
            }
            if (objArray.Length >= 2)
            {
                limit = FixNum(objArray[1], errorPosition);
            }
            if ((objArray.Length >= 3) && (objArray[2] != null))
            {
                string str2 = objArray[2] as string;
                if ((str2 == null) || !string.IsNullOrEmpty(str2))
                {
                    options = ConvertTo <SplitOptions>(objArray[2], errorPosition);
                    if (predicate != null)
                    {
                        throw InterpreterError.NewInterpreterException(null, typeof(ParseException), errorPosition, "InvalidSplitOptionWithPredicate", ParserStrings.InvalidSplitOptionWithPredicate, new object[0]);
                    }
                    if (ignoreCase && ((options & SplitOptions.IgnoreCase) == 0))
                    {
                        options |= SplitOptions.IgnoreCase;
                    }
                }
            }
            else if (ignoreCase)
            {
                options |= SplitOptions.IgnoreCase;
            }
            if (predicate != null)
            {
                return(SplitWithPredicate(context, errorPosition, content, predicate, limit));
            }
            return(SplitWithPattern(context, errorPosition, content, separatorPattern, limit, options));
        }
        internal static string EnumDisambiguate(string text, Type enumType)
        {
            string[] strArray2;
            string[] enumNames = enumType.GetEnumNames();
            CompareInfo.GetCompareInfo(CultureInfo.InvariantCulture.LCID);
            List <string> list = new List <string>();

            foreach (string str in enumNames)
            {
                if (str.StartsWith(text, StringComparison.OrdinalIgnoreCase))
                {
                    list.Add(str);
                }
            }
            if (list.Count == 0)
            {
                throw InterpreterError.NewInterpreterException(null, typeof(RuntimeException), null, "NoEnumNameMatch", EnumExpressionEvaluatorStrings.NoEnumNameMatch, new object[] { text, EnumAllValues(enumType) });
            }
            if (list.Count == 1)
            {
                return(list[0]);
            }
            foreach (string str2 in list)
            {
                if (str2.Equals(text, StringComparison.OrdinalIgnoreCase))
                {
                    return(str2);
                }
            }
            if (specialDisambiguateCases.TryGetValue(enumType, out strArray2))
            {
                foreach (string str3 in strArray2)
                {
                    if (str3.StartsWith(text, StringComparison.OrdinalIgnoreCase))
                    {
                        return(str3);
                    }
                }
            }
            StringBuilder builder = new StringBuilder(list[0]);
            string        str4    = ", ";

            for (int i = 1; i < list.Count; i++)
            {
                builder.Append(str4);
                builder.Append(list[i]);
            }
            throw InterpreterError.NewInterpreterException(null, typeof(RuntimeException), null, "MultipleEnumNameMatch", EnumExpressionEvaluatorStrings.MultipleEnumNameMatch, new object[] { text, builder.ToString() });
        }