Add while statement
This commit is contained in:
parent
c62b73a247
commit
3b9c44434e
3 changed files with 21 additions and 1 deletions
|
@ -157,6 +157,15 @@ class Interpreter implements Expr.Visitor<Object>, Stmt.Visitor<Void> {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Void visitWhileStmt(Stmt.While stmt) {
|
||||||
|
while (isTruthy(evaluate(stmt.condition))) {
|
||||||
|
execute(stmt.body);
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Object visitAssignExpr(Expr.Assign expr) {
|
public Object visitAssignExpr(Expr.Assign expr) {
|
||||||
Object value = evaluate(expr.value);
|
Object value = evaluate(expr.value);
|
||||||
|
|
|
@ -47,6 +47,8 @@ class Parser {
|
||||||
return ifStatement();
|
return ifStatement();
|
||||||
if (match(PRINT))
|
if (match(PRINT))
|
||||||
return printStatement();
|
return printStatement();
|
||||||
|
if (match(WHILE))
|
||||||
|
return whileStatement();
|
||||||
if (match(LEFT_BRACE))
|
if (match(LEFT_BRACE))
|
||||||
return new Stmt.Block(block());
|
return new Stmt.Block(block());
|
||||||
|
|
||||||
|
@ -85,6 +87,15 @@ class Parser {
|
||||||
return new Stmt.Var(name, initializer);
|
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() {
|
private Stmt expressionStatement() {
|
||||||
Expr expr = expression();
|
Expr expr = expression();
|
||||||
consume(SEMICOLON, "Expect ';' after expression.");
|
consume(SEMICOLON, "Expect ';' after expression.");
|
||||||
|
|
|
@ -22,7 +22,7 @@ public class GenerateAst {
|
||||||
defineAst(outputDir, "Stmt",
|
defineAst(outputDir, "Stmt",
|
||||||
Arrays.asList("Block : List<Stmt> statements", "Expression : Expr expression",
|
Arrays.asList("Block : List<Stmt> statements", "Expression : Expr expression",
|
||||||
"If : Expr condition, Stmt thenBranch, Stmt elseBranch", "Print : 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<String> types) throws IOException {
|
private static void defineAst(String outputDir, String baseName, List<String> types) throws IOException {
|
||||||
|
|
Loading…
Reference in a new issue