-
Notifications
You must be signed in to change notification settings - Fork 0
/
eval.go
277 lines (238 loc) · 5.46 KB
/
eval.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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
package fatlisp
import "fmt"
type Context struct {
global *Env
}
type Env struct {
parent *Env
defs map[string]Value
}
var defaults = map[string]Value{
"add": newFn(add, 2, 2),
"subtract": newFn(subtract, 2, 2),
"multiply": newFn(multiply, 2, 2),
"divide": newFn(divide, 2, 2),
"compare": newFn(compare, 2, 2),
"puts": newFn(puts, 0, -1),
"def": newForm("def", def, 2, 2, []Type{idType}),
"fn": newForm("fn", fn, 2, 2, []Type{listType}),
"if": newForm("if", _if, 2, 3, []Type{}),
"quote": newForm("quote", quote, 1, 1, []Type{}),
}
func NewContext() *Context {
global := newEnvWithDefs(defaults)
return &Context{global}
}
func newEnv() *Env {
return &Env{defs: make(map[string]Value, 1)}
}
func newEnvWithDefs(defs map[string]Value) *Env {
return &Env{defs: defs}
}
// Construct a new function scope based on parent scope.
func newFunctionEnv(parent *Env, params Value, args []Value) *Env {
env := newEnv()
env.parent = parent
for i, p := range val2slice(params) {
name := val2str(p)
value := args[i]
env.set(name, value)
}
return env
}
func (e *Env) set(key string, v Value) {
e.defs[key] = v
}
func (e Env) get(val Value) (Value, error) {
id := val2str(val)
v, ok := e.defs[id]
if !ok {
if e.parent != nil {
parent := *e.parent
return parent.get(val)
} else {
err := newError(val.origin, "unable to resolve %s", id)
return Value{}, err
}
}
return v, nil
}
func (ctx *Context) Eval(root Value) ([]Value, error) {
results := []Value{}
for _, v := range val2slice(root) {
res, err := eval(v, ctx.global)
if err != nil {
return results, err
} else {
results = append(results, res)
}
}
return results, nil
}
func eval(v Value, e *Env) (Value, error) {
switch v.typ {
case idType:
return e.get(v)
case listType:
return evalList(v, e)
default:
return v, nil
}
}
func evalList(list Value, env *Env) (Value, error) {
slice := val2slice(list)
args := make([]Value, len(slice)-1)
id := slice[0]
// Eval the first item in the list
first, err := eval(id, env)
if err != nil {
return Value{}, err
}
// Check if the first item is a fn or a special form.
// Returning an error if neither.
switch first.typ {
case fnType:
// Loop over the rest of the list and eval each of
// the function's arguments.
for i, c := range slice[1:] {
res, err := eval(c, env)
if err != nil {
return Value{}, err
} else {
args[i] = res
}
}
fn := val2fn(first)
if err := validateFnArgs(fn, args); err != nil {
err := newError(id.origin, err.Error())
return Value{}, err
}
val, err := fn.fn(args...)
if err != nil {
return val, err
}
return val, err
case formType:
form := val2form(first)
if err := validateFormArgs(form, slice[1:]); err != nil {
err := newError(id.origin, err.Error())
return Value{}, err
}
return form.fn(env, slice...)
default:
err := newError(first.origin, "not a function: %v", slice[0])
return Value{}, err
}
}
func quote(e *Env, vals ...Value) (Value, error) {
return vals[1], nil
}
func fn(e *Env, vals ...Value) (Value, error) {
vals = vals[1:] // Pop off fn keyword
params := vals[0]
body := vals[1]
min := len(val2slice(params))
max := min
fn := newFn(func(args ...Value) (Value, error) {
res, err := eval(body, newFunctionEnv(e, params, args))
if err != nil {
return Value{}, err
}
return res, nil
}, min, max)
return fn, nil
}
func def(e *Env, args ...Value) (Value, error) {
args = args[1:]
id := val2str(args[0])
val, err := eval(args[1], e)
if err != nil {
return Value{}, err
}
// if value is a fn, set the name on its signature
// so it can be displayed in error messages
if val.typ == fnType {
fn := val2fn(val)
fn.sig.name = id
}
e.set(id, val)
return args[0], nil
}
func _if(env *Env, args ...Value) (Value, error) {
var val Value
var err error
args = args[1:]
val, err = eval(args[0], env)
if err != nil {
return Value{}, err
}
if truthy(val) {
val, err = eval(args[1], env)
} else if len(args) > 2 {
val, err = eval(args[2], env)
}
if err != nil {
return Value{}, err
}
return val, nil
}
func truthy(v Value) bool {
if v.typ == nilType {
return false
}
if v.typ == boolType && !val2bool(v) {
return false
}
return true
}
func puts(vals ...Value) (Value, error) {
for _, v := range vals {
fmt.Print(v)
fmt.Print(" ")
}
fmt.Print("\n")
return Value{typ: nilType}, nil
}
func validateFnArgs(fn *Fn, args []Value) error {
if err := validateArgCount(fn.sig, args); err != nil {
return err
}
return nil
}
func validateFormArgs(form *specialForm, args []Value) error {
if err := validateArgCount(form.sig, args); err != nil {
return err
}
if err := validateArgTypes(form.sig, args); err != nil {
return err
}
return nil
}
func validateArgCount(sig signature, args []Value) error {
argc := len(args)
if argc < sig.minArgs {
return argCountError(sig.name, sig.minArgs, argc)
}
if sig.maxArgs != -1 && argc > sig.maxArgs {
return argCountError(sig.name, sig.maxArgs, argc)
}
return nil
}
func validateArgTypes(sig signature, args []Value) error {
for i, typ := range sig.types {
if typ != args[i].typ {
err := fmt.Errorf("argument %d of %s should be %s, got %s",
i+1, sig.name, typ, args[i].typ)
return err
}
}
return nil
}
func argCountError(name string, expected, actual int) error {
arguments := "argument"
if expected != 1 {
arguments += "s"
}
return fmt.Errorf("%s expected %d %s, got %d",
name, expected, arguments, actual)
}