-
Notifications
You must be signed in to change notification settings - Fork 0
/
module.go
89 lines (74 loc) · 1.42 KB
/
module.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
package trompe
import (
"strings"
)
type Module struct {
Parent *Module
Subs map[string]*Module
Name string
File string
Env *Env
}
var RootModule *Module
var OpenedModules []*Module
var sep = "."
func GetModule(path string) *Module {
comps := strings.Split(path, sep)
owner := RootModule
for _, name := range comps {
if m, ok := owner.Subs[name]; ok {
owner = m
} else {
return nil
}
}
return owner
}
func AddTopModule(m *Module) {
RootModule.AddSub(m)
}
func AddOpenedModule(m *Module) {
OpenedModules = append(OpenedModules, m)
}
func GetModuleAttr(ms []*Module, name string) Value {
for _, m := range ms {
if v := m.GetAttr(name); v != nil {
return v
}
}
return nil
}
func NewModule(parent *Module, name string) *Module {
env := NewEnv(nil)
env.Imports = OpenedModules
return &Module{
Parent: parent,
Subs: make(map[string]*Module, 8),
Name: name,
Env: env,
}
}
func (m *Module) Path() string {
path := m.Name
cur := m.Parent
for cur != nil {
path += sep
path += cur.Name
cur = cur.Parent
}
return path
}
func (m *Module) AddSub(sub *Module) {
m.Subs[sub.Name] = sub
}
func (m *Module) GetAttr(name string) Value {
return m.Env.Get(name)
}
func (m *Module) AddAttr(name string, value Value) {
m.Env.Set(name, value)
}
func (m *Module) AddPrim(name string,
f func(*Context, []Value, int) (Value, error),
arity int) {
m.AddAttr(name, NewPrim(f, arity))
}