-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathenvironment.go
54 lines (47 loc) · 1.25 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
package runevm
type Environment struct {
vars map[string]interface{}
parent *Environment
}
func newEnvironment(parent *Environment) *Environment {
vars := make(map[string]interface{})
return &Environment{vars: vars, parent: parent}
}
func (env *Environment) extend() *Environment {
return newEnvironment(env)
}
func (env *Environment) lookup(name string) *Environment {
for scope := env; scope != nil; scope = scope.parent {
if _, found := scope.vars[name]; found {
return scope
}
}
return nil
}
func (env *Environment) get(name string, exp *expression) interface{} {
if value, found := env.vars[name]; found {
return value
}
if env.parent != nil {
return env.parent.get(name, exp)
}
evalError(exp, "Undefined variable '%s'", name)
return nil
}
// func (env *Environment) set(name string, value interface{}, exp *Expr) interface{} {
func (env *Environment) set(name string, value interface{}) interface{} {
scope := env.lookup(name)
// if scope == nil && env.parent != nil {
// Error(exp, "Undefined variable '%s'", name)
// }
if scope != nil {
scope.vars[name] = value
} else {
env.vars[name] = value
}
return value
}
func (env *Environment) def(name string, value interface{}) interface{} {
env.vars[name] = value
return value
}