diff options
author | Tom Willemse | 2020-11-18 18:18:25 -0800 |
---|---|---|
committer | Tom Willemse | 2020-11-18 18:18:25 -0800 |
commit | 8019f6aa414f5126ebbcd3afc44bcebc16855d5f (patch) | |
tree | 10e76f1ddcf8013f243f249fdbdf47c9568f4558 /src/com/craftinginterpreters/lox/Interpreter.java | |
parent | 055b5257fb6df2a0893c43ed342befd83d20af94 (diff) | |
download | crafting-interpreters-8019f6aa414f5126ebbcd3afc44bcebc16855d5f.tar.gz crafting-interpreters-8019f6aa414f5126ebbcd3afc44bcebc16855d5f.zip |
Chapter 8: Add expression and print statements
Diffstat (limited to 'src/com/craftinginterpreters/lox/Interpreter.java')
-rw-r--r-- | src/com/craftinginterpreters/lox/Interpreter.java | 28 |
1 files changed, 24 insertions, 4 deletions
diff --git a/src/com/craftinginterpreters/lox/Interpreter.java b/src/com/craftinginterpreters/lox/Interpreter.java index 24cf1c0..b8ba090 100644 --- a/src/com/craftinginterpreters/lox/Interpreter.java +++ b/src/com/craftinginterpreters/lox/Interpreter.java @@ -1,6 +1,8 @@ package com.craftinginterpreters.lox; -class Interpreter implements Expr.Visitor<Object> { +import java.util.List; + +class Interpreter implements Expr.Visitor<Object>, Stmt.Visitor<Void> { @Override public Object visitLiteralExpr(Expr.Literal expr) { return expr.value; @@ -76,6 +78,23 @@ class Interpreter implements Expr.Visitor<Object> { return expr.accept(this); } + private void execute(Stmt stmt) { + stmt.accept(this); + } + + @Override + public Void visitExpressionStmt(Stmt.Expression stmt) { + evaluate(stmt.expression); + return null; + } + + @Override + public Void visitPrintStmt(Stmt.Print stmt) { + Object value = evaluate(stmt.expression); + System.out.println(stringify(value)); + return null; + } + @Override public Object visitBinaryExpr(Expr.Binary expr) { Object left = evaluate(expr.left); @@ -123,10 +142,11 @@ class Interpreter implements Expr.Visitor<Object> { return null; } - public void interpret(Expr expression) { + public void interpret(List<Stmt> statements) { try { - Object value = evaluate(expression); - System.out.println(stringify(value)); + for (Stmt statement : statements) { + execute(statement); + } } catch (RuntimeError error) { Lox.runtimeError(error); } |