Beispiel #1
0
        private Stmt ForStatement()
        {
            Consume(TokenType.LEFT_PAREN, "Expect '(' after 'for'.");

            Stmt initializer;

            if (Match(TokenType.SEMICOLON))
            {
                initializer = null;
            }
            else if (Match(TokenType.VAR))
            {
                initializer = VarDeclaration();
            }
            else
            {
                initializer = ExpressionStatement();
            }

            Expr condition;

            if (!Check(TokenType.SEMICOLON))
            {
                condition = Expression();
            }
            else
            {
                condition = new Literal(true);
            }
            Consume(TokenType.SEMICOLON, "Expect ';' after loop condition.");

            Expr increment = null;

            if (!Check(TokenType.RIGHT_PAREN))
            {
                increment = Expression();
            }

            Consume(TokenType.RIGHT_PAREN, "Expect ')' after for clauses.");

            Stmt body = Statement();

            if (increment != null)
            {
                body = new Block(new List <Stmt> {
                    body, new Expression(increment)
                });
            }

            body = new While(condition, body);

            if (initializer != null)
            {
                body = new Block(new List <Stmt> {
                    initializer, body
                });
            }

            return(body);
        }
Beispiel #2
0
 public object VisitWhileStmt(While stmt)
 {
     while (IsTruthy(Evaluate(stmt.condition)))
     {
         Execute(stmt.body);
     }
     return(null);
 }
Beispiel #3
0
 public object VisitWhileStmt(While stmt)
 {
     Resolve(stmt.condition);
     Resolve(stmt.body);
     return(null);
 }