[jlox] Add while statement

This commit is contained in:
ctsk
2022-09-10 11:21:25 +02:00
parent 5327b3746a
commit a4c1076008
3 changed files with 25 additions and 2 deletions

View File

@@ -79,6 +79,14 @@ public class Interpreter implements Expr.Visitor<Object>, Stmt.Visitor<Void> {
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) {
var value = evaluate(expr.value());

View File

@@ -17,10 +17,13 @@ import static xyz.ctsk.lox.TokenType.*;
* statement → exprStmt
* | ifStmt
* | printStmt
* | whileStmt
* | block ;
* block → "{" declaration* "}" ;
* exprStmt → expression ";" ;
* ifStmt → "if" "(" expression ")" statement ( "else" statement )? ;
* whileStmt → "while" "(" expression ")" statement ;
* printStmt → "print" expression ";" ;
* exprStmt → expression ";" ;
* expression → equality ;
* expression → assignment ;
* assignment → IDENTIFIER "=" assignment
@@ -81,10 +84,12 @@ public class Parser {
private Stmt statement() {
if (match(IF)) return ifStatement();
if (match(PRINT)) return printStatement();
if (match(WHILE)) return whileStatement();
if (match(LEFT_BRACE)) return new Stmt.Block(blockStatement());
return expressionStatement();
}
private Stmt ifStatement() {
consume(LEFT_PAREN, "Expect '(' after 'if'.");
Expr condition = expression();
@@ -102,6 +107,15 @@ public class Parser {
return new Stmt.Print(value);
}
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 List<Stmt> blockStatement() {
var statements = new ArrayList<Stmt>();

View File

@@ -15,7 +15,8 @@
@Rule(head = "Expression", body = {"Expr expression"}),
@Rule(head = "If", body = {"Expr condition", "Stmt thenBranch", "Stmt elseBranch"}),
@Rule(head = "Print", body = {"Expr expression"}),
@Rule(head = "Var", body = {"Token name", "Expr initializer"})
@Rule(head = "Var", body = {"Token name", "Expr initializer"}),
@Rule(head = "While", body = {"Expr condition", "Stmt body"})
})
})
package xyz.ctsk.lox;