forked from erh/scheme
-
Notifications
You must be signed in to change notification settings - Fork 0
/
exec.go
69 lines (54 loc) · 1.09 KB
/
exec.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
package scheme
import (
"fmt"
)
type Scope map[string]*Value
type SchemeFunction func(args []*Value, scope Scope) (*Value, error)
func evalAll(es []*Expression, s Scope) ([]*Value, error) {
res := []*Value{}
for _, e := range es {
v, err := Eval(e, s)
if err != nil {
return nil, err
}
res = append(res, v)
}
return res, nil
}
func Eval(e *Expression, s Scope) (*Value, error) {
if e.Val != nil {
return e.Val, nil
}
if e.Var != nil {
v, ok := s[*e.Var]
if !ok {
v, ok = builtins[*e.Var]
}
if !ok {
return nil, fmt.Errorf("undefined variable: %s", *e.Var)
}
return v, nil
}
if e.Symbol != nil {
f, ok := symbols[*e.Symbol]
if !ok {
return nil, fmt.Errorf("unknown symbol: %s", *e.Symbol)
}
return f, nil
}
if len(e.Call) > 0 {
f, err := Eval(e.Call[0], s)
if err != nil {
return nil, err
}
if f.Func == nil {
return nil, fmt.Errorf("%s is not a function", e.Call[0].String())
}
args, err := evalAll(e.Call[1:], s)
if err != nil {
return nil, err
}
return f.Func(args, s)
}
return nil, fmt.Errorf("unknown thing: %#v", e)
}