-
Notifications
You must be signed in to change notification settings - Fork 5
/
main.ml
2998 lines (2942 loc) · 110 KB
/
main.ml
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
open Printf
module HashMap = struct
type ('a, 'b) t = ('a * 'b) list
let empty = []
let add k v m = (k, v) :: m
let rec find k = function
| (k', v') :: xs -> if k = k' then v' else find k xs
| [] -> raise Not_found
let mem k m =
try
ignore (find k m) ;
true
with Not_found -> false
let merge f m1 m2 =
let src = ref empty in
let rec iter_m1 = function
| (k, v) :: xs ->
( try src := add k (Some v, Some (find k m2)) !src
with Not_found -> src := add k (Some v, None) !src ) ;
iter_m1 xs
| [] -> ()
in
let rec iter_m2 = function
| (k, v) :: xs ->
if not (mem k m1) then src := add k (None, Some v) !src ;
iter_m2 xs
| [] -> ()
in
iter_m1 m1 ;
iter_m2 m2 ;
List.fold_left
(fun m (k, (l, r)) ->
match f k l r with None -> m | Some v -> add k v m )
empty !src
let union f m1 m2 =
merge
(fun k l r ->
match (l, r) with
| None, None -> None
| Some v, None -> l
| None, Some v -> r
| Some v1, Some v2 -> f k v1 v2 )
m1 m2
let cardinal m = List.length m
end
module Hashtbl = struct
type ('a, 'b) t = ('a, 'b) HashMap.t ref
let create size_hint = ref HashMap.empty
let add tbl k v = tbl := HashMap.add k v !tbl
let mem tbl k = HashMap.mem k !tbl
let find tbl k = HashMap.find k !tbl
let length tbl = HashMap.cardinal !tbl
end
let filter_after_map f lst =
List.map (function Some x -> x | None -> failwith "invalid op")
@@ List.filter (function Some x -> true | None -> false)
@@ List.map f lst
let rec list_unique lst =
let set = Hashtbl.create @@ List.length lst in
let rec aux res = function
| [] -> res
| x :: xs ->
if Hashtbl.mem set x then aux res xs
else (
Hashtbl.add set x () ;
aux (x :: res) xs )
in
aux [] lst
let is_capital = function 'A' .. 'Z' -> true | _ -> false
let is_lower = function 'a' .. 'z' -> true | _ -> false
let is_digit = function '0' .. '9' -> true | _ -> false
let is_ident_char = function
| 'a' .. 'z' | 'A' .. 'Z' | '0' .. '9' | '\'' | '_' -> true
| _ -> false
let string_of_list src = "[" ^ String.concat "; " src ^ "]"
let hashmap_of_list src =
let hashmap = ref HashMap.empty in
List.iter (fun (k, v) -> hashmap := HashMap.add k v !hashmap) src ;
!hashmap
let integrate od nw = HashMap.union (fun _ _ r -> Some r) od nw
let read_lines () =
let rec aux lines =
try
let line = read_line () in
aux (line :: lines)
with End_of_file -> lines
in
String.concat "\n" (List.rev (aux []))
let appfmt buf fmt =
ksprintf (fun str -> Buffer.add_string buf (str ^ "\n")) fmt
let appstr buf str = Buffer.add_string buf (str ^ "\n")
let escape_string str =
let buf = Buffer.create (String.length str) in
let rec aux i =
if i < String.length str then (
( match str.[i] with
| '\n' -> Buffer.add_string buf "\\n"
| '\r' -> Buffer.add_string buf "\\r"
| '\t' -> Buffer.add_string buf "\\t"
| '\\' -> Buffer.add_string buf "\\\\"
| '"' -> Buffer.add_string buf "\\\""
| ch -> Buffer.add_char buf ch ) ;
aux (i + 1) )
in
aux 0 ; Buffer.contents buf
let digit x =
match x with
| '0' .. '9' -> int_of_char x - int_of_char '0'
| _ -> failwith "unexpected char: not digit"
let id_counter = ref 0
let make_id base =
id_counter := !id_counter + 1 ;
sprintf "%s.%d" base !id_counter
let make_label () = make_id ".L"
type token =
| IntLiteral of int
| CharLiteral of char
| StringLiteral of string * string
| Plus
| Minus
| Star
| Slash
| CapitalIdent of string
| LowerIdent of string
| CapitalIdentWithModule of string
| LowerIdentWithModule of string
| LParen
| RParen
| LRParen
| Let
| Equal
| In
| Rec
| If
| Then
| Else
| LT
| GT
| LTGT
| Comma
| LBracket
| RBracket
| LRBracket
| ColonColon
| Semicolon
| SemicolonSemicolon
| Match
| With
| Arrow
| Pipe
| Fun
| Function
| As
| When
| Type
| Dot
| DotDot
| Of
| KwInt
| KwChar
| KwUnit
| KwBool
| KwString
| Apostrophe
| And
| Hat
| Naruto
| ColonEqual
| Exclam
| Try
| Exception
| Mod
| Lsl
| Lsr
| Asr
| DotLBracket
| Colon
| LBrace
| RBrace
| Module
| Struct
| End
| NarutoNaruto
| External
| LArrow
| Mutable
| Open
| PipePipe
| AndAnd
| Ampersand
| Lor
| Land
| For
| To
| Downto
| Do
| Done
| PipeGT
let string_of_token = function
| IntLiteral num -> string_of_int num
| CharLiteral ch -> "'" ^ String.make 1 ch ^ "'"
| StringLiteral (_, str) -> "\"" ^ str ^ "\""
| Plus -> "+"
| Minus -> "-"
| Star -> "*"
| Slash -> "/"
| CapitalIdent str
|LowerIdent str
|CapitalIdentWithModule str
|LowerIdentWithModule str ->
str
| LParen -> "("
| RParen -> ")"
| LRParen -> "()"
| Let -> "let"
| Equal -> "="
| In -> "in"
| Rec -> "rec"
| If -> "if"
| Then -> "then"
| Else -> "else"
| LT -> "<"
| GT -> ">"
| LTGT -> "<>"
| Comma -> ","
| LBracket -> "["
| RBracket -> "]"
| LRBracket -> "[]"
| ColonColon -> "::"
| Semicolon -> ";"
| SemicolonSemicolon -> ";;"
| Match -> "match"
| With -> "with"
| Arrow -> "->"
| Pipe -> "|"
| Fun -> "fun"
| Function -> "function"
| As -> "as"
| When -> "when"
| Type -> "type"
| Dot -> "."
| DotDot -> ".."
| Of -> "of"
| KwInt -> "int"
| KwChar -> "char"
| KwUnit -> "unit"
| KwBool -> "bool"
| KwString -> "string"
| Apostrophe -> "'"
| And -> "and"
| Hat -> "^"
| Naruto -> "@"
| ColonEqual -> ":="
| Exclam -> "!"
| Try -> "try"
| Exception -> "exception"
| Mod -> "mod"
| Lsl -> "lsl"
| Lsr -> "lsr"
| Asr -> "asr"
| DotLBracket -> ".["
| Colon -> ":"
| LBrace -> "{"
| RBrace -> "}"
| Module -> "module"
| Struct -> "struct"
| End -> "end"
| NarutoNaruto -> "@@"
| External -> "external"
| LArrow -> "<-"
| Mutable -> "mutable"
| Open -> "open"
| PipePipe -> "||"
| AndAnd -> "&&"
| Ampersand -> "&"
| Lor -> "lor"
| Land -> "land"
| For -> "for"
| To -> "to"
| Downto -> "downto"
| Do -> "do"
| Done -> "done"
| PipeGT -> "|>"
let raise_unexpected_token = function
| x :: _ ->
raise @@ failwith @@ sprintf "Unexpected token: %s" @@ string_of_token x
| [] -> failwith "Unexpected EOF"
exception EOF
let tokenize program =
let rec aux acc i =
let next_char i =
if i < String.length program then (i + 1, program.[i]) else raise EOF
in
let maybe_next_char i =
try
let i, ch = next_char i in
(i, Some ch)
with EOF -> (i + 1, None)
in
let rec next_int i acc =
match maybe_next_char i with
| _, None -> (i, acc)
| i, Some ch when is_digit ch -> next_int i ((acc * 10) + digit ch)
| i, Some _ -> (i - 1, acc)
in
let next_ident i =
let buf = Buffer.create 5 in
let rec aux i =
match maybe_next_char i with
| _, None -> (i, Buffer.contents buf)
| i, Some ch when is_ident_char ch -> Buffer.add_char buf ch ; aux i
| i, Some _ -> (i - 1, Buffer.contents buf)
in
aux i
in
let next_char_literal i =
let i, ch = next_char i in
match ch with
| '\\' -> (
let i, ch = next_char i in
( i + 1
, match ch with
| 'n' -> '\n'
| 'r' -> '\r'
| 't' -> '\t'
| '\\' -> '\\'
| '"' -> '"'
| '\'' -> '\''
| _ -> failwith @@ sprintf "unexpected char in char literal: %c" ch
) )
| ch -> (i + 1, ch)
in
let next_string_literal i =
let buf = Buffer.create 16 in
let rec aux i =
let i, ch = next_char i in
match ch with
| '"' -> (i, Buffer.contents buf)
| '\\' -> (
let i, ch = next_char i in
match ch with
| 'n' -> Buffer.add_char buf '\n' ; aux i
| 't' -> Buffer.add_char buf '\t' ; aux i
| '\\' -> Buffer.add_char buf '\\' ; aux i
| '"' -> Buffer.add_char buf '"' ; aux i
| '\n' ->
(* string chained with backslash *)
let rec skip_space_and_tab i =
let i, ch = next_char i in
match ch with
| ' ' | '\t' -> skip_space_and_tab i
| _ -> i - 1
in
aux @@ skip_space_and_tab i
| ch ->
Buffer.add_char buf '\\' ;
aux (i - 1) )
| _ -> Buffer.add_char buf ch ; aux i
in
aux i
in
let skip_comment i =
let rec aux i depth =
let i, ch = next_char i in
match ch with
| '(' -> (
let i, ch = next_char i in
match ch with '*' -> aux i (depth + 1) | _ -> aux (i - 1) depth )
| '*' -> (
let i, ch = next_char i in
match ch with
| ')' -> if depth = 1 then i else aux i (depth - 1)
| _ -> aux (i - 1) depth )
| _ -> aux i depth
in
aux i 1
in
let switch_char i default tbl =
match maybe_next_char i with
| _, None -> aux (default :: acc) i
| i, Some ch ->
let i, token =
try
let _, token = List.find (fun (x, _) -> x = ch) tbl in
(i, token)
with Not_found -> (i - 1, default)
in
aux (token :: acc) i
in
match maybe_next_char i with
| _, None -> List.rev acc
| i, Some ch -> (
match ch with
| ' ' | '\t' | '\n' | '\r' -> aux acc i
| '0' .. '9' ->
let i, num = next_int (i - 1) 0 in
aux (IntLiteral num :: acc) i
| '\'' -> (
let _, ch0 = next_char i in
let _, ch1 = next_char (i + 1) in
match (ch0, ch1) with
| _, '\'' | '\\', _ ->
let i, ch = next_char_literal i in
aux (CharLiteral ch :: acc) i
| _ -> aux (Apostrophe :: acc) i )
| '"' ->
let i, str = next_string_literal i in
aux (StringLiteral (make_id "string", str) :: acc) i
| 'a' .. 'z' | 'A' .. 'Z' | '_' -> (
let i, str = next_ident (i - 1) in
match str with
| "let" -> aux (Let :: acc) i
| "in" -> aux (In :: acc) i
| "rec" -> aux (Rec :: acc) i
| "true" -> aux (IntLiteral 1 :: acc) i (* TODO: boolean type *)
| "false" -> aux (IntLiteral 0 :: acc) i
| "if" -> aux (If :: acc) i
| "then" -> aux (Then :: acc) i
| "else" -> aux (Else :: acc) i
| "match" -> aux (Match :: acc) i
| "with" -> aux (With :: acc) i
| "fun" -> aux (Fun :: acc) i
| "function" -> aux (Function :: acc) i
| "as" -> aux (As :: acc) i
| "when" -> aux (When :: acc) i
| "type" -> aux (Type :: acc) i
| "of" -> aux (Of :: acc) i
| "int" -> aux (KwInt :: acc) i
| "char" -> aux (KwChar :: acc) i
| "unit" -> aux (KwUnit :: acc) i
| "bool" -> aux (KwBool :: acc) i
| "string" -> aux (KwString :: acc) i
| "and" -> aux (And :: acc) i
| "try" -> aux (Try :: acc) i
| "exception" -> aux (Exception :: acc) i
| "mod" -> aux (Mod :: acc) i
| "lsl" -> aux (Lsl :: acc) i
| "lsr" -> aux (Lsr :: acc) i
| "asr" -> aux (Asr :: acc) i
| "module" -> aux (Module :: acc) i
| "struct" -> aux (Struct :: acc) i
| "end" -> aux (End :: acc) i
| "external" -> aux (External :: acc) i
| "mutable" -> aux (Mutable :: acc) i
| "open" -> aux (Open :: acc) i
| "land" -> aux (Land :: acc) i
| "lor" -> aux (Lor :: acc) i
| "for" -> aux (For :: acc) i
| "to" -> aux (To :: acc) i
| "downto" -> aux (Downto :: acc) i
| "do" -> aux (Do :: acc) i
| "done" -> aux (Done :: acc) i
| _ when is_capital str.[0] ->
let rec aux' i cap acc =
match maybe_next_char i with
| i, Some '.' ->
let i, str = next_ident i in
aux' i (is_capital str.[0]) (str :: acc)
| i, _ -> (
let str = String.concat "." @@ List.rev acc in
( i - 1
, match (cap, List.length acc > 1) with
| false, false -> LowerIdent str
| false, true -> LowerIdentWithModule str
| true, false -> CapitalIdent str
| true, true -> CapitalIdentWithModule str ) )
in
let i, tk = aux' i true [str] in
aux (tk :: acc) i
| _ -> aux (LowerIdent str :: acc) i )
| '+' -> aux (Plus :: acc) i
| '*' -> aux (Star :: acc) i
| '/' -> aux (Slash :: acc) i
| ')' -> aux (RParen :: acc) i
| '>' -> aux (GT :: acc) i
| '=' -> aux (Equal :: acc) i
| ',' -> aux (Comma :: acc) i
| ']' -> aux (RBracket :: acc) i
| '^' -> aux (Hat :: acc) i
| '!' -> aux (Exclam :: acc) i
| '{' -> aux (LBrace :: acc) i
| '}' -> aux (RBrace :: acc) i
| '|' -> switch_char i Pipe [('|', PipePipe); ('>', PipeGT)]
| '&' -> switch_char i Ampersand [('&', AndAnd)]
| '@' -> switch_char i Naruto [('@', NarutoNaruto)]
| '.' -> switch_char i Dot [('.', DotDot); ('[', DotLBracket)]
| '-' -> switch_char i Minus [('>', Arrow)]
| '<' -> switch_char i LT [('>', LTGT); ('-', LArrow)]
| '[' -> switch_char i LBracket [(']', LRBracket)]
| ':' -> switch_char i Colon [(':', ColonColon); ('=', ColonEqual)]
| ';' -> switch_char i Semicolon [(';', SemicolonSemicolon)]
| '(' -> (
match maybe_next_char i with
| i, Some '*' ->
let i = skip_comment i in
aux acc i
| i, Some ')' -> aux (LRParen :: acc) i
| _, (Some _ | None) -> aux (LParen :: acc) i )
| _ -> failwith (sprintf "unexpected char: '%c'" ch) )
in
aux [] 0
type typ =
| TyInt
| TyChar
| TyUnit
| TyBool
| TyString
| TyTuple of typ list
| TyCustom of string
| TyVar of string
| TyCtorApp of typ * string
| TyArgs of typ list
| TyFunc of typ * typ
type ast =
| UnitValue
| IntValue of int
| CharValue of char
| StringValue of string * string
| TupleValue of ast list
| RecordValue of string option * (string * ast) list
| RecordValueWith of ast * (string * ast) list
| RecordDotAccess of string option * ast * string
| Add of ast * ast
| Sub of ast * ast
| Mul of ast * ast
| Div of ast * ast
| Rem of ast * ast
| LogicalLeftShift of ast * ast
| LogicalRightShift of ast * ast
| ArithmeticRightShift of ast * ast
| LogicalAnd of ast * ast
| LogicalOr of ast * ast
| BitwiseAnd of ast * ast
| BitwiseOr of ast * ast
| StringConcat of ast * ast
| ListConcat of ast * ast
| Negate of ast
| Positate of ast
| StructEqual of (ast * ast)
| StructInequal of (ast * ast)
| LessThan of (ast * ast)
| LessThanEqual of (ast * ast)
| IfThenElse of (ast * ast * ast option)
| Var of string
| FuncVar of string * int
| AppCls of (ast * ast list)
| AppDir of (string * ast list)
| LetAnd of (bool * (pattern list * ast) list * ast option)
| LetVar of (bool * pattern * ast)
(* recursive?, funcname, args, function body, free variables *)
| LetFunc of (bool * string * pattern list * ast * string list)
| LetAndAnalyzed of ast list * ast
| Cons of (ast * ast)
| EmptyList
| ExprSeq of ast list
| MatchWith of ast * (pattern * ast option * ast) list
| MakeCls of string * int * string list
| Lambda of pattern list * ast
| TypeAnd of typedef list
| CtorApp of string option * string * ast option
| RefAssign of ast * ast
| RecordAssign of string option * ast * string * ast
| Deref of ast
| ExpDef of string * typ option
| TryWith of ast * (pattern * ast option * ast) list
| StringGet of ast * ast
| StringSet of ast * ast * ast
| ForLoop of for_loop_dir * string * ast * ast * ast
| Nope
| ModuleDef of string * ast list
(* for analysis *)
| ModuleDefEnd
| ExternalDecl of string * typ * string
| OpenModuleDef of string
(* TODO: module Ptn *)
| PtnOr of pattern * pattern
| PtnAlias of pattern * ast
| PtnRange of char * char
and pattern = ast
and typedef =
| DefVariant of typ option * string * (string * typ option) list
| DefTypeAlias of typ option * string * typ
| DefRecord of string * (string * typ) list
and for_loop_dir = ForTo | ForDownto
exception Unexpected_ast
let rec varnames_in_pattern = function
(* TODO: much faster algorithm? *)
| UnitValue | IntValue _ | CharValue _ | StringValue _ | EmptyList
|PtnRange _ ->
[]
| Var varname -> [varname]
| Cons (car, cdr) ->
List.rev_append (varnames_in_pattern car) (varnames_in_pattern cdr)
| TupleValue values ->
List.fold_left
(fun a b -> List.rev_append a (varnames_in_pattern b))
[] values
| CtorApp (_, _, None) -> []
| CtorApp (_, _, Some arg) -> varnames_in_pattern arg
| PtnOr (lhs, rhs) ->
List.rev_append (varnames_in_pattern lhs) (varnames_in_pattern rhs)
| PtnAlias (ptn, Var name) -> name :: varnames_in_pattern ptn
| _ -> raise Unexpected_ast
let parse tokens =
let is_primary = function
| ( IntLiteral _ | CharLiteral _ | StringLiteral _ | LowerIdent _
| LowerIdentWithModule _ | CapitalIdent _ | CapitalIdentWithModule _
| LRBracket | NarutoNaruto | LParen | LBracket | LRParen | LBrace )
:: _ ->
true
| _ -> false
in
let is_dot = function (Dot | DotLBracket) :: _ -> true | _ -> false in
let is_prefix = function Exclam :: _ -> true | _ -> false in
let is_let = function
| (Function | Fun | Match | Try | Let) :: _ -> true
| _ -> false
in
let is_if = function If :: _ -> true | _ -> false in
let rec parse_primary = function
| IntLiteral num :: tokens -> (tokens, IntValue num)
| CharLiteral ch :: tokens -> (tokens, CharValue ch)
| StringLiteral (id, str) :: tokens -> (tokens, StringValue (id, str))
| LRParen :: tokens -> (tokens, UnitValue)
| (LowerIdentWithModule varname | LowerIdent varname) :: tokens ->
(tokens, Var varname)
| (CapitalIdentWithModule ctorname | CapitalIdent ctorname) :: tokens ->
(tokens, CtorApp (None, ctorname, None))
| LRBracket :: tokens -> (tokens, EmptyList)
| NarutoNaruto :: tokens -> parse_let tokens
| LParen :: tokens -> (
let tokens, ast = parse_expression tokens in
match tokens with
| RParen :: tokens -> (tokens, ast)
| x -> raise_unexpected_token x )
| LBracket :: tokens ->
let rec aux = function
| Semicolon :: tokens ->
let tokens, car = parse_let tokens in
let tokens, cdr = aux tokens in
(tokens, Cons (car, cdr))
| RBracket :: tokens -> (tokens, EmptyList)
| x -> raise_unexpected_token x
in
let tokens, car = parse_let tokens in
let tokens, cdr = aux tokens in
(tokens, Cons (car, cdr))
| LBrace :: tokens -> (
let rec parse_record_fields first fields tokens =
let aux fieldname = function
| Equal :: tokens -> parse_let tokens
| (Semicolon | RBrace) :: _ as tokens -> (tokens, Var fieldname)
| x -> raise_unexpected_token x
in
match tokens with
| (LowerIdent fieldname | LowerIdentWithModule fieldname) :: tokens
when first ->
let tokens, ast = aux fieldname tokens in
parse_record_fields false ((fieldname, ast) :: fields) tokens
| Semicolon
:: (LowerIdent fieldname | LowerIdentWithModule fieldname)
:: tokens
when not first ->
let tokens, ast = aux fieldname tokens in
parse_record_fields false ((fieldname, ast) :: fields) tokens
| RBrace :: tokens -> (tokens, fields)
| x -> raise_unexpected_token x
in
match tokens with
| (LowerIdent _ | LowerIdentWithModule _) :: (Equal | Semicolon) :: _
->
let tokens, fields = parse_record_fields true [] tokens in
(tokens, RecordValue (None, fields))
| _ -> (
let tokens, base = parse_prefix tokens in
match tokens with
| With :: tokens ->
let tokens, fields = parse_record_fields true [] tokens in
(tokens, RecordValueWith (base, fields))
| x -> raise_unexpected_token x ) )
| x -> raise_unexpected_token x
and parse_prefix = function
| Exclam :: tokens ->
let tokens, ast = parse_primary tokens in
(tokens, Deref ast)
| tokens -> parse_primary tokens
and parse_dot tokens =
let tokens, lhs = parse_prefix tokens in
match tokens with
| Dot :: LowerIdent fieldname :: tokens ->
(tokens, RecordDotAccess (None, lhs, fieldname))
| DotLBracket :: tokens -> (
let tokens, rhs = parse_expression tokens in
match tokens with
| RBracket :: tokens -> (tokens, StringGet (lhs, rhs))
| x -> raise_unexpected_token x )
| _ -> (tokens, lhs)
and parse_funccall tokens =
let rec aux tokens =
if is_primary tokens || is_dot tokens || is_prefix tokens then
let tokens, arg = parse_dot tokens in
let tokens, args = aux tokens in
(tokens, arg :: args)
else (tokens, [])
in
let tokens, func = parse_dot tokens in
let tokens, args = aux tokens in
if args = [] then (tokens, func) (* not function call *)
else (tokens, AppCls (func, args))
and parse_unary = function
| Minus :: tokens ->
let tokens, ast = parse_unary tokens in
(tokens, Negate ast)
| Plus :: tokens ->
let tokens, ast = parse_unary tokens in
(tokens, Positate ast)
| tokens -> parse_funccall tokens
and parse_shift tokens =
let rec aux lhs = function
| Lsl :: tokens ->
let tokens, rhs = parse_unary tokens in
aux (LogicalLeftShift (lhs, rhs)) tokens
| Lsr :: tokens ->
let tokens, rhs = parse_unary tokens in
aux (LogicalRightShift (lhs, rhs)) tokens
| Asr :: tokens ->
let tokens, rhs = parse_unary tokens in
aux (ArithmeticRightShift (lhs, rhs)) tokens
| tokens -> (tokens, lhs)
in
let tokens, lhs = parse_unary tokens in
aux lhs tokens
and parse_multiplicative tokens =
let rec aux lhs = function
| Star :: tokens ->
let tokens, rhs = parse_shift tokens in
aux (Mul (lhs, rhs)) tokens
| Slash :: tokens ->
let tokens, rhs = parse_shift tokens in
aux (Div (lhs, rhs)) tokens
| Mod :: tokens ->
let tokens, rhs = parse_shift tokens in
aux (Rem (lhs, rhs)) tokens
| Land :: tokens ->
let tokens, rhs = parse_shift tokens in
aux (BitwiseAnd (lhs, rhs)) tokens
| Lor :: tokens ->
let tokens, rhs = parse_shift tokens in
aux (BitwiseOr (lhs, rhs)) tokens
| tokens -> (tokens, lhs)
in
let tokens, ast = parse_shift tokens in
aux ast tokens
and parse_additive tokens =
let rec aux lhs tokens =
match tokens with
| Plus :: tokens ->
let tokens, rhs = parse_multiplicative tokens in
aux (Add (lhs, rhs)) tokens
| Minus :: tokens ->
let tokens, rhs = parse_multiplicative tokens in
aux (Sub (lhs, rhs)) tokens
| _ -> (tokens, lhs)
in
let tokens, ast = parse_multiplicative tokens in
aux ast tokens
and parse_cons tokens =
let tokens, car = parse_additive tokens in
match tokens with
| ColonColon :: tokens ->
let tokens, cdr = parse_cons tokens in
(tokens, Cons (car, cdr))
| _ -> (tokens, car)
and parse_string_concat tokens =
let rec aux lhs tokens =
match tokens with
| Hat :: tokens ->
let tokens, rhs = parse_cons tokens in
aux (StringConcat (lhs, rhs)) tokens
| Naruto :: tokens ->
let tokens, rhs = parse_cons tokens in
aux (ListConcat (lhs, rhs)) tokens
| _ -> (tokens, lhs)
in
let tokens, ast = parse_cons tokens in
aux ast tokens
and parse_structural_equal tokens =
let rec aux lhs tokens =
match tokens with
| Equal :: tokens ->
let tokens, rhs = parse_string_concat tokens in
aux (StructEqual (lhs, rhs)) tokens
| LTGT :: tokens ->
let tokens, rhs = parse_string_concat tokens in
aux (StructInequal (lhs, rhs)) tokens
| LT :: Equal :: tokens ->
let tokens, rhs = parse_string_concat tokens in
aux (LessThanEqual (lhs, rhs)) tokens
| GT :: Equal :: tokens ->
let tokens, rhs = parse_string_concat tokens in
aux (LessThanEqual (rhs, lhs)) tokens
| LT :: tokens ->
let tokens, rhs = parse_string_concat tokens in
aux (LessThan (lhs, rhs)) tokens
| GT :: tokens ->
let tokens, rhs = parse_string_concat tokens in
aux (LessThan (rhs, lhs)) tokens
| PipeGT :: tokens ->
let tokens, rhs = parse_string_concat tokens in
aux
( match rhs with
| AppCls (func, args) ->
AppCls (func, List.rev (lhs :: List.rev args))
| _ -> AppCls (rhs, [lhs]) )
tokens
| _ -> (tokens, lhs)
in
let tokens, ast = parse_string_concat tokens in
aux ast tokens
and parse_logical_and tokens =
let rec aux lhs = function
| AndAnd :: tokens ->
let tokens, rhs = parse_structural_equal tokens in
aux (LogicalAnd (lhs, rhs)) tokens
| tokens -> (tokens, lhs)
in
let tokens, ast = parse_structural_equal tokens in
aux ast tokens
and parse_logical_or tokens =
let rec aux lhs = function
| PipePipe :: tokens ->
let tokens, rhs = parse_logical_and tokens in
aux (LogicalOr (lhs, rhs)) tokens
| tokens -> (tokens, lhs)
in
let tokens, ast = parse_logical_and tokens in
aux ast tokens
and parse_tuple tokens =
let rec aux lhs tokens =
match tokens with
| Comma :: tokens ->
let tokens, rhs =
if is_let tokens || is_if tokens then parse_let tokens
else parse_logical_or tokens
in
aux (rhs :: lhs) tokens
| _ -> (tokens, lhs)
in
let tokens, ast = parse_logical_or tokens in
let tokens, ast_list = aux [ast] tokens in
match ast_list with
| [] -> raise_unexpected_token []
| [ast] -> (tokens, ast)
| asts -> (tokens, TupleValue (List.rev asts))
and parse_assignment tokens =
let tokens, lhs = parse_tuple tokens in
match tokens with
| ColonEqual :: tokens ->
let tokens, rhs = parse_let tokens in
(tokens, RefAssign (lhs, rhs))
| LArrow :: tokens -> (
let tokens, rhs = parse_let tokens in
match lhs with
| StringGet (str, idx) -> (tokens, StringSet (str, idx, rhs))
| RecordDotAccess (None, lhs, fieldname) ->
(tokens, RecordAssign (None, lhs, fieldname, rhs))
| _ -> raise_unexpected_token tokens )
| _ -> (tokens, lhs)
and parse_if = function
| If :: tokens -> (
let tokens, cond = parse_expression tokens in
match tokens with
| Then :: tokens -> (
let tokens, then_body = parse_let tokens in
match tokens with
| Else :: tokens ->
let tokens, else_body = parse_let tokens in
(tokens, IfThenElse (cond, then_body, Some else_body))
| _ -> (tokens, IfThenElse (cond, then_body, None)) )
| x -> raise_unexpected_token x )
| tokens -> parse_assignment tokens
and parse_pattern_match tokens =
let rec aux first cases tokens =
let aux' tokens =
let tokens, ptn = parse_pattern tokens in
let tokens, whn =
match tokens with
| When :: tokens ->
let tokens, expr = parse_expression tokens in
(tokens, Some expr)
| _ -> (tokens, None)
in
match tokens with
| Arrow :: tokens ->
let tokens, case = parse_expression tokens in
let tokens, cases = aux false ((ptn, whn, case) :: cases) tokens in
(tokens, cases)
| x -> raise_unexpected_token x
in
match tokens with
| Pipe :: tokens -> aux' tokens
| _ -> if first then aux' tokens else (tokens, List.rev cases)
in
aux true [] tokens
and parse_let = function
| Function :: tokens ->
let argname = ".arg" in
let tokens, cases = parse_pattern_match tokens in
(tokens, Lambda ([Var argname], MatchWith (Var argname, cases)))
| Fun :: tokens ->
let rec aux = function
| Arrow :: tokens -> (tokens, [])
| tokens ->
let tokens, arg = parse_pattern tokens in
let tokens, args = aux tokens in
(tokens, arg :: args)
in
let tokens, args = aux tokens in
let tokens, func = parse_expression tokens in
(tokens, Lambda (args, func))
| Match :: tokens -> (
let tokens, cond = parse_expression tokens in
match tokens with
| With :: tokens ->
let tokens, cases = parse_pattern_match tokens in
(tokens, MatchWith (cond, cases))
| x -> raise_unexpected_token x )
| Try :: tokens -> (
let tokens, cond = parse_expression tokens in
match tokens with
| With :: tokens ->
let tokens, cases = parse_pattern_match tokens in
(tokens, TryWith (cond, cases))
| x -> raise_unexpected_token x )
| For :: LowerIdent indexname :: Equal :: tokens -> (
let tokens, expr1 = parse_expression tokens in
match tokens with
| ((To | Downto) as dir) :: tokens -> (
let tokens, expr2 = parse_expression tokens in
match tokens with
| Do :: tokens -> (
let tokens, expr3 = parse_expression tokens in
match tokens with
| Done :: tokens ->
( tokens
, ForLoop
( (if dir = To then ForTo else ForDownto)
, indexname
, expr1
, expr2
, expr3 ) )
| x -> raise_unexpected_token x )
| x -> raise_unexpected_token x )
| x -> raise_unexpected_token x )
| Let :: tokens -> (
let parse_let_binding tokens =