-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcompile.ml
2664 lines (2545 loc) · 115 KB
/
compile.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
open Pretty
open Phases
open Exprs
open Assembly
open Errors
open Graph
module StringSet = Set.Make (String)
type 'a name_envt = (string * 'a) list
type 'a tag_envt = (tag * 'a) list
let print_env env how =
debug_printf "Env is\n";
List.iter (fun (id, bind) -> debug_printf " %s -> %s\n" id (how bind)) env
let const_true = HexConst 0xFFFFFFFFFFFFFFFFL
let const_false = HexConst 0x7FFFFFFFFFFFFFFFL
let bool_mask = HexConst 0x8000000000000000L
let bool_tag = 0x0000000000000007L
let bool_tag_mask = 0x0000000000000007L
let num_tag = 0x0000000000000000L
let num_tag_mask = 0x0000000000000001L
let closure_tag = 0x0000000000000005L
let closure_tag_mask = 0x0000000000000007L
let tuple_tag = 0x0000000000000001L
let tuple_tag_mask = 0x0000000000000007L
let struct_tag = 0x0000000000000003L
let struct_tag_mask = 0x0000000000000007L
let const_nil = HexConst tuple_tag
let err_COMP_NOT_NUM = 1L
let err_ARITH_NOT_NUM = 2L
let err_LOGIC_NOT_BOOL = 3L
let err_IF_NOT_BOOL = 4L
let err_OVERFLOW = 5L
let err_GET_NOT_TUPLE = 6L
let err_GET_LOW_INDEX = 7L
let err_GET_HIGH_INDEX = 8L
let err_NIL_DEREF = 9L
let err_OUT_OF_MEMORY = 10L
let err_SET_NOT_TUPLE = 11L
let err_SET_LOW_INDEX = 12L
let err_SET_HIGH_INDEX = 13L
let err_CALL_NOT_CLOSURE = 14L
let err_CALL_ARITY_ERR = 15L
let err_SET_NOT_NUM = 16L
let err_GET_NOT_NUM = 17L
let err_TUPLE_BAD_DESTRUCT = 18L
let err_GETTER_NOT_STRUCT = 19L
let err_SETTER_NOT_STRUCT = 20L
let err_GETTER_FIELD_NOT_FOUND = 21L
let err_SETTER_FIELD_NOT_FOUND = 22L
let err_SETTER_FIELD_WRONG_STRUCT = 23L
let err_CONSTRUCT_FIELD_WRONG_STRUCT = 24L
let dummy_span = (Lexing.dummy_pos, Lexing.dummy_pos)
let first_six_args_registers = [RDI; RSI; RDX; RCX; R8; R9]
let callee_saved_regs : arg list = [Reg R12; Reg R14; Reg RBX]
let reg_colors : arg list =
[Reg R10; Reg R12; Reg R13; Reg R14; Reg RBX; Reg RDI; Reg RSI; Reg RDX; Reg R8; Reg R9]
let max_color_weight = List.length reg_colors - 1
let heap_reg = R15
let scratch_reg = R11
(* you can add any functions or data defined by the runtime here for future use *)
let wrappable_native_fun_env : int name_envt =
[("input", 0); ("testarg", 9); ("equal", 2); ("print", 1)]
let natives_fun_env : int name_envt =
wrappable_native_fun_env @ [("error", 2); ("our_code_starts_here", 2); ("printStack", 1)]
(* You may find some of these helpers useful *)
let find_pos ls x =
let rec help ls i =
match ls with
| [] -> -1
| y :: rest -> if y = x then i else help rest (i + 1)
in
help ls 0
let rec find ls x =
match ls with
| [] -> raise (InternalCompilerError (sprintf "Name %s not found" (ExtLib.dump x)))
| (y, v) :: rest -> if y = x then v else find rest x
let rec find_one_named (l : ('a * _) list) (name : 'a) : bool =
match l with
| [] -> false
| (x, _) :: xs -> name = x || find_one_named xs name
let option_get (opt : 'a option) : 'a =
match opt with
| Some x -> x
| _ -> raise (InternalCompilerError "Tried to unwrap an option that had none as a value")
(* looks up in the environment from the given tag and finds the first value named the given name *)
let rec find_in_env_tag (env : arg name_envt tag_envt) (name : string) (tag : tag) =
match env with
| [] -> raise (InternalCompilerError (sprintf "Name %s not found in tag-space: %d" name tag))
| (env_tag, n_env) :: rest ->
if env_tag = tag
then try find n_env name with InternalCompilerError _ -> find_in_env_tag [] name tag
else find_in_env_tag rest name tag
(* looks up all values in the nested environment and finds the first value named the given name *)
let rec find_in_env (env : arg name_envt tag_envt) (name : string) : arg =
match env with
| [] -> raise (InternalCompilerError (sprintf "Name %s not found" name))
| (_, n_env) :: rest -> (
try find n_env name with InternalCompilerError _ -> find_in_env rest name )
let int_map (f : int -> 'a) (i : int) (start : int) : 'a list =
let rec help (acc : int) = if acc = i then [] else f acc :: help (acc + 1) in
help start
let count_vars e =
let rec helpA e =
match e with
| ASeq (e1, e2, _) -> max (helpC e1) (helpA e2)
| ALet (_, bind, body, _) -> 1 + max (helpC bind) (helpA body)
| ALetRec (binds, body, _) ->
List.length binds
+ List.fold_left max (helpA body) (List.map (fun (_, rhs) -> helpC rhs) binds)
| ACExpr e -> helpC e
and helpC e =
match e with
| CIf (_, t, f, _) -> max (helpA t) (helpA f)
| _ -> 0
in
helpA e
let rec replicate x i = if i = 0 then [] else x :: replicate x (i - 1)
let deepest_stack env =
List.fold_left
(fun max (_, arg) ->
match arg with
| RegOffset (si, RBP) ->
let off = si * -1 / word_size in
if off > max then off else max
| _ -> max )
0 env
let rec find_decl (ds : 'a decl list) (name : string) : 'a decl option =
match ds with
| [] -> None
| (DFun (fname, _, _, _) as d) :: ds_rest ->
if name = fname then Some d else find_decl ds_rest name
let rec find_one (l : 'a list) (elt : 'a) : bool =
match l with
| [] -> false
| x :: xs -> elt = x || find_one xs elt
let rec find_dup (l : 'a list) : 'a option =
match l with
| [] -> None
| [x] -> None
| x :: xs -> if find_one xs x then Some x else find_dup xs
let rec find_opt (env : 'a name_envt) (elt : string) : 'a option =
match env with
| [] -> None
| (x, v) :: rst -> if x = elt then Some v else find_opt rst elt
(* Prepends a list-like env onto an name_envt *)
let merge_envs list_env1 list_env2 = list_env1 @ list_env2
(* Combines two name_envts into one, preferring the first one *)
let prepend env1 env2 =
let rec help env1 env2 =
match env1 with
| [] -> env2
| ((k, _) as fst) :: rst ->
let rst_prepend = help rst env2 in
if List.mem_assoc k env2 then rst_prepend else fst :: rst_prepend
in
help env1 env2
let env_keys e = List.map fst e
(* Represents the type of binding in the environment *)
type btype =
| BTId
| BTFun of int (* where int is the arity of the function *)
| BTStruct of int
(* where int is the number of fields of the struct *)
(* Represents the information of a binding, with it's type of binding information *)
type bind_info = btype * sourcespan
(* Runs checks through the AST and either returns the program unchanged (if everything is good) *)
(* or returns a list of errors from the failed checks *)
let is_well_formed (p : sourcespan program) : sourcespan program fallible =
(* constant that defines the shadow environment, such that self cannot be redefined *)
let self_bind = [BName ("self", false, dummy_span)] in
(* Helper function to find a certain binding in the environment. *)
let rec find_in_env (env : bind_info name_envt) ((x_name, x_btype) : string * btype) :
bind_info option =
match env with
| [] -> None
| (el_name, (el_btype, loc)) :: rest -> (
match (x_btype, el_btype) with
| (BTId, BTId | BTFun _, BTFun _ | BTStruct _, BTStruct _) when el_name = x_name ->
Some (el_btype, loc)
| _ -> find_in_env rest (x_name, x_btype) )
in
(* Checks whether a struct of the given name exists in the environment *)
let check_unbound_stru_errs
(stru_name : string)
(stru_pos : sourcespan)
(env : bind_info name_envt) : exn list =
match find_in_env env (stru_name, BTStruct 0) with
| None -> [UnboundStruct (stru_name, stru_pos)]
| _ -> []
in
(* Checks for errors for the given binding and for duplicate bindings in the bind list *)
let rec check_bind_errs
(bind : sourcespan bind)
(binds : sourcespan bind list)
(env : bind_info name_envt) : exn list =
(* Helper to get all duplicate binding errors *)
let rec get_bind_dupes ((name, pos) as bname) (binds : sourcespan bind list) (err_acc : exn list)
: exn list =
match binds with
| [] -> err_acc
| BBlank _ :: rest -> get_bind_dupes bname rest err_acc
| BName (dup_name, _, dup_pos) :: rest | BStruct (dup_name, _, dup_pos) :: rest ->
if name = dup_name
then get_bind_dupes bname rest (DuplicateId (name, pos, dup_pos) :: err_acc)
else get_bind_dupes bname rest err_acc
| BTuple (dup_binds, dup_pos) :: rest -> get_bind_dupes bname (dup_binds @ rest) err_acc
in
match bind with
| BBlank _ -> []
| BName (name, _, pos) -> get_bind_dupes (name, pos) binds []
| BStruct (name, stru_name, pos) ->
let unbound_stru_errs = check_unbound_stru_errs stru_name pos env in
get_bind_dupes (name, pos) binds unbound_stru_errs
| BTuple (dup_binds, pos) -> check_bind_list_errs (dup_binds @ binds) env
and check_bind_list_errs (binds : sourcespan bind list) (env : bind_info name_envt) : exn list =
(* Checks for duplicate bind names in a list of binds *)
match binds with
| [] -> []
| bind :: rest -> check_bind_errs bind rest env @ check_bind_list_errs rest env
in
(* Adds the bind to the given environment, does not check for duplicates! *)
let rec build_bind_env (bind : sourcespan bind) (env : bind_info name_envt) : bind_info name_envt
=
match bind with
| BBlank _ -> env
| BName (name, _, pos) | BStruct (name, _, pos) -> (name, (BTId, pos)) :: env
| BTuple (binds, _) -> build_bind_list_env binds env
and build_bind_list_env (binds : sourcespan bind list) (env : bind_info name_envt) :
bind_info name_envt =
(* Adds the binds in the bind list to the given environment, does not check for duplicates! *)
List.fold_left (fun prev_env b -> build_bind_env b prev_env) env binds
in
(* Helper function to run a well-formed check on a single expression. *)
let rec wf_E (env : bind_info name_envt) (e : sourcespan expr) : exn list =
match e with
| EBool _ -> []
| ENil _ -> []
| ENumber (i, loc) ->
(* Checks if the number is between bounds *)
if i > Int64.div Int64.max_int 2L || i < Int64.div Int64.min_int 2L
then [Overflow (i, loc)]
else []
| EId (x, loc) ->
(* Checks if the given identifier is in the environment *)
if find_one_named env x then [] else [UnboundId (x, loc)]
| EPrim1 (_, body, _) -> wf_E env body
| EPrim2 (_, l, r, _) -> wf_E env l @ wf_E env r
| EIf (c, t, f, _) -> wf_E env c @ wf_E env t @ wf_E env f
| ELet (bindings, body, loc) ->
let env', _, errs =
List.fold_left
(fun (prev_env, prev_binds, prev_errs) binding ->
let bind, e, b_pos = binding in
let bind_errs = check_bind_errs bind prev_binds env in
let expr_errs = wf_E prev_env e in
let env' = build_bind_env bind prev_env in
(env', bind :: prev_binds, expr_errs @ bind_errs @ prev_errs) )
(env, self_bind, []) bindings
in
wf_E env' body @ errs
| EApp (func, args, cl, loc) ->
let arity = List.length args in
let call_errs =
match func with
| EId (name, _) -> (
match find_in_env env (name, BTFun arity) with
| Some (BTFun env_arity, _) when env_arity != arity -> [Arity (env_arity, arity, loc)]
| _ -> [] )
| _ -> []
in
let funexpr_errs = wf_E env func in
let args_errs = List.concat_map (fun a -> wf_E env a) args in
call_errs @ funexpr_errs @ args_errs
| EConstruct (stru_name, fields, pos) ->
let arity = List.length fields in
let unbound_stru_errs, env_res =
match find_in_env env (stru_name, BTStruct arity) with
| Some (BTStruct env_arity, env_pos) -> ([], Some (env_arity, env_pos))
| None | Some _ -> ([UnboundStruct (stru_name, pos)], None)
in
let arity_errs =
match env_res with
| Some (env_arity, env_pos) ->
if env_arity = arity then [] else [StructArity (env_arity, arity, pos)]
| None -> []
in
unbound_stru_errs @ arity_errs @ List.concat_map (fun e -> wf_E env e) fields
| EGetter (expr, field, _) ->
(* NOTE: there is no way without a type system we could check if the field exists or not *)
wf_E env expr
| ESetter (expr, field, new_expr, _) ->
(* NOTE: there is no way without a type system we could check if the field exists or not *)
wf_E env expr @ wf_E env new_expr
| EIs (e, stru_name, pos) | EAs (e, stru_name, pos) ->
let unbound_stru_errs = check_unbound_stru_errs stru_name pos env in
unbound_stru_errs @ wf_E env e
| ETuple (exprs, _) -> List.concat_map (fun e -> wf_E env e) exprs
| ESeq (l, r, _) -> wf_E env l @ wf_E env r
| EGetItem (e, index, _) -> wf_E env e @ wf_E env index
| ESetItem (e, index, new_e, _) -> wf_E env e @ wf_E env index @ wf_E env new_e
| ELambda (binds, body, _) ->
let bind_errs = check_bind_list_errs (self_bind @ binds) env in
let env' = build_bind_list_env binds env in
bind_errs @ wf_E env' body
| ELetRec (bindings, body, _) ->
let env', _, bind_errs =
List.fold_left
(fun (prev_env, prev_binds, prev_errs) binding ->
let bind, e, b_pos = binding in
let bind_errs = check_bind_errs bind prev_binds env in
let env' = build_bind_env bind prev_env in
let letrec_non_function_errs =
match e with
| ELambda _ -> []
| _ -> [LetRecNonFunction (bind, b_pos)]
in
(env', bind :: prev_binds, letrec_non_function_errs @ bind_errs @ prev_errs) )
(env, self_bind, []) bindings
in
let lambda_errs = List.concat_map (fun (_, expr, _) -> wf_E env' expr) bindings in
lambda_errs @ bind_errs @ wf_E env' body
and wf_D (env : bind_info name_envt) (d : sourcespan decl) : exn list =
match d with
| DFun (funname, binds, body, loc) ->
let body_env = build_bind_list_env binds env in
wf_E body_env body @ check_bind_list_errs binds env
and wf_DG (env : bind_info name_envt) (ds : sourcespan decl list) : exn list * bind_info name_envt
=
(* Helper function to build an environment of declaration names, in order to allow mutually referential functions *)
let rec build_decls_env (env : bind_info name_envt) (decls : sourcespan decl list) :
exn list * bind_info name_envt =
match decls with
| [] -> ([], [])
| DFun (name, args, body, loc) :: rest ->
let arity = List.length args in
(* Checks for duplicate function names in the environment *)
let fun_dup_errs =
match find_in_env env (name, BTFun arity) with
| Some (BTFun env_arity, env_loc) -> [DuplicateFun (name, loc, env_loc)]
| _ -> []
in
let decl_env = [(name, (BTFun arity, loc))] in
let next_errs, next_env = build_decls_env decl_env rest in
(fun_dup_errs @ next_errs, decl_env @ next_env)
in
(* Builds the function name environment from each declaration *)
let decls_errs, decls_env = build_decls_env env ds in
let decl_inner_errs = List.concat_map (fun d -> wf_D (decls_env @ env) d) ds in
(decl_inner_errs @ decls_errs, decls_env)
(* Helper function to run a well-formed check on a single method. *)
and wf_M (env : bind_info name_envt) (m : 'a mthd) (stru_name : string) :
exn list * (string * bind_info) =
match m with
| DMethod (name, binds, body, pos) ->
let arity = List.length binds in
let method_dup_err =
match find_in_env env (name, BTFun arity) with
| Some (BTFun env_arity, env_loc) -> [DuplicateMethod (name, pos, env_loc)]
| _ -> []
in
let self_binding = BStruct ("self", stru_name, pos) in
let env_entry = (name, (BTFun arity, pos)) in
let body_env = build_bind_list_env (self_binding :: binds) (env @ [env_entry]) in
let arg_dup_errs = check_bind_list_errs (self_binding :: binds) env in
let body_errs = wf_E body_env body in
(method_dup_err @ arg_dup_errs @ body_errs, env_entry)
(* Helper function to run a well-formed check on a single struct. *)
and wf_S (env : bind_info name_envt) (s : 'a stru) : exn list * bind_info name_envt =
match s with
| DStruct (stru_name, fields, methods, pos) ->
let arity = List.length fields in
let env_entries = [(stru_name, (BTStruct arity, pos))] in
let env' = env_entries @ env in
let rec process_field_errs (fields : sourcespan strufield list) =
let rec get_dupes (name : string) (fields : sourcespan strufield list) =
match fields with
| [] -> []
| FName dup_name :: rest ->
if name = dup_name then [DuplicateField (name, pos)] else get_dupes name rest
| FStruct (dup_name, _) :: rest ->
if name = dup_name then [DuplicateField (name, pos)] else get_dupes name rest
| _ ->
raise (InternalCompilerError "FMethod fields shouldn't be generated in well_formed")
in
match fields with
| [] -> []
| FName name :: rest -> get_dupes name rest @ process_field_errs rest
| FStruct (name, stru_name) :: rest ->
let dup_errs = get_dupes name rest in
let unbound_stru_errs = check_unbound_stru_errs stru_name pos env' in
dup_errs @ unbound_stru_errs @ process_field_errs rest
| _ -> raise (InternalCompilerError "FMethod fields shouldn't be generated in well_formed")
in
let dup_stru_errs =
match find_in_env env (stru_name, BTStruct arity) with
| Some (BTStruct _, env_pos) -> [DuplicateStruct (stru_name, pos, env_pos)]
| _ -> []
in
let mthds_errs, mthds_env =
List.fold_left
(fun (prev_errs, prev_env) m ->
let mthd_errs, ((mthd_name, (_, mthd_pos)) as mthd_entry) =
wf_M (prev_env @ env') m stru_name
in
let clashing_field_err =
List.fold_left
(fun next f ->
let name =
match f with
| FName name -> name
| FStruct (name, _) -> name
| _ ->
raise
(InternalCompilerError
"FMethod fields shouldn't be generated in well_formed" )
in
if name = mthd_name then [DuplicateField (name, mthd_pos)] @ next else next )
[] fields
in
(mthd_errs @ clashing_field_err @ prev_errs, mthd_entry :: prev_env) )
([], []) methods
in
let field_errs = process_field_errs fields in
(dup_stru_errs @ mthds_errs @ field_errs, env_entries)
in
match p with
| Program (strus, decls_groups, body, _) -> (
(* builds initial environment from builtins *)
let builtins_env =
List.map
(fun (name, arity) -> (name, (BTFun arity, (Lexing.dummy_pos, Lexing.dummy_pos))))
natives_fun_env
in
(* finds errors and builds environment from structs *)
let stru_errs, stru_env =
List.fold_left
(fun (prev_errs, prev_env) stru ->
let errs, env' = wf_S prev_env stru in
(errs @ prev_errs, env' @ prev_env) )
([], builtins_env) strus
in
(* finds errors and builds environment from decls *)
let dg_errs, dg_env =
List.fold_right
(fun decls (prev_errs, prev_env) ->
let errs, env = wf_DG stru_env decls in
(errs @ prev_errs, env @ prev_env) )
decls_groups ([], stru_env)
in
match wf_E dg_env body @ dg_errs @ stru_errs with
| [] -> Ok p
| errs -> Error errs )
(* ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;; DESUGARING ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; *)
(* represents an environment of structs to their methods name and their desugared expressions. *)
type 'a cenv = (string * 'a expr) list name_envt
let desugar (p : 'a program) : 'a program =
let gensym =
let next = ref 0 in
fun name ->
next := !next + 1;
sprintf "%s?%d" name !next
in
(* helper to patch the given methods into fields of a constructor *)
let patch_methods stru_id stru_name methods =
let info = expr_info stru_id in
List.fold_left
(fun next_e name ->
ESeq
( ESetter
( EAs (stru_id, stru_name, info),
name,
EApp (EId ("tempcurry_" ^ name, info), [stru_id], Snake, info),
info ),
next_e,
info ) )
stru_id methods
in
let rec desugar_E (e : 'a expr) (cenv : 'a cenv) : 'a expr =
(* Helper function to desugar a binding. Assumes that for a tuple binding, the binding pattern matches
the shape of the bound tuple. Desugar based on the pattern. *)
let rec desugar_binding (b : 'a binding) : 'a binding list =
match b with
| BBlank bpos, e, pos -> [(BBlank bpos, desugar_E e cenv, pos)]
| BName (name, shadow, bpos), e, pos -> [(BName (name, shadow, bpos), desugar_E e cenv, pos)]
| BStruct (name, stru_name, bpos), e, pos ->
[(BStruct (name, stru_name, bpos), desugar_E e cenv, pos)]
| BTuple (binds, bpos), rhs, pos ->
let temp_name = gensym "tup" in
let temp_id = EId (temp_name, bpos) in
[ (BName (temp_name, false, bpos), rhs, pos);
( BBlank pos,
EPrim2 (CheckSize, temp_id, ENumber (Int64.of_int (List.length binds), pos), pos),
pos ) ]
@ List.concat
(List.mapi
(fun i b ->
desugar_binding
(b, EGetItem (temp_id, ENumber (Int64.of_int i, bpos), bpos), bpos) )
binds )
in
match e with
| EBool _ -> e
| ENumber _ -> e
| ENil _ -> e
| EId _ -> e
| EPrim1 (op, e, info) -> EPrim1 (op, desugar_E e cenv, info)
| EPrim2 (op, l, r, info) -> (
(* Double negates the given expression to ensure that a Boolean error is thrown if the expression is not bool *)
let double_negate (e : 'a expr) : 'a expr =
EPrim1 (Not, EPrim1 (Not, e, expr_info e), expr_info e)
in
let desugared_l = double_negate (desugar_E l cenv) in
let desugared_r = double_negate (desugar_E r cenv) in
(* Desugars and/or into ifs to preserve short-circuiting semantics *)
match op with
| And -> EIf (desugared_l, desugared_r, desugared_l, info)
| Or -> EIf (desugared_l, desugared_l, desugared_r, info)
| _ -> EPrim2 (op, desugar_E l cenv, desugar_E r cenv, info) )
| EIf (c, t, f, info) -> EIf (desugar_E c cenv, desugar_E t cenv, desugar_E f cenv, info)
| EApp (func, args, call_type, info) ->
EApp (desugar_E func cenv, List.map (fun a -> desugar_E a cenv) args, call_type, info)
| ELet (bindings, body, info) ->
ELet (List.concat (List.map desugar_binding bindings), desugar_E body cenv, info)
| ETuple (exprs, info) -> ETuple (List.map (fun e -> desugar_E e cenv) exprs, info)
| EGetItem (e, index, info) -> EGetItem (desugar_E e cenv, desugar_E index cenv, info)
| ESetItem (e, index, new_e, info) ->
ESetItem (desugar_E e cenv, desugar_E index cenv, desugar_E new_e cenv, info)
| ESeq (l, r, info) -> ELet ([(BBlank info, desugar_E l cenv, info)], desugar_E r cenv, info)
| ELambda (binds, body, info) ->
let rec desugar_bind (b : 'a bind) : 'a bind list * 'a binding list =
match b with
| BBlank binfo -> ([BName ("_", false, binfo)], [])
| BName (name, shadow, binfo) -> ([BName (name, shadow, binfo)], [])
| BStruct (name, stru_name, binfo) -> ([BStruct (name, stru_name, binfo)], [])
| BTuple (binds, binfo) ->
let temp_name = gensym "arg_tup" in
let temp_bind = BName (temp_name, false, binfo) in
let temp_id = EId (temp_name, binfo) in
let temp_binding = (b, temp_id, binfo) in
([temp_bind], [temp_binding])
in
let desugared_binds, body_bindings =
List.fold_right
(fun bind (prev_bs, prev_bings) ->
let bs, bings = desugar_bind bind in
(bs @ prev_bs, bings @ prev_bings) )
binds ([], [])
in
let des_body =
match body_bindings with
| [] -> desugar_E body cenv
| _ -> desugar_E (ELet (body_bindings, body, info)) cenv
in
ELambda (desugared_binds, des_body, info)
| ELetRec (bindings, body, info) ->
ELetRec (List.concat (List.map desugar_binding bindings), desugar_E body cenv, info)
| EConstruct (stru_name, fields, info) -> (
(* when we encounter a constructor, we check if that constructor has any methods, if not, we don't *)
(* patch the methods. if it does have methods, we check if we have desugared this constructor already *)
(* (this might be the body of a method), if wwe have, we don't patch methods. otherwise, we patch *)
(* the methods of this constructor to be curried (on the self parameter) first-class functions. *)
let maybe_methods = find_opt cenv stru_name in
match maybe_methods with
| None -> EConstruct (stru_name, List.map (fun f -> desugar_E f cenv) fields, info)
| Some ms when List.length ms = 0 ->
EConstruct (stru_name, List.map (fun f -> desugar_E f cenv) fields, info)
| Some methods ->
let temp_stru_inner = gensym stru_name in
let stru_id_inner = EId (temp_stru_inner, info) in
let methods_bindings =
List.map
(fun (name, body) ->
( BName ("tempcurry_" ^ name, false, info),
ELambda ([BStruct ("self", stru_name, info)], body, info),
info ) )
methods
in
let unpatched_construct =
EConstruct
( stru_name,
List.map (fun f -> desugar_E f cenv) fields
@ List.map (fun _ -> ENil info) methods,
info )
in
let method_names = List.map (fun (name, _) -> name) methods in
let patched_methods = patch_methods stru_id_inner stru_name method_names in
let letrecs = ELetRec (methods_bindings, patched_methods, info) in
ELet
( [(BStruct (temp_stru_inner, stru_name, info), unpatched_construct, info)],
letrecs,
info ) )
| EGetter (expr, field, info) -> EGetter (desugar_E expr cenv, field, info)
| ESetter (expr, field, new_expr, info) ->
ESetter (desugar_E expr cenv, field, desugar_E new_expr cenv, info)
| EIs (e, stru_name, info) -> EIs (desugar_E e cenv, stru_name, info)
| EAs (e, stru_name, info) -> EAs (desugar_E e cenv, stru_name, info)
(* helper to desugar a decl *)
and desugar_D (d : 'a decl) (cenv : 'a cenv) : 'a binding =
match d with
| DFun (funname, binds, body, info) ->
(BName (funname, false, info), desugar_E (ELambda (binds, body, info)) cenv, info)
(* helper to desugar a struct. it additionally generates a cenv from this struct and the previous struct *)
and desugar_S (s : 'a stru) (cenv : 'a cenv) : 'a stru * 'a cenv =
match s with
| DStruct (sname, fields, mthds, tag) ->
let method_names =
List.map
(fun m ->
match m with
| DMethod (name, _, _, _) -> name )
mthds
in
(* helper to desugar a method. generates the environment entry for this method. *)
let rec desugar_M (m : 'a mthd) : 'a strufield * (string * 'a expr) =
match m with
| DMethod (name, binds, body, tag) ->
(* helper to recur on expressions. *)
let rec helpE (e : 'a expr) =
match e with
| ESeq (e1, e2, t) -> ESeq (helpE e1, helpE e2, t)
| ETuple (exprs, tag) -> ETuple (List.map helpE exprs, tag)
| EConstruct (stru_name, fields, tag) ->
(* when we encounter a constructor: if the constructor is constructing the current struct, *)
(* then we desugar it to include the patched methods. otherwise we recur on the fields. *)
if stru_name = sname
then
let stru_temp = gensym stru_name in
let stru_id = EId (stru_temp, tag) in
let method_fields =
List.map (fun name -> EGetter (EId ("self", tag), name, tag)) method_names
in
let patched_methods = patch_methods stru_id stru_name method_names in
ELet
( [ ( BStruct (stru_temp, stru_name, tag),
EConstruct (stru_name, List.map helpE fields @ method_fields, tag),
tag ) ],
patched_methods,
tag )
else EConstruct (stru_name, List.map helpE fields, tag)
| EGetter (expr, field, tag) -> EGetter (helpE expr, field, tag)
| ESetter (expr, field, new_expr, tag) ->
ESetter (helpE expr, field, helpE new_expr, tag)
| EIs (e, stru_name, tag) -> EIs (helpE e, stru_name, tag)
| EAs (e, stru_name, tag) -> EAs (helpE e, stru_name, tag)
| EGetItem (e, idx, tag) -> EGetItem (helpE e, helpE idx, tag)
| ESetItem (e, idx, newval, tag) -> ESetItem (helpE e, helpE idx, helpE newval, tag)
| EId (x, tag) -> EId (x, tag)
| ENumber (n, tag) -> ENumber (n, tag)
| EBool (b, tag) -> EBool (b, tag)
| ENil tag -> ENil tag
| EPrim1 (op, e, tag) -> EPrim1 (op, helpE e, tag)
| EPrim2 (op, e1, e2, tag) -> EPrim2 (op, helpE e1, helpE e2, tag)
| ELet (binds, body, tag) ->
ELet (List.map (fun (b, e, tag) -> (b, helpE e, tag)) binds, helpE body, tag)
| EIf (cond, thn, els, tag) -> EIf (helpE cond, helpE thn, helpE els, tag)
| EApp (func, args, native, tag) ->
EApp (helpE func, List.map helpE args, native, tag)
| ELetRec (binds, body, tag) ->
ELetRec (List.map (fun (b, e, tag) -> (b, helpE e, tag)) binds, helpE body, tag)
| ELambda (binds, body, tag) -> ELambda (binds, helpE body, tag)
in
(* we fully-desugar the body in order to desugar potential constructors from other structs. *)
(* NOTE: we don't create duplicate code, as we have a check in desugar_E to verify if the constructor *)
(* needs to be desugared or not. *)
let reconstructed_body = ELambda (binds, helpE body, tag) in
let desugared_body = desugar_E reconstructed_body cenv in
(FMethod (name, binds, desugared_body), (name, desugared_body))
in
let fmethods, env_entries =
List.fold_left
(fun (prev_fms, prev_env) m ->
let fm, env = desugar_M m in
(fm :: prev_fms, env :: prev_env) )
([], []) mthds
in
(DStruct (sname, fields @ List.rev fmethods, [], tag), [(sname, env_entries)])
in
match p with
| Program (strus, dgs, body, info) ->
let desugared_strus, cenv =
List.fold_left
(fun (prev_st, prev_env) s ->
let st, env = desugar_S s prev_env in
(st :: prev_st, env @ prev_env) )
([], []) strus
in
let desguared_groups =
List.fold_right
(fun decls prev_expr ->
let bindings = List.map (fun d -> desugar_D d cenv) decls in
ELetRec (bindings, prev_expr, info) )
dgs (desugar_E body cenv)
in
Program (List.rev desugared_strus, [], desguared_groups, info)
(* ASSUMES desugaring is complete *)
let rename_and_tag (p : tag program) : tag program =
let rec rename env p =
match p with
| Program (strus, decls, body, tag) ->
Program
( List.map (helpS env) strus,
List.map (fun group -> List.map (helpD env) group) decls,
helpE env body,
tag )
and helpM env m =
match m with
| DMethod (name, binds, body, tag) -> DMethod (name, binds, helpE env body, tag)
and helpF env f =
match f with
| FMethod (name, binds, body) ->
let binds', env' = helpBS env binds in
FMethod (name, binds', helpE (env' @ env) body)
| _ -> f
and helpS env s =
match s with
| DStruct (name, fields, methods, tag) ->
DStruct (name, List.map (helpF env) fields, List.map (helpM env) methods, tag)
and helpD env decl =
match decl with
| DFun (name, args, body, tag) ->
let newArgs, env' = helpBS env args in
DFun (name, newArgs, helpE env' body, tag)
and helpB env b =
match b with
| BBlank tag -> (b, env)
| BName (name, allow_shadow, tag) ->
let name' = sprintf "%s_%d" name tag in
(BName (name', allow_shadow, tag), (name, name') :: env)
| BStruct (name, stru_name, tag) ->
let name' = sprintf "%s_%d" name tag in
(BStruct (name', stru_name, tag), (name, name') :: env)
| BTuple (binds, tag) ->
let binds', env' = helpBS env binds in
(BTuple (binds', tag), env')
and helpBS env (bs : tag bind list) =
match bs with
| [] -> ([], env)
| b :: bs ->
let b', env' = helpB env b in
let bs', env'' = helpBS env' bs in
(b' :: bs', env'')
and helpBG env (bindings : tag binding list) =
match bindings with
| [] -> ([], env)
| (b, e, a) :: bindings ->
let b', env' = helpB env b in
let e' = helpE env e in
let bindings', env'' = helpBG env' bindings in
((b', e', a) :: bindings', env'')
and helpE env e =
match e with
| ESeq (e1, e2, tag) -> ESeq (helpE env e1, helpE env e2, tag)
| ETuple (es, tag) -> ETuple (List.map (helpE env) es, tag)
| EGetItem (e, idx, tag) -> EGetItem (helpE env e, helpE env idx, tag)
| ESetItem (e, idx, newval, tag) -> ESetItem (helpE env e, helpE env idx, helpE env newval, tag)
| EConstruct (stru_name, fields, tag) -> EConstruct (stru_name, List.map (helpE env) fields, tag)
| EGetter (expr, field, tag) -> EGetter (helpE env expr, field, tag)
| ESetter (expr, field, new_expr, tag) ->
ESetter (helpE env expr, field, helpE env new_expr, tag)
| EIs (e, stru_name, tag) -> EIs (helpE env e, stru_name, tag)
| EAs (e, stru_name, tag) -> EAs (helpE env e, stru_name, tag)
| EPrim1 (op, arg, tag) -> EPrim1 (op, helpE env arg, tag)
| EPrim2 (op, left, right, tag) -> EPrim2 (op, helpE env left, helpE env right, tag)
| EIf (c, t, f, tag) -> EIf (helpE env c, helpE env t, helpE env f, tag)
| ENumber _ -> e
| EBool _ -> e
| ENil _ -> e
| EId (name, tag) -> ( try EId (find env name, tag) with InternalCompilerError _ -> e )
| EApp (func, args, native, tag) -> (
match func with
| EId (name, _) when find_one_named natives_fun_env name ->
EApp (func, List.map (helpE env) args, Native, tag)
| _ ->
let func = helpE env func in
EApp (func, List.map (helpE env) args, Snake, tag) )
| ELet (binds, body, tag) ->
let binds', env' = helpBG env binds in
let body' = helpE env' body in
ELet (binds', body', tag)
| ELetRec (bindings, body, tag) ->
let revbinds, env =
List.fold_left
(fun (revbinds, env) (b, e, t) ->
let b, env = helpB env b in
((b, e, t) :: revbinds, env) )
([], env) bindings
in
let bindings' =
List.fold_left (fun bindings (b, e, tag) -> (b, helpE env e, tag) :: bindings) [] revbinds
in
let body' = helpE env body in
ELetRec (bindings', body', tag)
| ELambda (binds, body, tag) ->
let binds', env' = helpBS env binds in
let body' = helpE env' body in
ELambda (binds', body', tag)
in
rename [] p
(* ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;; STRUCT SYMBOL TABLE GENERATION ;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; *)
(* helper to return the type of a type-tagged expr *)
let e_ty (e : (strutype * tag) expr) : strutype = (fun (ty, _) -> ty) (expr_info e)
(* tries to infer the struct type of the given expression, if it has one *)
(* used to figure out getter/setter struct types, and type annotates the expressions *)
let rec inferP (p : tag program) : (strutype * tag) program =
let rec inferE (e : tag expr) (env : styenv) : (strutype * tag) expr =
match e with
| ESeq (e1, e2, tag) ->
let e2_ans = inferE e2 env in
ESeq (inferE e1 env, e2_ans, (e_ty e2_ans, tag))
| ETuple (exprs, tag) ->
(* NOTE: all of the tuple elements have to be the same type (ok to have some STNone) to be infered *)
let elem_ans = List.map (fun e -> inferE e env) exprs in
let elem_types = List.map (fun e -> e_ty e) elem_ans in
(* filter out all STNone *)
let struct_types =
List.filter
(fun st ->
match st with
| STNone -> false
| _ -> true )
elem_types
in
let ty =
match struct_types with
| x :: xs when List.fold_left (fun prev t -> x = t && prev) true xs -> STTup x
| _ -> STTup STNone
in
ETuple (elem_ans, (ty, tag))
| EConstruct (stru_name, fields, tag) ->
EConstruct (stru_name, List.map (fun f -> inferE f env) fields, (STSome stru_name, tag))
| EGetter (expr, field, tag) ->
let expr_ans = inferE expr env in
let ty =
match e_ty expr_ans with
| STSome stru_name ->
List.fold_left
(fun next (sb, st) ->
match sb with
| SBField name when field = name -> st
| _ -> next )
STNone env
| _ -> STNone
in
EGetter (expr_ans, field, (ty, tag))
| ESetter (expr, field, new_expr, tag) ->
let new_e_ans = inferE new_expr env in
ESetter (inferE expr env, field, new_e_ans, (e_ty new_e_ans, tag))
| EIs (e, stru_name, tag) -> EIs (inferE e env, stru_name, (STNone, tag))
| EAs (e, stru_name, tag) -> EAs (inferE e env, stru_name, (STSome stru_name, tag))
| EGetItem (e, idx, tag) ->
(* NOTE: all of the tuple elements have to be the same type to be infered *)
let e_ans = inferE e env in
let ty =
match e_ty e_ans with
| STTup s -> s
| _ -> STNone
in
EGetItem (e_ans, inferE idx env, (ty, tag))
| ESetItem (e, idx, newval, tag) ->
let newval_ans = inferE newval env in
ESetItem (inferE e env, inferE idx env, newval_ans, (e_ty newval_ans, tag))
| EId (x, tag) ->
let ty =
List.fold_left
(fun next (sb, st) ->
match sb with
| SBId name when x = name -> st
| _ -> next )
STNone env
in
EId (x, (ty, tag))
| ENumber (n, tag) -> ENumber (n, (STNone, tag))
| EBool (b, tag) -> EBool (b, (STNone, tag))
| ENil tag -> ENil (STNone, tag)
| EPrim1 (op, e, tag) -> EPrim1 (op, inferE e env, (STNone, tag))
| EPrim2 (op, e1, e2, tag) -> EPrim2 (op, inferE e1 env, inferE e2 env, (STNone, tag))
| ELet (bindings, body, tag) ->
let env', binds_ans = inferBS bindings env in
let body_ans = inferE body (env' @ env) in
ELet (binds_ans, body_ans, (e_ty body_ans, tag))
| ELetRec (binds, body, tag) ->
let unpatched, _ = inferBS binds env in
let patched =
List.fold_left
(fun next (sb, st) ->
match st with
| STClos (binds, body, fenv) -> (sb, STClos (binds, body, unpatched @ fenv)) :: next
| _ -> next )
[] unpatched
in
let _, binds_ans = inferBS binds (patched @ env) in
let body_ans = inferE body (patched @ env) in
ELetRec (binds_ans, body_ans, (e_ty body_ans, tag))
| EIf (cond, thn, els, tag) ->
(* NOTE: if either branch return a type related to a struct, then this EIf has that type.
however, if both branches return a "structy-type", and it isn't the same type, then
we can't infer a type.
*)
let then_res = inferE thn env in
let then_ty = e_ty then_res in
let else_res = inferE els env in
let else_ty = e_ty else_res in
let ty =
match (then_ty, else_ty) with
| STSome s1, STSome s2 when s1 = s2 -> STSome s1
| STSome s, STNone -> STSome s
| STNone, STSome s -> STSome s
| STClos _, STNone -> then_ty
| STNone, STClos _ -> else_ty
| STTup _, STNone -> then_ty
| STNone, STTup _ -> else_ty
| _ -> STNone
in
EIf (inferE cond env, then_res, else_res, (ty, tag))
| EApp ((EId (name, idtag) as func), args, Native, tag) -> (
match name with
| "print" ->
let a_ans = inferE (List.hd args) env in
EApp (inferE func env, [a_ans], Native, (e_ty a_ans, tag))