-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
ScriptLanguage.Lisp.cs
3542 lines (3084 loc) · 145 KB
/
ScriptLanguage.Lisp.cs
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
/*
Copyright (c) 2017 OKI Software Co., Ltd.
Copyright (c) 2018 SUZUKI Hisao
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
// H29.3/1 - H30.6/27 by SUZUKI Hisao
// lisp.exe: csc /doc:lisp.xml /o lisp.cs
// doc: mdoc update -i lisp.xml -o xml lisp.exe; mdoc export-html -o html xml
// [assembly: AssemblyProduct("Nukata Lisp Light")]
// [assembly: AssemblyVersion("1.2.2.*")]
// [assembly: AssemblyTitle("A Lisp interpreter in C# 7")]
// [assembly: AssemblyCopyright("© 2017 Oki Software Co., Ltd.; " +
// "© 2018 SUZUKI Hisao [MIT License]")]
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using ServiceStack.IO;
using ServiceStack.Text;
using ServiceStack.Text.Json;
namespace ServiceStack.Script
{
public sealed class ScriptLisp : ScriptLanguage, IConfigureScriptContext
{
private ScriptLisp() {} // force usage of singleton
public static readonly ScriptLanguage Language = new ScriptLisp();
public override string Name => "lisp";
public override string LineComment => ";";
public void Configure(ScriptContext context)
{
Lisp.Init();
context.ScriptMethods.Add(new LispScriptMethods());
context.ScriptBlocks.Add(new DefnScriptBlock());
}
public override List<PageFragment> Parse(ScriptContext context, ReadOnlyMemory<char> body, ReadOnlyMemory<char> modifiers)
{
var quiet = false;
if (!modifiers.IsEmpty)
{
quiet = modifiers.EqualsOrdinal("q") || modifiers.EqualsOrdinal("quiet") || modifiers.EqualsOrdinal("mute");
if (!quiet)
throw new NotSupportedException($"Unknown modifier '{modifiers.ToString()}', expected 'code|q', 'code|quiet' or 'code|mute'");
}
return new List<PageFragment> {
new PageLispStatementFragment(context.ParseLisp(body)) {
Quiet = quiet
}
};
}
public override async Task<bool> WritePageFragmentAsync(ScriptScopeContext scope, PageFragment fragment, CancellationToken token)
{
if (fragment is PageLispStatementFragment blockFragment)
{
if (blockFragment.Quiet && scope.OutputStream != Stream.Null)
scope = scope.ScopeWithStream(Stream.Null);
await WriteStatementAsync(scope, blockFragment.LispStatements, token);
return true;
}
return false;
}
public override async Task<bool> WriteStatementAsync(ScriptScopeContext scope, JsStatement statement, CancellationToken token)
{
var page = scope.PageResult;
if (statement is LispStatements lispStatement)
{
var lispCtx = scope.PageResult.GetLispInterpreter(scope);
page.ResetIterations();
var len = lispStatement.SExpressions.Length;
foreach (var sExpr in lispStatement.SExpressions)
{
var value = lispCtx.Eval(sExpr, null);
if (value != null && value != JsNull.Value && value != StopExecution.Value && value != IgnoreResult.Value)
{
if (value is Lisp.Sym s)
continue;
var strValue = page.Format.EncodeValue(value);
if (!string.IsNullOrEmpty(strValue))
{
var bytes = strValue.ToUtf8Bytes();
await scope.OutputStream.WriteAsync(bytes, token);
}
if (len > 1) // don't emit new lines for single expressions
await scope.OutputStream.WriteAsync(JsTokenUtils.NewLineUtf8, token);
}
}
}
else return false;
return true;
}
}
public class LispStatements : JsStatement
{
public object[] SExpressions { get; }
public LispStatements(object[] sExpressions) => SExpressions = sExpressions;
protected bool Equals(LispStatements other) => Equals(SExpressions, other.SExpressions);
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((LispStatements) obj);
}
public override int GetHashCode() => (SExpressions != null ? SExpressions.GetHashCode() : 0);
}
public class PageLispStatementFragment : PageFragment
{
public LispStatements LispStatements { get; }
public bool Quiet { get; set; }
public PageLispStatementFragment(LispStatements statements) => LispStatements = statements;
protected bool Equals(PageLispStatementFragment other) => Equals(LispStatements, other.LispStatements);
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((PageJsBlockStatementFragment) obj);
}
public override int GetHashCode() => (LispStatements != null ? LispStatements.GetHashCode() : 0);
}
public class LispScriptMethods : ScriptMethods
{
public List<string> symbols(ScriptScopeContext scope)
{
var interp = scope.GetLispInterpreter();
return interp.Globals.Keys.Map(x => x.Name).OrderBy(x => x).ToList();
}
public List<GistLink> gistindex(ScriptScopeContext scope)
{
return Lisp.Interpreter.GetGistIndexLinks(scope);
}
}
/// <summary>
/// Define and export a LISP function to the page
/// Usage: {{#defn calc [a, b] }}
/// (let ( (c (* a b)) )
/// (+ a b c)
/// )
/// {{/defn}}
/// </summary>
public class DefnScriptBlock : ScriptBlock
{
public override string Name => "defn";
public override ScriptLanguage Body => ScriptLanguage.Verbatim;
public override Task WriteAsync(ScriptScopeContext scope, PageBlockFragment block, CancellationToken token)
{
// block.Argument key is unique to exact memory fragment, not string equality
// Parse sExpression once for all Page Results
var sExpr = (List<object>) scope.Context.CacheMemory.GetOrAdd(block.Argument, key => {
var literal = block.Argument.Span.ParseVarName(out var name);
var strName = name.ToString();
var strFragment = (PageStringFragment) block.Body[0];
var lispDefnAndExport =
$@"(defn {block.Argument} {strFragment.Value}) (export {strName} (to-delegate {strName}))";
return Lisp.Parse(lispDefnAndExport);
});
var interp = scope.PageResult.GetLispInterpreter(scope);
interp.Eval(sExpr);
return TypeConstants.EmptyTask;
}
}
/// <summary>Exception in evaluation</summary>
public class LispEvalException: Exception
{
/// <summary>Stack trace of Lisp evaluation</summary>
public List<string> Trace { get; } = new List<string>();
/// <summary>Construct with a base message, cause, and
/// a flag whether to quote strings in the cause.</summary>
public LispEvalException(string msg, object x, bool quoteString=true)
: base(msg + ": " + Lisp.Str(x, quoteString)) {}
/// <summary>Return a string representation which contains
/// the message and the stack trace.</summary>
public override string ToString()
{
var sb = StringBuilderCache.Allocate().Append($"EvalException: {Message}");
foreach (var line in Trace)
sb.Append($"\n\t{line}");
return StringBuilderCache.ReturnAndFree(sb);
}
}
public static class ScriptLispUtils
{
public static Lisp.Interpreter GetLispInterpreter(this ScriptScopeContext scope) =>
scope.PageResult.GetLispInterpreter(scope);
public static Lisp.Interpreter GetLispInterpreter(this PageResult pageResult, ScriptScopeContext scope)
{
if (!pageResult.Args.TryGetValue(nameof(ScriptLisp), out var oInterp))
{
var interp = Lisp.CreateInterpreter();
pageResult.Args[nameof(ScriptLisp)] = interp;
interp.Scope = scope;
return interp;
}
else
{
var interp = (Lisp.Interpreter) oInterp;
interp.Scope = scope;
return interp;
}
}
public static SharpPage LispSharpPage(this ScriptContext context, string lisp)
=> context.Pages.OneTimePage(lisp, context.PageFormats[0].Extension,p => p.ScriptLanguage = ScriptLisp.Language);
private static void AssertLisp(this ScriptContext context)
{
if (!context.ScriptLanguages.Contains(ScriptLisp.Language))
throw new NotSupportedException($"ScriptLisp.Language is not registered in {context.GetType().Name}.{nameof(context.ScriptLanguages)}");
}
private static PageResult GetLispPageResult(ScriptContext context, string lisp, Dictionary<string, object> args)
{
context.AssertLisp();
PageResult pageResult = null;
try
{
var page = context.LispSharpPage(lisp);
pageResult = new PageResult(page);
args.Each((x, y) => pageResult.Args[x] = y);
return pageResult;
}
catch (Exception e)
{
if (ScriptContextUtils.ShouldRethrow(e))
throw;
throw ScriptContextUtils.HandleException(e, pageResult ?? new PageResult(context.EmptyPage));
}
}
public static string RenderLisp(this ScriptContext context, string lisp, Dictionary<string, object> args=null)
{
var pageResult = GetLispPageResult(context, lisp, args);
return pageResult.RenderScript();
}
public static async Task<string> RenderLispAsync(this ScriptContext context, string lisp, Dictionary<string, object> args=null)
{
var pageResult = GetLispPageResult(context, lisp, args);
return await pageResult.RenderScriptAsync();
}
public static LispStatements ParseLisp(this ScriptContext context, string lisp) =>
context.ParseLisp(lisp.AsMemory());
public static LispStatements ParseLisp(this ScriptContext context, ReadOnlyMemory<char> lisp)
{
var sExpressions = Lisp.Parse(lisp);
return new LispStatements(sExpressions.ToArray());
}
public static T EvaluateLisp<T>(this ScriptContext context, string lisp, Dictionary<string, object> args = null) =>
context.EvaluateLisp(lisp, args).ConvertTo<T>();
public static object EvaluateLisp(this ScriptContext context, string lisp, Dictionary<string, object> args=null)
{
var pageResult = GetLispPageResult(context, lisp, args);
if (!pageResult.EvaluateResult(out var returnValue))
throw new NotSupportedException(ScriptContextUtils.ErrorNoReturn);
return ScriptLanguage.UnwrapValue(returnValue);
}
public static async Task<T> EvaluateLispAsync<T>(this ScriptContext context, string lisp, Dictionary<string, object> args = null) =>
(await context.EvaluateLispAsync(lisp, args)).ConvertTo<T>();
public static async Task<object> EvaluateLispAsync(this ScriptContext context, string lisp, Dictionary<string, object> args=null)
{
var pageResult = GetLispPageResult(context, lisp, args);
var ret = await pageResult.EvaluateResultAsync();
if (!ret.Item1)
throw new NotSupportedException(ScriptContextUtils.ErrorNoReturn);
return ScriptLanguage.UnwrapValue(ret.Item2);
}
public static string EnsureReturn(string lisp)
{
// if code doesn't contain a return, wrap and return the expression
if ((lisp ?? throw new ArgumentNullException(nameof(lisp))).IndexOf("(return",StringComparison.Ordinal) == -1)
lisp = "(return (let () " + lisp + " ))";
return lisp;
}
}
internal static class Utils
{
internal static object lispBool(this bool t) => t ? Lisp.TRUE : null;
internal static object fromLisp(this object o) => o == Lisp.TRUE ? true : o;
internal static object lastArg(this object[] a)
{
var last = a[a.Length - 1];
return last is Lisp.Cell lastCell ? lastCell.Car : last;
}
internal static IEnumerable assertEnumerable(this object a)
{
if (a == null)
return TypeConstants.EmptyObjectArray;
if (a is IEnumerable e)
return e;
throw new LispEvalException("not IEnumerable", a);
}
internal static int compareTo(this object a, object b)
{
return a == null || b == null
? (a == b ? 0 : a == null ? -1 : 1)
: DynamicNumber.IsNumber(a.GetType())
? DynamicNumber.CompareTo(a, b)
: a is IComparable c
? (int) c.CompareTo(b)
: throw new LispEvalException("not IComparable", a);
}
public static Lisp.Cell unwrapDataListArgs(this Lisp.Cell arg)
{
if (arg.Car is Lisp.Cell c && c.Car == Lisp.LIST) // allow clojure data list [] for fn args list by unwrapping (list ...) => ...
arg.Car = c.Cdr;
return arg;
}
internal static object unwrapScriptValue(this object o)
{
if (o is Task t)
o = t.GetResult();
if (o is bool b)
return b ? Lisp.TRUE : null;
return ScriptLanguage.UnwrapValue(o);
}
}
/// <summary>
/// A Lisp interpreter written in C# 7
/// </summary><remarks>
/// This is ported from Nuka Lisp in Dart
/// (https://github.com/nukata/lisp-in-dart) except for bignum.
/// It is named after ex-Nukata Town in Japan.
/// </remarks>
public static class Lisp
{
/// <summary>
/// Allow loading of remote scripts
/// - https://example.org/lib.l
/// - gist:{gist-id}
/// - gist:{gist-id}/file.l
/// - index:{name}
/// - index:{name}/file.l
/// </summary>
public static bool AllowLoadingRemoteScripts { get; set; } = true;
/// <summary>
/// Gist where to resolve `index:{name}` references from
/// </summary>
public static string IndexGistId { get; set; } = "3624b0373904cfb2fc7bb3c2cb9dc1a3";
private static Interpreter GlobalInterpreter;
static Lisp()
{
Reset();
}
/// <summary>
/// Reset Global Symbols back to default
/// </summary>
public static void Reset()
{
//Create and cache pre-loaded global symbol table once.
GlobalInterpreter = new Interpreter();
Run(GlobalInterpreter, new Reader(InitScript.AsMemory()));
}
/// <summary>
/// Load Lisp into Global Symbols, a new CreateInterpreter() starts with a copy of global symbols
/// </summary>
public static void Import(string lisp) => Import(lisp.AsMemory());
/// <summary>
/// Load Lisp into Global Symbols, a new CreateInterpreter() starts with a copy of global symbols
/// </summary>
public static void Import(ReadOnlyMemory<char> lisp)
{
Run(GlobalInterpreter, new Reader(lisp));
}
public static void Set(string symbolName, object value)
{
GlobalInterpreter.Globals[Sym.New(symbolName)] = value;
}
public static void Init() {} // Force running static initializers
/// <summary>Create a Lisp interpreter initialized pre-configured with Global Symbols.</summary>
public static Interpreter CreateInterpreter() {
Init();
var interp = new Interpreter(GlobalInterpreter);
return interp;
}
/// <summary>Cons cell</summary>
public sealed class Cell : IEnumerable
{
/// <summary>Head part of the cons cell</summary>
public object Car;
/// <summary>Tail part of the cons cell</summary>
public object Cdr;
/// <summary>Construct a cons cell with its head and tail.</summary>
public Cell(object car, object cdr) {
Car = car;
Cdr = cdr;
}
/// <summary>Make a simple string representation.</summary>
/// <remarks>Do not invoke this for any circular list.</remarks>
public override string ToString() =>
$"({Car ?? "null"} . {Cdr ?? "null"})";
/// <summary>Length as a list</summary>
public int Length => FoldL(0, this, (i, e) => i + 1);
public IEnumerator GetEnumerator()
{
var j = this;
do {
yield return j.Car;
} while ((j = CdrCell(j)) != null);
}
public void Walk(Action<Cell> fn)
{
fn(this);
if (Car is Cell l)
l.Walk(fn);
if (Cdr is Cell r)
r.Walk(fn);
}
}
// MapCar((a b c), fn) => (fn(a) fn(b) fn(c))
static Cell MapCar(Cell j, Func<object, object> fn) {
if (j == null)
return null;
object a = fn(j.Car);
object d = j.Cdr;
if (d is Cell dc)
d = MapCar(dc, fn);
if (j.Car == a && j.Cdr == d)
return j;
return new Cell(a, d);
}
// FoldL(x, (a b c), fn) => fn(fn(fn(x, a), b), c)
static T FoldL<T> (T x, Cell j, Func<T, object, T> fn) {
while (j != null) {
x = fn(x, j.Car);
j = (Cell) j.Cdr;
}
return x;
}
// Supports both Cell + IEnumerable
static T FoldL<T> (T x, IEnumerable j, Func<T, object, T> fn) {
foreach (var e in j)
x = fn(x, e);
return x;
}
/// <summary>Lisp symbol</summary>
public class Sym {
/// <summary>The symbol's name</summary>
public string Name { get; }
/// <summary>Construct a symbol that is not interned.</summary>
public Sym(string name) {
Name = name;
}
/// <summary>Return the symbol's name</summary>
public override string ToString() => Name;
/// <summary>Return the hashcode of the symbol's name</summary>
public override int GetHashCode() => Name.GetHashCode();
/// <summary>Table of interned symbols</summary>
protected static readonly Dictionary<string, Sym> Table =
new Dictionary<string, Sym>();
/// <summary>Return an interned symbol for the name.</summary>
/// <remarks>If the name is not interned yet, such a symbol
/// will be constructed with <paramref name="make"/>.</remarks>
protected static Sym New(string name, Func<string, Sym> make) {
lock (Table) {
if (! Table.TryGetValue(name, out Sym result)) {
result = make(name);
Table[name] = result;
}
return result;
}
}
/// <summary>Construct an interned symbol.</summary>
public static Sym New(string name) => New(name, s => new Sym(s));
/// <summary>Is it interned?</summary>
public bool IsInterned {
get {
lock (Table) {
return Table.TryGetValue(Name, out Sym s) &&
Object.ReferenceEquals(this, s);
}
}
}
}
// Expression keyword
sealed class Keyword: Sym {
Keyword(string name): base(name) {}
internal static new Sym New(string name)
=> New(name, s => new Keyword(s));
}
/// <summary>The symbol of <c>t</c></summary>
public static readonly Sym TRUE = Sym.New("t");
public static readonly Sym BOOL_TRUE = Sym.New("true");
public static readonly Sym BOOL_FALSE = Sym.New("false");
static readonly Sym VERBOSE = Sym.New("verbose");
static readonly Sym COND = Keyword.New("cond");
static readonly Sym LAMBDA = Keyword.New("lambda");
static readonly Sym FN = Keyword.New("fn");
static readonly Sym MACRO = Keyword.New("macro");
static readonly Sym PROGN = Keyword.New("progn");
static readonly Sym QUASIQUOTE = Keyword.New("quasiquote");
static readonly Sym QUOTE = Keyword.New("quote");
static readonly Sym SETQ = Keyword.New("setq");
static readonly Sym EXPORT = Keyword.New("export");
static readonly Sym BOUND = Sym.New("bound?");
static readonly Sym BACK_QUOTE = Sym.New("`");
static readonly Sym COMMAND_AT = Sym.New(",@");
static readonly Sym COMMA = Sym.New(",");
static readonly Sym DOT = Sym.New(".");
static readonly Sym LEFT_PAREN = Sym.New("(");
static readonly Sym RIGHT_PAREN = Sym.New(")");
static readonly Sym SINGLE_QUOTE = Sym.New("'");
static readonly Sym APPEND = Sym.New("append");
static readonly Sym CONS = Sym.New("cons");
internal static readonly Sym LIST = Sym.New("list");
static readonly Sym REST = Sym.New("&rest");
static readonly Sym UNQUOTE = Sym.New("unquote");
static readonly Sym UNQUOTE_SPLICING = Sym.New("unquote-splicing");
static readonly Sym LEFT_BRACE = Sym.New("{");
static readonly Sym RIGHT_BRACE = Sym.New("}");
static readonly Sym HASH = Sym.New("#");
static readonly Sym PERCENT = Sym.New("%");
static readonly Sym NEWMAP = Sym.New("new-map");
static readonly Sym ARG = Sym.New("_a");
static readonly Sym LEFT_BRACKET = Sym.New("[");
static readonly Sym RIGHT_BRACKET = Sym.New("]");
//------------------------------------------------------------------
// Get cdr of list x as a Cell or null.
static Cell CdrCell(Cell x) {
var k = x.Cdr;
if (k == null) {
return null;
} else {
if (k is Cell c)
return c;
else
throw new LispEvalException("proper list expected", x);
}
}
/// <summary>Common base class of Lisp functions</summary>
public abstract class LispFunc {
/// <summary>Number of arguments, made negative if the function
/// has &rest</summary>
public int Carity { get; }
int Arity => (Carity < 0) ? -Carity : Carity;
bool HasRest => (Carity < 0);
// Number of fixed arguments
int FixedArgs => (Carity < 0) ? -Carity - 1 : Carity;
/// <summary>Construct with Carity.</summary>
protected LispFunc(int carity) {
Carity = carity;
}
/// <summary>Make a frame for local variables from a list of
/// actual arguments.</summary>
public object[] MakeFrame(Cell arg) {
var frame = new object[Arity];
int n = FixedArgs;
int i;
for (i = 0; i < n && arg != null; i++) {
// Set the list of fixed arguments.
frame[i] = arg.Car;
arg = CdrCell(arg);
}
if (i != n || (arg != null && !HasRest))
throw new LispEvalException("arity not matched", this);
if (HasRest)
frame[n] = arg;
return frame;
}
/// <summary>Evaluate each expression in a frame.</summary>
public void EvalFrame(object[] frame, Interpreter interp, Cell env) {
int n = FixedArgs;
for (int i = 0; i < n; i++)
frame[i] = interp.Eval(frame[i], env);
if (HasRest) {
if (frame[n] is Cell j) {
Cell z = null;
Cell y = null;
do {
var e = interp.Eval(j.Car, env);
Cell x = new Cell(e, null);
if (z == null)
z = x;
else
y.Cdr = x;
y = x;
j = CdrCell(j);
} while (j != null);
frame[n] = z;
}
}
}
}
// Common base class of functions which are defined with Lisp expressions
abstract class DefinedFunc: LispFunc {
// Lisp list as the function body
public readonly Cell Body;
protected DefinedFunc(int carity, Cell body): base(carity) {
Body = body;
}
}
// Common function type which represents any factory method of DefinedFunc
delegate DefinedFunc FuncFactory(int carity, Cell body, Cell env);
// Compiled macro expression
sealed class Macro: DefinedFunc {
Macro(int carity, Cell body): base(carity, body) {}
public override string ToString() => $"#<macro:{Carity}:{Str(Body)}>";
// Expand the macro with a list of actual arguments.
public object ExpandWith(Interpreter interp, Cell arg) {
object[] frame = MakeFrame(arg);
Cell env = new Cell(frame, null);
object x = null;
for (Cell j = Body; j != null; j = CdrCell(j))
x = interp.Eval(j.Car, env);
return x;
}
public static DefinedFunc Make(int carity, Cell body, Cell env) {
Debug.Assert(env == null);
return new Macro(carity, body);
}
}
// Compiled lambda expression (Within another function)
sealed class Lambda: DefinedFunc {
Lambda(int carity, Cell body): base(carity, body) {}
public override string ToString() => $"#<lambda:{Carity}:{Str(Body)}>";
public static DefinedFunc Make(int carity, Cell body, Cell env) {
Debug.Assert(env == null);
return new Lambda(carity, body);
}
}
// Compiled lambda expression (Closure with environment)
sealed class Closure: DefinedFunc {
// The environment of the closure
public readonly Cell Env;
Closure(int carity, Cell body, Cell env): base(carity, body) {
Env = env;
}
public Closure(Lambda x, Cell env): this(x.Carity, x.Body, env) {}
public override string ToString() =>
$"#<closure:{Carity}:{Str(Env)}:{Str(Body)}>";
// Make an environment to evaluate the body from a list of actual args.
public Cell MakeEnv(Interpreter interp, Cell arg, Cell interpEnv) {
object[] frame = MakeFrame(arg);
EvalFrame(frame, interp, interpEnv);
return new Cell(frame, Env); // Prepend the frame to this Env.
}
public static DefinedFunc Make(int carity, Cell body, Cell env) =>
new Closure(carity, body, env);
}
/// <summary>Function type which represents any built-in function body
/// </summary>
public delegate object BuiltInFuncBody(Interpreter interp, object[] frame);
/// <summary>Built-in function</summary>
public sealed class BuiltInFunc: LispFunc {
/// <summary>Name of this function</summary>
public string Name { get; }
/// <summary>C# function as the body of this function</summary>
public BuiltInFuncBody Body { get; }
/// <summary>Construct with Name, Carity and Body.</summary>
public BuiltInFunc(string name, int carity, BuiltInFuncBody body)
: base(carity) {
Name = name;
Body = body;
}
/// <summary>Return a string representation in Lisp.</summary>
public override string ToString() => $"#<{Name}:{Carity}>";
/// <summary>Invoke the built-in function with a list of
/// actual arguments.</summary>
public object EvalWith(Interpreter interp, Cell arg, Cell interpEnv) {
object[] frame = MakeFrame(arg);
EvalFrame(frame, interp, interpEnv);
try {
return Body(interp, frame);
} catch (LispEvalException) {
throw;
} catch (Exception ex) {
throw new LispEvalException($"{ex} -- {Name}", frame);
}
}
}
// Bound variable in a compiled lambda/macro expression
sealed class Arg {
public readonly int Level;
public readonly int Offset;
public readonly Sym Symbol;
public Arg(int level, int offset, Sym symbol) {
Level = level;
Offset = offset;
Symbol = symbol;
}
public override string ToString() => $"#{Level}:{Offset}:{Symbol}";
// Set a value x to the location corresponding to the variable in env.
public void SetValue(object x, Cell env) {
for (int i = 0; i < Level; i++)
env = (Cell) env.Cdr;
object[] frame = (object[]) env.Car;
frame[Offset] = x;
}
// Get a value from the location corresponding to the variable in env.
public object GetValue(Cell env) {
for (int i = 0; i < Level; i++)
env = (Cell) env.Cdr;
object[] frame = (object[]) env.Car;
if (frame == null || Offset >= frame.Length)
throw new IndexOutOfRangeException();
return frame[Offset];
}
}
// Exception which indicates on absence of a variable
sealed class NotVariableException: LispEvalException {
public NotVariableException(object x): base("variable expected", x) {}
}
//------------------------------------------------------------------
public static Cell ToCons(IEnumerable seq)
{
if (!(seq is IEnumerable e))
return null;
Cell j = null;
foreach (var item in e.Cast<object>().Reverse())
{
j = new Cell(item, j);
}
return j;
}
static bool isTrue(object test) => test != null && !(test is bool b && !b);
/// <summary>Core of the Lisp interpreter</summary>
public class Interpreter
{
private static int totalEvaluations = 0;
public static int TotalEvaluations => Interlocked.CompareExchange(ref totalEvaluations, 0, 0);
public int Evaluations { get; set; }
/// <summary>Table of the global values of symbols</summary>
internal readonly Dictionary<Sym, object> Globals = new Dictionary<Sym, object>();
public object GetSymbolValue(string name) => Globals.TryGetValue(Sym.New(name), out var value)
? value.fromLisp()
: null;
public void SetSymbolValue(string name, object value) => Globals[Sym.New(name)] = value.unwrapScriptValue();
/// <summary>Standard out</summary>
public TextWriter COut { get; set; } = Console.Out;
/// <summary>Set each built-in function/variable as the global value
/// of symbol.</summary>
public Interpreter() {
InitGlobals();
}
public Interpreter(Interpreter globalInterp)
{
Globals = new Dictionary<Sym, object>(globalInterp.Globals); // copy existing globals
}
public string ReplEval(ScriptContext context, Stream outputStream, string lisp, Dictionary<string, object> args=null)
{
var returnResult = ScriptLispUtils.EnsureReturn(lisp);
var page = new PageResult(context.LispSharpPage(returnResult)) {
Args = {
[nameof(ScriptLisp)] = this
}
};
args?.Each(x => page.Args[x.Key] = x.Value);
this.Scope = new ScriptScopeContext(page, outputStream, args);
var output = page.RenderScript();
if (page.ReturnValue != null)
{
var ret = ScriptLanguage.UnwrapValue(page.ReturnValue.Result);
if (ret == null)
return output;
if (ret is Cell c)
return Str(c);
if (ret is Sym sym)
return Str(sym);
if (ret is string s)
return s;
if (Globals.TryGetValue(VERBOSE, out var verbose) && isTrue(verbose))
return ret.Dump();
return ret.ToSafeJsv();
}
return output;
}
Func<object, object> resolve1ArgFn(object f, Interpreter interp)
{
switch (f) {
case Closure fnclosure:
return x => interp.invoke(fnclosure, x);
case Macro fnmacro:
return x => interp.invoke(fnmacro, x);
case BuiltInFunc fnbulitin:
return x => interp.invoke(fnbulitin, x);
case Delegate fndel:
return x => interp.invoke(fndel, x);
default:
throw new LispEvalException("not applicable", f);
}
}
Func<object, object, object> resolve2ArgFn(object f, Interpreter interp)
{
switch (f) {
case Closure fnclosure:
return (x,y) => interp.invoke(fnclosure, x,y);
case Macro fnmacro:
return (x,y) => interp.invoke(fnmacro, x, y);
case BuiltInFunc fnbulitin:
return (x,y) => interp.invoke(fnbulitin, x, y);
case Delegate fndel:
return (x,y) => interp.invoke(fndel, x, y);
default:
throw new LispEvalException("not applicable", f);
}
}
Func<object, bool> resolvePredicate(object f, Interpreter interp)
{
var fn = resolve1ArgFn(f, interp);
return x => isTrue(fn(x));
}
object invoke(Closure fnclosure, params object[] args)
{
var env = fnclosure.MakeEnv(this, ToCons(args), null);
var ret = EvalProgN(fnclosure.Body, env);
ret = Eval(ret, env);
return ret;
}
object invoke(Macro fnmacro, params object[] args)
{
var ret = fnmacro.ExpandWith(this, ToCons(args));
ret = Eval(ret, null);
return ret;
}
object invoke(BuiltInFunc fnbulitin, params object[] args) => fnbulitin.Body(this, args);
object invoke(Delegate fndel, params object[] args)
{
var scriptMethodArgs = new List<object>(EvalArgs(ToCons(args), this));
var ret = JsCallExpression.InvokeDelegate(fndel, null, isMemberExpr: false, scriptMethodArgs);
return ret.unwrapScriptValue();
}
List<object> toList(IEnumerable seq) => seq == null
? new List<object>()
: seq.Cast<object>().ToList();