Chapter 8: Add expression and print statements

This commit is contained in:
Tom Willemse 2020-11-18 18:18:25 -08:00
parent 055b5257fb
commit 8019f6aa41
3 changed files with 53 additions and 11 deletions

View file

@ -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);
}

View file

@ -53,13 +53,13 @@ public class Lox {
Scanner scanner = new Scanner(source);
List<Token> tokens = scanner.scanTokens();
Parser parser = new Parser(tokens);
Expr expression = parser.parse();
List<Stmt> statements = parser.parse();
// Stop if there was a syntax error
if (hadError)
return;
interpreter.interpret(expression);
interpreter.interpret(statements);
}
public static void error(int line, String message) {

View file

@ -2,6 +2,7 @@ package com.craftinginterpreters.lox;
import static com.craftinginterpreters.lox.TokenType.*;
import java.util.ArrayList;
import java.util.List;
class Parser {
@ -15,18 +16,39 @@ class Parser {
this.tokens = tokens;
}
public Expr parse() {
try {
return expression();
} catch (ParseError error) {
return null;
public List<Stmt> parse() {
List<Stmt> statements = new ArrayList<>();
while (!isAtEnd()) {
statements.add(statement());
}
return statements;
}
private Expr expression() {
return equality();
}
private Stmt statement() {
if (match(PRINT))
return printStatement();
return expressionStatement();
}
private Stmt printStatement() {
Expr value = expression();
consume(SEMICOLON, "Expect ';' after value.");
return new Stmt.Print(value);
}
private Stmt expressionStatement() {
Expr expr = expression();
consume(SEMICOLON, "Expect ';' after expression.");
return new Stmt.Expression(expr);
}
private Expr equality() {
Expr expr = comparison();