From 899ecea236288b5ebc7795c204fdad59b3276002 Mon Sep 17 00:00:00 2001 From: Tom Willemse Date: Wed, 18 Nov 2020 23:30:46 -0800 Subject: Chapter 8: Add variable declarations --- src/com/craftinginterpreters/lox/Interpreter.java | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) (limited to 'src/com/craftinginterpreters/lox/Interpreter.java') diff --git a/src/com/craftinginterpreters/lox/Interpreter.java b/src/com/craftinginterpreters/lox/Interpreter.java index b8ba090..f4e7f99 100644 --- a/src/com/craftinginterpreters/lox/Interpreter.java +++ b/src/com/craftinginterpreters/lox/Interpreter.java @@ -3,6 +3,8 @@ package com.craftinginterpreters.lox; import java.util.List; class Interpreter implements Expr.Visitor, Stmt.Visitor { + private Environment environment = new Environment(); + @Override public Object visitLiteralExpr(Expr.Literal expr) { return expr.value; @@ -24,6 +26,11 @@ class Interpreter implements Expr.Visitor, Stmt.Visitor { return null; } + @Override + public Object visitVariableExpr(Expr.Variable expr) { + return environment.get(expr.name); + } + private void checkNumberOperand(Token operator, Object operand) { if (operand instanceof Double) return; @@ -95,6 +102,17 @@ class Interpreter implements Expr.Visitor, Stmt.Visitor { return null; } + @Override + public Void visitVarStmt(Stmt.Var stmt) { + Object value = null; + if (stmt.initializer != null) { + value = evaluate(stmt.initializer); + } + + environment.define(stmt.name.lexeme, value); + return null; + } + @Override public Object visitBinaryExpr(Expr.Binary expr) { Object left = evaluate(expr.left); -- cgit v1.2.3-54-g00ecf