diff --git a/ruby/lib/lox/interpreter.rb b/ruby/lib/lox/interpreter.rb index d842cc9..c04c6e7 100644 --- a/ruby/lib/lox/interpreter.rb +++ b/ruby/lib/lox/interpreter.rb @@ -1,5 +1,12 @@ +require_relative "environment" + module Lox class Interpreter + + def initialize + @env = Environment.new + end + # The book does printing and error catching here, but # we're going to do it in the runner instead. def interpret(stmts) @@ -20,6 +27,12 @@ module Lox nil end + def visit_var(stmt) + value = stmt.initializer&.yield_self { evaluate(_1) } + @env.define(stmt.name.lexeme, value) + nil + end + def visit_grouping(expr) = evaluate(expr.expr) def visit_literal(expr) = expr.value @@ -35,6 +48,10 @@ module Lox end end + def visit_variable(expr) + @env.get(expr.name) + end + def visit_binary(expr) left = evaluate(expr.left) right = evaluate(expr.right) diff --git a/ruby/test/lox/test_interpreter.rb b/ruby/test/lox/test_interpreter.rb index d26cc96..af0eb94 100644 --- a/ruby/test/lox/test_interpreter.rb +++ b/ruby/test/lox/test_interpreter.rb @@ -97,6 +97,16 @@ class TestInterpreter < Lox::Test SRC end + def test_environment + assert_interpreted <<~EXPECTED.chomp, <<~SRC + 3 + EXPECTED + var a = 1; + var b = 2; + print a + b; + SRC + end + private def assert_interpreted(expected, src)