-
Notifications
You must be signed in to change notification settings - Fork 2
/
lisp.go
1790 lines (1614 loc) · 43.9 KB
/
lisp.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
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Nukata Lisp 2.0 in Go 1.11 by SUZUKI Hisao (H27.05.11/H31.2.13)
This is a Lisp interpreter written in Go.
It is intended to implement the same language as Lisp in Dart(*1)
except that it has also two concurrent constructs, future and force.
Numbers are represented by the Number type in *2.
*1: http://github.com/nukata/lisp-in-dart
*2: http://github.com/nukata/goarith
*/
package main
import (
"bufio"
"errors"
"fmt"
"github.com/nukata/goarith"
"io"
"math/big"
"os"
"regexp"
"runtime"
"strconv"
"strings"
"sync"
"unicode/utf8"
)
// Cell represents a cons cell.
// &Cell{car, cdr} works as the "cons" operation.
type Cell struct {
Car interface{}
Cdr interface{}
}
// Nil is a nil of type *Cell and it represents the empty list.
var Nil *Cell = nil
// CdrCell returns cdr of the cell as a *Cell or Nil.
func (j *Cell) CdrCell() *Cell {
if c, ok := j.Cdr.(*Cell); ok {
return c
}
panic(NewEvalError("proper list expected", j))
}
// (a b c).FoldL(x, fn) returns fn(fn(fn(x, a), b), c)
func (j *Cell) FoldL(x interface{},
fn func(interface{}, interface{}) interface{}) interface{} {
for j != Nil {
x = fn(x, j.Car)
j = j.CdrCell()
}
return x
}
// Len returns the length of list j
func (j *Cell) Len() int {
return j.FoldL(0, func(i, e interface{}) interface{} {
return i.(int) + 1
}).(int)
}
// (a b c).MapCar(fn) returns (fn(a) fn(b) fn(c))
func (j *Cell) MapCar(fn func(interface{}) interface{}) interface{} {
if j == Nil {
return Nil
}
a := fn(j.Car)
d := j.Cdr
if cdr, ok := d.(*Cell); ok {
d = cdr.MapCar(fn)
}
if j.Car == a && j.Cdr == d {
return j
}
return &Cell{a, d}
}
// String returns a raw textual representation of j for debugging.
func (j *Cell) String() string {
return fmt.Sprintf("(%v . %v)", j.Car, j.Cdr)
}
//----------------------------------------------------------------------
// Sym represents a symbol (or an expression keyword) in Lisp.
// &Sym{name, false} constructs a symbol which is not interned yet.
type Sym struct {
Name string
IsKeyword bool
}
// NewSym constructs an interned symbol for name.
func NewSym(name string) *Sym {
return NewSym2(name, false)
}
// symbols is a table of interned symbols.
var symbols = make(map[string]*Sym)
// symLock is an exclusive lock for the table.
var symLock sync.RWMutex
// NewSym2 constructs an interned symbol (or an expression keyword
// if isKeyword is true on its first construction) for name.
func NewSym2(name string, isKeyword bool) *Sym {
symLock.Lock()
sym, ok := symbols[name]
if !ok {
sym = &Sym{name, isKeyword}
symbols[name] = sym
}
symLock.Unlock()
return sym
}
// IsInterned returns true if sym is interned.
func (sym *Sym) IsInterned() bool {
symLock.RLock()
s, ok := symbols[sym.Name]
symLock.RUnlock()
return ok && s == sym
}
// String returns a textual representation of sym.
func (sym *Sym) String() string {
return sym.Name
}
// Defined symbols
var BackQuoteSym = NewSym("`")
var CommaAtSym = NewSym(",@")
var CommaSym = NewSym(",")
var DotSym = NewSym(".")
var LeftParenSym = NewSym("(")
var RightParenSym = NewSym(")")
var SingleQuoteSym = NewSym("'")
var AppendSym = NewSym("append")
var ConsSym = NewSym("cons")
var ListSym = NewSym("list")
var RestSym = NewSym("&rest")
var UnquoteSym = NewSym("unquote")
var UnquoteSplicingSym = NewSym("unquote-splicing")
// Expression keywords
var CondSym = NewSym2("cond", true)
var FutureSym = NewSym2("future", true)
var LambdaSym = NewSym2("lambda", true)
var MacroSym = NewSym2("macro", true)
var ProgNSym = NewSym2("progn", true)
var QuasiquoteSym = NewSym2("quasiquote", true)
var QuoteSym = NewSym2("quote", true)
var SetqSym = NewSym2("setq", true)
//----------------------------------------------------------------------
// Func is a common base type of Lisp functions.
type Func struct {
// Carity is a number of arguments, made negative if the func has &rest.
Carity int
}
// hasRest returns true if fn has &rest.
func (fn *Func) hasRest() bool {
return fn.Carity < 0
}
// fixedArgs returns the number of fixed arguments.
func (fn *Func) fixedArgs() int {
if c := fn.Carity; c < 0 {
return -c - 1
} else {
return c
}
}
// MakeFrame makes a call-frame from a list of actual arguments.
// Argument x will be used instead of fn only in error messages.
func (fn *Func) MakeFrame(arg *Cell, x interface{}) []interface{} {
arity := fn.Carity // number of arguments, counting the whole rests as one
if arity < 0 {
arity = -arity
}
frame := make([]interface{}, arity)
n := fn.fixedArgs()
i := 0
for i < n && arg != Nil { // Set the list of fixed arguments.
frame[i] = arg.Car
arg = arg.CdrCell()
i++
}
if i != n || (arg != Nil && !fn.hasRest()) {
panic(NewEvalError("arity not matched", x))
}
if fn.hasRest() {
frame[n] = arg
}
return frame
}
// EvalFrame evaluates each expression of frame with interp in env.
func (fn *Func) EvalFrame(frame []interface{}, interp *Interp, env *Cell) {
n := fn.fixedArgs()
for i := 0; i < n; i++ {
frame[i] = interp.Eval(frame[i], env)
}
if fn.hasRest() {
if j, ok := frame[n].(*Cell); ok {
z := Nil
y := Nil
for j != Nil {
e := interp.Eval(j.Car, env)
x := &Cell{e, Nil}
if z == Nil {
z = x
} else {
y.Cdr = x
}
y = x
j = j.CdrCell()
}
frame[n] = z
}
}
}
//----------------------------------------------------------------------
// Macro represents a compiled macro expression.
type Macro struct {
Func
// body is a list which will be used as the function body.
body *Cell
}
// NewMacro constructs a Macro.
func NewMacro(carity int, body *Cell, env *Cell) interface{} {
return &Macro{Func{carity}, body}
}
// ExpandWith expands the macro with a list of actual arguments.
func (x *Macro) ExpandWith(interp *Interp, arg *Cell) interface{} {
frame := x.MakeFrame(arg, x)
env := &Cell{frame, Nil}
var y interface{} = Nil
for j := x.body; j != Nil; j = j.CdrCell() {
y = interp.Eval(j.Car, env)
}
return y
}
// String returns a textual representation of the macro.
func (x *Macro) String() string {
return fmt.Sprintf("#<macro:%d:%s>", x.Carity, Str(x.body))
}
// Lambda represents a compiled lambda expression (within another function).
type Lambda struct {
Func
// Body is a list which will be used as the function body.
Body *Cell
}
// NewLambda constructs a Lambda.
func NewLambda(carity int, body *Cell, env *Cell) interface{} {
return &Lambda{Func{carity}, body}
}
// String returns a textual representation of the lambda.
func (x *Lambda) String() string {
return fmt.Sprintf("#<lambda:%d:%s>", x.Carity, Str(x.Body))
}
// Closure represents a compiled lambda expression with its own environment.
type Closure struct {
Lambda
// Env is the closure's own environment.
Env *Cell
}
// NewClosure constructs a Closure.
func NewClosure(carity int, body *Cell, env *Cell) interface{} {
return &Closure{Lambda{Func{carity}, body}, env}
}
// MakeEnv makes a new environment from a list of acutual arguments,
// which will be used in evaluation of the body of the closure.
func (x *Closure) MakeEnv(interp *Interp, arg *Cell, interpEnv *Cell) *Cell {
frame := x.MakeFrame(arg, x)
x.EvalFrame(frame, interp, interpEnv)
return &Cell{frame, x.Env} // Prepend the frame to Env of the closure.
}
// String returns a textual representation of the closure.
func (x *Closure) String() string {
return fmt.Sprintf("#<closure:%d:%s:%s>",
x.Carity, Str(x.Env), Str(x.Body))
}
//----------------------------------------------------------------------
// BuiltInFunc represents a built-in function.
type BuiltInFunc struct {
Func
name string
body func([]interface{}) interface{}
}
// NewBuiltInFunc constructs a BuiltInFunc.
func NewBuiltInFunc(name string, carity int,
body func([]interface{}) interface{}) *BuiltInFunc {
return &BuiltInFunc{Func{carity}, name, body}
}
// EvalWith invokes the built-in function with a list of actual arguments.
func (x *BuiltInFunc) EvalWith(interp *Interp, arg *Cell,
interpEnv *Cell) interface{} {
frame := x.MakeFrame(arg, x)
x.EvalFrame(frame, interp, interpEnv)
defer func() {
if err := recover(); err != nil {
if _, ok := err.(*EvalError); ok {
panic(err)
} else {
msg := fmt.Sprintf("%v -- %s", err, x.name)
panic(NewEvalError(msg, frame))
}
}
}()
return x.body(frame)
}
// String returns a textual representation of the BuiltInFunc.
func (x *BuiltInFunc) String() string {
return fmt.Sprintf("#<%s:%d>", x.name, x.Carity)
}
//----------------------------------------------------------------------
// Arg represents a bound variable in a compiled lambda/macro expression.
// It is constructed with &Arg{level, offset, symbol}.
type Arg struct {
// Level is a nesting level of the lexical scope.
// 0 for the innermost scope.
Level int
// Offset is an offset of the variable within the frame of the Level.
// 0 for the first variable within the frame.
Offset int
// Sym is a symbol which represented the variable before compilation.
Symbol *Sym
}
// GetValue gets a value from the location corresponding to the variable x
// within an environment env.
func (x *Arg) GetValue(env *Cell) interface{} {
for i := 0; i < x.Level; i++ {
env = env.Cdr.(*Cell)
}
return (env.Car.([]interface{}))[x.Offset]
}
// SetValue sets a value y to the location corresponding to the variable x
// within an environment env.
func (x *Arg) SetValue(y interface{}, env *Cell) {
for i := 0; i < x.Level; i++ {
env = env.Cdr.(*Cell)
}
(env.Car.([]interface{}))[x.Offset] = y
}
// String returns a textual representation of the Arg.
func (x *Arg) String() string {
return fmt.Sprintf("#%d:%d:%v", x.Level, x.Offset, x.Symbol)
}
//----------------------------------------------------------------------
// EvalError represents an error in evaluation.
type EvalError struct {
Message string
Trace []string
}
// NewEvalError constructs an EvalError.
func NewEvalError(msg string, x interface{}) *EvalError {
return &EvalError{msg + ": " + Str(x), nil}
}
// NewNotVariableError constructs an EvalError which indicates an absence
// of variable.
func NewNotVariableError(x interface{}) *EvalError {
return NewEvalError("variable expected", x)
}
// Error returns a textual representation of the error.
// It is defined in compliance with the error type.
func (err *EvalError) Error() string {
s := "EvalError: " + err.Message
for _, line := range err.Trace {
s += "\n\t" + line
}
return s
}
// EofToken is a token which represents the end of file.
var EofToken error = errors.New("end of file")
//----------------------------------------------------------------------
// Interp represents a core of the interpreter.
type Interp struct {
globals map[*Sym]interface{}
lock sync.RWMutex
}
// Future represents a "promise" for future/force.
type Future struct {
// Chan is a channel which transmits a pair of result and error.
// The pair is represented by Cell.
Chan <-chan Cell
// Result is a pair of the result (in a narrow meaning) and the error.
Result Cell
// Lock is an exclusive lock to receive the result at "force".
Lock sync.Mutex
}
// String returns a textual representation of the Future.
func (fu *Future) String() string {
return fmt.Sprintf("#<future:%v:%s:%v>",
fu.Chan, Str(&fu.Result), &fu.Lock)
}
// GetGlobalVar gets a global value of symbol sym within the interpreter.
func (interp *Interp) GetGlobalVar(sym *Sym) (interface{}, bool) {
interp.lock.RLock()
val, ok := interp.globals[sym]
interp.lock.RUnlock()
return val, ok
}
// SetGlobalVar sets a global value of symbol sym within the interpreter.
func (interp *Interp) SetGlobalVar(sym *Sym, val interface{}) {
interp.lock.Lock()
interp.globals[sym] = val
interp.lock.Unlock()
}
var Number0 = goarith.AsNumber(0)
var Number1 = goarith.AsNumber(1)
// NewInterp constructs an interpreter and sets built-in functions etc. as
// the global values of symbols within the interpreter.
func NewInterp() *Interp {
interp := &Interp{globals: make(map[*Sym]interface{})}
interp.Def("car", 1, func(a []interface{}) interface{} {
if a[0] == Nil {
return Nil
}
return a[0].(*Cell).Car
})
interp.Def("cdr", 1, func(a []interface{}) interface{} {
if a[0] == Nil {
return Nil
}
return a[0].(*Cell).Cdr
})
interp.Def("cons", 2, func(a []interface{}) interface{} {
return &Cell{a[0], a[1]}
})
interp.Def("atom", 1, func(a []interface{}) interface{} {
if j, ok := a[0].(*Cell); ok && j != Nil {
return Nil
}
return true
})
interp.Def("eq", 2, func(a []interface{}) interface{} {
if a[0] == a[1] { // Cells are compared by address.
return true
}
return Nil
})
interp.Def("list", -1, func(a []interface{}) interface{} {
return a[0]
})
interp.Def("rplaca", 2, func(a []interface{}) interface{} {
a[0].(*Cell).Car = a[1]
return a[1]
})
interp.Def("rplacd", 2, func(a []interface{}) interface{} {
a[0].(*Cell).Cdr = a[1]
return a[1]
})
interp.Def("length", 1, func(a []interface{}) interface{} {
switch x := a[0].(type) {
case *Cell:
return goarith.AsNumber(x.Len())
case string: // Each multi-bytes character counts 1.
return goarith.AsNumber(utf8.RuneCountInString(x))
default:
panic(NewEvalError("list or string expected", x))
}
})
interp.Def("stringp", 1, func(a []interface{}) interface{} {
if _, ok := a[0].(string); ok {
return true
}
return Nil
})
interp.Def("numberp", 1, func(a []interface{}) interface{} {
if goarith.AsNumber(a[0]) != nil {
return true
}
return Nil
})
interp.Def("eql", 2, func(a []interface{}) interface{} {
if a[0] == a[1] {
return true
}
if x := goarith.AsNumber(a[0]); x != nil {
if y := goarith.AsNumber(a[1]); y != nil {
if x.Cmp(y) == 0 {
return true
}
}
}
return Nil
})
interp.Def("<", 2, func(a []interface{}) interface{} {
if goarith.AsNumber(a[0]).Cmp(goarith.AsNumber(a[1])) < 0 {
return true
}
return Nil
})
interp.Def("%", 2, func(a []interface{}) interface{} {
_, q := goarith.AsNumber(a[0]).QuoRem(goarith.AsNumber(a[1]))
return q
})
interp.Def("mod", 2, func(a []interface{}) interface{} {
x, y := goarith.AsNumber(a[0]), goarith.AsNumber(a[1])
xs, ys := x.Cmp(Number0), y.Cmp(Number0)
_, q := x.QuoRem(y)
if (xs < 0 && ys > 0) || (xs > 0 && ys < 0) {
return q.Add(y)
}
return q
})
interp.Def("+", -1, func(a []interface{}) interface{} {
return a[0].(*Cell).FoldL(Number0,
func(x, y interface{}) interface{} {
return goarith.AsNumber(x).Add(goarith.AsNumber(y))
})
})
interp.Def("*", -1, func(a []interface{}) interface{} {
return a[0].(*Cell).FoldL(Number1,
func(x, y interface{}) interface{} {
return goarith.AsNumber(x).Mul(goarith.AsNumber(y))
})
})
interp.Def("-", -2, func(a []interface{}) interface{} {
if a[1] == Nil {
return Number0.Sub(goarith.AsNumber(a[0]))
} else {
return a[1].(*Cell).FoldL(goarith.AsNumber(a[0]),
func(x, y interface{}) interface{} {
return goarith.AsNumber(x).Sub(goarith.AsNumber(y))
})
}
})
interp.Def("/", -3, func(a []interface{}) interface{} {
q := goarith.AsNumber(a[0]).RQuo(goarith.AsNumber(a[1]))
return a[2].(*Cell).FoldL(q,
func(x, y interface{}) interface{} {
return goarith.AsNumber(x).RQuo(goarith.AsNumber(y))
})
})
interp.Def("truncate", -2, func(a []interface{}) interface{} {
x, y := goarith.AsNumber(a[0]), a[1].(*Cell)
if y == Nil {
q, _ := x.QuoRem(Number1)
return q
} else if y.Cdr == Nil {
q, _ := x.QuoRem(goarith.AsNumber(y.Car))
return q
} else {
panic("one or two arguments expected")
}
})
interp.Def("prin1", 1, func(a []interface{}) interface{} {
fmt.Print(Str2(a[0], true))
return a[0]
})
interp.Def("princ", 1, func(a []interface{}) interface{} {
fmt.Print(Str2(a[0], false))
return a[0]
})
interp.Def("terpri", 0, func(a []interface{}) interface{} {
fmt.Println()
return true
})
gensymCounterSym := NewSym("*gensym-counter*")
interp.SetGlobalVar(gensymCounterSym, Number1)
interp.Def("gensym", 0, func(a []interface{}) interface{} {
interp.lock.Lock()
defer interp.lock.Unlock()
x := goarith.AsNumber(interp.globals[gensymCounterSym])
interp.globals[gensymCounterSym] = x.Add(Number1)
return &Sym{fmt.Sprintf("G%s", x.String()), false}
})
interp.Def("make-symbol", 1, func(a []interface{}) interface{} {
return &Sym{a[0].(string), false}
})
interp.Def("intern", 1, func(a []interface{}) interface{} {
return NewSym(a[0].(string))
})
interp.Def("symbol-name", 1, func(a []interface{}) interface{} {
return a[0].(*Sym).Name
})
interp.Def("apply", 2, func(a []interface{}) interface{} {
args := a[1].(*Cell).MapCar(QqQuote)
return interp.Eval(&Cell{a[0], args}, Nil)
})
interp.Def("exit", 1, func(a []interface{}) interface{} {
n, exact := goarith.AsNumber(a[0]).Int()
if !exact {
panic("int expected")
}
os.Exit(int(n))
return Nil // *not reached*
})
interp.Def("dump", 0, func(a []interface{}) interface{} {
interp.lock.RLock()
defer interp.lock.RUnlock()
r := Nil
for key := range interp.globals {
r = &Cell{key, r}
}
return r
})
// Wait until the "promise" of Future is delivered.
interp.Def("force", 1, func(a []interface{}) interface{} {
if fu, ok := a[0].(*Future); ok {
fu.Lock.Lock()
defer fu.Lock.Unlock()
if fu.Chan != nil {
fu.Result = <-fu.Chan
fu.Chan = nil
}
if err := fu.Result.Cdr; err != nil {
fu.Result.Cdr = nil
panic(err) // Transmit the error.
}
return fu.Result.Car
} else {
return a[0]
}
})
interp.SetGlobalVar(NewSym("*version*"),
&Cell{
goarith.AsNumber(2.0),
&Cell{
fmt.Sprintf("%s %s/%s",
runtime.Version(), runtime.GOOS, runtime.GOARCH),
&Cell{
"Nukata Lisp",
Nil}}})
// named after Nukata-gun (額田郡) in Tōkai-dō Mikawa-koku (東海道 三河国)
return interp
}
// Def defines a built-in function by giving a name, arity, and body.
func (interp *Interp) Def(name string, carity int,
body func([]interface{}) interface{}) {
sym := NewSym(name)
fnc := NewBuiltInFunc(name, carity, body)
interp.SetGlobalVar(sym, fnc)
}
// Eval evaluates a Lisp expression in a given environment env.
func (interp *Interp) Eval(expression interface{}, env *Cell) interface{} {
defer func() {
if err := recover(); err != nil {
if ex, ok := err.(*EvalError); ok {
if ex.Trace == nil {
ex.Trace = make([]string, 0, 10)
}
if len(ex.Trace) < 10 {
ex.Trace = append(ex.Trace, Str(expression))
}
}
panic(err)
}
}()
for {
switch x := expression.(type) {
case *Arg:
return x.GetValue(env)
case *Sym:
r, ok := interp.GetGlobalVar(x)
if ok {
return r
}
panic(NewEvalError("void variable", x))
case *Cell:
if x == Nil {
return x // an empty list
}
fn := x.Car
arg := x.CdrCell()
sym, ok := fn.(*Sym)
if ok && sym.IsKeyword {
switch sym {
case QuoteSym:
if arg != Nil && arg.Cdr == Nil {
return arg.Car
}
panic(NewEvalError("bad quote", x))
case ProgNSym:
expression = interp.evalProgN(arg, env)
case CondSym:
expression = interp.evalCond(arg, env)
case SetqSym:
return interp.evalSetQ(arg, env)
case LambdaSym:
return interp.compile(arg, env, NewClosure)
case MacroSym:
if env != Nil {
panic(NewEvalError("nested macro", x))
}
return interp.compile(arg, Nil, NewMacro)
case QuasiquoteSym:
if arg != Nil && arg.Cdr == Nil {
expression = QqExpand(arg.Car)
} else {
panic(NewEvalError("bad quasiquote", x))
}
case FutureSym:
ch := make(chan Cell)
go interp.futureTask(arg, env, ch)
return &Future{Chan: ch}
default:
panic(NewEvalError("bad keyword", fn))
}
} else { // Apply fn to arg.
// Expand fn = interp.Eval(fn, env) here on Sym for speed.
if ok {
fn, ok = interp.GetGlobalVar(sym)
if !ok {
panic(NewEvalError("undefined", x.Car))
}
} else {
fn = interp.Eval(fn, env)
}
switch f := fn.(type) {
case *Closure:
env = f.MakeEnv(interp, arg, env)
expression = interp.evalProgN(f.Body, env)
case *Macro:
expression = f.ExpandWith(interp, arg)
case *BuiltInFunc:
return f.EvalWith(interp, arg, env)
default:
panic(NewEvalError("not applicable", fn))
}
}
case *Lambda:
return &Closure{*x, env}
default:
return x // numbers, strings etc.
}
}
}
// SafeEval evaluates a Lisp expression in a given environment env and
// returns the result and nil.
// If an error happens, it returns Nil and the error
func (interp *Interp) SafeEval(expression interface{}, env *Cell) (
result interface{}, err interface{}) {
defer func() {
if e := recover(); e != nil {
result, err = Nil, e
}
}()
return interp.Eval(expression, env), nil
}
// evalProgN evaluates E1, E2, .., E(n-1) and returns the tail expression En.
func (interp *Interp) evalProgN(j *Cell, env *Cell) interface{} {
if j == Nil {
return Nil
}
for {
x := j.Car
j = j.CdrCell()
if j == Nil {
return x // The tail expression will be evaluated at the caller.
}
interp.Eval(x, env)
}
}
// futureTask is a task for goroutine to deliver the "promise" of Future.
// It returns the En value of (future E1 E2 .. En) via the channel and
// closes the channel.
func (interp *Interp) futureTask(j *Cell, env *Cell, ch chan<- Cell) {
defer close(ch)
result, err := interp.safeProgN(j, env)
ch <- Cell{result, err}
}
// safeProgN evaluates E1, E2, .. En and returns the value of En and nil.
// If an error happens, it returns Nil and the error.
func (interp *Interp) safeProgN(j *Cell, env *Cell) (result interface{},
err interface{}) {
defer func() {
if e := recover(); e != nil {
result, err = Nil, e
}
}()
x := interp.evalProgN(j, env)
return interp.Eval(x, env), nil
}
// evalCond evaluates a conditional expression and returns the selection
// unevaluated.
func (interp *Interp) evalCond(j *Cell, env *Cell) interface{} {
for j != Nil {
clause, ok := j.Car.(*Cell)
if ok {
if clause != Nil {
result := interp.Eval(clause.Car, env)
if result != Nil { // If the condition holds...
body := clause.CdrCell()
if body == Nil {
return QqQuote(result)
} else {
return interp.evalProgN(body, env)
}
}
}
} else {
panic(NewEvalError("cond test expected", j.Car))
}
j = j.CdrCell()
}
return Nil // No clause holds.
}
// evalSeqQ evaluates each Ei of (setq .. Vi Ei ..) and assigns it to Vi
// repectively. It returns the value of the last expression En.
func (interp *Interp) evalSetQ(j *Cell, env *Cell) interface{} {
var result interface{} = Nil
for j != Nil {
lval := j.Car
j = j.CdrCell()
if j == Nil {
panic(NewEvalError("right value expected", lval))
}
result = interp.Eval(j.Car, env)
switch v := lval.(type) {
case *Arg:
v.SetValue(result, env)
case *Sym:
if v.IsKeyword {
panic(NewNotVariableError(lval))
}
interp.SetGlobalVar(v, result)
default:
panic(NewNotVariableError(lval))
}
j = j.CdrCell()
}
return result
}
// compile compiles a Lisp list (macro ...) or (lambda ...).
func (interp *Interp) compile(arg *Cell, env *Cell,
factory func(int, *Cell, *Cell) interface{}) interface{} {
if arg == Nil {
panic(NewEvalError("arglist and body expected", arg))
}
table := make(map[*Sym]*Arg)
hasRest := makeArgTable(arg.Car, table)
arity := len(table)
body := arg.CdrCell()
body = scanForArgs(body, table).(*Cell)
body = interp.expandMacros(body, 20).(*Cell) // Expand up to 20 nestings.
body = interp.compileInners(body).(*Cell)
if hasRest {
arity = -arity
}
return factory(arity, body, env)
}
// expandMacros expands macros and quasi-quotes in x up to count nestings.
func (interp *Interp) expandMacros(x interface{}, count int) interface{} {
if count > 0 {
if j, ok := x.(*Cell); ok {
if j == Nil {
return Nil
}
switch k := j.Car; k {
case QuoteSym, LambdaSym, MacroSym:
return j
case QuasiquoteSym:
d := j.CdrCell()
if d != Nil && d.Cdr == Nil {
z := QqExpand(d.Car)
return interp.expandMacros(z, count)
}
panic(NewEvalError("bad quasiquote", j))
default:
if sym, ok := k.(*Sym); ok {
if v, ok := interp.GetGlobalVar(sym); ok {
k = v
}
}
if f, ok := k.(*Macro); ok {
d := j.CdrCell()
z := f.ExpandWith(interp, d)
return interp.expandMacros(z, count-1)
} else {
return j.MapCar(func(y interface{}) interface{} {
return interp.expandMacros(y, count)
})
}
}
}
}
return x
}
// compileInners replaces inner lambda-expressions with Lambda instances.
func (interp *Interp) compileInners(x interface{}) interface{} {
if j, ok := x.(*Cell); ok {
if j == Nil {
return Nil
}
switch k := j.Car; k {
case QuoteSym:
return j
case LambdaSym:
d := j.CdrCell()
return interp.compile(d, Nil, NewLambda)
case MacroSym:
panic(NewEvalError("nested macro", j))
default:
return j.MapCar(func(y interface{}) interface{} {
return interp.compileInners(y)
})
}
}
return x
}
//----------------------------------------------------------------------
// makeArgTable makes an argument-table. It returns true if x has &rest.
func makeArgTable(x interface{}, table map[*Sym]*Arg) bool {