Exemple #1
0
 private ExpressionAst ArrayLiteralRule()
 {
     ExpressionAst errorExpressionAst = this.UnaryExpressionRule();
     ExpressionAst expressionAst = errorExpressionAst;
     Token token = this.PeekToken();
     if (token.Kind != TokenKind.Comma || this._disableCommaOperator)
     {
         return errorExpressionAst;
     }
     else
     {
         List<ExpressionAst> expressionAsts = new List<ExpressionAst>();
         expressionAsts.Add(errorExpressionAst);
         List<ExpressionAst> expressionAsts1 = expressionAsts;
         while (token.Kind == TokenKind.Comma)
         {
             this.SkipToken();
             this.SkipNewlines();
             errorExpressionAst = this.UnaryExpressionRule();
             if (errorExpressionAst != null)
             {
                 expressionAsts1.Add(errorExpressionAst);
                 token = this.PeekToken();
             }
             else
             {
                 object[] text = new object[1];
                 text[0] = token.Text;
                 this.ReportIncompleteInput(Parser.After(token), ParserStrings.MissingExpressionAfterToken, text);
                 errorExpressionAst = new ErrorExpressionAst(token.Extent, null);
                 expressionAsts1.Add(errorExpressionAst);
                 break;
             }
         }
         return new ArrayLiteralAst(Parser.ExtentOf(expressionAst, errorExpressionAst), expressionAsts1);
     }
 }
 public object VisitErrorExpression(ErrorExpressionAst errorExpressionAst) { throw new UnexpectedElementException(); }
Exemple #3
0
 public override AstVisitAction VisitErrorExpression(ErrorExpressionAst ast) { return CheckParent(ast); }
Exemple #4
0
 private RedirectionAst RedirectionRule(RedirectionToken redirectionToken, RedirectionAst[] redirections, ref IScriptExtent extent)
 {
     RedirectionAst fileRedirectionAst;
     string allStream;
     FileRedirectionToken fileRedirectionToken = redirectionToken as FileRedirectionToken;
     if (fileRedirectionToken != null || redirectionToken as InputRedirectionToken != null)
     {
         ExpressionAst singleCommandArgument = this.GetSingleCommandArgument(Parser.CommandArgumentContext.FileName);
         if (singleCommandArgument == null)
         {
             this.ReportError(Parser.After(redirectionToken), ParserStrings.MissingFileSpecification, new object[0]);
             singleCommandArgument = new ErrorExpressionAst(redirectionToken.Extent, null);
         }
         if (fileRedirectionToken != null)
         {
             fileRedirectionAst = new FileRedirectionAst(Parser.ExtentOf(fileRedirectionToken, singleCommandArgument), fileRedirectionToken.FromStream, singleCommandArgument, fileRedirectionToken.Append);
         }
         else
         {
             object[] text = new object[1];
             text[0] = redirectionToken.Text;
             this.ReportError(redirectionToken.Extent, ParserStrings.RedirectionNotSupported, text);
             extent = Parser.ExtentOf(redirectionToken, singleCommandArgument);
             return null;
         }
     }
     else
     {
         MergingRedirectionToken mergingRedirectionToken = (MergingRedirectionToken)redirectionToken;
         RedirectionStream fromStream = mergingRedirectionToken.FromStream;
         RedirectionStream toStream = mergingRedirectionToken.ToStream;
         if (toStream == RedirectionStream.Output)
         {
             if (fromStream == toStream)
             {
                 object[] objArray = new object[1];
                 objArray[0] = mergingRedirectionToken.Text;
                 this.ReportError(redirectionToken.Extent, ParserStrings.RedirectionNotSupported, objArray);
             }
         }
         else
         {
             object[] text1 = new object[1];
             text1[0] = mergingRedirectionToken.Text;
             this.ReportError(redirectionToken.Extent, ParserStrings.RedirectionNotSupported, text1);
             toStream = RedirectionStream.Output;
         }
         fileRedirectionAst = new MergingRedirectionAst(mergingRedirectionToken.Extent, mergingRedirectionToken.FromStream, toStream);
     }
     if (redirections[(int)fileRedirectionAst.FromStream] != null)
     {
         RedirectionStream redirectionStream = fileRedirectionAst.FromStream;
         if (redirectionStream == RedirectionStream.All)
         {
             allStream = ParserStrings.AllStream;
         }
         else if (redirectionStream == RedirectionStream.Output)
         {
             allStream = ParserStrings.OutputStream;
         }
         else if (redirectionStream == RedirectionStream.Error)
         {
             allStream = ParserStrings.ErrorStream;
         }
         else if (redirectionStream == RedirectionStream.Warning)
         {
             allStream = ParserStrings.WarningStream;
         }
         else if (redirectionStream == RedirectionStream.Verbose)
         {
             allStream = ParserStrings.VerboseStream;
         }
         else if (redirectionStream == RedirectionStream.Debug)
         {
             allStream = ParserStrings.DebugStream;
         }
         else if (redirectionStream == RedirectionStream.Host)
         {
             allStream = ParserStrings.HostStream;
         }
         else
         {
             throw PSTraceSource.NewArgumentOutOfRangeException("result.FromStream", (object)fileRedirectionAst.FromStream);
         }
         object[] objArray1 = new object[1];
         objArray1[0] = allStream;
         this.ReportError(fileRedirectionAst.Extent, ParserStrings.StreamAlreadyRedirected, objArray1);
     }
     else
     {
         redirections[(int)fileRedirectionAst.FromStream] = fileRedirectionAst;
     }
     extent = fileRedirectionAst.Extent;
     return fileRedirectionAst;
 }
Exemple #5
0
 public object VisitErrorExpression(ErrorExpressionAst errorExpressionAst)
 {
     return ExpressionCache.Constant(1);
 }
 /// <summary/>
 public virtual object VisitErrorExpression(ErrorExpressionAst errorExpressionAst)
 {
     return _decorated.VisitErrorExpression(errorExpressionAst);
 }
Exemple #7
0
        private ExpressionAst ElementAccessRule(ExpressionAst primaryExpression, Token lBracket)
        {
            //G  element-access:
            //G      primary-expression   '['   new-lines:opt   expression   new-lines:opt   ']'

            SkipNewlines();
            ExpressionAst indexExpr = ExpressionRule();
            if (indexExpr == null)
            {
                // ErrorRecovery: hope we see a closing bracket.  If we don't, we'll pretend we saw
                // the closing bracket, but build an expression that can't compile.

                var errorExtent = After(lBracket);
                ReportIncompleteInput(errorExtent, () => ParserStrings.MissingArrayIndexExpression);
                indexExpr = new ErrorExpressionAst(lBracket.Extent);
            }

            SkipNewlines();
            Token rBracket = NextToken();
            if (rBracket.Kind != TokenKind.RBracket)
            {
                // ErrorRecovery: just pretend we had a closing bracket and continue parsing.

                UngetToken(rBracket);
                // Skip reporting the error if we've already reported a missing index.
                if (!(indexExpr is ErrorExpressionAst))
                {
                    ReportIncompleteInput(After(indexExpr), () => ParserStrings.MissingEndSquareBracket);
                }
                rBracket = null;
            }

            return new IndexExpressionAst(ExtentOf(primaryExpression, ExtentFromFirstOf(rBracket, indexExpr)), primaryExpression, indexExpr);
        }
Exemple #8
0
 public object VisitErrorExpression(ErrorExpressionAst errorExpressionAst) { throw PSTraceSource.NewArgumentException("ast"); }
Exemple #9
0
        private ExpressionAst ExpressionRule()
        {
            //G  expression:
            //G      logical-expression
            //G
            //G  logical-expression:
            //G      bitwise-expression
            //G      logical-expression   '-and'   new-lines:opt   bitwise-expression
            //G      logical-expression   '-or'   new-lines:opt   bitwise-expression
            //G      logical-expression   '-xor'   new-lines:opt   bitwise-expression
            //G
            //G  bitwise-expression:
            //G      comparison-expression
            //G      bitwise-expression   '-band'   new-lines:opt   comparison-expression
            //G      bitwise-expression   '-bor'   new-lines:opt   comparison-expression
            //G      bitwise-expression   '-bxor'   new-lines:opt   comparison-expression
            //G
            //G  comparison-expression:
            //G      additive-expression
            //G      comparison-expression   comparison-operator   new-lines:opt   additive-expression
            //G
            //G  additive-expression:
            //G      multiplicative-expression
            //G      additive-expression   '+'   new-lines:opt   multiplicative-expression
            //G      additive-expression   dash   new-lines:opt   multiplicative-expression
            //G
            //G  multiplicative-expression:
            //G      format-expression
            //G      multiplicative-expression   '*'   new-lines:opt   format-expression
            //G      multiplicative-expression   '/'   new-lines:opt   format-expression
            //G      multiplicative-expression   '%'   new-lines:opt   format-expression
            //G
            //G  format-expression:
            //G      range-expression
            //G      format-expression   format-operator    new-lines:opt   range-expression
            //G
            //G  range-expression:
            //G      array-literal-expression
            //G      range-expression   '..'   new-lines:opt   array-literal-expression
            RuntimeHelpers.EnsureSufficientExecutionStack();
            var oldTokenizerMode = _tokenizer.Mode;
            try
            {
                SetTokenizerMode(TokenizerMode.Expression);

                ExpressionAst lhs, rhs;
                ExpressionAst expr = ArrayLiteralRule();

                if (expr == null)
                {
                    return null;
                }

                ParameterToken paramToken;
                Token token = PeekToken();
                if (!token.Kind.HasTrait(TokenFlags.BinaryOperator))
                {
                    paramToken = token as ParameterToken;
                    if (paramToken != null)
                    {
                        return ErrorRecoveryParameterInExpression(paramToken, expr);
                    }
                    return expr;
                }

                SkipToken();

                Stack<ExpressionAst> operandStack = new Stack<ExpressionAst>();
                Stack<Token> operatorStack = new Stack<Token>();

                operandStack.Push(expr);
                operatorStack.Push(token);

                int precedence = token.Kind.GetBinaryPrecedence();
                while (true)
                {
                    SkipNewlines();

                    expr = ArrayLiteralRule();
                    if (expr == null)
                    {
                        // ErrorRecovery: create an error expression to fill out the ast and keep parsing.

                        IScriptExtent extent = After(token);
                        // Use token.Text, not token.Kind.Text() b/c the kind might not match the actual operator used
                        // when a case insensitive operator is used.
                        ReportIncompleteInput(extent, () => ParserStrings.ExpectedValueExpression, token.Text);
                        expr = new ErrorExpressionAst(extent);
                    }
                    operandStack.Push(expr);

                    token = NextToken();

                    if (!token.Kind.HasTrait(TokenFlags.BinaryOperator))
                    {
                        // Remember the token that we stopped on, but only parameters, used for error recovery
                        paramToken = token as ParameterToken;
                        UngetToken(token);
                        break;
                    }

                    int newPrecedence = token.Kind.GetBinaryPrecedence();
                    while (newPrecedence <= precedence)
                    {
                        rhs = operandStack.Pop();
                        lhs = operandStack.Pop();
                        Token op = operatorStack.Pop();
                        operandStack.Push(new BinaryExpressionAst(ExtentOf(lhs, rhs), lhs, op.Kind, rhs, op.Extent));
                        if (operatorStack.Count == 0)
                            break;
                        precedence = operatorStack.Peek().Kind.GetBinaryPrecedence();
                    }
                    operatorStack.Push(token);
                    precedence = newPrecedence;
                }
                rhs = operandStack.Pop();
                Diagnostics.Assert(operandStack.Count == operatorStack.Count, "Stacks out of sync");
                while (operandStack.Count > 0)
                {
                    lhs = operandStack.Pop();
                    token = operatorStack.Pop();
                    rhs = new BinaryExpressionAst(ExtentOf(lhs, rhs), lhs, token.Kind, rhs, token.Extent);
                }

                if (paramToken != null)
                {
                    return ErrorRecoveryParameterInExpression(paramToken, rhs);
                }

                return rhs;
            }
            finally
            {
                SetTokenizerMode(oldTokenizerMode);
            }
        }
Exemple #10
0
        private ExpressionAst ArrayLiteralRule()
        {
            //G  array-literal-expression:
            //G      unary-expression
            //G      unary-expression   ','    new-lines:opt   array-literal-expression

            ExpressionAst lastExpr = UnaryExpressionRule();
            ExpressionAst firstExpr = lastExpr;

            Token commaToken = PeekToken();
            if (commaToken.Kind != TokenKind.Comma || _disableCommaOperator)
            {
                return lastExpr;
            }

            var arrayValues = new List<ExpressionAst> { lastExpr };

            while (commaToken.Kind == TokenKind.Comma)
            {
                SkipToken();
                SkipNewlines();

                lastExpr = UnaryExpressionRule();
                if (lastExpr == null)
                {
                    // ErrorRecovery: create an error expression for the ast and break.

                    ReportIncompleteInput(After(commaToken), () => ParserStrings.MissingExpressionAfterToken, commaToken.Text);
                    lastExpr = new ErrorExpressionAst(commaToken.Extent);
                    arrayValues.Add(lastExpr);
                    break;
                }
                arrayValues.Add(lastExpr);

                commaToken = PeekToken();
            }

            return new ArrayLiteralAst(ExtentOf(firstExpr, lastExpr), arrayValues);
        }
Exemple #11
0
        private RedirectionAst RedirectionRule(RedirectionToken redirectionToken, RedirectionAst[] redirections, ref IScriptExtent extent)
        {
            //G  redirections:
            //G      redirection
            //G      redirections   redirection
            //G  redirection:
            //G      merging-redirection-operator
            //G      file-redirection-operator   redirected-file-name
            //G  redirected-file-name:
            //G      command-argument
            //G      primary-expression

            RedirectionAst result;

            var fileRedirectionToken = redirectionToken as FileRedirectionToken;
            if (fileRedirectionToken != null || (redirectionToken is InputRedirectionToken))
            {
                // get location
                var filename = GetSingleCommandArgument(CommandArgumentContext.FileName);
                if (filename == null)
                {
                    // ErrorRecovery: Just pretend we have a filename and continue parsing.

                    ReportError(After(redirectionToken), () => ParserStrings.MissingFileSpecification);
                    filename = new ErrorExpressionAst(redirectionToken.Extent);
                }

                if (fileRedirectionToken == null)
                {
                    // Must be an input redirection
                    ReportError(redirectionToken.Extent, () => ParserStrings.RedirectionNotSupported, redirectionToken.Text);
                    extent = ExtentOf(redirectionToken, filename);
                    return null;
                }

                result = new FileRedirectionAst(ExtentOf(fileRedirectionToken, filename), fileRedirectionToken.FromStream,
                                                filename, fileRedirectionToken.Append);
            }
            else
            {
                var mergingRedirectionToken = (MergingRedirectionToken)redirectionToken;

                RedirectionStream fromStream = mergingRedirectionToken.FromStream;
                RedirectionStream toStream = mergingRedirectionToken.ToStream;
                if (toStream != RedirectionStream.Output)
                {
                    // Have we seen something like 1>&2 or 2>&3
                    // ErrorRecovery: This is just a semantic error, so no special recovery.

                    ReportError(redirectionToken.Extent, () => ParserStrings.RedirectionNotSupported, mergingRedirectionToken.Text);
                    toStream = RedirectionStream.Output;
                }
                else if (fromStream == toStream)
                {
                    // Make sure 1>&1, 2>&2, etc. is an error.
                    // ErrorRecovery: This is just a semantic error, so no special recovery.

                    ReportError(redirectionToken.Extent, () => ParserStrings.RedirectionNotSupported, mergingRedirectionToken.Text);
                }

                result = new MergingRedirectionAst(mergingRedirectionToken.Extent, mergingRedirectionToken.FromStream, toStream);
            }

            if (redirections[(int)result.FromStream] == null)
            {
                redirections[(int)result.FromStream] = result;
            }
            else
            {
                string errorStream;
                switch (result.FromStream)
                {
                    case RedirectionStream.All: errorStream = ParserStrings.AllStream; break;
                    case RedirectionStream.Output: errorStream = ParserStrings.OutputStream; break;
                    case RedirectionStream.Error: errorStream = ParserStrings.ErrorStream; break;
                    case RedirectionStream.Warning: errorStream = ParserStrings.WarningStream; break;
                    case RedirectionStream.Verbose: errorStream = ParserStrings.VerboseStream; break;
                    case RedirectionStream.Debug: errorStream = ParserStrings.DebugStream; break;
                    case RedirectionStream.Information: errorStream = ParserStrings.InformationStream; break;
                    default:
                        throw PSTraceSource.NewArgumentOutOfRangeException("result.FromStream", result.FromStream);
                }
                ReportError(result.Extent, () => ParserStrings.StreamAlreadyRedirected, errorStream);
            }

            extent = result.Extent;
            return result;
        }
Exemple #12
0
        /// <summary>
        /// Parse a dynamic keyword statement which will be either of the form
        ///     keyword [parameters] [name] { a=1; b=2; } # constructor with properties
        /// or
        ///     keyword [parameters] [name] { ... }  # constructor with a simple body.
        /// or keywordcommand parameters 
        /// This custom keyword does not introduce a new AST node type. Instead it generates a
        /// CommandAst that calls a PowerShell command to implement the keyword's logic.
        /// This command has one of two signatures:
        ///     keywordImplCommand
        /// </summary>
        /// <param name="functionName">The name of the function to invoke</param>
        /// <param name="keywordData">The data for this keyword definition</param>
        /// <returns></returns>
        private StatementAst DynamicKeywordStatementRule(Token functionName, DynamicKeyword keywordData)
        {
            //////////////////////////////////////////////////////////////////////////////////
            // If a custom action was provided. then invoke it
            //////////////////////////////////////////////////////////////////////////////////
            if (keywordData.PreParse != null)
            {
                try
                {
                    ParseError[] errors = keywordData.PreParse(keywordData);
                    if (errors != null && errors.Length > 0)
                    {
                        foreach (var e in errors)
                        {
                            ReportError(e);
                        }
                    }
                }
                catch (Exception e)
                {
                    ReportError(functionName.Extent, () => ParserStrings.DynamicKeywordPreParseException, keywordData.ResourceName, e.ToString());
                    return null;
                }
            }

            if (keywordData.IsReservedKeyword)
            {
                // ErrorRecovery: eat the token
                ReportError(functionName.Extent, () => ParserStrings.UnsupportedReservedKeyword, keywordData.Keyword);
                return null;
            }

            if (keywordData.HasReservedProperties)
            {
                // ErrorRecovery: eat the token
                ReportError(functionName.Extent, () => ParserStrings.UnsupportedReservedProperty, "'Require', 'Trigger', 'Notify', 'Before', 'After' and 'Subscribe'");
                return null;
            }

            string elementName = string.Empty;

            DynamicKeywordStatementAst dynamicKeywordAst;
            if (keywordData.BodyMode == DynamicKeywordBodyMode.Command)
            {
                UngetToken(functionName);
                dynamicKeywordAst = (DynamicKeywordStatementAst)CommandRule(forDynamicKeyword: true);
                dynamicKeywordAst.Keyword = keywordData;
                dynamicKeywordAst.FunctionName = functionName;
            }
            else
            {
                SkipNewlines();

                // The expression that returns the resource name or names.
                ExpressionAst instanceName = null;

                Token nameToken = NextToken();
                if (nameToken.Kind == TokenKind.EndOfInput)
                {
                    UngetToken(nameToken);

                    if (keywordData.NameMode == DynamicKeywordNameMode.NameRequired || keywordData.NameMode == DynamicKeywordNameMode.SimpleNameRequired)
                    {
                        ReportIncompleteInput(After(functionName), () => ParserStrings.RequiredNameOrExpressionMissing);
                    }
                    else
                    {
                        // Name not required so report missing brace
                        ReportIncompleteInput(After(functionName.Extent), () => ParserStrings.MissingBraceInObjectDefinition);
                    }
                    return null;
                }

                // If it's an lcurly, then no name was provided, and we skip to the body processing
                Token lCurly = null;
                if (nameToken.Kind == TokenKind.LCurly)
                {
                    lCurly = nameToken;
                    if (keywordData.NameMode == DynamicKeywordNameMode.NameRequired || keywordData.NameMode == DynamicKeywordNameMode.SimpleNameRequired)
                    {
                        ReportError(After(functionName), () => ParserStrings.RequiredNameOrExpressionMissing);
                        UngetToken(nameToken);
                        return null;
                    }
                }
                else if (nameToken.Kind == TokenKind.Identifier || nameToken.Kind == TokenKind.DynamicKeyword)
                {
                    if (keywordData.NameMode == DynamicKeywordNameMode.NoName)
                    {
                        ReportError(After(functionName), () => ParserStrings.UnexpectedNameForType, functionName.Text, nameToken.Text);
                        UngetToken(nameToken);
                        return null;
                    }

                    // If it's an identifier then this is the name for the data object
                    elementName = nameToken.Text;

                    // If only a simple name is allowed, then the string must be non-null.
                    if ((keywordData.NameMode == DynamicKeywordNameMode.SimpleNameRequired || keywordData.NameMode == DynamicKeywordNameMode.SimpleOptionalName) && string.IsNullOrEmpty(elementName))
                    {
                        ReportIncompleteInput(After(functionName), () => ParserStrings.RequiredNameOrExpressionMissing);
                        UngetToken(nameToken);
                        return null;
                    }
                }
                else
                {
                    // see if an expression was provided instead of a bare word...
                    UngetToken(nameToken);
                    instanceName = GetSingleCommandArgument(CommandArgumentContext.CommandName);

                    if (instanceName == null)
                    {
                        if (keywordData.NameMode == DynamicKeywordNameMode.SimpleNameRequired || keywordData.NameMode == DynamicKeywordNameMode.SimpleOptionalName)
                        {
                            ReportError(After(functionName), () => ParserStrings.RequiredNameOrExpressionMissing);
                        }
                        else
                        {
                            // It wasn't an '{' and it wasn't a name expression so it's a unexpected token.
                            ReportError(After(functionName), () => ParserStrings.UnexpectedToken, nameToken.Text);
                        }
                        return null;
                    }

                    // Ok, we got a name expression, but we're expecting no name, so it's and error.
                    if (keywordData.NameMode == DynamicKeywordNameMode.NoName)
                    {
                        ReportError(After(functionName), () => ParserStrings.UnexpectedNameForType, functionName.Text, instanceName.ToString());
                        return null;
                    }

                    // We were expecting a simple name so report an error
                    if (keywordData.NameMode == DynamicKeywordNameMode.SimpleNameRequired || keywordData.NameMode == DynamicKeywordNameMode.SimpleOptionalName)
                    {
                        // If no match, then this is an incomplete token BUGBUG fix message
                        ReportError(nameToken.Extent, () => ParserStrings.UnexpectedToken, nameToken.Text);
                        return null;
                    }
                }

                // If we didn't get a resource expression AST, then we need to build one out of the
                // name that was specified. It may be the case that we don't have
                // a resource name in which case it will be the empty string. Even in the cases were
                // we aren't expecting a name, we still do this so that the signature of the implementing function remains
                // the same.
                ExpressionAst originalInstanceName = instanceName;
                if (instanceName == null)
                {
                    instanceName = new StringConstantExpressionAst(nameToken.Extent, elementName, StringConstantType.BareWord);
                }

                SkipNewlines();

                //
                // Now look for the body of the data statement.
                //
                if (lCurly == null)
                {
                    lCurly = NextToken();

                    if (lCurly.Kind == TokenKind.EndOfInput)
                    {
                        UngetToken(lCurly);
                        ReportIncompleteInput(After(functionName.Extent), () => ParserStrings.MissingBraceInObjectDefinition);

                        // Preserve the name expression for tab completion
                        return originalInstanceName == null
                                   ? null
                                   : new ErrorStatementAst(ExtentOf(functionName, originalInstanceName),
                                                           GetNestedErrorAsts(originalInstanceName));
                    }

                    if (lCurly.Kind != TokenKind.LCurly)
                    {
                        // We need to generate a reasonable error message for this case:
                        //
                        // Configuration C {
                        //   node $AllNode.NodeName{ # There is no space before curly, and we are converting scriptblock to and argument to call 'NodeName'
                        //     ...
                        //   }
                        // } # we don't want to simple report an unexpected token here, it would be super-confusing.

                        InvokeMemberExpressionAst instanceInvokeMemberExpressionAst = instanceName as InvokeMemberExpressionAst;

                        if (instanceInvokeMemberExpressionAst != null &&
                            instanceInvokeMemberExpressionAst.Arguments.Count == 1 &&
                            instanceInvokeMemberExpressionAst.Arguments[0] is ScriptBlockExpressionAst &&
                            // the last condition checks that there is no space between "method" name and '{'
                            instanceInvokeMemberExpressionAst.Member.Extent.EndOffset == instanceInvokeMemberExpressionAst.Arguments[0].Extent.StartOffset)
                        {
                            ReportError(LastCharacterOf(instanceInvokeMemberExpressionAst.Member.Extent), () => ParserStrings.UnexpectedTokenInDynamicKeyword, functionName.Text);
                        }
                        else
                        {
                            ReportError(lCurly.Extent, () => ParserStrings.UnexpectedToken, lCurly.Text);
                        }

                        if (lCurly.Kind == TokenKind.Dot && originalInstanceName != null && lCurly.Extent.StartOffset == originalInstanceName.Extent.EndOffset)
                        {
                            // Generate more useful ast for tab-completing extension methods on special DSC collection variables
                            // e.g. configuration foo { node $AllNodes.<tab>

                            IScriptExtent errorExtent = ExtentOf(originalInstanceName, lCurly);
                            var errorExpr = new ErrorExpressionAst(errorExtent);
                            var memberExpr = new MemberExpressionAst(originalInstanceName.Extent, originalInstanceName, errorExpr, @static: false);

                            return new ErrorStatementAst(errorExtent, new[] { memberExpr });
                        }

                        UngetToken(lCurly);
                        // Preserve the name expression for tab completion
                        return originalInstanceName == null
                                   ? null
                                   : new ErrorStatementAst(ExtentOf(functionName, originalInstanceName),
                                                           GetNestedErrorAsts(originalInstanceName));
                    }
                }

                //
                // The keyword data is used to see
                // if a scriptblock or a hashtable is expected.
                //
                ExpressionAst body = null;
                if (keywordData.BodyMode == DynamicKeywordBodyMode.ScriptBlock)
                {
                    var oldInConfiguraiton = _inConfiguration;
                    try
                    {
                        _inConfiguration = false;
                        body = ScriptBlockExpressionRule(lCurly);
                    }
                    finally
                    {
                        _inConfiguration = oldInConfiguraiton;
                    }
                }
                else if (keywordData.BodyMode == DynamicKeywordBodyMode.Hashtable)
                {
                    // Resource property value could be set to nested DSC resources except Script resource
                    bool isScriptResource = String.Compare(functionName.Text, @"Script", StringComparison.OrdinalIgnoreCase) == 0;
                    try
                    {
                        if (isScriptResource)
                            DynamicKeyword.Push();
                        body = HashExpressionRule(lCurly, true /* parsingSchemaElement */);
                    }
                    finally
                    {
                        if (isScriptResource)
                            DynamicKeyword.Pop();
                    }
                }
                // commandast
                // elements: instancename/dynamickeyword/hashtable or scripblockexpress
                if (body == null)
                {
                    // Failed to read the statement body
                    ReportIncompleteInput(After(lCurly), () => ParserStrings.MissingStatementAfterKeyword, keywordData.Keyword);

                    // Preserve the name expression for tab completion
                    return originalInstanceName == null
                               ? null
                               : new ErrorStatementAst(ExtentOf(functionName, originalInstanceName),
                                                       GetNestedErrorAsts(originalInstanceName));
                }

                //////////////////////////////////////////////////////////////////////////
                // The statement is now fully parsed
                //////////////////////////////////////////////////////////////////////////

                //
                // Create DynamicKeywordStatementAst
                //
                Collection<CommandElementAst> commandElements = new Collection<CommandElementAst>
                {
                    new StringConstantExpressionAst(functionName.Extent, functionName.Text, StringConstantType.BareWord),
                    (ExpressionAst)instanceName.Copy(),
                    (ExpressionAst)body.Copy()
                };
                Token nextToken = NextToken();
                IScriptExtent dynamicKeywordExtent = ExtentOf(functionName, Before(nextToken));
                UngetToken(nextToken);
                dynamicKeywordAst = new DynamicKeywordStatementAst(dynamicKeywordExtent, commandElements)
                {
                    Keyword = keywordData,
                    LCurly = lCurly,
                    FunctionName = functionName,
                    InstanceName = instanceName,
                    OriginalInstanceName = originalInstanceName,
                    BodyExpression = body,
                    ElementName = elementName,
                };
            }

            //////////////////////////////////////////////////////////////////////////////////
            // If a custom action was provided. then invoke it
            //////////////////////////////////////////////////////////////////////////////////
            if (keywordData.PostParse != null)
            {
                try
                {
                    ParseError[] errors = keywordData.PostParse(dynamicKeywordAst);
                    if (errors != null && errors.Length > 0)
                    {
                        foreach (var e in errors)
                        {
                            ReportError(e);
                        }
                    }
                }
                catch (Exception e)
                {
                    ReportError(functionName.Extent, () => ParserStrings.DynamicKeywordPostParseException, keywordData.Keyword, e.ToString());
                    return null;
                }
            }

            return dynamicKeywordAst;
        }
Exemple #13
0
        private void AttributeArgumentsRule(ICollection<ExpressionAst> positionalArguments,
                                            ICollection<NamedAttributeArgumentAst> namedArguments,
                                            ref IScriptExtent lastItemExtent)
        {
            //G  attribute-arguments:
            //G      attribute-argument
            //G      attribute-argument   new-lines:opt   ','   attribute-arguments
            //G  attribute-argument:
            //G      new-lines:opt   expression
            //G      new-lines:opt   property-name   '='   new-lines:opt   expression

            bool oldDisableCommaOperator = _disableCommaOperator;
            Token commaToken = null;
            HashSet<string> keysSeen = new HashSet<string>();
            try
            {
                _disableCommaOperator = true;
                while (true)
                {
                    SkipNewlines();

                    StringConstantExpressionAst name = SimpleNameRule();
                    ExpressionAst expr;
                    bool expressionOmitted = false;

                    if (name != null)
                    {
                        Token token = PeekToken();
                        if (token.Kind == TokenKind.Equals)
                        {
                            token = NextToken();
                            SkipNewlines();

                            expr = ExpressionRule();

                            if (expr == null)
                            {
                                // ErrorRecovery: ?

                                IScriptExtent errorPosition = After(token);
                                ReportIncompleteInput(errorPosition, () => ParserStrings.MissingExpressionInNamedArgument);
                                expr = new ErrorExpressionAst(errorPosition);
                                SyncOnError(true, TokenKind.Comma, TokenKind.RParen, TokenKind.RBracket, TokenKind.NewLine);
                            }
                            lastItemExtent = expr.Extent;
                        }
                        else
                        {
                            // If the expression is missing, assume the value true
                            // and record that it was defaulted for better error messages.
                            expr = new ConstantExpressionAst(name.Extent, true);
                            expressionOmitted = true;
                            NoteV3FeatureUsed();
                        }
                    }
                    else
                    {
                        expr = ExpressionRule();
                    }

                    if (name != null)
                    {
                        if (keysSeen.Contains(name.Value))
                        {
                            // ErrorRecovery: this is a semantic error, so just keep parsing.

                            ReportError(name.Extent, () => ParserStrings.DuplicateNamedArgument, name.Value);
                        }
                        else
                        {
                            namedArguments.Add(new NamedAttributeArgumentAst(ExtentOf(name, expr),
                                name.Value, expr, expressionOmitted));
                        }
                    }
                    else if (expr != null)
                    {
                        positionalArguments.Add(expr);
                        lastItemExtent = expr.Extent;
                    }
                    else if (commaToken != null)
                    {
                        // ErrorRecovery: Pretend we saw the argument and keep going.

                        IScriptExtent errorExtent = After(commaToken);
                        ReportIncompleteInput(errorExtent, () => ParserStrings.MissingExpressionAfterToken,
                            commaToken.Kind.Text());
                        positionalArguments.Add(new ErrorExpressionAst(errorExtent));
                        lastItemExtent = errorExtent;
                    }

                    SkipNewlines();
                    commaToken = PeekToken();
                    if (commaToken.Kind != TokenKind.Comma)
                    {
                        break;
                    }

                    lastItemExtent = commaToken.Extent;
                    SkipToken();
                }
            }
            finally
            {
                _disableCommaOperator = oldDisableCommaOperator;
            }
        }
Exemple #14
0
 public override AstVisitAction VisitErrorExpression(ErrorExpressionAst ast)
 {
     return this.Check(ast);
 }
Exemple #15
0
 private ExpressionAst ElementAccessRule(ExpressionAst primaryExpression, Token lBracket)
 {
     this.SkipNewlines();
     ExpressionAst errorExpressionAst = this.ExpressionRule();
     if (errorExpressionAst == null)
     {
         IScriptExtent scriptExtent = Parser.After(lBracket);
         this.ReportIncompleteInput(scriptExtent, ParserStrings.MissingArrayIndexExpression, new object[0]);
         errorExpressionAst = new ErrorExpressionAst(lBracket.Extent, null);
     }
     this.SkipNewlines();
     Token token = this.NextToken();
     if (token.Kind != TokenKind.RBracket)
     {
         this.UngetToken(token);
         if (errorExpressionAst as ErrorExpressionAst == null)
         {
             this.ReportIncompleteInput(Parser.After(errorExpressionAst), ParserStrings.MissingEndSquareBracket, new object[0]);
         }
         token = null;
     }
     object[] objArray = new object[2];
     objArray[0] = token;
     objArray[1] = errorExpressionAst;
     return new IndexExpressionAst(Parser.ExtentOf(primaryExpression, Parser.ExtentFromFirstOf(objArray)), primaryExpression, errorExpressionAst);
 }
Exemple #16
0
 public object VisitErrorExpression(ErrorExpressionAst errorExpressionAst) { return AutomationNull.Value; }
Exemple #17
0
 private void AttributeArgumentsRule(ICollection<ExpressionAst> positionalArguments, ICollection<NamedAttributeArgumentAst> namedArguments, ref IScriptExtent lastItemExtent)
 {
     ExpressionAst constantExpressionAst;
     bool flag = this._disableCommaOperator;
     Token token = null;
     HashSet<string> strs = new HashSet<string>();
     try
     {
         this._disableCommaOperator = true;
         while (true)
         {
             this.SkipNewlines();
             StringConstantExpressionAst stringConstantExpressionAst = this.SimpleNameRule();
             bool flag1 = false;
             if (stringConstantExpressionAst == null)
             {
                 constantExpressionAst = this.ExpressionRule();
             }
             else
             {
                 Token token1 = this.PeekToken();
                 if (token1.Kind != TokenKind.Equals)
                 {
                     constantExpressionAst = new ConstantExpressionAst(stringConstantExpressionAst.Extent, (object)(true));
                     flag1 = true;
                     this.NoteV3FeatureUsed();
                 }
                 else
                 {
                     token1 = this.NextToken();
                     this.SkipNewlines();
                     constantExpressionAst = this.ExpressionRule();
                     if (constantExpressionAst == null)
                     {
                         IScriptExtent scriptExtent = Parser.After(token1);
                         this.ReportIncompleteInput(scriptExtent, ParserStrings.MissingExpressionInNamedArgument, new object[0]);
                         constantExpressionAst = new ErrorExpressionAst(scriptExtent, null);
                         TokenKind[] tokenKindArray = new TokenKind[4];
                         tokenKindArray[0] = TokenKind.Comma;
                         tokenKindArray[1] = TokenKind.RParen;
                         tokenKindArray[2] = TokenKind.RBracket;
                         tokenKindArray[3] = TokenKind.NewLine;
                         this.SyncOnError(tokenKindArray);
                     }
                     lastItemExtent = constantExpressionAst.Extent;
                 }
             }
             if (stringConstantExpressionAst == null)
             {
                 if (constantExpressionAst == null)
                 {
                     if (token != null)
                     {
                         IScriptExtent scriptExtent1 = Parser.After(token);
                         object[] objArray = new object[1];
                         objArray[0] = token.Kind.Text();
                         this.ReportIncompleteInput(scriptExtent1, ParserStrings.MissingExpressionAfterToken, objArray);
                         positionalArguments.Add(new ErrorExpressionAst(scriptExtent1, null));
                         lastItemExtent = scriptExtent1;
                     }
                 }
                 else
                 {
                     positionalArguments.Add(constantExpressionAst);
                     lastItemExtent = constantExpressionAst.Extent;
                 }
             }
             else
             {
                 if (!strs.Contains(stringConstantExpressionAst.Value))
                 {
                     namedArguments.Add(new NamedAttributeArgumentAst(Parser.ExtentOf(stringConstantExpressionAst, constantExpressionAst), stringConstantExpressionAst.Value, constantExpressionAst, flag1));
                 }
                 else
                 {
                     object[] value = new object[1];
                     value[0] = stringConstantExpressionAst.Value;
                     this.ReportError(stringConstantExpressionAst.Extent, ParserStrings.DuplicateNamedArgument, value);
                 }
             }
             this.SkipNewlines();
             token = this.PeekToken();
             if (token.Kind != TokenKind.Comma)
             {
                 break;
             }
             lastItemExtent = token.Extent;
             this.SkipToken();
         }
     }
     finally
     {
         this._disableCommaOperator = flag;
     }
 }
Exemple #18
0
 public virtual AstVisitAction VisitErrorExpression(ErrorExpressionAst errorExpressionAst)
 {
     return AstVisitAction.Continue;
 }
Exemple #19
0
 private ExpressionAst ExpressionRule()
 {
     ExpressionAst expressionAst;
     ExpressionAst binaryExpressionAst;
     ParameterToken parameterToken;
     ExpressionAst expressionAst1;
     RuntimeHelpers.EnsureSufficientExecutionStack();
     TokenizerMode mode = this._tokenizer.Mode;
     try
     {
         this.SetTokenizerMode(TokenizerMode.Expression);
         ExpressionAst errorExpressionAst = this.ArrayLiteralRule();
         if (errorExpressionAst != null)
         {
             Token token = this.PeekToken();
             if (token.Kind.HasTrait(TokenFlags.BinaryOperator))
             {
                 this.SkipToken();
                 Stack<ExpressionAst> expressionAsts = new Stack<ExpressionAst>();
                 Stack<Token> tokens = new Stack<Token>();
                 expressionAsts.Push(errorExpressionAst);
                 tokens.Push(token);
                 int binaryPrecedence = token.Kind.GetBinaryPrecedence();
                 while (true)
                 {
                     this.SkipNewlines();
                     errorExpressionAst = this.ArrayLiteralRule();
                     if (errorExpressionAst == null)
                     {
                         IScriptExtent scriptExtent = Parser.After(token);
                         object[] text = new object[1];
                         text[0] = token.Text;
                         this.ReportIncompleteInput(scriptExtent, ParserStrings.ExpectedValueExpression, text);
                         errorExpressionAst = new ErrorExpressionAst(scriptExtent, null);
                     }
                     expressionAsts.Push(errorExpressionAst);
                     token = this.NextToken();
                     if (!token.Kind.HasTrait(TokenFlags.BinaryOperator))
                     {
                         break;
                     }
                     int num = token.Kind.GetBinaryPrecedence();
                     while (num <= binaryPrecedence)
                     {
                         binaryExpressionAst = expressionAsts.Pop();
                         expressionAst = expressionAsts.Pop();
                         Token token1 = tokens.Pop();
                         expressionAsts.Push(new BinaryExpressionAst(Parser.ExtentOf(expressionAst, binaryExpressionAst), expressionAst, token1.Kind, binaryExpressionAst, token1.Extent));
                         if (tokens.Count == 0)
                         {
                             break;
                         }
                         binaryPrecedence = tokens.Peek().Kind.GetBinaryPrecedence();
                     }
                     tokens.Push(token);
                     binaryPrecedence = num;
                 }
                 parameterToken = token as ParameterToken;
                 this.UngetToken(token);
                 binaryExpressionAst = expressionAsts.Pop();
                 while (expressionAsts.Any<ExpressionAst>())
                 {
                     expressionAst = expressionAsts.Pop();
                     token = tokens.Pop();
                     binaryExpressionAst = new BinaryExpressionAst(Parser.ExtentOf(expressionAst, binaryExpressionAst), expressionAst, token.Kind, binaryExpressionAst, token.Extent);
                 }
                 if (parameterToken == null)
                 {
                     expressionAst1 = binaryExpressionAst;
                 }
                 else
                 {
                     expressionAst1 = this.ErrorRecoveryParameterInExpression(parameterToken, binaryExpressionAst);
                 }
             }
             else
             {
                 parameterToken = token as ParameterToken;
                 if (parameterToken == null)
                 {
                     expressionAst1 = errorExpressionAst;
                 }
                 else
                 {
                     expressionAst1 = this.ErrorRecoveryParameterInExpression(parameterToken, errorExpressionAst);
                 }
             }
         }
         else
         {
             expressionAst1 = null;
         }
     }
     finally
     {
         this.SetTokenizerMode(mode);
     }
     return expressionAst1;
 }
 /// <summary>
 /// Visit error expression
 /// </summary>
 /// <param name="errorExpressionAst"></param>
 /// <returns></returns>
 public object VisitErrorExpression(ErrorExpressionAst errorExpressionAst)
 {
     return null;
 }
Exemple #21
0
 private ExpressionAst MemberAccessRule(ExpressionAst targetExpr, Token operatorToken)
 {
     CommandElementAst commandElementAst = this.MemberNameRule();
     if (commandElementAst != null)
     {
         Token token = this.NextInvokeMemberToken();
         if (token != null)
         {
             return this.MemberInvokeRule(targetExpr, token, operatorToken, commandElementAst);
         }
     }
     else
     {
         this.ReportIncompleteInput(Parser.After(operatorToken), ParserStrings.MissingPropertyName, new object[0]);
         ExpressionAst singleCommandArgument = this.GetSingleCommandArgument(Parser.CommandArgumentContext.CommandArgument);
         CommandElementAst errorExpressionAst = singleCommandArgument;
         if (singleCommandArgument == null)
         {
             errorExpressionAst = new ErrorExpressionAst(Parser.ExtentOf(targetExpr, operatorToken), null);
         }
         commandElementAst = errorExpressionAst;
     }
     return new MemberExpressionAst(Parser.ExtentOf(targetExpr, commandElementAst), targetExpr, commandElementAst, operatorToken.Kind == TokenKind.ColonColon);
 }
 public object VisitErrorExpression(ErrorExpressionAst errorExpressionAst)
 {
     return false;
 }
 public object VisitErrorExpression(ErrorExpressionAst errorExpressionAst)
 {
     throw new NotImplementedException();
 }