-
Notifications
You must be signed in to change notification settings - Fork 151
/
scope.go
121 lines (97 loc) · 2.3 KB
/
scope.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
package interpreter
import (
"github.com/influxdata/flux/values"
)
type Scope interface {
// Lookup a name in the current scope
Lookup(name string) (values.Value, bool)
// Bind a variable in the current scope
Set(name string, v values.Value)
// Create a new scope by nesting the current scope
// If the passed in object is not nil, its values will be added to the new nested scope.
Nest(values.Object) Scope
// Return the parent of the current scope
Pop() Scope
// Number of visible names in scope
Size() int
// Range over all variable bindings in scope applying f
Range(f func(k string, v values.Value))
// Range over all variable bindings only in the current scope
LocalRange(f func(k string, v values.Value))
// Set the return value of the scope
SetReturn(values.Value)
// Retrieve the return values of the scope
Return() values.Value
// Create a copy of the scope
Copy() Scope
}
type scope struct {
parent Scope
values values.Object
returnValue values.Value
}
func NewScope() Scope {
return &scope{
values: values.NewObject(),
}
}
func NewNestedScope(s Scope, obj values.Object) Scope {
if obj == nil {
obj = values.NewObject()
}
return &scope{
parent: s,
values: obj,
}
}
func (s *scope) Lookup(name string) (values.Value, bool) {
v, ok := s.values.Get(name)
if !ok && s.parent != nil {
return s.parent.Lookup(name)
}
return v, ok
}
func (s *scope) Set(name string, v values.Value) {
s.values.Set(name, v)
}
func (s *scope) Nest(obj values.Object) Scope {
return NewNestedScope(s, obj)
}
func (s *scope) Pop() Scope {
return s.parent
}
func (s *scope) Size() int {
if s.parent == nil {
return s.values.Len()
}
return s.values.Len() + s.parent.Size()
}
func (s *scope) Range(f func(k string, v values.Value)) {
s.values.Range(f)
if s.parent != nil {
s.parent.Range(f)
}
}
func (s *scope) LocalRange(f func(k string, v values.Value)) {
s.values.Range(f)
}
func (s *scope) SetReturn(v values.Value) {
s.returnValue = v
}
func (s *scope) Return() values.Value {
return s.returnValue
}
func (s *scope) Copy() Scope {
obj := values.NewObjectWithBacking(s.values.Len())
s.values.Range(func(k string, v values.Value) {
obj.Set(k, v)
})
var parent Scope
if s.parent != nil {
parent = s.parent.Copy()
}
return &scope{
values: obj,
parent: parent,
}
}