Chapter 8: Add blocks and scopes

This commit is contained in:
Tom Willemse 2020-11-25 23:10:58 -08:00
parent 57e87978ef
commit ca9fd3ae3a
5 changed files with 75 additions and 4 deletions

View file

@ -1,5 +1,7 @@
package com.craftinginterpreters.lox; package com.craftinginterpreters.lox;
import java.util.List;
/** /**
* AstPrinter * AstPrinter
*/ */
@ -55,6 +57,11 @@ class AstPrinter implements Expr.Visitor<String>, Stmt.Visitor<String> {
return expression.expression.accept(this); return expression.expression.accept(this);
} }
@Override
public String visitBlockStmt(Stmt.Block block) {
return parenthesize("", block.statements);
}
private String parenthesize(String name, Expr... exprs) { private String parenthesize(String name, Expr... exprs) {
StringBuilder builder = new StringBuilder(); StringBuilder builder = new StringBuilder();
@ -68,6 +75,19 @@ class AstPrinter implements Expr.Visitor<String>, Stmt.Visitor<String> {
return builder.toString(); return builder.toString();
} }
private String parenthesize(String name, List<Stmt> statements) {
StringBuilder builder = new StringBuilder();
builder.append("(").append(name);
for (Stmt statement : statements) {
builder.append(" ");
builder.append(statement.accept(this));
}
builder.append(")");
return builder.toString();
}
public static void main(String[] args) { public static void main(String[] args) {
Expr expression = new Expr.Binary( Expr expression = new Expr.Binary(
new Expr.Unary(new Token(TokenType.MINUS, "-", null, 1), new Expr.Literal(123)), new Expr.Unary(new Token(TokenType.MINUS, "-", null, 1), new Expr.Literal(123)),

View file

@ -4,13 +4,25 @@ import java.util.HashMap;
import java.util.Map; import java.util.Map;
class Environment { class Environment {
private final Environment enclosing;
private final Map<String, Object> values = new HashMap<>(); private final Map<String, Object> values = new HashMap<>();
Environment() {
enclosing = null;
}
Environment(Environment enclosing) {
this.enclosing = enclosing;
}
Object get(Token name) { Object get(Token name) {
if (values.containsKey(name.lexeme)) { if (values.containsKey(name.lexeme)) {
return values.get(name.lexeme); return values.get(name.lexeme);
} }
if (enclosing != null)
return enclosing.get(name);
throw new RuntimeError(name, "Undefined variable '" + name.lexeme + "'."); throw new RuntimeError(name, "Undefined variable '" + name.lexeme + "'.");
} }
@ -20,6 +32,11 @@ class Environment {
return; return;
} }
if (enclosing != null) {
enclosing.assign(name, value);
return;
}
throw new RuntimeError(name, "Undefined variable '" + name.lexeme + "'."); throw new RuntimeError(name, "Undefined variable '" + name.lexeme + "'.");
} }

View file

@ -89,6 +89,26 @@ class Interpreter implements Expr.Visitor<Object>, Stmt.Visitor<Void> {
stmt.accept(this); stmt.accept(this);
} }
private void executeBlock(List<Stmt> statements, Environment environment) {
Environment previous = this.environment;
try {
this.environment = environment;
for (Stmt statement : statements) {
execute(statement);
}
} finally {
this.environment = previous;
}
}
@Override
public Void visitBlockStmt(Stmt.Block stmt) {
executeBlock(stmt.statements, new Environment(environment));
return null;
}
@Override @Override
public Void visitExpressionStmt(Stmt.Expression stmt) { public Void visitExpressionStmt(Stmt.Expression stmt) {
evaluate(stmt.expression); evaluate(stmt.expression);

View file

@ -45,6 +45,8 @@ class Parser {
private Stmt statement() { private Stmt statement() {
if (match(PRINT)) if (match(PRINT))
return printStatement(); return printStatement();
if (match(LEFT_BRACE))
return new Stmt.Block(block());
return expressionStatement(); return expressionStatement();
} }
@ -73,6 +75,17 @@ class Parser {
return new Stmt.Expression(expr); return new Stmt.Expression(expr);
} }
private List<Stmt> block() {
List<Stmt> statements = new ArrayList<>();
while (!check(RIGHT_BRACE) && !isAtEnd()) {
statements.add(declaration());
}
consume(RIGHT_BRACE, "Expect '}' after block.");
return statements;
}
private Expr assignment() { private Expr assignment() {
Expr expr = equality(); Expr expr = equality();

View file

@ -15,10 +15,11 @@ public class GenerateAst {
String outputDir = args[0]; String outputDir = args[0];
defineAst(outputDir, "Expr", defineAst(outputDir, "Expr",
Arrays.asList("Assign : Token name, Expr value", "Binary : Expr left, Token operator, Expr right", "Grouping : Expr expression", Arrays.asList("Assign : Token name, Expr value", "Binary : Expr left, Token operator, Expr right",
"Literal : Object value", "Unary : Token operator, Expr right", "Variable : Token name")); "Grouping : Expr expression", "Literal : Object value", "Unary : Token operator, Expr right",
defineAst(outputDir, "Stmt", Arrays.asList("Expression : Expr expression", "Print : Expr expression", "Variable : Token name"));
"Var : Token name, Expr initializer")); defineAst(outputDir, "Stmt", Arrays.asList("Block : List<Stmt> statements", "Expression : Expr expression",
"Print : Expr expression", "Var : Token name, Expr initializer"));
} }
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 {