-
Notifications
You must be signed in to change notification settings - Fork 9
/
Ast.fx
1592 lines (1430 loc) · 49.4 KB
/
Ast.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 abstract syntax definition + helper structures and functions ////////
import Map, Set, Hashmap, Hashset
import File, Filename, Options, Sys
/*
we represent all the symbols in the code using Id.t variant, essentially, by a pair of integers <a, b>.
Initially, b=0 (i.e. id ~ Id.Name(a)) and it represents the textual name as it occurs in the code, e.g. "i".
"a" is the index in the array of strings that contains identifiers occured in the program.
Later on, the type checker resolves the names and replaces b with
some unique integer representing the particular object ("i") referenced in the particular
context. For example:
val i = 5
val i = i + 1
=>
val i@100 : int = 5
val i@101 : int = i@100 : int + 1
(here i@100 means Id.Val(i, 100) and foo@101 means Id.Val(foo, 357), where i & foo are indices in the global
table of symbolic names that corresponds to the abstract names "i", "foo", whereas 100 and 357
are indices in the same table corresponding to the actually defined values.
Internally the compiler uses unique names i@100 etc. to distinguish between values
with the same name, but it uses the original names in error messages; it also uses the original name (i)
to search for the symbol, i.e. Id.Name(f) can be matched with Id.Val(f, 12345) or Id.Val(f, 9876) or
some other Id.Val(f, ...), depending on the current environment).
There is a big global table of all symbols, so for each symbol we can retrieve its properties:
the original name, inferred type, when and how it's defined.
Sometimes we need a temporary value or a temporary function, i.e. when we do not have a user-specified
name. In this case we use some common prefix, e.g. "t" for intermediate results in complex expressions,
"lambda" for anonymous functions etc. but we represent the id as Id.Temp(prefix, N). Such id is
always displayed as prefix@@N, e.g. "t@@1000" or "lambda@@777", and it can only be matched with
itself (prefix@@N). That is, it's really unique.
*/
type id_t = IdName: int | IdVal: (int, int) | IdTemp: (int, int)
fun cmp_id(a: id_t, b: id_t) {
| (IdName(a1), IdName(b1)) => a1 <=> b1
| (IdVal(a1, a2), IdVal(b1, b2)) =>
val d1 = a1 <=> b1
if d1 != 0 {d1} else {a2 <=> b2}
| (IdTemp(a1, a2), IdTemp(b1, b2)) =>
val d1 = a1 <=> b1
if d1 != 0 {d1} else {a2 <=> b2}
| _ => a.__tag__ <=> b.__tag__
}
operator <=> (a: id_t, b: id_t) = cmp_id(a, b)
operator == (a: id_t, b: id_t) = a.__tag__ == b.__tag__ &&
(match (a, b) {
| (IdName(a), IdName(b)) => a == b
| (IdVal(a, ia), IdVal(b, ib)) => a == b && ia == ib
| (IdTemp(a, ia), IdTemp(b, ib)) => a == b && ia == ib
| _ => false
})
val noid = IdName(0)
val dummyid = IdName(1)
val __fold_result_id__ = IdName(2)
val __tag_id__ = IdName(3)
val __builtin_ids__ = [: "", "_", "__fold_result__", "__tag__" :]
type scope_t =
| ScBlock: int
| ScLoop: (bool, int)
| ScFold: int
| ScArrMap: int
| ScMap: int
| ScTry: int
| ScFun: id_t
| ScClass: id_t
| ScInterface: id_t
| ScModule: id_t
type loc_t =
{
fname: id_t;
line0: int;
col0: int;
line1: int;
col1: int
}
val noloc = loc_t {fname=noid, line0=0, col0=0, line1=0, col1=0}
fun loclist2loc(llist: loc_t list, default_loc: loc_t) =
fold loc = default_loc for loci <- llist {
val {fname, line0, col0, line1, col1} = loc
val {fname=loci_fname,
line0=loci_line0, col0=loci_col0,
line1=loci_line1, col1=loci_col1} = loci
if fname != loci_fname {
if fname == noid { loci } else { loc }
} else {
loc_t
{
fname=fname,
line0=min(line0, loci_line0),
col0=min(col0, loci_col0),
line1=max(line1, loci_line1),
col1=max(col1, loci_col1)
}
}
}
fun get_start_loc(loc: loc_t) {
val {fname, line0, col0} = loc
loc_t {fname=fname, line0=line0, col0=col0, line1=line0, col1=col0}
}
fun get_end_loc(loc: loc_t) {
val {fname, line1, col1} = loc
loc_t {fname=fname, line0=line1, col0=col1, line1=line1, col1=col1}
}
fun string(loc: loc_t) = f"{pp(loc.fname)}:{loc.line0}:{loc.col0}"
exception CompileError: (loc_t, string)
exception PropagateCompileError
type lit_t =
| LitInt: int64
| LitSInt: (int, int64)
| LitUInt: (int, uint64)
| LitFloat: (int, double)
| LitString: string
| LitChar: char
| LitBool: bool
| LitNil
type defparam_t = lit_t
type typ_t =
| TypVar: typ_t? ref
| TypVarTuple: typ_t?
| TypVarArray: typ_t
| TypVarRecord
| TypInt
| TypSInt: int
| TypUInt: int
| TypFloat: int
| TypString
| TypChar
| TypBool
| TypVoid
| TypFun: (typ_t list, typ_t)
| TypList: typ_t
| TypTuple: typ_t list
| TypRef: typ_t
| TypArray: (int, typ_t)
| TypRecord: ((id_t, typ_t, defparam_t?) list, bool) ref
| TypExn
| TypErr
| TypCPointer
| TypApp: (typ_t list, id_t)
| TypDecl
| TypModule
fun make_new_typ() = TypVar(ref None)
fun make_new_ctx(l: loc_t) = (make_new_typ(), l)
type op_assoc_t = AssocLeft | AssocRight
type cmpop_t = CmpEQ | CmpNE | CmpLT | CmpLE | CmpGE | CmpGT
type binary_t = OpAdd | OpSub | OpMul | OpDiv | OpMod | OpPow
| OpShiftLeft | OpShiftRight | OpDotMul | OpDotDiv | OpDotMod | OpDotPow
| OpBitwiseAnd | OpLogicAnd | OpBitwiseOr | OpLogicOr | OpBitwiseXor
| OpCmp: cmpop_t | OpDotCmp: cmpop_t | OpSpaceship | OpDotSpaceship | OpSame | OpCons
type unary_t = OpPlus | OpNegate | OpDotMinus | OpBitwiseNot | OpLogicNot
| OpMkRef | OpDeref | OpExpand | OpApos
type intrin_t =
| IntrinPopExn
| IntrinVariantTag
| IntrinVariantCase
| IntrinListHead
| IntrinListTail
| IntrinStrConcat
| IntrinGetSize
| IntrinCheckIdx
| IntrinCheckIdxRange
| IntrinMath: id_t
type val_flags_t =
{
val_flag_arg: bool = false;
val_flag_mutable: bool = false;
val_flag_temp: bool = false;
val_flag_tempref: bool = false;
val_flag_private: bool = false;
val_flag_subarray: bool = false;
val_flag_ctor: id_t;
val_flag_global: scope_t list = []
}
fun default_val_flags() = val_flags_t {val_flag_ctor=noid}
fun default_arg_flags() = default_val_flags().{val_flag_arg=true}
fun default_var_flags() = default_val_flags().{val_flag_mutable=true}
fun default_tempval_flags() = default_val_flags().{val_flag_temp=true}
fun default_tempref_flags() = default_val_flags().{val_flag_tempref=true}
fun default_tempvar_flags() = default_tempval_flags().{val_flag_mutable=true}
type fun_constr_t =
| CtorNone
| CtorStruct
| CtorVariant: id_t
| CtorFP: id_t
| CtorExn: id_t
type fun_flags_t =
{
fun_flag_pure: int=-1;
fun_flag_ccode: bool=false;
fun_flag_has_keywords: bool=false;
fun_flag_inline: bool=false;
fun_flag_nothrow: bool=false;
fun_flag_really_nothrow: bool=false;
fun_flag_private: bool=false;
fun_flag_ctor: fun_constr_t;
fun_flag_uses_fv: bool=false;
fun_flag_recursive: bool=false
}
fun default_fun_flags() = fun_flags_t {fun_flag_ctor=CtorNone}
type for_make_t = ForMakeNone | ForMakeArray | ForMakeList | ForMakeTuple
type for_flags_t =
{
for_flag_parallel: bool = false;
for_flag_make: for_make_t;
for_flag_unzip: bool = false;
for_flag_fold: bool = false;
for_flag_nested: bool = false
}
fun default_for_flags() = for_flags_t
{
for_flag_parallel=false,
for_flag_make=ForMakeNone,
for_flag_unzip=false,
for_flag_fold=false,
for_flag_nested=false
}
type border_t =
| BorderNone
| BorderClip
| BorderZero
type interpolate_t =
| InterpNone
| InterpLinear
val max_zerobuf_size = 256
type var_flags_t =
{
var_flag_object: id_t;
var_flag_record: bool = false;
var_flag_recursive: bool = false;
var_flag_have_tag: bool = false;
var_flag_opt: bool = false
}
fun default_variant_flags() = var_flags_t {var_flag_object=noid}
type ctx_t = (typ_t, loc_t)
type exp_t =
| ExpNop: loc_t
| ExpBreak: (bool, loc_t)
| ExpContinue: loc_t
| ExpRange: (exp_t?, exp_t?, exp_t?, ctx_t)
| ExpLit: (lit_t, ctx_t)
| ExpIdent: (id_t, ctx_t)
| ExpBinary: (binary_t, exp_t, exp_t, ctx_t)
| ExpUnary: (unary_t, exp_t, ctx_t)
| ExpIntrin: (intrin_t, exp_t list, ctx_t)
| ExpSeq: (exp_t list, ctx_t)
| ExpMkTuple: (exp_t list, ctx_t)
| ExpMkArray: (exp_t list list, ctx_t)
| ExpMkRecord: (exp_t, (id_t, exp_t) list, ctx_t)
| ExpUpdateRecord: (exp_t, (id_t, exp_t) list, ctx_t)
| ExpCall: (exp_t, exp_t list, ctx_t)
| ExpAt: (exp_t, border_t, interpolate_t, exp_t list, ctx_t)
| ExpAssign: (exp_t, exp_t, loc_t)
| ExpMem: (exp_t, exp_t, ctx_t)
| ExpThrow: (exp_t, loc_t)
| ExpIf: (exp_t, exp_t, exp_t, ctx_t)
| ExpWhile: (exp_t, exp_t, loc_t)
| ExpDoWhile: (exp_t, exp_t, loc_t)
| ExpFor: ((pat_t, exp_t) list, pat_t, exp_t, for_flags_t, loc_t)
| ExpMap: (((pat_t, exp_t) list, pat_t) list, exp_t, for_flags_t, ctx_t)
| ExpTryCatch: (exp_t, (pat_t, exp_t) list, ctx_t)
| ExpMatch: (exp_t, (pat_t, exp_t) list, ctx_t)
| ExpCast: (exp_t, typ_t, ctx_t)
| ExpTyped: (exp_t, typ_t, ctx_t)
| ExpCCode: (string, ctx_t)
| DefVal: (pat_t, exp_t, val_flags_t, loc_t)
| DefFun: deffun_t ref
| DefExn: defexn_t ref
| DefTyp: deftyp_t ref
| DefVariant: defvariant_t ref
| DefInterface: definterface_t ref
| DirImport: ((id_t, id_t) list, loc_t)
| DirImportFrom: (id_t, id_t list, loc_t)
| DirPragma: (string list, loc_t)
type pat_t =
| PatAny: loc_t
| PatLit: (lit_t, loc_t)
| PatIdent: (id_t, loc_t)
| PatTuple: (pat_t list, loc_t)
| PatVariant: (id_t, pat_t list, loc_t)
| PatRecord: (id_t?, (id_t, pat_t) list, loc_t)
| PatCons: (pat_t, pat_t, loc_t)
| PatAs: (pat_t, id_t, loc_t)
| PatTyped: (pat_t, typ_t, loc_t)
| PatWhen: (pat_t, exp_t, loc_t)
| PatAlt: (pat_t list, loc_t)
| PatRef: (pat_t, loc_t)
type env_entry_t =
| EnvId: id_t
| EnvTyp: typ_t
/*
Environment (env_t) is the mapping from id_t to env_entry_t list.
It's the key data structure used by the type checker.
That is, for each id Id.Name(i) (which corresponds to some abstract symbol <i>)
we store a list of possible matches Id.Val(i, j) - the really defined symbols.
When the key is Id.Temp(prefix, k), we can only have a single match Id.Temp(prefix, k).
Why have a list of possible matches? Because:
* in the nested scopes we can redefine a symbol from the outer scope
* a defined value can be redefined later in the same block: val a = 5; val a = a + 1
* we can have overloaded functions, e.g. sin:float->float and sin:double->double
* types and functions/values with the same name can co-exist without conflicts, e.g.
string type and string:'t->string functions.
Note that we use purely-functional data structure (Map) to store the environment.
Such immutable data structure let us forget about the neccesity to "undo" environment changes
when we get back from the nested expression analysis, at the expense of slight loss in efficiency
(however, the type checker is very inexpensive compiler stage, even in "-O0" compile mode)
*/
type env_t = (id_t, env_entry_t list) Map.t
type idmap_t = (id_t, id_t) Map.t
type idset_t = id_t Set.t
val empty_env: env_t = Map.empty(cmp_id)
val empty_idset: idset_t = Set.empty(cmp_id)
val empty_idmap: idmap_t = Map.empty(cmp_id)
type id_hashset_t = id_t Hashset.t
fun hash((x, y, z): (int, int, int)) =
(((FNV_1A_OFFSET ^ uint64(x))*FNV_1A_PRIME ^ uint64(y))*
FNV_1A_PRIME ^ uint64(z))*FNV_1A_PRIME
fun hash(n: id_t): hash_t
{
| IdName(i) => hash(i)
| IdVal(i, j) => hash((1, i, j))
| IdTemp(i, j) => hash((2, i, j))
}
fun empty_id_hashset(size0: int): id_t Hashset.t = Hashset.empty(size0, noid, hash)
fun id_hashset(s: idset_t) {
val hs = empty_id_hashset(s.size*2)
s.app(fun (x) {hs.add(x)})
hs
}
type defval_t =
{
dv_name: id_t; dv_typ: typ_t;
dv_flags: val_flags_t;
dv_scope: scope_t list;
dv_loc: loc_t
}
type deffun_t =
{
df_name: id_t; df_templ_args: id_t list;
df_args: pat_t list; df_typ: typ_t; df_body: exp_t;
df_flags: fun_flags_t; df_scope: scope_t list;
df_loc: loc_t; df_templ_inst: id_t list ref; df_env: env_t
}
type defexn_t =
{
dexn_name: id_t; dexn_typ: typ_t;
dexn_scope: scope_t list; dexn_loc: loc_t
}
type deftyp_t =
{
dt_name: id_t; dt_templ_args: id_t list;
dt_typ: typ_t; dt_finalized: bool;
dt_scope: scope_t list; dt_loc: loc_t
}
/* variants are represented in a seemingly complex but logical way;
the structure contains the list of variant cases (dvar_cases, a list of (id_t, typ_t) pairs),
as well as the variant constructors (dvar_ctors). Think of the id_t's in dvar_cases
as of enumeration elements that represent different "tag" values.
Whereas the constructors will eventually (in the final compiled code)
become real functions that take the case arguments on input and return the variant instance.
If the variant is generic, then it may have some instances,
which are listed in dvar_templ_inst.
In this case each constructor is also a generic function,
which contains the corresponding list of instances as well.
When variant type is instantiated, its instance is added to dvar_templ_list.
Also, instances of all its constructors are created as well and added
to the corresponding df_templ_inst' lists of the generic constructors.
*/
type defvariant_t =
{
dvar_name: id_t; dvar_templ_args: id_t list;
dvar_alias: typ_t; dvar_flags: var_flags_t;
dvar_cases: (id_t, typ_t) list;
dvar_ctors: id_t list; dvar_templ_inst: id_t list ref;
dvar_scope: scope_t list; dvar_loc: loc_t
}
type definterface_t =
{
di_name: id_t; di_base: id_t; di_members: exp_t list;
di_scope: scope_t list; di_loc: loc_t
}
type defmodule_t =
{
dm_name: id_t; dm_filename: string;
dm_defs: exp_t list; dm_idx: int;
dm_deps: id_t list; dm_env: env_t;
dm_parsed: bool; dm_real: bool
}
type pragmas_t =
{
pragma_cpp: bool;
pragma_clibs: (string, loc_t) list
}
type id_info_t =
| IdNone
| IdDVal: defval_t
| IdFun: deffun_t ref
| IdExn: defexn_t ref
| IdTyp: deftyp_t ref
| IdVariant: defvariant_t ref
| IdInterface: definterface_t ref
| IdModule: defmodule_t ref
type 't dynvec_t =
{
count: int;
data: 't [];
val0: 't
}
fun dynvec_create(v0: 't): 't dynvec_t ref = ref (dynvec_t {
count=0,
data=(array(): 't []),
val0=v0
})
fun dynvec_clear(v: 't dynvec_t ref) {
v->count = 0
v->data = (array() : 't [])
}
fun dynvec_isempty(v: 't dynvec_t ref) = v->count == 0
fun dynvec_init(v: 't dynvec_t ref, n: int) {
v->count = n
v->data = array(n, v->val0)
}
fun dynvec_push(v: 't dynvec_t ref) {
val sz = size(v->data)
val n0 = v->count
if sz <= n0 {
val n1 = max(n0, 128)*3/2
val old_data = v->data
val new_data = [| for i <- 0:n1 { if i < n0 {old_data[i]} else {v->val0} } |]
v->data = new_data
}
val i = n0
v->count = n0 + 1
i
}
fun dynvec_get(v: 't dynvec_t ref, i: int) = v->data[i]
fun dynvec_set(v: 't dynvec_t ref, i: int, newv: 't) = v->data[i] = newv
var freeze_ids = false
val all_ids = dynvec_create(IdNone)
var all_strhash: (string, int) Hashmap.t = Hashmap.empty(1024, "", -1, hash)
val all_strings = dynvec_create("")
var all_modules: (string, id_t) Hashmap.t = Hashmap.empty(1024, "", noid, hash)
var all_modules_sorted: id_t list = []
var builtin_exceptions = empty_idmap
var all_compile_errs: exn list = []
var all_compile_err_ctx: string list = []
var block_scope_idx = -1
fun new_id_idx() {
if freeze_ids {
throw Fail("internal error: attempt to add new AST id during K-phase or C code generation phase")
}
dynvec_push(all_ids)
}
fun dump_id(i: id_t) {
| IdName(i) => f"IdName({i})"
| IdVal(i, j) => f"IdVal({i}, {j})"
| IdTemp(i, j) => f"IdTemp({i}, {j})"
}
fun id2str_(i: id_t, pp: bool): string =
if i == noid { "<noid>" }
else {
val (infix, prefix, suffix) =
match i {
| IdName(i) => ("", i, -1)
| IdVal(i, j) => ("@", i, j)
| IdTemp(i, j) => ("@@", i, j)
}
val prefix = dynvec_get(all_strings, prefix)
if pp || suffix < 0 { prefix }
else { f"{prefix}{infix}{suffix}" }
}
fun string(i: id_t): string = id2str_(i, false)
fun pp(i: id_t): string = id2str_(i, true)
fun compile_err(loc: loc_t, msg: string) {
val whole_msg = f"{loc}: error: {msg}"
val whole_msg = match all_compile_err_ctx {
| [] => whole_msg
| ctx => "\n\t".join(whole_msg :: ctx)
}
CompileError(loc, whole_msg)
}
fun compile_warning(loc: loc_t, msg: string) {
val whole_msg = f"{loc}: warning: {msg}"
println(whole_msg)
}
fun push_compile_err(err: exn) { all_compile_errs = err :: all_compile_errs }
fun check_compile_errs() =
match all_compile_errs {
| err :: _ => throw PropagateCompileError
| _ => {}
}
fun print_compile_err(err: exn) {
| CompileError(loc, msg) => println(msg)
| Fail(msg) => println(f"Failure: {msg}")
| _ => println("\n\nException {err} occured")
}
fun pr_verbose(str: string): void =
if Options.opt.verbose {
val eol = if str.endswith("\n") {""} else {"\n"}
print(f"{str}{eol}")
File.stdout.flush()
}
fun id2prefix(i: id_t) {
val prefix =
match i {
| IdName(i) => i
| IdVal(i, _) => i
| IdTemp(i, _) => i
}
dynvec_get(all_strings, prefix)
}
fun id2idx_(i: id_t, loc: loc_t) =
match i {
| IdVal(_, i_real) => i_real
| IdTemp(_, i_real) => i_real
| IdName _ => throw compile_err(loc,
f"attempt to query information about unresolved '{i}'")
}
fun id2idx(i: id_t) = id2idx_(i, noloc)
fun id_info(i: id_t, loc: loc_t) = dynvec_get(all_ids, id2idx_(i, loc))
fun is_unique_id(i: id_t) {
| IdName _ => false
| _ => true
}
fun get_id_prefix(s: string): int
{
val h_idx = all_strhash.find_idx_or_insert(s)
val idx = all_strhash.r->table[h_idx].data
if idx >= 0 { idx }
else {
val idx = dynvec_push(all_strings)
all_strhash.r->table[h_idx].data = idx
dynvec_set(all_strings, idx, s)
idx
}
}
fun get_id(s: string): id_t {
val i = get_id_prefix(s)
IdName(i)
}
fun gen_temp_id(s: string): id_t {
val i_name = get_id_prefix(s)
val i_real = new_id_idx()
IdTemp(i_name, i_real)
}
fun dup_id(old_id: id_t) {
val k = new_id_idx()
match old_id {
| IdName(i) => IdVal(i, k)
| IdVal(i, _) => IdVal(i, k)
| IdTemp(i, _) => IdTemp(i, k)
}
}
fun get_orig_id(i: id_t) {
| IdName _ => i
| IdVal(i, _) => IdName(i)
| IdTemp(_, _) => i
}
fun set_id_entry(i: id_t, n: id_info_t) {
val idx = id2idx(i)
dynvec_set(all_ids, idx, n)
}
fun get_exp_ctx(e: exp_t) {
| ExpNop(l) => (TypVoid, l)
| ExpBreak(_, l) => (TypVoid, l)
| ExpContinue(l) => (TypVoid, l)
| ExpRange(_, _, _, c) => c
| ExpLit(_, c) => c
| ExpIdent(_, c) => c
| ExpBinary(_, _, _, c) => c
| ExpUnary(_, _, c) => c
| ExpIntrin(_, _, c) => c
| ExpSeq(_, c) => c
| ExpMkTuple(_, c) => c
| ExpMkRecord(_, _, c) => c
| ExpMkArray(_, c) => c
| ExpUpdateRecord(_, _, c) => c
| ExpCall(_, _, c) => c
| ExpAt(_, _, _, _, c) => c
| ExpAssign(_, _, l) => (TypVoid, l)
| ExpMem(_, _, c) => c
| ExpThrow(_, l) => (TypErr, l)
| ExpIf(_, _, _, c) => c
| ExpWhile(_, _, l) => (TypVoid, l)
| ExpDoWhile(_, _, l) => (TypVoid, l)
| ExpFor(_, _, _, _, l) => (TypVoid, l)
| ExpMap(_, _, _, c) => c
| ExpTryCatch(_, _, c) => c
| ExpMatch(_, _, c) => c
| ExpCast(_, _, c) => c
| ExpTyped(_, _, c) => c
| ExpCCode(_, c) => c
| DefVal(_, _, _, dv_loc) => (TypDecl, dv_loc)
| DefFun (ref {df_loc}) => (TypDecl, df_loc)
| DefExn (ref {dexn_loc}) => (TypDecl, dexn_loc)
| DefTyp (ref {dt_loc}) => (TypDecl, dt_loc)
| DefVariant (ref {dvar_loc}) => (TypDecl, dvar_loc)
| DefInterface (ref {di_loc}) => (TypDecl, di_loc)
| DirImport(_, l) => (TypDecl, l)
| DirImportFrom(_, _, l) => (TypDecl, l)
| DirPragma(_, l) => (TypDecl, l)
}
fun get_exp_typ(e: exp_t) = get_exp_ctx(e).0
fun get_exp_loc(e: exp_t) = get_exp_ctx(e).1
fun get_pat_loc(p: pat_t) {
| PatAny(l) => l
| PatLit(_, l) => l
| PatIdent(_, l) => l
| PatTuple(_, l) => l
| PatVariant(_, _, l) => l
| PatRecord(_, _, l) => l
| PatCons(_, _, l) => l
| PatAs(_, _, l) => l
| PatTyped(_, _, l) => l
| PatRef(_, l) => l
| PatWhen(_, _, l) => l
| PatAlt(_, l) => l
}
fun pat_skip_typed(p: pat_t) {
| PatTyped(p, _, _) => pat_skip_typed(p)
| _ => p
}
fun get_module(m: id_t) =
match id_info(m, noloc) {
| IdModule(minfo) => minfo
| _ => throw Fail(f"internal error in process_all: {pp(m)} is not a module")
}
fun get_module_env(m: id_t) = get_module(m)->dm_env
fun find_module(mname_id: id_t, mfname: string) =
match all_modules.find_opt(mfname) {
| Some(m_id) => get_module(m_id)
| _ =>
val m_fresh_id = dup_id(mname_id)
val newmodule = ref (defmodule_t {
dm_name=m_fresh_id, dm_filename=mfname,
dm_idx=-1, dm_defs=[], dm_deps=[],
dm_env=empty_env, dm_parsed=false, dm_real=true
})
set_id_entry(m_fresh_id, IdModule(newmodule))
all_modules.add(mfname, m_fresh_id)
newmodule
}
fun new_block_scope() {
block_scope_idx += 1
ScBlock(block_scope_idx)
}
fun new_loop_scope(nested: bool) {
block_scope_idx += 1
ScLoop(nested, block_scope_idx)
}
fun new_map_scope() {
block_scope_idx += 1
ScMap(block_scope_idx)
}
fun new_arr_map_scope() {
block_scope_idx += 1
ScArrMap(block_scope_idx)
}
fun new_fold_scope() {
block_scope_idx += 1
ScFold(block_scope_idx)
}
fun new_try_scope() {
block_scope_idx += 1
ScTry(block_scope_idx)
}
fun scope2str(sc: scope_t list) {
| scj :: rest =>
val prefix = match scj {
| ScBlock(b) => f"block({b})"
| ScLoop(f, b) =>
val nested = if f {"nested_"} else {""}
f"{nested}loop_block({b})"
| ScArrMap(b) => f"arr_map_block({b})"
| ScMap(b) => f"map_block({b})"
| ScFold(b) => f"fold_block({b})"
| ScTry(b) => f"try_block({b})"
| ScFun(f) => f"fun({f})"
| ScClass(c) => f"class({c})"
| ScInterface(i) => f"interface({i})"
| ScModule(m) => f"mod({m})"
}
match rest {
| _ :: _ => prefix + "." + scope2str(rest)
| _ => prefix
}
| _ => ""
}
fun get_module_scope(sc: scope_t list, loc: loc_t) =
match sc {
| ScModule _ :: _ => sc
| _ :: rest => get_module_scope(rest, loc)
| _ => []
}
fun curr_module(sc: scope_t list, loc: loc_t): id_t =
match get_module_scope(sc, loc) {
| ScModule(m) :: _ => m
| _ :: rest => curr_module(rest, loc)
| _ => noid
}
fun is_global_scope(sc: scope_t list)
{
| ScModule _ :: _ => true
| [] => true
| _ => false
}
fun get_qualified_name(name: string, sc: scope_t list) =
match sc {
| (ScModule(m) :: _) when pp(m) == "Builtins" => name
| ScModule(m) :: r => get_qualified_name(pp(m) + "." + name, r)
| [] => name
| sc_top :: r => get_qualified_name(name, r)
}
// out of 'A.B.C.D' we leave just 'D'. just 'D' stays 'D'
fun get_bare_name(n: id_t): id_t {
val n_str = pp(n)
val dot_pos = n_str.rfind('.')
get_id(if dot_pos < 0 {n_str} else {n_str[dot_pos+1:]})
}
fun get_scope(id_info: id_info_t) {
| IdNone => []
| IdDVal ({dv_scope}) => dv_scope
| IdFun (ref {df_scope}) => df_scope
| IdExn (ref {dexn_scope}) => dexn_scope
| IdTyp (ref {dt_scope}) => dt_scope
| IdVariant (ref {dvar_scope}) => dvar_scope
| IdInterface (ref {di_scope}) => di_scope
| IdModule _ => []
}
fun get_idinfo_loc(id_info: id_info_t) {
| IdNone | IdModule _ => noloc
| IdDVal ({dv_loc}) => dv_loc
| IdFun (ref {df_loc}) => df_loc
| IdExn (ref {dexn_loc}) => dexn_loc
| IdTyp (ref {dt_loc}) => dt_loc
| IdVariant (ref {dvar_loc}) => dvar_loc
| IdInterface (ref {di_loc}) => di_loc
| _ => noloc
}
fun get_idinfo_typ(id_info: id_info_t, loc: loc_t): typ_t =
match id_info {
| IdModule _ => TypModule
| IdDVal ({dv_typ}) => dv_typ
| IdFun (ref {df_typ}) => df_typ
| IdExn (ref {dexn_typ}) => dexn_typ
| IdTyp (ref {dt_typ}) => dt_typ
| IdVariant (ref {dvar_alias}) => dvar_alias
| IdInterface (ref {di_name}) => TypApp([], di_name)
| IdNone => throw compile_err(loc, "ast: attempt to request type of non-existing symbol")
}
fun get_idinfo_private_flag(id_info: id_info_t) {
| IdNone => true
| IdDVal ({dv_flags}) =>
dv_flags.val_flag_private ||
dv_flags.val_flag_temp ||
dv_flags.val_flag_tempref
| IdFun (ref {df_flags}) => df_flags.fun_flag_private
| IdExn _ => false
| IdTyp _ => false
| IdVariant _ => false
| IdInterface _ => false
| IdModule _ => true
}
fun get_id_typ(i: id_t, loc: loc_t) =
match i {
| IdName _ => make_new_typ()
| _ => get_idinfo_typ(id_info(i, loc), loc)
}
fun get_lit_typ(l: lit_t) {
| LitInt _ => TypInt
| LitSInt(b, _) => TypSInt(b)
| LitUInt(b, _) => TypUInt(b)
| LitFloat(b, _) => TypFloat(b)
| LitString _ => TypString
| LitChar _ => TypChar
| LitBool _ => TypBool
| LitNil => TypList(make_new_typ())
}
/* shorten type specification by redirecting the references in TypVar
to the "root" of each connected component tree - a cluster of equivalent/unified types.
In other words, if we had
t -> t2 -> t3 ... -> root
before the call, after the call we will have
t -> root, t2 -> root, t3 -> root, ...
Returns the root. */
fun deref_typ(t: typ_t): typ_t {
| TypVar _ =>
fun find_root(t: typ_t) {
| TypVar (ref Some(TypVarArray _)) => t
| TypVar (ref Some(TypVarTuple _)) => t
| TypVar (ref Some(TypVarRecord)) => t
| TypVar (ref Some(t2)) => find_root(t2)
| _ => t
}
fun update_refs(t: typ_t, root: typ_t): typ_t =
match t {
| TypVar((ref Some(TypVar(ref Some _) as t1)) as r) =>
*r = Some(root); update_refs(t1, root)
| _ => root
}
update_refs(t, find_root(t))
| _ => t
}
fun is_typ_scalar(t: typ_t): bool {
| TypInt | TypSInt _ | TypUInt _ | TypFloat _ | TypBool | TypChar => true
| TypVar (ref Some(t)) => is_typ_scalar(t)
| _ => false
}
fun get_numeric_typ_size(t: typ_t, allow_tuples: bool): int =
match deref_typ(t) {
| TypInt => 8 // assume 64 bits for simplicity
| TypSInt b => b/8
| TypUInt b => b/8
| TypFloat b => b/8
| TypBool => 1
| TypChar => 4
| TypVar (ref Some(t)) => get_numeric_typ_size(t, allow_tuples)
| TypTuple(tl) =>
if !allow_tuples {-1}
else {
fold sz=0 for t<-tl {
val szj = get_numeric_typ_size(t, true)
if szj < 0 || sz < 0 {-1} else {sz + szj}
}
}
| _ => -1
}
fun string(fm: for_make_t)
{
| ForMakeNone => "ForMakeNone"
| ForMakeArray => "ForMakeArray"
| ForMakeList => "ForMakeList"
| ForMakeTuple => "ForMakeTuple"
| _ => "ForMake???"
}
fun string(c: cmpop_t) {
| CmpEQ => "=="
| CmpNE => "!="
| CmpLT => "<"
| CmpLE => "<="
| CmpGE => ">="
| CmpGT => ">"
}
fun string(bop: binary_t) {
| OpAdd => "+"
| OpSub => "-"
| OpMul => "*"
| OpDiv => "/"
| OpMod => "%"
| OpPow => "**"
| OpDotMul => ".*"
| OpDotDiv => "./"
| OpDotMod => ".%"
| OpDotPow => ".**"
| OpShiftLeft => "<<"
| OpShiftRight => ">>"
| OpBitwiseAnd => "&"
| OpLogicAnd => "&&"
| OpBitwiseOr => "|"
| OpLogicOr => "||"
| OpBitwiseXor => "^"
| OpSpaceship => "<=>"
| OpDotSpaceship => ".<=>"
| OpSame => "==="
| OpCmp(c) => string(c)
| OpDotCmp(c) => "."+string(c)
| OpCons => "::"
}
fun string(uop: unary_t) {
| OpPlus => "+"
| OpNegate => "-"
| OpDotMinus => ".-"
| OpBitwiseNot => "~"
| OpLogicNot => "!"
| OpExpand => "\\"
| OpMkRef => "REF"