Class: Lox::Environment

Inherits:
Object
  • Object
show all
Defined in:
lib/loxby/helpers/environment.rb

Overview

Stores namespaces for a Lox interpreter. Environments can be nested (for scope).

Instance Method Summary collapse

Constructor Details

#initialize(enclosing = nil) ⇒ Environment

Returns a new instance of Environment.



9
10
11
12
# File 'lib/loxby/helpers/environment.rb', line 9

def initialize(enclosing = nil)
  @enclosing = enclosing
  @values = {}
end

Instance Method Details

#[](name) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
# File 'lib/loxby/helpers/environment.rb', line 34

def [](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

#[]=(name, value) ⇒ Object Also known as: define



18
19
20
# File 'lib/loxby/helpers/environment.rb', line 18

def []=(name, value)
  set name.lexeme, value
end

#assign(name, value) ⇒ Object



46
47
48
49
50
51
52
53
54
# File 'lib/loxby/helpers/environment.rb', line 46

def assign(name, value)
  if declared? name
    self[name] = value
  elsif @enclosing
    @enclosing.assign(name, value)
  else
    raise undefined_variable(name)
  end
end

#declared?(name) ⇒ Boolean

Returns:

  • (Boolean)


28
29
30
31
32
# File 'lib/loxby/helpers/environment.rb', line 28

def declared?(name)
  # We can't check for a dummy value
  # since loxby uses `nil` as well
  @values.keys.member? name.lexeme
end

#set(name, value) ⇒ Object

Used to set a static association. For example:

env.set 'static_function_name', static_function


24
25
26
# File 'lib/loxby/helpers/environment.rb', line 24

def set(name, value)
  @values[name] = value
end

#undefined_variable(name) ⇒ Object



14
15
16
# File 'lib/loxby/helpers/environment.rb', line 14

def undefined_variable(name)
  Lox::RunError.new(name, "Undefined variable '#{name.lexeme}'")
end