-
Notifications
You must be signed in to change notification settings - Fork 9
/
Parser.fx
1734 lines (1639 loc) · 69.3 KB
/
Parser.fx
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
/*
This file is a part of ficus language project.
See ficus/LICENSE for the licensing terms
*/
// Ficus recursive descent parser
import File, Map, Sys
from Ast import *
from Lexer import *
exception ParseError: (loc_t, string)
type parser_ctx_t =
{
module_id: id_t;
filename: string;
deps: id_t list;
inc_dirs: string list;
default_loc: loc_t;
}
var parser_ctx = parser_ctx_t { module_id=noid, filename="", deps=[], inc_dirs=[], default_loc=noloc }
fun add_to_imported_modules(mname_id: id_t, loc: loc_t): id_t {
val mname = pp_id2str(mname_id)
val mfname = mname.replace(".", Filename.dir_sep()) + ".fx"
val mfname =
try Sys.locate_file(mfname, parser_ctx.inc_dirs)
catch {
| NotFoundError => throw ParseError(loc, f"module {mname} is not found")
}
val dep_minfo = find_module(mname_id, mfname)
val mname_unique_id = dep_minfo->dm_name
if !parser_ctx.deps.mem(mname_unique_id) {
parser_ctx.deps = mname_unique_id :: parser_ctx.deps
}
mname_unique_id
}
type kw_mode_t = KwNone | KwMaybe | KwMust
type tklist_t = (token_t, loc_t) list
type elist_t = exp_t list
type id_exp_t = (id_t, exp_t)
type id_elist_t = id_exp_t list
fun good_variant_name(s: string) {
val c = s[0]
('A' <= c <= 'Z') || s.contains('.')
}
fun tok2str(ts: (token_t, loc_t) list) =
" ".join([: for (t, _) <- ts {tok2str(t).0} :])
fun make_unary(uop: unary_t, e: exp_t, loc: loc_t) = ExpUnary(uop, e, make_new_ctx(loc))
fun make_binary(bop: binary_t, e1: exp_t, e2: exp_t, loc: loc_t) = ExpBinary(bop, e1, e2, make_new_ctx(loc))
fun make_literal(lit: lit_t, loc: loc_t) = ExpLit(lit, (get_lit_typ(lit), loc))
fun make_ident(i: id_t, loc: loc_t) = ExpIdent(i, make_new_ctx(loc))
fun make_ident(s: string, loc: loc_t) = ExpIdent(get_id(s), make_new_ctx(loc))
fun make_tuple(el: exp_t list, loc: loc_t) = ExpMkTuple(el, make_new_ctx(loc))
fun get_string(lit: lit_t, loc: loc_t): string =
match lit {
| LitString(s) => s
| _ => throw ParseError(loc, "string literal is expected")
}
fun plist2exp(pl: pat_t list, prefix: string, loc: loc_t): (pat_t list, exp_t)
{
fun pat2exp_(p: pat_t): (pat_t, exp_t)
{
| PatAny(loc) =>
val param_id = gen_temp_id(prefix)
(PatIdent(param_id, loc), make_ident(param_id, loc))
| PatIdent(i, loc) => (p, make_ident(i, loc))
| PatAs(p, i, loc) => (p, make_ident(i, loc))
| PatTyped(p, t, loc) =>
val (p, e) = pat2exp_(p)
(PatTyped(p, t, loc), e)
| _ =>
val loc = get_pat_loc(p)
val param_id = gen_temp_id(prefix)
(PatAs(p, param_id, loc), make_ident(param_id, loc))
}
val fold (plist, elist) = ([], []) for p <- pl {
val (p_, e_) = pat2exp_(p)
(p_ :: plist, e_ :: elist)
}
(plist.rev(), match elist { | e :: [] => e | _ => ExpMkTuple(elist.rev(), make_new_ctx(loc)) })
}
type for_data_t = ((pat_t, exp_t) list, pat_t, for_flags_t, loc_t)
fun transform_fold_exp(special: string, fold_pat: pat_t, fold_init_exp: exp_t, for_exp: exp_t, for_iter_exp: exp_t, fold_loc: loc_t)
{
fun unpack_for_(e: exp_t, result: for_data_t list): (for_data_t list, exp_t) =
match e {
| ExpFor(pe_l, idxp, body, flags, loc)
when result.empty() || flags.for_flag_nested =>
unpack_for_(body, (pe_l, idxp, flags, loc) :: result)
| _ => (result, e)
}
val acc_loc = get_pat_loc(fold_pat)
val fr_id = __fold_result_id__
val fr_exp = make_ident(fr_id, acc_loc)
val (nested_fors, fold_body) = unpack_for_(for_exp, [])
val body_loc = get_exp_loc(fold_body)
val body_end_loc = get_end_loc(body_loc)
val void_ctx = (TypVoid, body_loc)
val bool_ctx = (TypBool, body_loc)
val (fr_decl, new_body, fr_exp) =
match special {
| "" =>
val fr_decl = DefVal(PatIdent(fr_id, acc_loc), fold_init_exp, default_var_flags(), acc_loc)
val acc_decl = DefVal(fold_pat, fr_exp, default_tempval_flags(), acc_loc)
val update_fr = ExpAssign(fr_exp, fold_body, body_loc)
val new_body = ExpSeq([: acc_decl, update_fr :], void_ctx)
(fr_decl, new_body, fr_exp)
| "all" | "exists" =>
val is_all = special == "all"
val fr_decl = DefVal(PatIdent(fr_id, acc_loc), ExpLit(LitBool(is_all),
(TypBool, acc_loc)), default_var_flags(), acc_loc)
val break_exp = ExpSeq([: ExpAssign(fr_exp, ExpLit(LitBool(!is_all), bool_ctx), body_loc),
ExpBreak(true, body_loc) :], void_ctx)
val predicate_exp = if !is_all { fold_body }
else { ExpUnary(OpLogicNot, fold_body, bool_ctx) }
val new_body = ExpIf(predicate_exp, break_exp, ExpNop(body_loc), void_ctx)
(fr_decl, new_body, fr_exp)
| "find" | "find_opt" =>
val none = get_id("None")
val some = get_id("Some")
val fr_decl = DefVal(PatIdent(fr_id, acc_loc), make_ident(none, acc_loc),
default_var_flags(), acc_loc)
val mksome_exp = ExpCall(make_ident(some, body_loc), for_iter_exp :: [],
make_new_ctx(body_loc))
val break_exp = ExpSeq([: ExpAssign(fr_exp, mksome_exp, body_loc),
ExpBreak(true, body_loc) :], void_ctx)
val new_body = ExpIf(fold_body, break_exp, ExpNop(body_loc), void_ctx)
val new_fr_exp =
match special {
| "find" =>
val x = get_id("x")
val some_case = ([: PatVariant(some, [: PatIdent(x, body_end_loc) :],
body_end_loc) :], make_ident(x, body_end_loc))
val none_case = ([: PatAny(body_end_loc) :], ExpThrow(ExpIdent(
get_id("NotFoundError"), (TypExn, body_end_loc)), body_end_loc))
ExpMatch(fr_exp, [: some_case, none_case :], (make_new_typ(), body_end_loc))
| _ => fr_exp
}
(fr_decl, new_body, new_fr_exp)
| _ => throw ParseError(acc_loc, f"unknown fold variation '{special}'")
}
// pack for back
val fold for_exp = new_body for (pe_l, idxp, flags, loc) <- nested_fors {
ExpFor(pe_l, idxp, for_exp, flags.{for_flag_fold=true}, loc)
}
ExpSeq(fr_decl :: for_exp :: fr_exp :: [], make_new_ctx(fold_loc))
}
fun parse_err(ts: tklist_t, msg: string): exn
{
val loc = match ts {
| (_, l) :: _ => l
| _ => parser_ctx.default_loc
}
ParseError(loc, msg)
}
fun exp2expseq(e: exp_t): exp_t list
{
| ExpNop(_) => []
| ExpSeq(eseq, _) => eseq
| _ => e :: []
}
fun expseq2exp(eseq: exp_t list, loc: loc_t) =
match eseq {
| [] => ExpNop(loc)
| e :: [] => e
| _ =>
val llist = [: for e <- eseq {get_exp_loc(e)} :]
val loc = loclist2loc(llist, loc)
ExpSeq(eseq, (make_new_typ(), loc))
}
fun match_paren((ts: tklist_t, e: exp_t), ct: token_t, ol: loc_t): (tklist_t, exp_t)
{
match ts {
| (ct_, l) :: rest when ct_ == ct => (rest, e)
| _ => throw parse_err(ts, f"'{tok2str(ct).1}' is expected; the opening paren is here {ol}")
}
}
fun is_for_start((t: token_t, l: loc_t), nested: bool) =
match t {
| FOR(ne) => (ne | nested)
| PARALLEL => !nested
| UNZIP => !nested
| _ => false
}
fun check_ne(ne: bool, ts: tklist_t) = if !ne {
throw parse_err(ts, "new line or ';' is expected before new expression")
}
fun parse_exp_list_f(ts0: tklist_t, parse_exp_f: tklist_t -> (tklist_t, exp_t),
ct: token_t, ~kw_mode: kw_mode_t, ~allow_empty: bool,
~stop_at_semicolon: bool=false): (tklist_t, bool, elist_t, id_elist_t)
{
fun parse_exp_list_(ts: tklist_t, expect_comma: bool, el: elist_t,
kw_el: id_elist_t): (tklist_t, bool, elist_t, id_elist_t) =
match ts {
| (COMMA, _) :: rest =>
if expect_comma { parse_exp_list_(rest, false, el, kw_el) }
else { throw parse_err(ts, "extra ','?") }
| (t, _) :: rest when t == ct =>
(rest, true, el.rev(), kw_el.rev())
| (SEMICOLON, _) :: rest =>
if !stop_at_semicolon {throw parse_err(ts, "unxpected ';'")}
(rest, false, el.rev(), kw_el.rev())
| (t, _) :: rest =>
if expect_comma {
val semi_msg = if stop_at_semicolon {"';' or "} else {""}
throw parse_err(ts, f"',' or {semi_msg}'{tok2str(ct).1}' is expected")
}
match ts {
| (IDENT(_, i), _) :: (EQUAL, _) :: rest =>
if kw_mode == KwNone { throw parse_err(ts, f"unexpected keyword element '{i}=...'") }
val (ts, e) = parse_complex_exp(rest)
parse_exp_list_(ts, true, el, (get_id(i), e) :: kw_el)
| _ =>
if kw_mode == KwMust { throw parse_err(ts, f"expect a keyword element here '<ident> = ...'") }
val (ts, e) = parse_exp_f(ts)
parse_exp_list_(ts, true, e :: el, kw_el)
}
| _ => throw parse_err(ts0, "the expression list is not complete by the end of file, check parentheses")
}
val (ts, f, el, kw_el) = parse_exp_list_(ts0, false, [], [])
if !allow_empty && el.empty() && kw_el.empty() {
throw parse_err(ts, "empty expression list is not allowed here")
}
(ts, f, el, kw_el)
}
fun parse_exp_list(ts0: tklist_t, ct: token_t, ~kw_mode: kw_mode_t, ~allow_empty: bool,
~stop_at_semicolon: bool=false): (tklist_t, bool, elist_t, id_elist_t)
{
parse_exp_list_f(ts0, parse_typed_exp, ct, kw_mode=kw_mode, allow_empty=allow_empty,
stop_at_semicolon=stop_at_semicolon)
}
fun parse_dot_ident(ts: tklist_t, expect_dot: bool, result: string): (tklist_t, string)
{
match (ts, expect_dot) {
| ((DOT, _) :: rest, _) =>
if expect_dot { parse_dot_ident(rest, false, result) }
else { throw parse_err(ts, "extra '.'?") }
| (_, true) => (ts, result)
| ((IDENT(_, i), _) :: rest, _) =>
parse_dot_ident(rest, true, if result == "" {i} else {result + "." + i})
| _ =>
throw parse_err(ts, "identifier is expected")
}
}
fun parse_ident_list(ts: tklist_t, expect_comma: bool, result: id_t list): (tklist_t, id_t list) =
match ts {
| (COMMA, _) :: rest =>
if expect_comma {parse_ident_list(rest, false, result)}
else {throw parse_err(ts, "extra ','?")}
| (IDENT(_, i), _) :: rest =>
if expect_comma { (ts, result.rev()) }
else { parse_ident_list(rest, true, get_id(i) :: result) }
| _ =>
if result.empty() { throw parse_err(ts, "empty id list") }
(ts, result.rev())
}
fun parse_atomic_exp(ts: tklist_t): (tklist_t, exp_t)
{
//println(f"parse_atomic_exp @ {ts.hd().1}\n")
match ts {
| (IDENT(ne, i), l1) :: rest =>
check_ne(ne, ts)
(rest, make_ident(i, l1))
| (LITERAL(lit), l1) :: rest => (rest, make_literal(lit, l1))
| (LPAREN(true), l1) :: (t, l2) :: (RPAREN, _) :: rest
when get_opname(t) != noid =>
val opname = get_opname(t)
(rest, ExpIdent(opname, make_new_ctx(l2)))
| (LPAREN(ne), l1) :: (LBRACE, _) :: _ =>
check_ne(ne, ts)
match_paren(parse_block(ts.tl()), RPAREN, l1)
| (LPAREN(ne), l1) :: (FOR(_), _) :: _ =>
check_ne(ne, ts)
val (ts, for_exp, _) = parse_for(ts.tl(), ForMakeTuple)
match_paren((ts, for_exp), RPAREN, l1)
| (LPAREN(ne), l1) :: rest =>
check_ne(ne, ts)
val (ts, _, el, _) = parse_exp_list(rest, RPAREN, kw_mode=KwNone, allow_empty=false)
(ts, match el {
| e :: [] => e
| _ => make_tuple(el, l1)
})
| (LSQUARE(ne), l1) :: f :: rest when is_for_start(f, false) =>
check_ne(ne, ts)
val (ts, for_exp, _) = parse_for(ts.tl(), ForMakeArray)
match_paren((ts, for_exp), RSQUARE, l1)
| (LSQUARE(ne), l1) :: rest =>
check_ne(ne, ts)
var vts = rest, result = []
while true {
val (ts, done, el, _) = parse_exp_list(vts, RSQUARE, kw_mode=KwNone,
allow_empty=false, stop_at_semicolon=true)
vts = ts
result = el :: result
if done { break }
}
(vts, ExpMkArray(result.rev(), make_new_ctx(l1)))
| (LLIST, l1) :: f :: _ when is_for_start(f, false) =>
val (ts, for_exp, _) = parse_for(ts.tl(), ForMakeList)
match_paren((ts, for_exp), RLIST, l1)
| (LLIST, l1) :: rest =>
val (ts, _, el, _) = parse_exp_list(rest, RLIST, kw_mode=KwNone, allow_empty=true)
(ts, fold mklist_e = make_literal(LitNil, l1) for e <- el.rev() {
ExpBinary(OpCons, e, mklist_e, make_new_ctx(get_exp_loc(e)))
})
| (t, _) :: _ =>
throw parse_err(ts, f"unxpected token '{tok2str(t).1}'. An identifier, literal or expression enclosed in '( )', '[ ]' or '[: :]' brackets is expected here")
| _ =>
throw parse_err(ts, f"premature end of the stream; check the parens")
}
}
fun parse_simple_exp(ts: tklist_t): (tklist_t, exp_t)
{
//println(f"simple_exp({tok2str(ts)})\n")
fun extend_simple_exp_(ts: tklist_t, e: exp_t) {
//println(f"extend_simple_exp({tok2str(ts)})\n")
val eloc = get_exp_loc(e)
// 1. element access (.|->) (int|ident)
// 2. array access [...]
// 3. function call (...)
match ts {
| (LPAREN(false), l1) :: (FOR(_), l2) :: rest =>
val eloc = get_exp_loc(e)
val istr = match e {
| ExpIdent(i, _) => pp_id2str(i)
| _ => throw ParseError(l2, "incorrect use of for (';' or newline or maybe 'fold' is missing?)")
}
val (ts, for_exp, for_iter_exp) = parse_for(ts.tl(), ForMakeNone)
val fold_exp = transform_fold_exp(istr, PatAny(eloc), ExpNop(eloc), for_exp, for_iter_exp, eloc)
val (ts, fold_exp) = match_paren((ts, fold_exp), RPAREN, l1)
extend_simple_exp_(ts, fold_exp)
| (LPAREN(false), l1) :: rest =>
// function call ([TODO] support keyword args)
val (ts_, _, args, kw_args) = parse_exp_list(rest, RPAREN,
kw_mode=KwMaybe, allow_empty=true)
val args =
if kw_args.empty() {args}
else {
args + (ExpMkRecord(ExpNop(l1), kw_args, make_new_ctx(l1)) :: [])
}
extend_simple_exp_(ts_, ExpCall(e, args, make_new_ctx(eloc)))
| (LSQUARE(false), _) :: rest =>
// array access ([TODO] support ranges)
val (ts, _, idxs, _) = parse_exp_list_f(rest, parse_range_exp,
RSQUARE, kw_mode=KwNone, allow_empty=false)
extend_simple_exp_(ts, ExpAt(e, BorderNone, InterpNone, idxs, make_new_ctx(eloc)))
| (t1, _) :: (t2, l2) :: rest when
// [TODO] add support for alternating patterns right into the pattern matching syntax
(match t1 {| DOT | ARROW => true | _ => false}) &&
(match t2 {| IDENT(true, _) | LITERAL(LitInt _) => true | _ => false}) =>
val e = match t1 { | ARROW => make_unary(OpDeref, e, eloc) | _ => e }
val i = match t2 {
| IDENT(true, i) => make_ident(i, l2)
| LITERAL(LitInt(i)) => make_literal(LitInt(i), l2)
| _ => ExpNop(l2)
}
extend_simple_exp_(rest, ExpMem(e, i, make_new_ctx(eloc)))
| (t1, _) :: (LBRACE, l2) :: rest when (match t1 {| DOT | ARROW => true | _ => false}) =>
val e = match t1 { | ARROW => make_unary(OpDeref, e, eloc) | _ => e }
val (ts, _, _, rec_init_elems) = parse_exp_list(rest, RBRACE, kw_mode=KwMust, allow_empty=true)
extend_simple_exp_(ts, ExpUpdateRecord(e, rec_init_elems, make_new_ctx(eloc)))
| _ => (ts, e)
}
}
val (ts, e) = parse_atomic_exp(ts)
extend_simple_exp_(ts, e)
}
fun parse_deref_exp(ts: tklist_t): (tklist_t, exp_t)
{
| (STAR(true), l1) :: rest =>
val (ts, e) = parse_deref_exp(rest)
(ts, make_unary(OpDeref, e, l1))
| _ =>
parse_simple_exp(ts)
}
fun parse_apos_exp(ts: tklist_t): (tklist_t, exp_t)
{
val (ts, e) = parse_deref_exp(ts)
match ts {
| (APOS, l1) :: rest => (rest, ExpUnary(OpApos, e, make_new_ctx(l1)))
| _ => (ts, e)
}
}
fun parse_unary_exp(ts: tklist_t): (tklist_t, exp_t)
{
//println(f"unary_exp({tok2str(ts)})\n")
match ts {
| (REF(true), l1) :: rest =>
val (ts, e) = parse_unary_exp(rest)
(ts, make_unary(OpMkRef, e, l1))
| (MINUS(true), l1) :: rest =>
val (ts, e) = parse_unary_exp(rest)
(ts, make_unary(OpNegate, e, l1))
| (DOT_MINUS(true), l1) :: rest =>
val (ts, e) = parse_unary_exp(rest)
(ts, make_unary(OpDotMinus, e, l1))
| (PLUS(true), l1) :: rest =>
val (ts, e) = parse_unary_exp(rest)
(ts, make_unary(OpPlus, e, l1))
| (TILDE, l1) :: rest =>
val (ts, e) = parse_unary_exp(rest)
(ts, make_unary(OpBitwiseNot, e, l1))
| (LOGICAL_NOT, l1) :: rest =>
val (ts, e) = parse_unary_exp(rest)
(ts, make_unary(OpLogicNot, e, l1))
| (BACKSLASH, l1) :: rest =>
val (ts, e) = parse_unary_exp(rest)
(ts, make_unary(OpExpand, e, l1))
| _ =>
parse_apos_exp(ts)
}
}
fun parse_binary_exp(ts: tklist_t) : (tklist_t, exp_t)
{
//println(f"binary_exp({tok2str(ts)})\n")
fun parse_binary_exp_(ts: tklist_t, result: exp_t, min_prec: int) =
match ts {
| (t, l) :: rest =>
// roughly sort binary ops by how often they are met in the code,
// so that we have less checks in general
val (bop, prec, assoc) = match t {
| PLUS(false) => (OpAdd, 210, AssocLeft)
| MINUS(false) => (OpSub, 210, AssocLeft)
| STAR(false) => (OpMul, 220, AssocLeft)
| SLASH => (OpDiv, 220, AssocLeft)
| PERCENT => (OpMod, 220, AssocLeft)
| CONS => (OpCons, 100, AssocRight)
| POWER => (OpPow, 230, AssocRight)
| SHIFT_LEFT => (OpShiftLeft, 200, AssocLeft)
| SHIFT_RIGHT => (OpShiftRight, 200, AssocLeft)
| BITWISE_OR => (OpBitwiseOr, 130, AssocLeft)
| BITWISE_AND => (OpBitwiseAnd, 150, AssocLeft)
| BITWISE_XOR => (OpBitwiseXor, 140, AssocLeft)
| SPACESHIP => (OpSpaceship, 170, AssocLeft)
| DOT_MINUS(false) => (OpSub, 210, AssocLeft)
| DOT_STAR => (OpDotMul, 220, AssocLeft)
| DOT_SLASH => (OpDotDiv, 220, AssocLeft)
| DOT_PERCENT => (OpDotMod, 220, AssocLeft)
| DOT_STAR => (OpDotMul, 220, AssocLeft)
| DOT_POWER => (OpDotPow, 230, AssocRight)
| DOT_CMP(cmpop) => (OpDotCmp(cmpop), 180, AssocLeft)
| DOT_SPACESHIP => (OpDotSpaceship, 190, AssocLeft)
//| SAME => (OpSame, 190, AssocLeft)
| _ => (OpAdd, -1, AssocLeft)
}
if prec < min_prec { (ts, result) }
else {
val next_min_prec = match assoc { | AssocLeft => prec+1 | _ => prec }
val (ts, e) = parse_unary_exp(rest)
// non-tail call, parse rhs
val (ts, rhs) = parse_binary_exp_(ts, e, next_min_prec)
val result = make_binary(bop, result, rhs, l)
parse_binary_exp_(ts, result, min_prec)
}
| _ => (ts, result)
}
val (ts, e) = parse_unary_exp(ts)
parse_binary_exp_(ts, e, 0)
}
fun parse_exp(ts: tklist_t): (tklist_t, exp_t)
{
fun extend_chained_cmp_(ts: tklist_t,
chain: ((cmpop_t, loc_t), exp_t) list): (tklist_t, exp_t)
{
//println(f"binary_exp({tok2str(ts)})\n")
match ts {
| (CMP(cmpop), l1) :: rest =>
val (ts, e) = parse_binary_exp(rest)
extend_chained_cmp_(ts, ((cmpop, l1), e) :: chain)
| _ =>
val result = match chain {
| (_, e1) :: [] => e1
| ((cmpop, l2), e2) :: (_, e1) :: [] =>
ExpBinary(OpCmp(cmpop), e1, e2, (TypBool, l2))
| _ =>
val chain = chain.rev()
val nexp = chain.length()
val fold (result, prev_e, code) = (ExpNop(noloc), chain.hd().1, [])
for ((cmpop, loc), e)@i <- chain.tl() {
val (next_e, code) = if i == nexp-2 {(e, code)} else {
match e {
| ExpLit(_, _) | ExpIdent(_, _) => (e, code)
| _ =>
val e_loc = get_exp_loc(e)
val tmp_id = gen_temp_id("t")
val tmp_decl = DefVal(PatIdent(tmp_id, e_loc), e,
default_tempval_flags(), e_loc)
(make_ident(tmp_id, e_loc), tmp_decl :: code)
}
}
val cmp_exp = ExpBinary(OpCmp(cmpop), prev_e, next_e, (TypBool, loc))
val result = if i == 0 {cmp_exp}
else { ExpBinary(OpBitwiseAnd, result, cmp_exp, (TypBool, loc)) }
(result, next_e, code)
}
expseq2exp(code.rev() + (result :: []), get_exp_loc(result))
}
(ts, result)
}}
fun parse_chained_cmp_(ts: tklist_t): (tklist_t, exp_t)
{
val (ts, e) = parse_binary_exp(ts)
extend_chained_cmp_(ts, ((CmpEQ, noloc), e) :: [])
}
fun parse_logic_exp_(ts: tklist_t, result: exp_t, min_prec: int) =
match ts {
| (t, l) :: rest =>
val (bop, prec, assoc) = match t {
| LOGICAL_OR => (OpLogicOr, 10, AssocLeft)
| LOGICAL_AND => (OpLogicAnd, 20, AssocLeft)
| _ => (OpAdd, -1, AssocLeft)
}
if prec < min_prec { (ts, result) }
else {
val next_min_prec = match assoc { | AssocLeft => prec+1 | _ => prec }
val (ts, e) = parse_chained_cmp_(rest)
// non-tail call, parse rhs
val (ts, rhs) = parse_logic_exp_(ts, e, next_min_prec)
val result = ExpBinary(bop, result, rhs, (TypBool, l))
parse_logic_exp_(ts, result, min_prec)
}
| _ => (ts, result)
}
val (ts, e) = parse_chained_cmp_(ts)
parse_logic_exp_(ts, e, 0)
}
fun parse_exp_or_block(ts: tklist_t): (tklist_t, exp_t)
{
| (LBRACE, _) :: _ => parse_block(ts)
| _ => parse_exp(ts)
}
fun parse_complex_exp_or_block(ts: tklist_t): (tklist_t, exp_t)
{
| (LBRACE, _) :: _ => parse_block(ts)
| _ => parse_complex_exp(ts)
}
fun parse_block(ts: tklist_t): (tklist_t, exp_t)
{
| (LBRACE, l1) :: rest =>
val (ts, eseq) = parse_expseq(rest, false)
val e = expseq2exp(eseq, l1)
match_paren((ts, e), RBRACE, l1)
| _ =>
throw parse_err(ts, "'{' is expected")
}
fun parse_ccode_exp(ts: tklist_t): (tklist_t, exp_t)
{
| (CCODE, l1) :: (LITERAL(lit), l2) :: rest =>
val s = get_string(lit, l2)
(rest, ExpCCode(s, make_new_ctx(l1)))
| _ => throw parse_err(ts, "'ccode {...}' is expected")
}
fun parse_range_exp(ts0: tklist_t): (tklist_t, exp_t)
{
val loc = match ts0 { | _ :: _ => ts0.hd().1 | _ => noloc }
fun parse_range_(ts: tklist_t, expect_sep: bool, result: exp_t? list): (tklist_t, exp_t? list) =
match ts {
| (CONS, _) :: rest =>
val result = if expect_sep {None :: result} else {None :: None :: result}
parse_range_(rest, false, result)
| (COLON, _) :: rest =>
val result = if expect_sep {result} else {None :: result}
parse_range_(rest, false, result)
| (LBRACE, _) :: _ | (FOR(_), _) :: _ | (RSQUARE, _) :: _ | (COMMA, _) :: _ =>
if !expect_sep && result.length() != 1 {
throw parse_err(ts, "range expression may not end with ':', unless it's ':' or '<start>:' ")
}
val result = if expect_sep {result} else {None :: result}
(ts, result.rev())
| _ =>
if expect_sep { throw parse_err(ts, "':' is expected") }
val (ts, e) = parse_exp(ts)
parse_range_(ts, true, Some(e) :: result)
}
val (ts, elist) = parse_range_(ts0, false, [])
val ctx = make_new_ctx(loc)
val e = match elist {
| Some(e) :: [] => e // scalar index
| None :: None :: [] => ExpRange(None, None, None, ctx) // :
| [] => throw parse_err(ts0, "empty range expression")
| None :: [] | None :: None :: None :: [] => throw parse_err(ts0, "invalid range expression")
| e1 :: [] => ExpRange(e1, None, None, ctx) // a:
| e1 :: e2 :: [] => ExpRange(e1, e2, None, ctx) // a:b or :b
| e1 :: e2 :: e3 :: [] => ExpRange(e1, e2, e3, ctx) // a:b:c or a::c or :b:c or ::c
| _ => throw parse_err(ts0, f"invalid range expression of {elist.length()} components")
}
(ts, e)
}
fun parse_expseq(ts: tklist_t, toplevel: bool): (tklist_t, exp_t list)
{
fun extend_expseq_(ts: tklist_t, result: exp_t list): (tklist_t, exp_t list)
{
val ts = match ts {
| (SEMICOLON, _) :: rest =>
if result.empty() {
throw parse_err(ts, "unexpected ';' in the beginning of expression sequence")
}
rest
| _ => ts
}
match ts {
| (RBRACE, _) :: _ | (BAR, _) :: _ | (EOF, _) :: _ =>
if toplevel && (match ts {| (EOF, _) :: _ => false | _ => true}) {
throw parse_err(ts, "unexpected '}'")
}
(ts, result.rev())
| (VAL, _) :: _ | (PRIVATE, _) :: (VAL, _) :: _
| (VAR, _) :: _ | (PRIVATE, _) :: (VAR, _) :: _ =>
val (ts, defvals) = parse_defvals(ts)
extend_expseq_(ts, defvals + result)
| (OBJECT, _) :: (TYPE, _) :: _ | (TYPE, _) :: _ =>
val (ts, deftyp) = parse_deftype(ts)
extend_expseq_(ts, deftyp :: result)
| (FUN, _) :: (LPAREN(_), _) :: _ =>
val (ts, e) = parse_lambda(ts)
extend_expseq_(ts, e :: result)
| (PRIVATE, _) :: _ | (PURE, _) :: _ | (NOTHROW, _) :: _
| (INLINE, _) :: _ | (FUN, _) :: _ | (OPERATOR, _) :: _ =>
val (ts, defun) = parse_defun(ts)
extend_expseq_(ts, defun :: result)
| (EXCEPTION, l1) :: rest =>
if !toplevel { throw parse_err(ts, "exceptions can only be defined at module level") }
val (ts, i) = match rest {
| (IDENT(_, i), _) :: rest =>
if !good_variant_name(i) {
throw parse_err(ts, "exception name should start with a capital letter (A..Z)")
}
(rest, get_id(i))
| _ =>
throw parse_err(rest, "identifier is expected")
}
val (ts, t) = match ts {
| (COLON, _) :: rest => parse_typespec(rest)
| _ => (ts, TypVoid)
}
val de = ref (defexn_t { dexn_name=i, dexn_typ=t, dexn_scope=ScGlobal :: [], dexn_loc=l1 })
extend_expseq_(ts, DefExn(de) :: result)
| (IMPORT(f), l1) :: rest =>
if !toplevel {throw parse_err(ts, "import directives can only be used at the module level")}
if !f { throw parse_err(ts, "';' or newline is expected before the import directive") }
fun parse_imported_(ts: tklist_t, expect_comma: bool, result: (id_t, id_t) list):
(tklist_t, (id_t, id_t) list) =
match ts {
| (COMMA, _) :: rest =>
if expect_comma {parse_imported_(rest, false, result)}
else {throw parse_err(ts, "extra ','?")}
| (IDENT(_, _), loc_i) :: _ =>
if expect_comma { (ts, result.rev()) }
else {
val (ts, i) = parse_dot_ident(ts, false, "")
val i = get_id(i)
val (ts, j) = match ts {
| (AS, _) :: (IDENT(_, j), _) :: rest => (rest, get_id(j))
| _ => (ts, i)
}
val i_ = add_to_imported_modules(i, loc_i)
parse_imported_(ts, true, (i_, j) :: result)
}
| _ =>
if result.empty() { throw parse_err(ts, "empty module list") }
(ts, result.rev())
}
val (ts, imported) = parse_imported_(rest, false, [])
extend_expseq_(ts, DirImport(imported, l1) :: result)
| (FROM, l1) :: rest =>
if !toplevel {throw parse_err(ts, "import directives can only be used at the module level")}
val (ts, m_) = parse_dot_ident(rest, false, "")
val m = get_id(m_)
val m_ = add_to_imported_modules(m, l1)
match ts {
| (IMPORT(_), _) :: (STAR(_), _) :: rest =>
extend_expseq_(rest, DirImportFrom(m_, [], l1) :: result)
| (IMPORT(_), _) :: rest =>
val (ts, il) = parse_ident_list(rest, false, [])
extend_expseq_(ts, DirImportFrom(m_, il, l1) :: result)
| _ =>
throw parse_err(ts, "'import' is expected")
}
| (PRAGMA, l1) :: (LITERAL(lit), l2) :: rest =>
if !toplevel {throw parse_err(ts, "pragma directives can only be used at the module level")}
val pr = get_string(lit, l2)
fun more_pragmas_(ts: tklist_t, prl: string list) =
match ts {
| (COMMA, _) :: (LITERAL(lit), l2) :: rest =>
val pr = get_string(lit, l2)
more_pragmas_(rest, pr :: prl)
| _ => (ts, prl.rev())
}
val (ts, prl) = more_pragmas_(rest, pr :: [])
extend_expseq_(ts, DirPragma(prl, l2) :: result)
| (CCODE, _) :: _ =>
if !toplevel {throw parse_err(ts, "C code is only allowed at the top level or as rhs of function or value definition")}
val (ts, e) = parse_ccode_exp(ts)
extend_expseq_(ts, e :: result)
| _ =>
val (ts, e) = parse_stmt(ts)
extend_expseq_(ts, e :: result)
}
}
extend_expseq_(ts, [])
}
fun parse_for(ts: tklist_t, for_make: for_make_t): (tklist_t, exp_t, exp_t)
{
var is_parallel = false, need_unzip = false
var vts = ts, nested_fors = ([] : ((pat_t, pat_t, exp_t) list, loc_t) list)
while true {
match vts {
| (PARALLEL, _) :: rest =>
if is_parallel {throw parse_err(ts, "duplicate @parallel attribute")}
is_parallel = true; vts = rest
| (UNZIP, _) :: rest =>
if need_unzip {throw parse_err(ts, "duplicate @unzip attribute")}
match for_make {
| ForMakeNone | ForMakeTuple =>
throw parse_err(ts, "@unzip can only be used with array and list comprehensions")
| _ => {}}
need_unzip = true; vts = rest
| (FOR(_), _) :: rest =>
break
| _ =>
throw parse_err(vts, "'for' is expected (after optional attributes)")
}
}
fun parse_for_clause_(ts: tklist_t, expect_comma: bool,
result: (pat_t, pat_t, exp_t) list, loc: loc_t): (tklist_t, (pat_t, pat_t, exp_t) list) =
match ts {
| (COMMA, _) :: rest =>
if expect_comma { parse_for_clause_(rest, false, result, loc) }
else { throw parse_err(ts, "extra ','?") }
| (FOR(_), _) :: _ | (LBRACE, _) :: _ when expect_comma =>
if result.empty() {
throw parse_err(ts, "empty for? (need at least one <iter_pat> <- <iter_range or collection>)")
}
(ts, result.rev())
| _ =>
if expect_comma { throw parse_err(ts, "',' is expected") }
val (ts, p) = parse_pat(ts, true)
val (ts, idx_pat) = match ts {
| (AT, _) :: rest =>
parse_pat(rest, true)
| _ => (ts, PatAny(loc))
}
val ts = match ts {
| (BACK_ARROW, _) :: rest => rest
| _ => throw parse_err(ts, "'<-' is expected")
}
val (ts, e) = parse_range_exp(ts)
parse_for_clause_(ts, true, (p, idx_pat, e) :: result, loc)
}
while true {
var loc_i = noloc
match vts {
| (FOR(_), l1) :: rest =>
vts = rest
loc_i = l1
| _ =>
nested_fors = nested_fors.rev()
break
}
val (ts, for_cl) = parse_for_clause_(vts, false, [], loc_i)
nested_fors = (for_cl, loc_i) :: nested_fors
vts = ts
}
val glob_loc = match nested_fors {| (_, loc) :: _ => loc | _ => noloc}
// process the nested for.
val fold (glob_el, nested_fors) = ([], []) for (ppe_list, loc) <- nested_fors {
val fold (glob_el, for_cl_, idx_pat) = (glob_el, [], PatAny(loc)) for (p, idxp, e) <- ppe_list {
val (p_, p_e) = plist2exp(p :: [], "x", get_pat_loc(p))
val p = List.hd(p_)
match (idxp, idx_pat) {
| (PatAny(_), idx_pat) => (p_e :: glob_el, (p, e) :: for_cl_, idx_pat)
| (_, PatAny(_)) =>
val (idxp_, idxp_e) = plist2exp(idxp :: [], "i", get_pat_loc(idxp))
(idxp_e :: p_e :: glob_el, (p, e) :: for_cl_, idxp)
| _ => throw ParseError(get_pat_loc(idxp), "@ is used more than once, which does not make sence and is not supported")
}
}
(glob_el, (for_cl_.rev(), idx_pat, loc) :: nested_fors)
}
val for_iter_exp = match glob_el.rev() { | e :: [] => e | el => make_tuple(el, glob_loc) }
val (ts, body) = match vts {
| (LBRACE, l1) :: (BAR, _) :: _ =>
val (ts, cases) = parse_match_cases(vts)
val match_e = ExpMatch(for_iter_exp, cases, make_new_ctx(l1))
(ts, match_e)
| (LBRACE, l1) :: _ =>
parse_block(vts)
| _ => throw parse_err(ts, "'{' is expected (beginning of for-loop body)")
}
val for_exp = match for_make
{
| ForMakeArray | ForMakeList | ForMakeTuple =>
val fold (pel_i_l, loc) = ([], noloc) for (pe_l, idxp, loc) <- nested_fors {
((pe_l, idxp) :: pel_i_l, loc)
}
ExpMap(pel_i_l, body, default_for_flags().{
for_flag_make=for_make,
for_flag_parallel=is_parallel,
for_flag_unzip=need_unzip},
make_new_ctx(loc))
| _ =>
val nfors = nested_fors.length()
fold e = body for (pe_l, idxp, loc)@i <- nested_fors {
val nested = i < nfors-1
val flags = default_for_flags()
val flags = if nested {flags.{for_flag_nested=true}}
else {flags.{for_flag_parallel=is_parallel}}
ExpFor(pe_l, idxp, e, flags, loc)
}
}
(ts, for_exp, for_iter_exp)
}
fun parse_defvals(ts: tklist_t): (tklist_t, exp_t list)
{
val (ts, is_private) = match ts {
| (PRIVATE, _) :: rest => (rest, true)
| _ => (ts, false)
}
val (ts, is_mutable) = match ts {
| (VAL, _) :: rest => (rest, false)
| (VAR, _) :: rest => (rest, true)
| _ => throw parse_err(ts, "'val' or 'var' is expected")
}
val flags = default_val_flags().{
val_flag_private=is_private,
val_flag_mutable=is_mutable
}
fun extend_defvals_(ts: tklist_t, expect_comma: bool, result: exp_t list): (tklist_t, exp_t list) =
match ts {
| (COMMA, _) :: rest =>
if expect_comma { extend_defvals_(rest, false, result) }
else { throw parse_err(ts, "extra ','?") }
| (IDENT(true, _), _) :: _ | (LPAREN(true), _) :: _
| (LBRACE, _) :: _ | (REF(true), _) :: _ =>
// do not reverse the result
if expect_comma { (ts, result) }
else {
val (ts, p) = parse_pat(ts, true)
match ts {
| (EQUAL, l1) :: (CCODE, l2) :: (LITERAL(LitString(ccode)), _) :: rest =>
val dv = DefVal(p, ExpCCode(ccode, make_new_ctx(l2)),
default_val_flags().
{val_flag_mutable=is_mutable,
val_flag_private=is_private}, l1)
extend_defvals_(rest, true, dv :: result)
| (EQUAL, l1) :: rest =>
val (ts, e) = parse_complex_exp_or_block(rest)
val dv = DefVal(p, e, flags, l1)
extend_defvals_(ts, true, dv :: result)
| _ => throw parse_err(ts, "'=' is expected")
}
}
| _ =>
// do not reverse the result
(ts, result)
}
match ts {
| (FOLD, l1) :: rest =>
val (ts, p) = parse_pat(rest, true)
val (ts, e) = match ts {
| (EQUAL, _) :: rest => parse_complex_exp(rest)
| _ => throw parse_err(ts, "'=' is expected")
}
val (ts, for_exp, for_iter_exp) = parse_for(ts, ForMakeNone)
val fold_exp = transform_fold_exp("", p, e, for_exp, for_iter_exp, l1)
(ts, DefVal(p, fold_exp, flags, get_pat_loc(p)) :: [])
| _ => extend_defvals_(ts, false, [])
}
}
fun get_opname(t: token_t): id_t =
match t {
| APOS => fname_op_apos()
| PLUS(_) => fname_op_add()
| MINUS(_) => fname_op_sub()
| STAR(_) => fname_op_mul()
| SLASH => fname_op_div()
| PERCENT => fname_op_mod()
| POWER => fname_op_pow()
| DOT_STAR => fname_op_dot_mul()
| DOT_SLASH => fname_op_dot_div()
| DOT_PERCENT => fname_op_dot_mod()
| DOT_POWER => fname_op_dot_pow()
| SHIFT_LEFT => fname_op_shl()
| SHIFT_RIGHT => fname_op_shr()
| BITWISE_AND => fname_op_bit_and()
| BITWISE_OR => fname_op_bit_or()
| BITWISE_XOR => fname_op_bit_xor()
| TILDE => fname_op_bit_not()
| SPACESHIP => fname_op_cmp()
//| SAME => fname_op_same()
| CMP(CmpEQ) => fname_op_eq()
| CMP(CmpNE) => fname_op_ne()
| CMP(CmpLE) => fname_op_le()
| CMP(CmpGE) => fname_op_ge()
| CMP(CmpLT) => fname_op_lt()
| CMP(CmpGT) => fname_op_gt()
| DOT_SPACESHIP => fname_op_dot_cmp()
| DOT_CMP(CmpEQ) => fname_op_dot_eq()
| DOT_CMP(CmpNE) => fname_op_dot_ne()
| DOT_CMP(CmpLE) => fname_op_dot_le()
| DOT_CMP(CmpGE) => fname_op_dot_ge()
| DOT_CMP(CmpLT) => fname_op_dot_lt()
| DOT_CMP(CmpGT) => fname_op_dot_gt()
| _ => noid
}
fun parse_defun(ts: tklist_t): (tklist_t, exp_t)
{
var is_private = false, is_pure = false, is_nothrow = false, is_inline = false
var vts = ts, fname = noid, loc = noloc
while true {
match vts {
| (PRIVATE, _) :: rest =>
if is_private {throw parse_err(ts, "duplicate @private attribute")}
is_private = true; vts = rest
| (PURE, _) :: rest =>
if is_pure {throw parse_err(ts, "duplicate @pure attribute")}
is_pure = true; vts = rest
| (NOTHROW, _) :: rest =>
if is_nothrow {throw parse_err(ts, "duplicate @nothrow attribute")}
is_nothrow = true; vts = rest
| (INLINE, _) :: rest =>
if is_inline {throw parse_err(ts, "duplicate @inline attribute")}
is_inline = true; vts = rest
| (FUN, l1) :: (IDENT(_, i), _) :: (LPAREN(_), _) :: rest =>
vts = rest; fname = get_id(i); loc = l1; break
| (OPERATOR, l1) :: (t, l2) :: (LPAREN(_), _) :: rest =>
vts = rest; fname = get_opname(t); loc = l1
if fname == noid { throw ParseError(l2, "invalid operator name") }
break
| _ =>
throw parse_err(vts, "'fun <funcname> (' is expected (after optional attributes)")
}
}
val (ts, params, rt, prologue, have_keywords) = parse_fun_params(vts)
val fname_exp = make_ident(fname, loc)
parse_body_and_make_fun(ts, fname, params, rt, prologue,
default_fun_flags().{
fun_flag_private=is_private,
fun_flag_nothrow=is_nothrow,
fun_flag_pure=if is_pure {1} else {-1},
fun_flag_inline=is_inline,
fun_flag_has_keywords=have_keywords}, loc)