-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathenvironment.go
More file actions
62 lines (53 loc) · 1.44 KB
/
Copy pathenvironment.go
File metadata and controls
62 lines (53 loc) · 1.44 KB
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
package main
import "fmt"
type Environment struct {
values map[string]interface{}
enclosing *Environment
}
func NewEnvironment(enclosing *Environment) Environment {
return Environment{
enclosing: enclosing,
values: make(map[string]interface{}),
}
}
func (e *Environment) define(name string, value interface{}) {
e.values[name] = value
}
func (env *Environment) get(token Token) (interface{}, error) {
if value, ok := env.values[token.Lexeme]; ok {
return value, nil
} else if env.enclosing != nil {
return env.enclosing.get(token)
} else {
return nil, &RuntimeError{
token: token,
message: fmt.Sprintf("Undefined variable '%v'", token.Lexeme),
}
}
}
func (env *Environment) assign(token Token, value interface{}) error {
if _, ok := env.values[token.Lexeme]; ok {
env.values[token.Lexeme] = value
return nil
} else if env.enclosing != nil {
return env.enclosing.assign(token, value)
} else {
return &RuntimeError{
token: token,
message: fmt.Sprintf("Undefined variable '%v'", token.Lexeme),
}
}
}
func (env *Environment) getAt(distance int, name string) interface{} {
return env.ancestor(distance).values[name]
}
func (env *Environment) assignAt(distance int, name Token, value interface{}) {
env.ancestor(distance).values[name.Lexeme] = value
}
func (env *Environment) ancestor(distance int) *Environment {
var _env = env
for i := 0; i < distance; i++ {
_env = _env.enclosing
}
return _env
}