-
-
Notifications
You must be signed in to change notification settings - Fork 299
/
scope.go
79 lines (58 loc) · 1.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
package compiler
import (
"github.com/MontFerret/ferret/pkg/runtime/core"
"github.com/MontFerret/ferret/pkg/runtime/values/types"
)
type (
scope struct {
parent *scope
vars map[string]core.Type
}
)
func newRootScope() *scope {
return &scope{
vars: make(map[string]core.Type),
}
}
func newScope(parent *scope) *scope {
s := newRootScope()
s.parent = parent
return s
}
func (s *scope) GetVariable(name string) (core.Type, error) {
local, exists := s.vars[name]
if exists {
return local, nil
}
if s.parent != nil {
parents, err := s.parent.GetVariable(name)
if err != nil {
return types.None, err
}
return parents, nil
}
return types.None, core.Error(ErrVariableNotFound, name)
}
func (s *scope) SetVariable(name string) error {
_, exists := s.vars[name]
if exists {
return core.Error(ErrVariableNotUnique, name)
}
// TODO: add type detection
s.vars[name] = types.None
return nil
}
func (s *scope) RemoveVariable(name string) error {
_, exists := s.vars[name]
if !exists {
return core.Error(ErrVariableNotFound, name)
}
delete(s.vars, name)
return nil
}
func (s *scope) ClearVariables() {
s.vars = make(map[string]core.Type)
}
func (s *scope) Fork() *scope {
return newScope(s)
}