-
Notifications
You must be signed in to change notification settings - Fork 12
/
lisp.dart
executable file
·1447 lines (1294 loc) · 40.7 KB
/
lisp.dart
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
#!/usr/bin/env dart
// Nukata Lisp 2.00.0 in Dart 2.5 (H27.03.16/R01.11.02) by SUZUKI Hisao
import "dart:async";
import "dart:convert";
import "dart:io";
const intBits = 63; // 53 for dart2js
/// Converts [a] into an int if possible.
normalize(BigInt a) => (a.bitLength <= intBits) ? a.toInt() : a;
/// Is [a] a number?
bool isNumber(a) => a is num || a is BigInt;
/// Calculates [a] + [b].
add(a, b) {
if (a is int) {
if (b is int) {
if (a.bitLength < intBits && b.bitLength < intBits) {
return a + b;
} else {
return normalize(BigInt.from(a) + BigInt.from(b));
}
} else if (b is double) {
return a + b;
} else if (b is BigInt) {
return normalize(BigInt.from(a) + b);
}
} else if (a is double) {
if (b is num) {
return a + b;
} else if (b is BigInt) {
return a + b.toDouble();
}
} else if (a is BigInt) {
if (b is int) {
return normalize(a + BigInt.from(b));
} else if (b is double) {
return a.toDouble() + b;
} else if (b is BigInt) {
return normalize(a + b);
}
}
throw ArgumentError("$a, $b");
}
/// Calculates [a] - [b].
subtract(a, b) {
if (a is int) {
if (b is int) {
if (a.bitLength < intBits && b.bitLength < intBits) {
return a - b;
} else {
return normalize(BigInt.from(a) - BigInt.from(b));
}
} else if (b is double) {
return a - b;
} else if (b is BigInt) {
return normalize(BigInt.from(a) - b);
}
} else if (a is double) {
if (b is num) {
return a - b;
} else if (b is BigInt) {
return a - b.toDouble();
}
} else if (a is BigInt) {
if (b is int) {
return normalize(a - BigInt.from(b));
} else if (b is double) {
return a.toDouble() - b;
} else if (b is BigInt) {
return normalize(a - b);
}
}
throw ArgumentError("$a, $b");
}
/// Compares [a] and [b].
/// Returns -1, 0 or 1 as [a] is less than, equal to, or greater than [b].
num compare(a, b) {
if (a is int) {
if (b is int) {
if (a.bitLength < intBits && b.bitLength < intBits) {
return (a - b).sign;
} else {
return (BigInt.from(a) - BigInt.from(b)).sign;
}
} else if (b is double) {
return (a - b).sign;
} else if (b is BigInt) {
return (BigInt.from(a) - b).sign;
}
} else if (a is double) {
if (b is num) {
return (a - b).sign;
} else if (b is BigInt) {
return (a - b.toDouble()).sign;
}
} else if (a is BigInt) {
if (b is int) {
return (a - BigInt.from(b)).sign;
} else if (b is double) {
return (a.toDouble() - b).sign;
} else if (b is BigInt) {
return (a - b).sign;
}
}
throw ArgumentError("$a, $b");
}
/// Calculates [a] * [b].
multiply(a, b) {
if (a is int) {
if (b is int) {
if (a.bitLength + b.bitLength < intBits) {
return a * b;
} else {
return normalize(BigInt.from(a) * BigInt.from(b));
}
} else if (b is double) {
return a * b;
} else if (b is BigInt) {
return BigInt.from(a) * b;
}
} else if (a is double) {
if (b is num) {
return a * b;
} else if (b is BigInt) {
return a * b.toDouble();
}
} else if (a is BigInt) {
if (b is int) {
return a * BigInt.from(b);
} else if (b is double) {
return a.toDouble() * b;
} else if (b is BigInt) {
return a * b;
}
}
throw ArgumentError("$a, $b");
}
/// Calculates [a] / [b] (rounded quotient).
double divide(a, b) {
if (a is int) {
if (b is num) {
return a / b;
} else if (b is BigInt) {
return BigInt.from(a) / b;
}
} else if (a is double) {
if (b is num) {
return a / b;
} else if (b is BigInt) {
return a / b.toDouble();
}
} else if (a is BigInt) {
if (b is int) {
return a / BigInt.from(b);
} else if (b is double) {
return a.toDouble() / b;
} else if (b is BigInt) {
return a / b;
}
}
throw ArgumentError("$a, $b");
}
/// Calculates the quotient of [a] and [b].
quotient(a, b) {
if (a is int) {
if (b is num) {
return a ~/ b;
} else if (b is BigInt) {
return normalize(BigInt.from(a) ~/ b);
}
} else if (a is double) {
if (b is num) {
return a ~/ b;
} else if (b is BigInt) {
return a ~/ b.toDouble();
}
} else if (a is BigInt) {
if (b is int) {
return normalize(a ~/ BigInt.from(b));
} else if (b is double) {
return a.toDouble() ~/ b;
} else if (b is BigInt) {
return normalize(a ~/ b);
}
}
throw ArgumentError("$a, $b");
}
/// Calculates the remainder of the quotient of [a] and [b].
remainder(a, b) {
if (a is int) {
if (b is num) {
return a.remainder(b);
} else if (b is BigInt) {
return normalize(BigInt.from(a).remainder(b));
}
} else if (a is double) {
if (b is num) {
return a.remainder(b);
} else if (b is BigInt) {
return a.remainder(b.toDouble());
}
} else if (a is BigInt) {
if (b is int) {
return normalize(a.remainder(BigInt.from(b)));
} else if (b is double) {
return a.toDouble().remainder(b);
} else if (b is BigInt) {
return normalize(a.remainder(b));
}
}
throw ArgumentError("$a, $b");
}
/// Tries to parse a string as an int, a BigInt or a double.
/// Returns null if [s] was not parsed successfully.
tryParse(String s) {
var r = BigInt.tryParse(s);
return (r == null) ? double.tryParse(s) : normalize(r);
}
//----------------------------------------------------------------------
/// Cons cell
class Cell {
var car;
var cdr;
Cell(this.car, this.cdr);
@override String toString() => "($car . $cdr)";
/// Length as a list
int get length => foldl(0, this, (i, e) => i + 1);
}
/// mapcar((a b c), fn) => (fn(a) fn(b) fn(c))
Cell mapcar(Cell j, fn(x)) {
if (j == null)
return null;
var a = fn(j.car);
var d = j.cdr;
if (d is Cell)
d = mapcar(d, fn);
if (identical(j.car, a) && identical(j.cdr, d))
return j;
return Cell(a, d);
}
/// foldl(x, (a b c), fn) => fn(fn(fn(x, a), b), c)
foldl(x, Cell j, fn(y, z)) {
while (j != null) {
x = fn(x, j.car);
j = j.cdr;
}
return x;
}
/// Lisp symbol
class Sym {
final String name;
/// Constructs a symbol that is not interned.
Sym.internal(this.name);
@override String toString() => name;
@override int get hashCode => name.hashCode; // Key to Speed for Dart
/// The table of interned symbols
static final Map<String, Sym> table = {};
/// Constructs an interned symbol.
/// Constructs a [Keyword] if [isKeyword] holds.
factory Sym(String name, [bool isKeyword=false]) {
var result = table[name];
assert(result == null || ! isKeyword);
if (result == null) {
result = isKeyword ? new Keyword.internal(name) : new Sym.internal(name);
table[name] = result;
}
return result;
}
/// Is it interned?
bool get isInterned => identical(this, table[name]);
}
/// Expression keyword
class Keyword extends Sym {
Keyword.internal(String name): super.internal(name);
factory Keyword(String name) => Sym(name, true);
}
final Sym backQuoteSym = Sym("`");
final Sym commaAtSym = Sym(",@");
final Sym commaSym = Sym(",");
final Sym dotSym = Sym(".");
final Sym leftParenSym = Sym("(");
final Sym rightParenSym = Sym(")");
final Sym singleQuoteSym = Sym("'");
final Sym appendSym = Sym("append");
final Sym consSym = Sym("cons");
final Sym listSym = Sym("list");
final Sym restSym = Sym("&rest");
final Sym unquoteSym = Sym("unquote");
final Sym unquoteSplicingSym = Sym("unquote-splicing");
//----------------------------------------------------------------------
/// Common base class of Lisp functions
abstract class Func {
/// Number of arguments, made negative if the function has &rest
final int carity;
int get arity => (carity < 0) ? -carity : carity;
bool get hasRest => (carity < 0);
int get fixedArgs => (carity < 0) ? -carity - 1 : carity; // # of fixed args.
Func(this.carity);
/// Makes a frame for local variables from a list of actual arguments.
List makeFrame(Cell arg) {
List frame = List(arity);
int n = fixedArgs;
int i;
for (i = 0; i < n && arg != null; i++) { // Sets the list of fixed args.
frame[i] = arg.car;
arg = cdrCell(arg);
}
if (i != n || (arg != null && !hasRest))
throw EvalException("arity not matched", this);
if (hasRest)
frame[n] = arg;
return frame;
}
/// Evaluates each expression in a frame.
void evalFrame(List frame, Interp interp, Cell env) {
int n = fixedArgs;
for (int i = 0; i < n; i++)
frame[i] = interp.eval(frame[i], env);
if (hasRest && frame[n] is Cell) {
Cell z = null;
Cell y = null;
for (Cell j = frame[n]; j != null; j = cdrCell(j)) {
var e = interp.eval(j.car, env);
Cell x = Cell(e, null);
if (z == null)
z = x;
else
y.cdr = x;
y = x;
}
frame[n] = z;
}
}
}
/// Common base class of functions which are defined with Lisp expressions
abstract class DefinedFunc extends Func {
/// Lisp list as the function body
final Cell body;
DefinedFunc(int carity, this.body): super(carity);
}
/// Common function type which represents any factory method of DefinedFunc
typedef DefinedFunc FuncFactory(int cariy, Cell body, Cell env);
/// Compiled macro expression
class Macro extends DefinedFunc {
Macro(int carity, Cell body): super(carity, body);
@override String toString() => "#<macro:$carity:${str(body)}>";
/// Expands the macro with a list of actual arguments.
expandWith(Interp interp, Cell arg) {
List frame = makeFrame(arg);
Cell env = Cell(frame, null);
var x = null;
for (Cell j = body; j != null; j = cdrCell(j))
x = interp.eval(j.car, env);
return x;
}
static DefinedFunc make(int carity, Cell body, Cell env) {
assert(env == null);
return Macro(carity, body);
}
}
/// Compiled lambda expression (Within another function)
class Lambda extends DefinedFunc {
Lambda(int carity, Cell body): super(carity, body);
@override String toString() => "#<lambda:$carity:${str(body)}>";
static DefinedFunc make(int carity, Cell body, Cell env) {
assert(env == null);
return Lambda(carity, body);
}
}
/// Compiled lambda expresssion (Closure with environment)
class Closure extends DefinedFunc {
/// The environment of the closure
final Cell env;
Closure(int carity, Cell body, this.env): super(carity, body);
Closure.from(Lambda x, Cell env): this(x.carity, x.body, env);
@override String toString() => "#<closure:$carity:${str(env)}:${str(body)}>";
/// Makes an environment to evaluate the body from a list of actual args.
Cell makeEnv(Interp interp, Cell arg, Cell interpEnv) {
List frame = makeFrame(arg);
evalFrame(frame, interp, interpEnv);
return Cell(frame, env); // Prepends the frame to the closure's env.
}
static DefinedFunc make(int carity, Cell body, Cell env) =>
Closure(carity, body, env);
}
/// Function type which represents any built-in function body
typedef BuiltInFuncBody(List frame);
/// Built-in function
class BuiltInFunc extends Func {
final String name;
final BuiltInFuncBody body;
BuiltInFunc(this.name, int carity, this.body): super(carity);
@override String toString() => "#<$name:$carity>";
/// Invokes the built-in function with a list of actual arguments.
evalWith(Interp interp, Cell arg, Cell interpEnv) {
List frame = makeFrame(arg);
evalFrame(frame, interp, interpEnv);
try {
return body(frame);
} on EvalException catch (ex) {
throw ex;
} catch (ex) {
throw EvalException("$ex -- $name", frame);
}
}
}
/// Bound variable in a compiled lambda/macro expression
class Arg {
final int level;
final int offset;
final Sym symbol;
Arg(this.level, this.offset, this.symbol);
@override String toString() => "#$level:$offset:$symbol";
/// Sets a value [x] to the location corresponding to the variable in [env].
void setValue(x, Cell env) {
for (int i = 0; i < level; i++)
env = env.cdr;
env.car[offset] = x;
}
/// Gets a value from the location corresponding to the variable in [env].
getValue(Cell env) {
for (int i = 0; i < level; i++)
env = env.cdr;
return env.car[offset];
}
}
/// Exception in evaluation
class EvalException implements Exception {
final String message;
final List<String> trace = [];
EvalException(String msg, Object x, [bool quoteString=true])
: message = msg + ": " + str(x, quoteString);
@override String toString() {
var s = "EvalException: $message";
for (String line in trace)
s += "\n\t$line";
return s;
}
}
/// Exception which indicates an absence of a variable
class NotVariableException extends EvalException {
NotVariableException(x): super("variable expected", x);
}
//----------------------------------------------------------------------
/// Core of the interpreter
class Interp {
/// Table of the global values of symbols
final Map<Sym, Object> globals = {};
/// Standard output of the interpreter
StringSink cout = stdout;
/// Sets built-in functions etc. as the global values of symbols.
Interp() {
def("car", 1, (List a) => (a[0] as Cell)?.car);
def("cdr", 1, (List a) => (a[0] as Cell)?.cdr);
def("cons", 2, (List a) => Cell(a[0], a[1]));
def("atom", 1, (List a) => (a[0] is Cell) ? null : true);
def("eq", 2, (List a) => identical(a[0], a[1]) ? true : null);
def("list", -1, (List a) => a[0]);
def("rplaca", 2, (List a) { a[0].car = a[1]; return a[1]; });
def("rplacd", 2, (List a) { a[0].cdr = a[1]; return a[1]; });
def("length", 1, (List a) => (a[0] == null) ? 0 : a[0].length);
def("stringp", 1, (List a) => (a[0] is String) ? true : null);
def("numberp", 1, (List a) => isNumber(a[0]) ? true : null);
def("eql", 2, (List a) {
var x = a[0];
var y = a[1];
return (x == y) ? true :
(isNumber(x) && isNumber(y) && compare(x, y) == 0) ? true : null;
});
def("<", 2, (List a) => (compare(a[0], a[1]) < 0) ? true : null);
def("%", 2, (List a) => remainder(a[0], a[1]));
def("mod", 2, (List a) {
var x = a[0];
var y = a[1];
var q = remainder(x, y);
return (compare(multiply(x, y), 0) < 0) ? add(q, y) : q;
});
def("+", -1, (List a) => foldl(0, a[0], (i, j) => add(i, j)));
def("*", -1, (List a) => foldl(1, a[0], (i, j) => multiply(i, j)));
def("-", -2, (List a) {
var x = a[0];
Cell y = a[1];
return (y == null) ? -x : foldl(x, y, (i, j) => subtract(i, j));
});
def("/", -3, (List a) =>
foldl(divide(a[0], a[1]), a[2], (i, j) => divide(i, j)));
def("truncate", -2, (List a) {
var x = a[0];
Cell y = a[1];
return (y == null) ? quotient(x, 1) :
(y.cdr == null) ? quotient(x, y.car) :
throw "one or two arguments expected";
});
def("prin1", 1, (List a) { cout.write(str(a[0], true)); return a[0]; });
def("princ", 1, (List a) { cout.write(str(a[0], false)); return a[0]; });
def("terpri", 0, (List a) { cout.writeln(); return true; });
var gensymCounterSym = Sym("*gensym-counter*");
globals[gensymCounterSym] = 1;
def("gensym", 0, (List a) {
int i = globals[gensymCounterSym];
globals[gensymCounterSym] = i + 1;
return new Sym.internal("G$i");
});
def("make-symbol", 1, (List a) => new Sym.internal(a[0]));
def("intern", 1, (List a) => Sym(a[0]));
def("symbol-name", 1, (List a) => (a[0] as Sym).name);
def("apply", 2, (List a) => eval(Cell(a[0], mapcar(a[1], qqQuote)), null));
def("exit", 1, (List a) => exit(a[0]));
def("dump", 0, (List a) => globals.keys.fold(null, (x, y) => Cell(y, x)));
globals[Sym("*version*")] =
Cell(2.000, Cell("Dart", Cell("Nukata Lisp", null)));
// named after Tōkai-dō Mikawa-koku Nukata-gun (東海道 三河国 額田郡)
}
/// Defines a built-in function by giving a name, an arity, and a body.
void def(String name, int carity, BuiltInFuncBody body) {
globals[Sym(name)] = BuiltInFunc(name, carity, body);
}
/// Evaluates a Lisp expression in an environment.
eval(x, Cell env) {
try {
for (;;) {
if (x is Arg) {
return x.getValue(env);
} else if (x is Sym) {
if (globals.containsKey(x))
return globals[x];
throw EvalException("void variable", x);
} else if (x is Cell) {
var fn = x.car;
Cell arg = cdrCell(x);
if (fn is Keyword) {
if (fn == quoteSym) {
if (arg != null && arg.cdr == null)
return arg.car;
throw EvalException("bad quote", x);
} else if (fn == prognSym) {
x = _evalProgN(arg, env);
} else if (fn == condSym) {
x = _evalCond(arg, env);
} else if (fn == setqSym) {
return _evalSetQ(arg, env);
} else if (fn == lambdaSym) {
return _compile(arg, env, Closure.make);
} else if (fn == macroSym) {
if (env != null)
throw EvalException("nested macro", x);
return _compile(arg, null, Macro.make);
} else if (fn == quasiquoteSym) {
if (arg != null && arg.cdr == null)
x = qqExpand(arg.car);
else
throw EvalException("bad quasiquote", x);
} else {
throw EvalException("bad keyword", fn);
}
} else { // Application of a function
// Expands fn = eval(fn, env) here on Sym for speed.
if (fn is Sym) {
fn = globals[fn];
if (fn == null)
throw EvalException("undefined", x.car);
} else {
fn = eval(fn, env);
}
if (fn is Closure) {
env = fn.makeEnv(this, arg, env);
x = _evalProgN(fn.body, env);
} else if (fn is Macro) {
x = fn.expandWith(this, arg);
} else if (fn is BuiltInFunc) {
return fn.evalWith(this, arg, env);
} else {
throw EvalException("not applicable", fn);
}
}
} else if (x is Lambda) {
return new Closure.from(x, env);
} else {
return x; // numbers, strings, null etc.
}
}
} on EvalException catch (ex) {
if (ex.trace.length < 10)
ex.trace.add(str(x));
throw ex;
}
}
/// (progn E1 E2.. En) => Evaluates E1, E2, .. except for En and returns it.
_evalProgN(Cell j, Cell env) {
if (j == null)
return null;
for (;;) {
var x = j.car;
j = cdrCell(j);
if (j == null)
return x; // The tail expression will be evaluated at the caller.
eval(x, env);
}
}
/// Evaluates a conditional expression and returns the selection unevaluated.
_evalCond(Cell j, Cell env) {
for (; j != null; j = cdrCell(j)) {
var clause = j.car;
if (clause is Cell) {
var result = eval(clause.car, env);
if (result != null) { // If the condition holds
Cell body = cdrCell(clause);
if (body == null)
return qqQuote(result);
else
return _evalProgN(body, env);
}
} else if (clause != null) {
throw EvalException("cond test expected", clause);
}
}
return null; // No clause holds.
}
/// (setq V1 E1 ..) => Evaluates Ei and assigns it to Vi; returns the last.
_evalSetQ(Cell j, Cell env) {
var result = null;
for (; j != null; j = cdrCell(j)) {
var lval = j.car;
j = cdrCell(j);
if (j == null)
throw EvalException("right value expected", lval);
result = eval(j.car, env);
if (lval is Arg)
lval.setValue(result, env);
else if (lval is Sym && lval is! Keyword)
globals[lval] = result;
else
throw NotVariableException(lval);
}
return result;
}
/// Compiles a Lisp list (macro ...) or (lambda ...).
DefinedFunc _compile(Cell arg, Cell env, FuncFactory make) {
if (arg == null)
throw EvalException("arglist and body expected", arg);
Map<Sym, Arg> table = {};
bool hasRest = _makeArgTable(arg.car, table);
int arity = table.length;
Cell body = cdrCell(arg);
body = _scanForArgs(body, table);
body = _expandMacros(body, 20); // Expands ms statically up to 20 nestings.
body = _compileInners(body);
return make((hasRest) ? -arity : arity, body, env);
}
/// Expands macros and quasi-quotations in an expression.
_expandMacros(j, int count) {
if (count > 0 && j is Cell) {
var k = j.car;
if (k == quoteSym || k == lambdaSym || k == macroSym) {
return j;
} else if (k == quasiquoteSym) {
Cell d = cdrCell(j);
if (d != null && d.cdr == null) {
var z = qqExpand(d.car);
return _expandMacros(z, count);
}
throw EvalException("bad quasiquote", j);
} else {
if (k is Sym)
k = globals[k]; // null if k does not have a value
if (k is Macro) {
Cell d = cdrCell(j);
var z = k.expandWith(this, d);
return _expandMacros(z, count - 1);
} else {
return mapcar(j, (x) => _expandMacros(x, count));
}
}
} else {
return j;
}
}
/// Replaces inner lambda-expressions with Lambda instances.
_compileInners(j) {
if (j is Cell) {
var k = j.car;
if (k == quoteSym) {
return j;
} else if (k == lambdaSym) {
Cell d = cdrCell(j);
return _compile(d, null, Lambda.make);
} else if (k == macroSym) {
throw EvalException("nested macro", j);
} else {
return mapcar(j, (x) => _compileInners(x));
}
} else {
return j;
}
}
}
//----------------------------------------------------------------------
/// Makes an argument-table; returns true if there is a rest argument.
bool _makeArgTable(arg, Map<Sym, Arg> table) {
if (arg == null) {
return false;
} else if (arg is Cell) {
int offset = 0; // offset value within the call-frame
bool hasRest = false;
for (; arg != null; arg = cdrCell(arg)) {
var j = arg.car;
if (hasRest)
throw EvalException("2nd rest", j);
if (j == restSym) { // &rest var
arg = cdrCell(arg);
if (arg == null)
throw NotVariableException(arg);
j = arg.car;
if (j == restSym)
throw NotVariableException(j);
hasRest = true;
}
Sym sym =
(j is Sym) ? j :
(j is Arg) ? j.symbol : throw NotVariableException(j);
if (table.containsKey(sym))
throw EvalException("duplicated argument name", sym);
table[sym] = Arg(0, offset, sym);
offset++;
}
return hasRest;
} else {
throw EvalException("arglist expected", arg);
}
}
/// Scans [j] for formal arguments in [table] and replaces them with Args.
/// And scans [j] for free Args not in [table] and promotes their levels.
_scanForArgs(j, Map<Sym, Arg> table) {
if (j is Sym) {
return table[j] ?? j;
} else if (j is Arg) {
return table[j.symbol] ?? Arg(j.level + 1, j.offset, j.symbol);
} else if (j is Cell) {
if (j.car == quoteSym) {
return j;
} else if (j.car == quasiquoteSym) {
return Cell(quasiquoteSym, _scanForQQ(j.cdr, table, 0));
} else {
return mapcar(j, (x) => _scanForArgs(x, table));
}
} else {
return j;
}
}
/// Scans for quasi-quotes.
/// And does [_scanForArgs] them depending on the nesting level.
_scanForQQ(j, Map<Sym, Arg> table, int level) {
if (j is Cell) {
var k = j.car;
if (k == quasiquoteSym) {
return Cell(k, _scanForQQ(j.cdr, table, level + 1));
} else if (k == unquoteSym || k == unquoteSplicingSym) {
var d = (level == 0) ? _scanForArgs(j.cdr, table) :
_scanForQQ(j.cdr, table, level - 1);
if (identical(d, j.cdr))
return j;
return Cell(k, d);
} else {
return mapcar(j, (x) => _scanForQQ(x, table, level));
}
} else {
return j;
}
}
/// Gets cdr of list [x] as a Cell or null.
Cell cdrCell(Cell x) {
var k = x.cdr;
if (k is Cell)
return k;
else if (k == null)
return null;
else
throw EvalException("proper list expected", x);
}
//----------------------------------------------------------------------
// Quasi-Quotation
/// Expands [x] of any quasi-quotation `x into the equivalent S-expression.
qqExpand(x) {
return _qqExpand0(x, 0); // Begins with the nesting level 0.
}
_qqExpand0(x, int level) {
if (x is Cell) {
if (x.car == unquoteSym) { // ,a
if (level == 0)
return x.cdr.car; // ,a => a
}
Cell t = _qqExpand1(x, level);
if (t.car is Cell && t.cdr == null) {
Cell k = t.car;
if (k.car == listSym || k.car == consSym)
return k;
}
return Cell(appendSym, t);
} else {
return qqQuote(x);
}
}
/// Quotes [x] so that the result evaluates to [x].
qqQuote(x) =>
(x is Sym || x is Cell) ? Cell(quoteSym, Cell(x, null)) : x;
// Expands [x] of `x so that the result can be used as an argument of append.
// Example 1: (,a b) => h=(list a) t=((list 'b)) => ((list a 'b))
// Example 2: (,a ,@(cons 2 3)) => h=(list a) t=((cons 2 3))
// => ((cons a (cons 2 3)))
Cell _qqExpand1(x, int level) {
if (x is Cell) {
if (x.car == unquoteSym) { // ,a
if (level == 0)
return x.cdr; // ,a => (a)
level--;
} else if (x.car == quasiquoteSym) { // `a
level++;
}
var h = _qqExpand2(x.car, level);
Cell t = _qqExpand1(x.cdr, level); // != null
if (t.car == null && t.cdr == null) {
return Cell(h, null);
} else if (h is Cell) {
if (h.car == listSym) {
if (t.car is Cell) {
Cell tcar = t.car;
if (tcar.car == listSym) {
var hh = _qqConcat(h, tcar.cdr);
return Cell(hh, t.cdr);
}
}
if (h.cdr is Cell) {
var hh = _qqConsCons(h.cdr, t.car);
return Cell(hh, t.cdr);
}
}
}
return Cell(h, t);
} else {
return Cell(qqQuote(x), null);
}
}
// (1 2), (3 4) => (1 2 3 4)
_qqConcat(Cell x, Object y) =>
(x == null) ? y : Cell(x.car, _qqConcat(x.cdr, y));
// (1 2 3), "a" => (cons 1 (cons 2 (cons 3 "a")))
_qqConsCons(Cell x, Object y) =>
(x == null) ? y :
Cell(consSym, Cell(x.car, Cell(_qqConsCons(x.cdr, y), null)));
// Expands [y] = x.car of `x so that result can be used as an arg of append.
// Example: ,a => (list a); ,@(foo 1 2) => (foo 1 2); b => (list 'b)
_qqExpand2(y, int level) {
if (y is Cell) {
if (y.car == unquoteSym) { // ,a
if (level == 0)
return Cell(listSym, y.cdr); // ,a => (list a)
level--;
} else if (y.car == unquoteSplicingSym) { // ,@a
if (level == 0)
return y.cdr.car; // ,@a => a
level--;
} else if (y.car == quasiquoteSym) { // `a
level++;
}
}
return Cell(listSym, Cell(_qqExpand0(y, level), null));
}
//----------------------------------------------------------------------
/// Reader of Lisp expressions
class Reader {
final StreamIterator<String> _rf;
var _token;
Iterator<String> _tokens = <String>[].iterator;
int _lineNo = 0;
bool _erred = false;
/// Constructs a Reader which will read Lisp expressions from a given arg.
Reader(this._rf);
/// Reads a Lisp expression; returns #EOF if the input runs out normally.
Future<Object> read() async {
try {
await _readToken();
return await _parseExpression();
} on FormatException catch (ex) {
_erred = true;
throw EvalException("syntax error",
"${ex.message} -- $_lineNo: ${_rf.current}", false);
}
}
Future<Object> _parseExpression() async {
if (_token == leftParenSym) { // (a b c)
await _readToken();
return await _parseListBody();
} else if (_token == singleQuoteSym) { // 'a => (quote a)