-
Notifications
You must be signed in to change notification settings - Fork 0
/
eval.go
714 lines (649 loc) · 13.5 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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
package main
import (
"errors"
"fmt"
"io"
"math"
"os"
"reflect"
"strconv"
"strings"
"github.com/rread/rsi/lexer"
"github.com/rread/rsi/log"
)
// Data is a fundamental type (symbol, boolean, string, number, pair, func)
type Data interface {
// temporarily removed this as error handling is integrated into Data
// String() string
}
type Symbol string
type Boolean bool
type Number float64
type String string
type InternalFunc func(Data) (Data, error)
func (sym Symbol) String() string {
return string(sym)
}
func (num Number) String() string {
return fmt.Sprintf("%v", float64(num))
}
func (fun InternalFunc) String() string {
return fmt.Sprintf("native-func '%v'", ((func(Data) (Data, error))(fun)))
}
func (b Boolean) String() string {
if b {
return "#t"
} else {
return "#f"
}
}
func (s String) String() string {
return fmt.Sprintf(`"%s"`, string(s))
}
type Null byte
var Empty Null = 0xfe // Null is nothing so it can be anything
func (n Null) String() string {
return "()"
}
func nullp(d Data) Boolean {
if v, ok := d.(Null); ok {
return Boolean(v == Empty)
}
return False
}
type Tokenizer interface {
NextItem() *lexer.TokenItem
}
var (
T = Boolean(true)
False = Boolean(false)
)
var ErrorEOF = errors.New("End of File")
func read(l Tokenizer) (Data, error) {
t := l.NextItem()
if t == nil {
return nil, ErrorEOF
}
//log.Debugf("scan: %v\n", t)
switch t.Token {
case lexer.LEFT_PAREN:
return readList(l)
case lexer.RIGHT_PAREN:
return nil, nil
case lexer.SYMBOL:
return internSymbol(t.Lit), nil
case lexer.QUOTE:
return readQuote(l)
case lexer.NUMBER:
v, err := strconv.ParseFloat(t.Lit, 64)
if err != nil {
log.Fatal("Number fail:", err)
}
return Number(v), nil
case lexer.EOF:
return nil, ErrorEOF
case lexer.STRING:
return StringWithValue(t.Lit), nil
case lexer.TRUE:
return T, nil
case lexer.FALSE:
return False, nil
case lexer.DOT:
return _dot, nil
case lexer.ILLEGAL:
return nil, errors.New(t.Lit)
case lexer.COMMENT:
return read(l)
}
return nil, errors.New("Malformed input")
}
func readQuote(lex Tokenizer) (Data, error) {
c, err := read(lex)
if err != nil {
return nil, fmt.Errorf("Failed to complete list: %v\n", err)
}
return cons(internSymbol("quote"), cons(c, Empty)), nil
}
func readList2(lex Tokenizer) (Data, error) {
c, err := read(lex)
if err != nil {
return nil, fmt.Errorf("Failed to complete list: %v\n", err)
}
if c == nil {
return Empty, nil
}
// handle (a b . c) but (a b . c d) is an error.
if c == _dot {
last, err := read(lex)
if err != nil {
return nil, err
}
end, _ := read(lex)
if end != nil {
return nil, fmt.Errorf("More than one object follows .")
}
log.Printf("last %v", last)
return last, nil
}
rest, err := readList2(lex)
if err != nil {
return nil, err
}
return cons(c, rest), nil
}
func readList(lex Tokenizer) (Data, error) {
li, err := readList2(lex)
if err != nil {
return nil, err
}
return li, nil
}
var (
_quote = internSymbol("quote")
_define = internSymbol("define")
_dot = internSymbol("::dot::")
_set = internSymbol("set!")
_if = internSymbol("if")
_begin = internSymbol("begin")
_quit = internSymbol("quit")
_lambda = internSymbol("lambda")
_let = internSymbol("let")
_vars = internSymbol(":vars")
_ok = internSymbol("ok")
)
func eval(expr Data, env *Env) (Data, error) {
log.Printf("eval: %T: %v\n", expr, expr)
switch e := expr.(type) {
case Boolean:
return e, nil
case Symbol:
return env.FindVar(e)
case Number:
return e, nil
case String:
return e, nil
case Null:
return e, nil
case *Pair:
c, _ := getSymbol(car(e))
/* non-Symbols fall through to default */
switch c {
case _quote:
return cadr(e), nil
case _define:
return evalDefine(e, env)
case _set:
return evalSet(e, env)
case _if:
return evalIf(e, env)
case _let:
return evalLet(e, env)
case _begin:
return evalSequential(cdr(e), env)
case _quit:
os.Exit(0)
case _lambda:
params, err := getList(cadr(e))
if err != nil {
return nil, fmt.Errorf("bad params: %v", err)
}
body, err := getList(cddr(e))
if err != nil {
return nil, fmt.Errorf("bad body: %v", err)
}
return evalLambda(params, body, env)
case _vars:
for k, v := range env.vars {
log.Printf("%v: %v\n", k, v)
}
return nil, nil
default:
log.Printf("procedure call %v", e)
proc, err := eval(car(e), env)
if err != nil {
return nil, err
}
args, err := evalArgs(cdr(e), env)
if err != nil {
return nil, err
}
switch f := proc.(type) {
case InternalFunc:
return f(args)
case *Lambda:
var err error
env, err = ExtendEnv(f.params, args, f.envt)
if err != nil {
return nil, err
}
return evalSequential(f.body, env)
default:
return nil, fmt.Errorf("apply to a non function: %#v %v", proc, args)
}
}
case nil:
log.Fatal("parsed a nil?")
return nil, nil
}
return nil, fmt.Errorf("Unparsable expression: %v", expr)
}
func evalDefine(e *Pair, env *Env) (Data, error) {
expr, err := getPair(cdr(e))
if err != nil {
return nil, err
}
err = definition(expr, env)
if err != nil {
return nil, err
}
// Return value of define is undefined
return _ok, nil
}
func evalSet(e *Pair, env *Env) (Data, error) {
d, err := getSymbol(cadr(e))
if err != nil {
return nil, err
}
val, err := eval(caddr(e), env)
if err != nil {
return nil, err
}
env.Find(d).Bind(d, val)
return _ok, nil
}
func evalIf(e *Pair, env *Env) (Data, error) {
test, _ := eval(cadr(e), env)
if isTrue(test) {
return eval(caddr(e), env)
} else if listLen(e) > 3 {
return eval(cadddr(e), env)
}
return Empty, nil
}
func evalLet(e *Pair, env *Env) (Data, error) {
letExpr, err := let(cdr(e), env)
if err != nil {
return nil, err
}
return letExpr, nil
}
func evalSequential(e Data, env *Env) (Data, error) {
var v Data
e, err := getPair(e)
if err != nil {
return nil, err
}
for !nullp(e) {
log.Printf("begin: %v", e)
v, err = eval(car(e), env)
if err != nil {
return nil, err
}
if nullp(cdr(e)) {
break
}
e, err = listNext(e)
if err != nil {
return nil, err
}
}
return v, nil
}
func definition(defn *Pair, env *Env) error {
var value Data
var name Symbol
var err error
switch e := car(defn).(type) {
// (define var value)
case Symbol:
name = e
value, err = eval(cadr(defn), env)
if err != nil {
return err
}
// (define (proc a b) (body))
case *Pair:
name, err = getSymbol(car(e))
if err != nil {
return err
}
params := cdr(e)
body, err := getPair(cdr(defn))
if err != nil {
return err
}
value, err = evalLambda(params, body, env)
if err != nil {
return err
}
}
env.Bind(name, value)
return nil
}
type Lambda struct {
index int
params []Symbol
body Data
envt *Env
}
var lambdaCounter int = 0
func NewLambda() *Lambda {
l := &Lambda{
index: lambdaCounter,
}
lambdaCounter++
return l
}
func (l *Lambda) String() string {
return fmt.Sprintf("#<compound-procedure: #%d>", l.index)
}
func evalLambda(params Data, body Data, env *Env) (Data, error) {
l := NewLambda()
for params != Empty {
var err error
p, err := getPair(params)
if err != nil {
return nil, fmt.Errorf("not a pair here %v", params)
}
switch arg := car(p).(type) {
case Symbol:
l.params = append(l.params, arg)
case *Pair:
return nil, fmt.Errorf("combo param not supported: %v", arg)
}
params = cdr(p)
}
l.body = body
l.envt = NewEnv(env)
return l, nil
}
func evalArgs(next Data, env *Env) (Data, error) {
if nullp(next) {
return Empty, nil
}
e, err := getPair(next)
if err != nil {
return nil, err
}
val, err := eval(car(e), env)
if err != nil {
return nil, err
}
if nullp(cdr(e)) {
return cons(val, Empty), nil
} else {
rest, err := evalArgs(cdr(e), env)
if err != nil {
return nil, err
}
return cons(val, rest), nil
}
}
func getError(d Data) error {
v, ok := d.(error)
if ok {
return v
}
return nil
}
func internalMap(f func(Data) Data, d Data) Data {
if nullp(d) {
return Empty
}
first := car(d)
if getError(first) != nil {
return first
}
e := f(first)
if err := getError(e); err != nil {
return err
}
rest := cdr(d)
if err := getError(rest); err != nil {
return err
}
return cons(e, internalMap(f, rest))
}
func let(expr Data, env *Env) (Data, error) {
arguments := internalMap(car, car(expr))
if err := getError(arguments); err != nil {
return nil, err
}
values := internalMap(cadr, car(expr))
if err := getError(values); err != nil {
return nil, err
}
body := cdr(expr)
if err := getError(body); err != nil {
return nil, err
}
result := cons(cons(_lambda, cons(arguments, body)), values)
log.Printf("lambda %v", result)
return eval(result, env)
}
func replReader(in io.Reader, env *Env) (Data, error) {
// l := NewScanner(in)
buf := make([]byte, 1024)
n, _ := in.Read(buf)
l := lexer.New("lispy", string(buf[:n]))
var result Data
for {
var err error
expr, err := read(l)
//log.Println(expr, err)
if err != nil {
if err == ErrorEOF {
return result, nil
}
return result, err
}
result, err = eval(expr, env)
if err != nil {
return result, err
}
}
}
func repl(in string, env *Env) (Data, error) {
return replReader(strings.NewReader(in), env)
}
func ApplyNumeric(f func(Number, Number) Number) InternalFunc {
return func(d Data) (Data, error) {
if nullp(d) {
return 0, nil
}
a, err := getPair(d)
if err != nil {
return nil, err
}
v, ok := car(a).(Number)
if !ok {
return nil, fmt.Errorf("Not a number: %v", car(a))
}
for {
var err error
if nullp(cdr(a)) {
break
}
a, err = listNext(a)
if err != nil {
return nil, err
}
if a == nil {
break
}
i, ok := car(a).(Number)
if !ok {
return nil, fmt.Errorf("Not a number: %v", car(a))
}
v = f(v, i)
}
return v, nil
}
}
func ApplyNumericBool(f func(Number, Number) Boolean) InternalFunc {
return func(d Data) (Data, error) {
var ret Boolean
if nullp(d) {
return 0, nil
}
a, err := getPair(d)
if err != nil {
return nil, err
}
v, ok := car(a).(Number)
if !ok {
return nil, fmt.Errorf("Not a number: %v", car(a))
}
for {
var err error
if nullp(cdr(a)) {
break
}
a, err = listNext(a)
if err != nil {
return nil, err
}
if a == nil {
break
}
i, ok := car(a).(Number)
if !ok {
return nil, fmt.Errorf("Not a number: %v", car(a))
}
ret = f(v, i)
if !ret {
return Boolean(ret), nil
}
v = i
}
return Boolean(ret), nil
}
}
func Apply1(f func(Data) (Data, error)) InternalFunc {
return func(args Data) (Data, error) {
if listLen(args) != 1 {
return nil, fmt.Errorf("Expected 1 arguments, received %d", listLen(args))
}
return f(car(args))
}
}
func Apply2(f func(Data, Data) (Data, error)) InternalFunc {
return func(args Data) (Data, error) {
if listLen(args) != 2 {
return nil, fmt.Errorf("Expected 2 arguments, received %d", listLen(args))
}
a, err := getPair(args)
if err != nil {
return nil, err
}
return f(car(a), cadr(a))
}
}
func isTrue(i Data) Boolean {
log.Printf("isTrue %T %v", i, i)
if b, ok := i.(Boolean); ok {
return b
}
if _, ok := i.(Symbol); ok {
return true
}
if n, ok := i.(Number); ok {
return !(n == 0)
}
if _, ok := i.(*Pair); ok {
return true
}
if _, ok := i.(Null); ok {
return true
}
if _, ok := i.(String); ok {
return true
}
return false
}
func EmptyEnv() *Env {
return NewEnv(nil)
}
func DefaultEnv() *Env {
env := EmptyEnv()
env.BindName("*", ApplyNumeric(func(x, y Number) Number {
return x * y
}))
env.BindName("-", ApplyNumeric(func(x, y Number) Number {
return x - y
}))
env.BindName("/", ApplyNumeric(func(x, y Number) Number {
return x / y
}))
env.BindName("+", ApplyNumeric(func(x, y Number) Number {
return x + y
}))
env.BindName("<", ApplyNumericBool(func(x, y Number) Boolean {
return x < y
}))
env.BindName("<=", ApplyNumericBool(func(x, y Number) Boolean {
return x <= y
}))
env.BindName(">", ApplyNumericBool(func(x, y Number) Boolean {
return x > y
}))
env.BindName(">=", ApplyNumericBool(func(x, y Number) Boolean {
return x >= y
}))
env.BindName("=", ApplyNumericBool(func(x, y Number) Boolean {
return x == y
}))
env.BindName("number?", InternalFunc(func(args Data) (Data, error) {
if listLen(args) > 1 {
return nil, fmt.Errorf("Too many arguments for number?: %v", args)
}
a, err := getPair(args)
if err != nil {
return nil, err
}
if _, ok := car(a).(Number); ok {
return T, nil
}
return False, nil
}))
env.BindName("equal?", InternalFunc(func(args Data) (Data, error) {
if listLen(args) != 2 {
return nil, fmt.Errorf("wrong number of arguments given to equal?")
}
a, err := getPair(args)
if err != nil {
return nil, err
}
return Boolean(reflect.DeepEqual(car(a), cadr(a))), nil
}))
env.BindName("pi", Number(math.Pi))
env.BindName("cons", Apply2(_cons))
env.BindName("car", Apply1(_car))
env.BindName("cdr", Apply1(_cdr))
env.BindName("null?", Apply1(_nullp))
env.BindName("pair?", Apply1(_pairp))
return env
}
func _cons(a Data, b Data) (Data, error) {
return cons(a, b), nil
}
func _car(a Data) (Data, error) {
p, err := getPair(a)
if err != nil {
return nil, fmt.Errorf("car received: %v", err)
}
return car(p), nil
}
func _cdr(a Data) (Data, error) {
p, err := getPair(a)
if err != nil {
return nil, fmt.Errorf("cdr received: %v", err)
}
return cdr(p), nil
}
func _nullp(a Data) (Data, error) {
return nullp(a), nil
}
func _pairp(a Data) (Data, error) {
return pairp(a), nil
}