Exemple #1
0
        private SyntaxNode ParseForStatement()
        {
            Consume(SyntaxKind.LeftParen, "expect'(' after 'for'.");
            SyntaxNode initializer;

            if (Match(SyntaxKind.Semicolon))
            {
                initializer = null;
            }
            else if (Match(SyntaxKind.Var))
            {
                initializer = ParseVariableDeclaration();
            }
            else
            {
                initializer = ParseExpressionStatement();
            }

            SyntaxNode condition = null;

            if (!Check(SyntaxKind.Semicolon))
            {
                condition = ParseExpression();
            }

            Consume(SyntaxKind.Semicolon, "expect';' after loop condition.");

            SyntaxNode increment = null;

            if (!Check(SyntaxKind.RightParen))
            {
                increment = ParseExpression();
            }

            Consume(SyntaxKind.RightParen, "expect ')' after for clauses.");

            SyntaxNode body = ParseStatement();

            // desugar into a while loop
            if (increment != null)
            {
                body = new BlockStatement(new List <SyntaxNode> {
                    body, new ExpressionStatement(increment)
                });
            }

            if (condition == null)
            {
                condition = new LiteralExpression(true);
            }

            body = new WhileStatement(condition, body);

            if (initializer != null)
            {
                body = new BlockStatement(new List <SyntaxNode> {
                    new ExpressionStatement(initializer), body
                });
            }

            return(body);
        }