diff options
Diffstat (limited to 'src/com/craftinginterpreters/lox')
-rw-r--r-- | src/com/craftinginterpreters/lox/Interpreter.java | 9 | ||||
-rw-r--r-- | src/com/craftinginterpreters/lox/Parser.java | 11 |
2 files changed, 20 insertions, 0 deletions
diff --git a/src/com/craftinginterpreters/lox/Interpreter.java b/src/com/craftinginterpreters/lox/Interpreter.java index 6c32233..6b3e409 100644 --- a/src/com/craftinginterpreters/lox/Interpreter.java +++ b/src/com/craftinginterpreters/lox/Interpreter.java @@ -158,6 +158,15 @@ class Interpreter implements Expr.Visitor<Object>, Stmt.Visitor<Void> { } @Override + public Void visitWhileStmt(Stmt.While stmt) { + while (isTruthy(evaluate(stmt.condition))) { + execute(stmt.body); + } + + return null; + } + + @Override public Object visitAssignExpr(Expr.Assign expr) { Object value = evaluate(expr.value); environment.assign(expr.name, value); diff --git a/src/com/craftinginterpreters/lox/Parser.java b/src/com/craftinginterpreters/lox/Parser.java index 1643129..a85d70f 100644 --- a/src/com/craftinginterpreters/lox/Parser.java +++ b/src/com/craftinginterpreters/lox/Parser.java @@ -47,6 +47,8 @@ class Parser { return ifStatement(); if (match(PRINT)) return printStatement(); + if (match(WHILE)) + return whileStatement(); if (match(LEFT_BRACE)) return new Stmt.Block(block()); @@ -85,6 +87,15 @@ class Parser { return new Stmt.Var(name, initializer); } + private Stmt whileStatement() { + consume(LEFT_PAREN, "Expect '(' after 'while'."); + Expr condition = expression(); + consume(RIGHT_PAREN, "Expect ')' after condition."); + Stmt body = statement(); + + return new Stmt.While(condition, body); + } + private Stmt expressionStatement() { Expr expr = expression(); consume(SEMICOLON, "Expect ';' after expression."); |