-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInc.fs
More file actions
1800 lines (1625 loc) · 62 KB
/
Inc.fs
File metadata and controls
1800 lines (1625 loc) · 62 KB
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) 2014, Gary Stephenson
* portions copyright 2010 Ashley Nathan Feniello
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* 3. Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*)
module Inc
open System
open System.Text
open System.Text.RegularExpressions
open System.Xml
open System.Numerics
open System.Threading
open System.IO
open System.Collections.Generic
open System.Collections.Concurrent
open System.Linq
open ImmutableCollections
open System.Reflection
open Utils
open Numeric
open Stm
open agent
open tokens
open IncTypes
let Globals = new GlobalEnvironment()
let parse fname source =
let e2vp posn e =
let pos,line,col = posn
let m = new IncMap([kwd("file"),str(fname)
kwd("pos"),incInt pos
kwd("line"),incInt line
kwd("col"),incInt col
])
IncValue.OfExpr(e,m)
let map posn t =
match t.tok with
| Token.Number(s) -> Number(Numeric.Parse(s)) |> e2vp posn
| Token.String(s) -> IncExpr.String(s) |> e2vp posn
| Token.Symbol(s) ->
match s with
| "true" -> incTrue
| "false" -> incFalse
| "nil" -> incNil
| _ -> IncExpr.Symbol(String.Intern(s)) |> e2vp posn
| Token.Keyword(s) -> IncExpr.Keyword(String.Intern(s)) |> e2vp posn
| Token.Char(c) -> IncExpr.Character((int c)) |> e2vp posn
| _ -> failwith "Syntax error."
let tagEl(v : IncValue,tag) =
match tag with
| Some(e) ->
match e with
| String("__implicit_function__") ->
match v.value with
| ExprList(l) ->
let syms = Dictionary<int,IncValue>()
let maxi = ref 0
let getsym i =
if i > !maxi then maxi := i
if not (syms.ContainsKey(i)) then
syms.[i] <- Globals.GenSym("p"+i.ToString())
syms.[i]
let rec _scan vs acc =
match vs with
| h :: t ->
match h.value with
| Symbol(s) when s.StartsWith("%") ->
if s = "%" then _scan t (getsym(1) :: acc)
else
let i = System.Int32.Parse(s.Substring(1))
_scan t (getsym(i) :: acc)
| ExprList(l) ->
let vs = _scan l []
_scan t ( (lst vs) :: acc)
| _ -> _scan t (h :: acc)
| [] -> List.rev acc
let tl = _scan l []
let prms = [for i in 1 .. !maxi -> getsym(i) ]
let rslt = lst([sym("fn*"); vect prms; lst(tl)])
rslt.SetMacro()
rslt
| _ -> failwith "Invalid implicit function"
| String("inst") ->
match v.value with
| String(cdt) ->
let x = IncExpr.DateTime(XmlConvert.ToDateTime(cdt,XmlDateTimeSerializationMode.Utc))
IncValue.OfExprM(x,v.metaMap)
| _ -> failwith "Syntax error"
| ExprDict(m) ->
for k,mv in m do
v.SetMetaValue(k,mv)
v
| _ -> failwith "Syntax error"
| None -> v
let rec addprs acc prs =
match prs with
| k :: v :: et -> addprs ((k,v) :: acc) et
| [] -> List.rev acc
| _ -> failwith "Malformed pairs for mapping."
let applyQuoting fs = // el bizarro - needs review :)
let rec _app acc forms =
let _app2 s t =
match _app [] t with
| h :: t ->
let rslt = (List.rev acc) @ (lst([s; h]) :: t)
rslt
| [] -> failwith "nothing to quote"
match forms with
| {value=Symbol("quote_")} :: t -> _app2 (sym "quote") t
| {value=Symbol("syntax-quote_")} :: t -> _app2 (sym "syntax-quote") t
| {value=Symbol("unquote_")} :: t -> _app2 (sym "unquote") t
| {value=Symbol("splice-unquote_")} :: t -> _app2 (sym "splice-unquote") t
| h :: t -> _app (h :: acc) t
| [] -> List.rev acc
_app [] fs
let rec xlist posn t acc tag =
let e, t' = parse' [] None t
parse' (tagEl(ExprList(applyQuoting(e)) |> e2vp posn ,tag) :: acc) None t'
and xvect posn t acc tag =
let e, t' = parse' [] None t
parse' (tagEl(ExprVector(Vec.create(applyQuoting(e))) |> e2vp posn,tag) :: acc) None t'
and xdict posn t acc tag =
let e, t' = parse' [] None t
let prs = addprs [] (applyQuoting(e))
parse' (tagEl(ExprDict(prs) |> e2vp posn,tag) :: acc) None t'
and xset posn t acc tag =
let e, t' = parse' [] None t
parse' (tagEl(ExprSet(applyQuoting(e)) |> e2vp posn,tag) :: acc) None t'
and parse' acc tag (toks : TokenPos list) =
let posn = match toks with
| h :: t -> (h.startpos,h.startline,h.startcol)
| [] -> (-1,-1,-1)
match toks with
| {tok=Open} :: t -> xlist posn t acc tag
| {tok=Close} :: t -> (List.rev acc), t
| {tok=OpenVector} :: t -> xvect posn t acc tag
| {tok=CloseVector} :: t -> (List.rev acc), t
| {tok=OpenDict} :: t -> xdict posn t acc tag
| {tok=CloseDict} :: t -> (List.rev acc), t
| {tok=OpenSet} :: t -> xset posn t acc tag
| {tok=Quote} :: t -> parse' (sym("quote_") :: acc) tag t
| {tok=Unquote} :: t -> parse' (sym("unquote_") :: acc) tag t
| {tok=SyntaxQuote} :: t -> parse' (sym("syntax-quote_") :: acc) tag t
| {tok=SpliceUnquote} :: t -> parse' (sym("splice-unquote_") :: acc) tag t
| {tok=TagTok("^")} :: {tok=OpenDict} :: t -> // metadata map
let m,t' = parse' [] None t
let prs = addprs [] (applyQuoting(m))
let meta = Some(ExprDict(prs))
parse' acc meta t'
| {tok=TagTok("^")} :: {tok=Token.Keyword(s)} :: t -> // metadata tag string
let meta = Some(ExprDict([Keyword("tag") |> e2v,String(s) |> e2v]))
parse' acc meta t
| {tok=TagTok("__ignore__")} :: h :: t ->
parse' acc tag t
| {tok=TagTok(s)} :: t -> parse' acc (Some(String(s))) t
| h :: t -> parse' (tagEl((map posn h),tag) :: acc) None t
| [] -> applyQuoting(List.rev acc), []
let toks = (tokenize source)
let result, _ = parse' [] None toks
result
let malformed n (v : IncValue) = sprintf "Malformed '%s': %s" n (v.ToString()) |> failwith
let Str cont args =
let rec _str acc l =
match l with
| [] -> String.Concat( List.rev acc)
| h :: t ->
match h.value with
| Character(i) -> _str ((char i).ToString() :: acc) t
| String(s) -> _str (s :: acc) t
| _ -> _str ( (h.ToPrint()) :: acc) t
String(_str [] args) |> e2v |> cont
let math ident unary op name (cont : Continuation) args =
let ident = Int(ident)
let unary = Int(unary)
let ns = [for x in args do
match x.value with
| Number(n) -> yield n
| EvaldSeq(s) -> yield! [for t in s do
match t.value with
| Number(n) -> yield n
| _ -> malformed name (vect args)
]
| _ -> malformed name (vect args) ]
match ns with
| [h] -> Number(unary * h)
| h :: t ->
Number(List.fold op h t)
| [] -> Number(ident)
|> e2v |> cont
let Add cont args = math 0 1 (+) "addition" cont args
let Subtract cont args = math 0 -1 (-) "subtraction" cont args
let Multiply cont args = math 1 1 (*) "multiplication" cont args
let Divide cont args = math 1 1 (/) "division" cont args
let Modulus cont args = math 1 1 (%) "modulus" cont args
let rec Compare pred name cont vs =
match vs with
| [{value=Number(a)}; {value=Number(b)}] -> (if pred a b then incTrue else incFalse) |> cont
| a :: b :: t ->
if (Compare pred name id [a ; b]).value.IsTrue then Compare pred name cont (b :: t)
else incFalse |> cont
| _ -> malformed name (vect vs)
let Greater cont = Compare (>) "greater" cont
let Less cont = Compare (<) "less" cont
let Equal c vs =
let es = [for v in vs -> v.value]
let cont e = e |> e2v |> c
match es with
| [a; b] ->
if (a.IsSeqable() && b.IsSeqable()) then
let sa = a.ToSeq()
let sb = b.ToSeq()
let cmp = Seq.compareWith (fun x y -> (compare x y)) sa sb
Boolean( cmp = 0 )
else Boolean( a = b )
|> cont
| m -> malformed "Equal" (vect vs)
let NotEqual c vs =
let es = [for v in vs -> v.value]
let cont e = e |> e2v |> c
match es with
| [a; b] -> Boolean( a <> b ) |> cont
| _ -> malformed "Equal" (vect vs)
let extend env (bindings : (IncValue * IncValue) seq) =
let dic = Frame.Empty()
for k,v in bindings do
dic.SetItem(k, v)
dic :: env
let ChangeNS cont args =
match args with
| [{value=Symbol(s)}] ->
match Globals.FindNS(s) with
| Some(ns) -> Globals.DefaultNS <- ns
| None -> let ns = Namespace(s)
Globals.LoadNS(ns)
Globals.DefaultNS <- ns
Dummy("in-ns") |> e2v |> cont
| _ -> malformed "in-ns" (vect args)
let Find cont args =
match args with
| [coll; k] ->
match coll.value with
| ExprDict(l) ->
match l |> List.tryFind (fun (k2,v) -> k = k2 ) with
| Some(_,v) -> MapEntry(KeyValuePair(k,v)) |> e2v
| None -> incNil
| EvaldDict(m) ->
if m.ContainsKey(k) then MapEntry(KeyValuePair(k,m.[k])) |> e2v
else incNil
| _ -> malformed "find" (vect args)
|> cont
| _ -> malformed "find" (vect args)
let FindNS cont args =
match args with
| [{value=Symbol(s)}] ->
match Globals.FindNS(s) with
| Some(ns) -> NS(ns) |> e2v |> cont
| None -> incNil |> cont
| _ -> malformed "find-ns" (vect args)
let rec UnDef cont = function
| [{value=NS(ns)}; {value=Symbol(s)}] ->
ns.UnIntern(s)
Dummy("ns-unmap "+(ns.Name)+"/"+s) |> e2v |> cont
| [{value=Symbol(ns)}; {value=Symbol(s)}] ->
match Globals.FindNS(ns) with
| Some(ns) -> ns.UnIntern(s)
| None -> failwith ("Unable to find namespace : "+ns)
Dummy("ns-unmap "+ns+"/"+s) |> e2v |> cont
| vs -> malformed "in-ns" (vect vs)
and print (v : IncValue) : string =
match v.value with
| Dummy(s) -> s
| _ -> v.ToPrint()
and zipargs env asmacro parameters args =
let rec _zip ps rs rslt =
match ps, rs with
| (p :: pt, r :: rt ) ->
match p.value with
| Symbol(s) ->
if s = "&" then
match pt with
| [p] ->
let mutable rest = r :: rt
if not asmacro then rest <- rest |> List.map (fun v -> eval id env v)
let v = match rest with
| [] | [{value=Nil}] -> incNil
| _ -> lst(rest)
(p, v) :: rslt
| _ -> failwith "Invalid parameter list"
else _zip pt rt ( (p,(if asmacro then r else (eval id env r)) ) :: rslt )
| _ -> failwith "Invalid parameter list"
| [], [] -> rslt
| [{value=Symbol("&")}; {value=Symbol(s)} as p], [] -> (p, incNil) :: rslt
| _, _ -> failwith "Invalid parameter list"
let l = List.rev (_zip parameters args [])
l
and If cont env form args =
match args with
| condition :: vs ->
let v = eval id env condition
match vs with
| [t; f] -> if v.IsTrue then eval cont env t
else eval cont env f
| [t] -> if v.IsTrue then eval cont env t
else eval cont env incNil
| _ -> malformed "if" (vect args)
| _ -> malformed "if" (vect args)
and LetStar cont env form args =
match args with
| {value=ExprVector(bindings)} :: body ->
let rec foldbind env' args' =
match args' with
| {value=Symbol(s)} as sm :: e :: t ->
if s.Contains("/") then failwith ("can't let qualified name : " + s)
let x = eval id env' e
let env'' = extend env' [sm, x]
foldbind env'' t
| [] ->
match body with
| [v] -> eval cont env' v
| _ -> Begin cont env' form body
| _ -> malformed "let*" (vect args')
foldbind env (Seq.toList (bindings.toSeq()))
| _ -> malformed "let" (vect args)
and Loop cont env form vs =
match vs with
| [{value=ExprVector(bindings)}; body] ->
let rec syms prms acc =
match prms with
| k :: v :: t -> syms t (k :: acc)
| [] -> vect (List.rev acc)
| _ -> malformed "loop" (vect vs)
let ps = syms (bindings.toList()) []
let f = Frame.RecurFrame(ps, body)
LetStar cont (f :: env) form vs
| {value=ExprVector(bindings)} as v :: body ->
let body = lst(sym("do") :: body)
Loop cont env form [v ; body]
| _ -> malformed "loop" (vect vs)
and Lambda cont env form args =
match args with
| [nm; l] ->
let nm = eval id env nm
let s = eval id env l
let vs = Seq.toList (s.ToSeq())
FnStar cont env form (nm :: vs)
| [l] ->
let s = eval id env l
let vs = Seq.toList (s.ToSeq())
FnStar cont env form vs
| _ -> malformed "lambda" (vect args)
and FnStar cont (env : Environment) form args =
let mutable nm = ""
let mutable doc = ""
let mutable meta = IncMap.Empty
let mutable rem = []
let mutable forms = []
let vs =
match args with
| {value=Symbol(s)} as sym :: t ->
nm <- s
match sym.metaMap with
| Some(m) -> meta <- m
| None -> ()
t
| _ -> args
match vs with
| {value=String(docstr)} :: {value=ExprDict(attribs)} :: body ->
doc <- docstr
for k,v in attribs do meta <- meta.Add(k, v)
rem <- body
| {value=ExprDict(attribs)} :: body ->
for k,v in attribs do meta <- meta.Add(k, v)
rem <- body
| {value=String(docstr)} :: body ->
doc <- docstr
rem <- body
| body ->
rem <- body
let nm_ = nm
let dic = new Dictionary<IncValue,IncValue>()
let rf = new Frame(dic,None)
let env =
if nm = "" then env
else
dic.[sym(nm)] <- incUnbound
rf :: env
let rec checkRecur canRecur (frms : IncValue list) =
match frms with
| h :: t ->
match h.value with
| ExprList(l) ->
let _canRecur = match t with
| [] -> canRecur
| _ -> false
match l with
| [{value=Symbol("if")}; cond; t; f] ->
checkRecur canRecur [t]
checkRecur canRecur [f]
| {value=Symbol("cond")} :: t ->
let rec chk vs =
match vs with
| tst :: xpr :: t ->
checkRecur canRecur [xpr]
chk t
| _ -> ()
chk t
| {value=Symbol("recur")} :: _ ->
if not _canRecur then failwith "recur not in tail position"
| {value=Symbol("loop")} :: t ->
checkRecur true t
| _ ->
checkRecur _canRecur l
| _ -> ()
checkRecur canRecur t
| [] -> ()
let vs = rem
rem <- [for v in vs ->
match v.value with
| EvaldExpr(ev) -> ev.Value
| EvaldSeq(s) -> lst(Seq.toList s)
| _ -> v]
match rem with
| [{value=ExprVector(prms)}; body] ->
forms <- [prms,body]
checkRecur true [body]
| [{value=ExprVector(prms)}] ->
forms <- [prms,incNil]
| {value=ExprVector(prms)} :: body ->
let body = lst(sym("do") :: body)
forms <- [prms,body]
checkRecur true [body]
| l ->
for v in l do
match v.value with
| ExprList(t) ->
match t with
| [{value=ExprVector(prms)}; body] ->
// check arity doesn't already exist
checkRecur true [body]
forms <- (prms,body) :: forms
| {value=ExprVector(prms)} :: body ->
let body = lst(sym("do") :: body)
forms <- (prms,body) :: forms
checkRecur true [body]
| _ -> malformed "fn*" (vect vs)
| Nil -> ()
| _ -> malformed "fn*" (vect vs)
meta <- meta.Add(kwd("name"), str(nm))
meta <- meta.Add(kwd("ns"), NS(Globals.DefaultNS) |> e2v)
meta <- meta.Add(kwd("macro"), incFalse);
if doc <> "" then meta <- meta.Add(kwd("doc"), str(doc))
let frms = forms |> List.rev
let closure cont' env' macro (args' : IncValue list) =
let ismacro,form = match macro with
| None -> false,incNil
| Some(f) -> true,f
let matchlen ps a =
match ps |> List.tryFindIndex (fun p -> match p.value with Symbol("&") -> true | _ -> false ) with
| Some(i) -> i <= a
| None -> ps.Length = a
let prms,body = frms |> List.find (fun (ps,_) -> matchlen (ps.toList()) args'.Length )
let binds = zipargs env' ismacro (prms.toList()) args'
if ismacro then
let env'' = env' @ env
let envrf = extend env'' [sym("&form"),form]
let env''' = binds |> extend envrf
eval id env''' body
else
let dic = new Dictionary<IncValue,IncValue>()
for k,v in binds do dic.[k] <- v
let rf = new Frame(dic,Some(vect(prms.toSeq()),body))
eval cont' (rf :: env) body
let def = IncValue.OfExprM(Special(closure),Some(meta))
if nm <> "" then dic.[sym(nm)] <- def
def |> cont
and Cat cont args =
match args with
| [{value=ExprList(a)}; {value=ExprList(b)}] -> ExprList(a @ b) |> e2v |> cont
| _ -> malformed "cat" (vect args)
and IncSeq cont (args : IncValue list) =
match args with
| [v] ->
let s = v.ToSeq()
if Seq.isEmpty s then incNil else evseq s
|> cont
| _ -> malformed "seq" (vect args)
and IncFirst cont args =
match args with
| [x] ->
let v = IncSeq id [x]
match v.value with
| EvaldSeq(s) -> let v = Seq.head s
v |> cont
| IncCons(cns) -> cns.head |> cont
| Nil -> incNil |> cont
| _ -> failwith "not a seq"
| _ -> malformed "first" (vect args)
and IncRest cont args =
match args with
| [x] ->
let v = (IncSeq id [x]).value
match v with
| EvaldSeq(s) ->
let s' = Seq.skip 1 s
evseq s' |> cont
| IncCons(cns) ->
match cns.tail.value with
| Nil | Unbound -> incEmptySeq |> cont
| _ -> cns.tail |> cont
| Nil -> incEmptySeq |> cont
| _ -> failwith "not a seq"
| _ -> malformed "rest" (vect args)
and IncNext cont args =
match args with
| [x] ->
let v = IncSeq id [x]
match v.value with
| EvaldSeq(s) ->
let s' = Seq.skip 1 s
if Seq.isEmpty s' then incNil
else evseq s'
|> cont
| IncCons(cns) -> cns.tail |> cont
| Nil -> incNil |> cont
| _ -> failwith "not a seq"
| _ -> malformed "next" (vect args)
and Nth (cont : Continuation) args =
match args with
| {value=EvaldExpr(x)} :: t -> Nth cont (x.Value :: t)
| [x; {value=Number(_)} as n] -> Nth cont [x; n; incUnbound]
| [x; {value=Number(n)}; dflt] ->
let deflt() =
match dflt.value with
| Unbound -> failwith "input sequence has insufficient elements"
| _ -> dflt |> cont
let n = n.ToInt()
let mutable s = x
for i = 0 to n - 1 do
s <- IncNext id [s]
IncFirst cont [s]
| _ -> malformed "nth" (vect args)
and Reverse cont (args : IncValue list) =
match args with
| [x] ->
let s = x.ToSeq()
evseq (s.Reverse()) |> cont
| _ -> malformed "reverse" (vect args)
and LazySeq cont env form args =
match args with
| [{value=EvaldExpr(x)}] -> LazySeq cont env form [x.Value]
| [x] ->
let lz = {fn = None; s = incNil}
let f = fun _ ->
lz.fn <- None
let t = eval id env x
lz.s <- t
lz.fn <- Some(f)
IncLazy(lz) |> e2v |> cont
| h :: t ->
let v = lst(sym("do") :: h :: t)
v.metaMap <- h.metaMap
LazySeq cont env form [v]
| _ -> malformed "lazy-seq" (vect args)
and Cons (cont : Continuation) (args : IncValue list) =
match args with
| [h; {value=EvaldExpr(x)}] -> Cons cont [h; x.Value]
| [{value=Nil}; t] -> failwith "fuck me"
| [{value=Symbol(s)} as symb; {value=ExprList(l)}] -> lst(symb :: l) |> cont
| [{value=Symbol(s)} as symb; {value=EvaldSeq(sq)}] -> lst(symb :: (Seq.toList sq)) |> cont
| [h; {value=IncLazy(_)} as t] ->
IncCons({head = h; tail = t}) |> e2v |> cont
| [h; t] ->
evseq (seq {yield h; yield! t.ToSeq()}) |> cont
| _ -> malformed "cons" (vect args)
and IncContains cont args =
match args with
| [{value=EvaldExpr(x)}; t] -> IncContains cont [x.Value; t]
| [h; {value=EvaldExpr(x)}] -> IncContains cont [h; x.Value]
| [h; t] ->
let rslt() =
match h.value with
| ExprVector(v) ->
match t.value with
| Number(n) -> let i = n.ToInt()
i >= 0 && i < v.Length
| _ -> malformed "contains?" (vect args)
| ExprSet(l) -> l.Contains(t)
| EvaldSet(s) -> s.Contains(t)
| EvaldSeq(s) -> s.Contains(t)
| ExprDict(l) -> l |> List.exists (fun (k,v) -> k = t)
| EvaldDict(m) -> m.ContainsKey(t)
| ExprList(l) -> l |> List.exists (fun x -> x = t)
| IncCons(c) ->
if c.head = t then true
else
let s = c.tail.ToSeq()
t.In(s)
| _ -> false //malformed "contains" (vect args)
(if rslt() then incTrue else incFalse) |> cont
| _ -> malformed "contains?" (vect args)
and Count cont args =
match args with
| [{value=EvaldExpr(x)}] -> Count cont [x.Value]
| [x] ->
let s = x.value.Unlazy()
let l = List.length s
Number(Int(l)) |> e2v |> cont
| _ -> malformed "count" (vect args)
and Assoc cont args =
match args with
| [tgt; key; value] ->
match tgt.value with
| EvaldExpr(v) -> Assoc cont [tgt; key; v.Value]
| ExprDict(l) ->
let tl = [for tk,v in l do if tk <> key then yield tk,v]
ExprDict((key,value) :: tl) |> e2v |> cont
| EvaldDict(m) ->
EvaldDict(m.Add(key,value)) |> e2v |> cont
| ExprVector(v) ->
match key.value with
| Number(n) ->
ExprVector(v.assocN(n.ToInt(),value)) |> e2v |> cont
| _ -> failwith "Invalid index for vector"
| _ -> malformed "assoc" (vect args)
| _ -> malformed "assoc" (vect args)
and Conjoin cont args =
match args with
| h :: t ->
let h = match h.value with
| EvaldExpr(h') -> h'.Value
| _ -> h
match h.value with
| ExprVector(v) ->
let mutable vt = v
for x in t do vt <- vt.cons(x)
vec(vt) |> cont
| ExprList(tl) ->
let mutable vt = tl
for x in t do vt <- x :: vt
lst(vt) |> cont
| ExprDict(prs) ->
let rec app acc t =
match t with
| {value=ExprVector(v)} :: t' ->
if v.Length <> 2 then failwith "invalid args to conj for map"
app ( (v.[0],v.[1]) :: acc) t'
| [] -> ExprDict(acc) |> e2v |> cont
| _ -> failwith "invalid args to conj for map"
app prs t
| EvaldDict(m) ->
let rec app (acc : IncMap) t =
match t with
| {value=EvaldExpr(v)} :: t' -> app acc (v.Value :: t')
| {value=ExprVector(v)} :: t' ->
if v.Length <> 2 then failwith "invalid args to conj for map"
app (acc.Add(v.[0],v.[1])) t'
| {value=EvaldDict(m)} :: t' ->
let mutable acc = acc
for kvp in m do acc <- acc.Add(kvp.Key,kvp.Value)
app acc t'
| {value=ExprDict(prs)} :: t' ->
let mutable acc = acc
for k,v in prs do acc <- acc.Add(k,v)
app acc t'
| [] -> EvaldDict(acc) |> e2v |> cont
| _ -> failwith "invalid args to conj for map"
app m t
| EvaldSet(s) ->
let mutable s = s
for x in t do s <- Set.add x s
EvaldSet(s) |> e2v |> cont
| EvaldSeq(s) -> evseq (seq {yield! s; yield! t}) |> cont
| _ -> failwith "not a collection"
| _ -> malformed "conj" (vect args)
and SyntaxQuote (cont : Continuation) env form args =
let symsgend = Dictionary<string,IncValue>()
let rec unquote v : IncValue =
let rec mapunquote acc vs : list<IncValue> =
match vs with
| h :: t ->
match h.value with
| Symbol(s) ->
let v = if s.EndsWith("#") then
if not(symsgend.ContainsKey(s)) then
symsgend.[s] <- Globals.GenSymAuto(s.Substring(0,s.Length - 1))
symsgend.[s]
else
sym(Globals.NSQualify(s))
mapunquote (v :: acc) t
| ExprList([{value=Symbol("splice-unquote")}; e]) ->
let x = eval id env e
let rec splice acc' = function
| h' :: t' ->
splice (h' :: acc') t'
| [] -> mapunquote acc' t
match x with
| {value=EvaldSeq(s)} ->
splice acc (Seq.toList s)
| {value=ExprVector(uqs)} ->
splice acc (uqs.toList())
| {value=ExprList(uqs)} ->
splice acc uqs
| {value=Nil} ->
splice acc []
| _ -> malformed "splice-unquote" e
| _ ->
let x = unquote h
mapunquote (x ::acc) t
| [] -> List.rev acc
match v.value with
| ExprList([{value=Symbol("unquote")}; e]) -> eval id env e
| ExprList(lst) ->
ExprList(mapunquote [] lst) |> e2v
| ExprVector(a) ->
let lst = a.toList()
vect(mapunquote [] lst)
| ExprDict(m) ->
let m' = [for k,v in m -> (unquote k),(unquote v)]
ExprDict(m') |> e2v
| ExprSet(s) ->
ExprSet(mapunquote [] s) |> e2v
| _ -> v
match args with
| [e] -> unquote e |> cont
| _ -> malformed "syntax-quote" (vect args)
and Quote cont env form args =
match args with
| [e] -> cont e
| _ -> malformed "quote" (vect args)
and UnQuote cont env form args =
match args with
| [e] -> eval cont env e
| _ -> malformed "unquote" (vect args)
and Eval cont env form args =
match args with
| [args] -> args |> eval (eval cont env) env
| _ -> malformed "eval" (vect args)
and Assign cont env form args =
match args with
| [{value=Symbol(s)}; v] ->
let x = eval id env v
Globals.setVar(s,x)
x |> cont
| _ -> malformed "set!" (vect args)
and SetValidator cont args =
match args with
| [h; f] ->
let tgt =
match h.value with
| Symbol(s) -> match Globals.GetVar(s) with Some(v) -> v | _ -> failwith ("unable to locate : " + s)
| Ref(_)
| Atom(_)
| Agent(_)
| Var(_) -> h
| _ -> failwith "invalid target for validator"
tgt.validator <- Some(f)
Dummy("validator set") |> e2v |> cont
| _ -> malformed "set-validator!" (vect args)
and SetMacro cont env form args =
match args with
| [{value=Symbol(s)} as sm] ->
sm.SetMacro()
match Globals.GetVar(s) with
| Some(v) ->
v.SetMacro()
match v.value with
| Var(r) -> let _,v = !r in v.SetMacro()
| _ -> failwith "cannot happen"
| _ -> failwith ("Unable to resolve symbol : " + s)
Dummy(":macro set") |> e2v |> cont
| _ -> malformed "set-macro" (vect args)
and Begin cont env form args =
match args with
| [v] -> eval cont env v
| _ ->
let mutable last = incNil
for v in args do last <- eval id env v
last |> cont
and MakeDelay cont env form args =
let body = match args with
| [v] -> v
| _ -> lst(sym("do") :: args)
Delay({body = body; env = env; evald = None}) |> e2v |> cont
and Force cont args =
match args with
| [{value=Delay(d)}] ->
match d.evald with
| Some(v) -> v |> cont
| None ->
let v = eval id d.env d.body
d.evald <- Some(v)
v |> cont
| _ -> malformed "force (not a delay)" (vect args)
and GenSym cont args =
match args with
| [{value=String(prfx)}] -> Globals.GenSym(prfx) |> cont
| [] -> Globals.GenSym() |> cont
| _ -> malformed "gensym" (vect args)
and Get cont args =
match args with
| [coll; k] -> Get cont [coll; k; incNil]
| [coll; k; nf] ->
match coll.value with
| EvaldExpr(x) -> Get cont [x.Value; k; nf]
| ExprDict(_)
| EvaldDict(_) ->
match (Find id [coll; k]).value with
| MapEntry(kvp) -> kvp.Value |> cont
| Nil -> nf |> cont
| _ -> failwith "no way jose"
| Nil -> nf |> cont
| _ -> Nth cont args
| _ -> malformed "get" (vect args)
and GetVar cont (env : Environment) form args =
match args with
| [{value=Symbol(s)} as v] ->
match Globals.GetVar s with
| Some(e) ->
e.metaMap <- v.metaMap
e |> cont
| None -> failwith ("Var not found : " + s )
| _ -> malformed "var" (vect args)
and Deref cont args =
match args with
| [{value=Ref(r)}] ->
readTVar r |> cont
| [{value=Atom(r)}] -> !r |> cont
| [{value=Delay(d)}] -> Force cont args
| _ -> malformed "deref" (vect args)
and DefRef cont args =
match args with
| [v] -> let r = newTVar v
IncValue.OfExpr(Ref(r)) |> cont
| _ -> malformed "ref" (vect args)
and DefAtom cont args =
match args with
| [v] -> let r = ref v
IncValue.OfExpr(Atom(r)) |> cont
| _ -> malformed "atom" (vect args)
and DoSync cont env form vs =
let rec _do l rslt =
match l with
| h :: t ->
let r = eval id env h
_do t r
| [] -> rslt
let rslt =
if inTrans() then _do vs incNil
else
atomically <|
stm {
let r = _do vs incNil
return r
}
rslt |> cont
and Alter cont env form args =
if not(inTrans()) then failwith "No transaction running"
let v,r,t = match args with
| {value=Symbol(s)} as sm :: t ->
let v = Lookup env sm
match v with
| {value=Ref(r)} -> v,r,t
| _ -> failwith ("unable to locate : " + s)
| {value=Ref(r)} :: t -> args.Head,r,t
| _ -> malformed "alter" (vect args)
let oldv = TLog.Current.ReadTVar(r)
let f' = match t with
| f :: t' -> ExprList(f :: oldv :: t') |> e2v
| _ -> malformed "alter" (vect args)
let newv = eval id env f'
TLog.Current.WriteTVar(r, newv)
fireWatchers env v oldv newv
newv |> cont
and DefAgent cont env form (args : IncValue list) =
match args with
| h :: t ->
let init = eval id env h
let agent = new Agent<IncValue>(init)
let v = IncValue.OfExpr(Agent(agent))
let rec parseOptions l =
match l with
| {value=Keyword("meta")} :: m :: t ->
let mutable meta = IncMap.Empty
match m with
| {value=ExprDict(m)} ->
for k,v in m do meta <- meta.Add(k,v)
| {value=EvaldDict(m)} ->
for kvp in m do meta <- meta.Add(kvp.Key,kvp.Value)
| _ -> malformed "meta data" (vect args)
v.metaMap <- Some(meta)
parseOptions t
| {value=Keyword("validator")} :: f :: t ->
let f' = fun v -> eval id env (ExprList([f; v]) |> e2v)
v.validator <- Some(f)
agent.Validator <- fun v -> (f' v).IsTrue
parseOptions t
| {value=Keyword("error-handler")} :: f :: t ->
agent.ErrorHandler <- fun ex -> eval id env (ExprList([f; e2v(Object(ex))]) |> e2v) |> ignore
parseOptions t
| [] -> ()
| _ -> malformed "agent" (vect args)
parseOptions t
agent.Start()
v |> cont
| _ -> malformed "agent" (vect args)
and Send cont env form args =
if not(inTrans()) then failwith "No transaction running"
let a,r,t = match args with