lib/loxby/helpers/environment.rb in loxby-0.0.2 vs lib/loxby/helpers/environment.rb in loxby-0.0.3
- old
+ new
@@ -1,13 +1,12 @@
# frozen_string_literal: true
require_relative 'errors'
class Lox
- # Lox::Environment stores namespace for
- # a Lox interpreter. Environments can be
- # nested (for scope).
+ # Stores namespaces for a Lox interpreter.
+ # Environments can be nested (for scope).
class Environment
def initialize(enclosing = nil)
@enclosing = enclosing
@values = {}
end
@@ -15,33 +14,45 @@
def undefined_variable(name)
Lox::RunError.new(name, "Undefined variable '#{name.lexeme}'")
end
def []=(name, value)
- @values[name.lexeme] = value
+ set name.lexeme, value
end
- def exists?(name)
+ # Used to set a static association. For example:
+ # env.set 'static_function_name', static_function
+ def set(name, value)
+ @values[name] = value
+ end
+
+ def declared?(name)
+ # We can't check for a dummy value
+ # since loxby uses `nil` as well
@values.keys.member? name.lexeme
end
def [](name)
- if exists? name
+ if @values[name.lexeme]
@values[name.lexeme]
+ elsif declared? name
+ raise Lox::RunError.new(name, "Declared variable not initialized: '#{name.lexeme}'")
elsif @enclosing
@enclosing[name]
else
raise undefined_variable(name)
end
end
def assign(name, value)
- if exists? name
+ if declared? name
self[name] = value
elsif @enclosing
@enclosing.assign(name, value)
else
raise undefined_variable(name)
end
end
+
+ alias define []=
end
end