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 @@ -157,6 +157,15 @@ class Interpreter implements Expr.Visitor, Stmt.Visitor { return null; } + @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); 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."); diff --git a/src/com/craftinginterpreters/tool/GenerateAst.java b/src/com/craftinginterpreters/tool/GenerateAst.java index a3935e1..8845c6e 100644 --- a/src/com/craftinginterpreters/tool/GenerateAst.java +++ b/src/com/craftinginterpreters/tool/GenerateAst.java @@ -22,7 +22,7 @@ public class GenerateAst { defineAst(outputDir, "Stmt", Arrays.asList("Block : List statements", "Expression : Expr expression", "If : Expr condition, Stmt thenBranch, Stmt elseBranch", "Print : Expr expression", - "Var : Token name, Expr initializer")); + "Var : Token name, Expr initializer", "While : Expr condition, Stmt body")); } private static void defineAst(String outputDir, String baseName, List types) throws IOException {