10.4.1 - environment

main
Alpha Chen 2 years ago
parent 9140a71593
commit bdb7d9f6c9

@ -2,6 +2,8 @@ require_relative "error"
module Lox module Lox
class Environment class Environment
attr_reader :values, :enclosing
def initialize(enclosing = nil) def initialize(enclosing = nil)
@enclosing = enclosing @enclosing = enclosing
@values = {} @values = {}
@ -11,6 +13,12 @@ module Lox
@values[name] = value @values[name] = value
end end
def ancestor(distance)
env = self
distance.times { env = env.enclosing }
env
end
def get(token) def get(token)
name = token.lexeme name = token.lexeme
@ -23,6 +31,10 @@ module Lox
end end
end end
def get_at(distance, name)
ancestor(distance).values.fetch(name)
end
def assign(name, value) def assign(name, value)
lexeme = name.lexeme lexeme = name.lexeme

@ -44,4 +44,16 @@ class TestEnvironment < Lox::Test
assert_equal "qux", enclosed.get(NAME_TOKEN) assert_equal "qux", enclosed.get(NAME_TOKEN)
assert_equal "bar", @env.get(NAME_TOKEN) assert_equal "bar", @env.get(NAME_TOKEN)
end end
def test_get_at
@env.define("name", "foo")
enclosed = Lox::Environment.new(@env)
enclosed.define("name", "bar")
assert_equal "foo", enclosed.get_at(1, "name")
assert_equal "bar", enclosed.get_at(0, "name")
assert_equal "foo", @env.get_at(0, "name")
end
end end

Loading…
Cancel
Save