-
Notifications
You must be signed in to change notification settings - Fork 2
/
environment.go
69 lines (55 loc) · 1.69 KB
/
environment.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package tlps
// Environment is struct of environment
type Environment struct {
Values map[string]interface{}
Enclosing *Environment
}
// NewEnvironment is constructor of Environment
func NewEnvironment(environment *Environment) *Environment {
return &Environment{
Values: make(map[string]interface{}, 0),
Enclosing: environment,
}
}
// Get returns value associated with name
func (e *Environment) Get(name *Token) (interface{}, error) {
if val, ok := e.Values[name.Lexeme]; ok {
return val, nil
}
if e.Enclosing != nil {
return e.Enclosing.Get(name)
}
return nil, RuntimeError.New(name, "Undefined variable '"+name.Lexeme+"'.")
}
// GetAt return value associated with name at distance depth environment.
func (e *Environment) GetAt(distance int, name string) (interface{}, error) {
return e.Ancestor(distance).Values[name], nil
}
// Ancestor returns `distance` th environment
func (e *Environment) Ancestor(distance int) *Environment {
environment := e
for i := 0; i < distance; i++ {
environment = environment.Enclosing
}
return environment
}
// Define defines variable
func (e *Environment) Define(name string, value interface{}) {
e.Values[name] = value
}
// Assign assigns value
func (e *Environment) Assign(name *Token, value interface{}) error {
if _, ok := e.Values[name.Lexeme]; ok {
e.Values[name.Lexeme] = value
return nil
}
if e.Enclosing != nil {
return e.Enclosing.Assign(name, value)
}
return RuntimeError.New(name, "Undefined variable '"+name.Lexeme+"'.")
}
// AssignAt assigns value at `distance` th environment
func (e *Environment) AssignAt(distance int, name *Token, value interface{}) error {
e.Ancestor(distance).Values[name.Lexeme] = value
return nil
}