Class: Baba::Environment

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(enclosing = nil) ⇒ Environment

Returns a new instance of Environment.



7
8
9
10
# File 'lib/baba/environment.rb', line 7

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

Instance Attribute Details

#enclosingObject (readonly)

Returns the value of attribute enclosing.



5
6
7
# File 'lib/baba/environment.rb', line 5

def enclosing
  @enclosing
end

#valuesObject (readonly)

Returns the value of attribute values.



5
6
7
# File 'lib/baba/environment.rb', line 5

def values
  @values
end

Instance Method Details

#[](name) ⇒ Object

Raises:



33
34
35
36
37
38
39
40
41
# File 'lib/baba/environment.rb', line 33

def [](name)
  if @values.include?(name.lexeme)
    return @values[name.lexeme]
  end

  return @enclosing[name] unless @enclosing.nil?

  raise BabaRuntimeError.new(name, "Undefined variable '#{name.lexeme}'.")
end

#[]=(name, value) ⇒ Object

Raises:



43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/baba/environment.rb', line 43

def []=(name, value)
  if @values.include?(name.lexeme)
    @values[name.lexeme] = value
    return
  end

  unless @enclosing.nil?
    @enclosing[name] = value
    return
  end

  raise BabaRuntimeError.new(name, "Undefined variable '#{name.lexme}'.")
end

#ancestor(distance) ⇒ Object



16
17
18
19
20
21
22
23
# File 'lib/baba/environment.rb', line 16

def ancestor(distance)
  environment = self
  1.upto(distance) do
    environment = environment.enclosing
  end

  environment
end

#assign_at(distance, name, value) ⇒ Object



29
30
31
# File 'lib/baba/environment.rb', line 29

def assign_at(distance, name, value)
  ancestor(distance).values[name.lexeme] = value
end

#define(name, value) ⇒ Object



12
13
14
# File 'lib/baba/environment.rb', line 12

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

#get_at(distance, name) ⇒ Object



25
26
27
# File 'lib/baba/environment.rb', line 25

def get_at(distance, name)
  ancestor(distance).values[name]
end