This repository has been archived by the owner on Aug 11, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
scope.go
101 lines (86 loc) · 2.22 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
package scope
// Scope is a map of values indexed by identifiers.
//
// A scope may have a parent scope. If the current scope does not store a value for a
// specific identifier, the parent scopes will be considered (recursively.)
type Scope struct {
// Parent is the parent scope of this scope.
Parent *Scope
values map[string]interface{}
locked bool
}
// Set stores the value v identified by name in the scope.
//
// If the scope has a parent scope, and that parent scope already stores a value for that
// identifier, the value is stored (overwritten) in the parent scope instead. Parent scopes are considered
// recursively until there is no parent scope.
//
// If the scope where the value should be stored is locked, nothing will happen.
func (s *Scope) Set(name string, v interface{}) {
ps := s.Parent
parentHasValue := false
for ps != nil {
if parentHasValue = hasValueSelf(ps, name); parentHasValue {
break
}
ps = ps.Parent
}
if parentHasValue {
ps.values[name] = v
return
}
if s.locked {
return
}
s.init()
s.values[name] = v
}
// HasValue returns whether the scope or any of its parent scopes store a value identified by name.
func (s *Scope) HasValue(name string) bool {
for {
if ok := hasValueSelf(s, name); ok {
return true
}
if s = s.Parent; s == nil {
return false
}
}
}
// Value returns the value identified by name in this scope or any of its parent scopes.
// If there is a value, ok will be true, otherwise it will be false.
func (s *Scope) Value(name string) (interface{}, bool) {
for {
if s.values != nil {
if v, ok := s.values[name]; ok {
return v, true
}
}
if s = s.Parent; s == nil {
return nil, false
}
}
}
// Lock prevents this scope from further modification. Parent scopes (if any) will not be locked.
func (s *Scope) Lock() {
s.locked = true
}
// ClearSelf removes all values associated with this scope, not including any parent scopes.
func (s *Scope) ClearSelf() {
if s.values != nil {
for k := range s.values {
delete(s.values, k)
}
}
}
func (s *Scope) init() {
if s.values == nil {
s.values = map[string]interface{}{}
}
}
func hasValueSelf(s *Scope, name string) bool {
if s.values == nil {
return false
}
_, ok := s.values[name]
return ok
}