-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcompile.ml
More file actions
2128 lines (2022 loc) · 84.6 KB
/
compile.ml
File metadata and controls
2128 lines (2022 loc) · 84.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
open Printf
open Pretty
open Phases
open Exprs
open Assembly
open Errors
open Graph
module StringSet = Set.Make (String)
let c_global_function_names =
["print"; "equal"; "error"; "print_stack"; "len"; "chr"; "ord"; "numToString"; "fromString"]
;;
let c_global_function_arities =
[ ("print", 1);
("equal", 2);
("error", 2);
("print_stack", 1);
("len", 1);
("chr", 1);
("ord", 1);
("numToString", 1);
("fromString", 1) ]
;;
let native_fun_bindings =
[ ("print", 1);
("equal", 2);
("error", 2);
("print_stack", 1);
("len", 1);
("chr", 1);
("ord", 1);
("numToString", 1);
("fromString", 1) ]
;;
let dummy_span = (Lexing.dummy_pos, Lexing.dummy_pos)
let initial_fun_env =
List.map (fun (name, arity) -> (name, (dummy_span, Some arity, Some arity))) native_fun_bindings
;;
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 string_tag = 1
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_GET_NOT_NUM = 16L
let err_SET_NOT_NUM = 17L
let err_TUPLE_DESTRUCTURE_MISMATCH = 18L
let err_CONCAT_NOT_SEQ = 19L
let err_CONCAT_NOT_SAME = 20L
let err_LENGTH_NOT_SEQ = 21L
let err_ORD_NOT_CHAR = 22L
let err_CHR_NOT_NUM = 23L
let err_SLICE_NOT_SEQ = 24L
let err_SLICE_NOT_NUM = 25L
let err_NUM_TO_STRING_NOT_NUM = 26L
let err_FROM_STR_NOT_STR = 27L
let err_FROM_STR_INVALID = 28L
let first_six_args_registers = [RDI; RSI; RDX; RCX; R8; R9]
let caller_saved_regs : arg list = [Reg RDI; Reg RSI; Reg RDX; Reg RCX; Reg R8; Reg R9; Reg R10]
let callee_saved_regs : arg list = [Reg R12; Reg R14; Reg RBX]
let reg_priority = List.map (fun r -> Reg r) [R10; R12; R13; R14; RBX; RSI; RDI; RCX; RDX; R8; R9]
let clear_registers =
[ILineComment "clear registers"]
@ List.concat_map (fun reg -> [IMov (reg, HexConst (Int64.of_int 0))]) reg_priority
;;
let push_callees =
[ILineComment "push callee save regisers"]
@ List.concat_map (fun reg -> [IPush reg]) callee_saved_regs
;;
let pop_callees =
[ILineComment "pop callee save regisers"]
@ List.rev (List.concat_map (fun reg -> [IPop reg]) callee_saved_regs)
;;
let heap_reg = R15
let scratch_reg = R11
(* you can add any functions or data defined by the runtime here for future use *)
let initial_val_env = []
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_with_tag ls t x =
match ls with
| [] -> raise (InternalCompilerError (sprintf "Name %s not found in tag env %d" x t))
| (tag, named_env) :: rest ->
if tag = t
then try find named_env x with InternalCompilerError _ -> find_with_tag [] t x
else find_with_tag rest t x
;;
(* 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 align_size (n : int) = n + (n mod (word_size * 2))
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
| [_] -> 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
(* Scope_info stores the location where something was defined,
and if it was a function declaration, then its type arity and argument arity *)
type scope_info = sourcespan * int option * int option
let is_well_formed (p : sourcespan program) : sourcespan program fallible =
let rec wf_E e (env : scope_info name_envt) =
debug_printf "In wf_E: %s\n" (ExtString.String.join ", " (env_keys env));
match e with
| EString (s, span) ->
let rec check_codes s =
match s with
| [] -> []
| '\\' :: ('n' | 'r' | 'b' | 't' | '\"' | '\\') :: chars -> check_codes chars
| '\\' :: c1 :: c2 :: c3 :: chars ->
(* Convert characters to numbers, then make them into a number together. Check that it's a valid ASCII code *)
let num1, num2, num3 = (Char.code c1 - 48, Char.code c2 - 48, Char.code c3 - 48) in
let code = (num1 * 100) + (num2 * 10) + num3 in
if code < 0 || code > 255
then InvalidASCIICode (code, span) :: check_codes chars
else check_codes chars
| _ :: chars -> check_codes chars
in
check_codes (List.of_seq (String.to_seq s))
| ESeq (e1, e2, _) -> wf_E e1 env @ wf_E e2 env
| ETuple (es, _) -> List.concat (List.map (fun e -> wf_E e env) es)
| ESlice (str, s, en, step, _) ->
let wf_slice e =
match e with
| Some x -> wf_E x env
| None -> []
in
wf_E str env @ wf_slice s @ wf_slice en @ wf_slice step
| EGetItem (e, idx, _) -> wf_E e env @ wf_E idx env
| ESetItem (e, idx, newval, _) -> wf_E e env @ wf_E idx env @ wf_E newval env
| ENil _ -> []
| EBool _ -> []
| ENumber (n, loc) ->
if n > Int64.div Int64.max_int 2L || n < Int64.div Int64.min_int 2L
then [Overflow (n, loc)]
else []
| EId (x, loc) -> if find_one (List.map fst env) x then [] else [UnboundId (x, loc)]
| EInput _ -> []
| EPrim1 (_, e, _) -> wf_E e env
| EPrim2 (_, l, r, _) -> wf_E l env @ wf_E r env
| EIf (c, t, f, _) -> wf_E c env @ wf_E t env @ wf_E f env
| ELet (bindings, body, _) ->
let rec find_locs x (binds : 'a bind list) : 'a list =
match binds with
| [] -> []
| BBlank _ :: rest -> find_locs x rest
| BName (y, _, loc) :: rest -> if x = y then loc :: find_locs x rest else find_locs x rest
| BTuple (binds, _) :: rest -> find_locs x binds @ find_locs x rest
in
let rec find_dupes (binds : 'a bind list) : exn list =
match binds with
| [] -> []
| BBlank _ :: rest -> find_dupes rest
| BName (x, _, def) :: rest ->
List.map (fun use -> DuplicateId (x, use, def)) (find_locs x rest) @ find_dupes rest
| BTuple (binds, _) :: rest -> find_dupes (binds @ rest)
in
let dupeIds = find_dupes (List.map (fun (b, _, _) -> b) bindings) in
let rec process_binds (rem_binds : 'a bind list) (env : scope_info name_envt) =
match rem_binds with
| [] -> (env, [])
| BBlank _ :: rest -> process_binds rest env
| BTuple (binds, _) :: rest -> process_binds (binds @ rest) env
| BName (x, allow_shadow, xloc) :: rest ->
let shadow =
if allow_shadow
then []
else
match find_opt env x with
| None -> []
| Some (existing, _, _) -> [ShadowId (x, xloc, existing)]
in
let new_env = (x, (xloc, None, None)) :: env in
let newer_env, errs = process_binds rest new_env in
(newer_env, shadow @ errs)
in
let rec process_bindings bindings (env : scope_info name_envt) =
match bindings with
| [] -> (env, [])
| (b, e, _) :: rest ->
let errs_e = wf_E e env in
let env', errs = process_binds [b] env in
let env'', errs' = process_bindings rest env' in
(env'', errs @ errs_e @ errs')
in
let env2, errs = process_bindings bindings env in
dupeIds @ errs @ wf_E body env2
| EApp (func, args, _, loc) ->
let rec_errors = List.concat (List.map (fun e -> wf_E e env) (func :: args)) in
( match func with
| EId (funname, _) -> (
match find_opt env funname with
| Some (_, _, Some arg_arity) ->
let actual = List.length args in
if actual != arg_arity then [Arity (arg_arity, actual, loc)] else []
| _ -> [] )
| _ -> [] )
@ rec_errors
| ELetRec (binds, body, _) ->
let nonfuns =
List.find_all
(fun b ->
match b with
| BName _, ELambda _, _ -> false
| _ -> true )
binds
in
let nonfun_errs = List.map (fun (b, _, where) -> LetRecNonFunction (b, where)) nonfuns in
let rec find_locs x (binds : 'a bind list) : 'a list =
match binds with
| [] -> []
| BBlank _ :: rest -> find_locs x rest
| BName (y, _, loc) :: rest -> if x = y then loc :: find_locs x rest else find_locs x rest
| BTuple (binds, _) :: rest -> find_locs x binds @ find_locs x rest
in
let rec find_dupes (binds : 'a bind list) : exn list =
match binds with
| [] -> []
| BBlank _ :: rest -> find_dupes rest
| BName (x, _, def) :: rest ->
List.map (fun use -> DuplicateId (x, use, def)) (find_locs x rest)
| BTuple (binds, _) :: rest -> find_dupes (binds @ rest)
in
let dupeIds = find_dupes (List.map (fun (b, _, _) -> b) binds) in
let rec process_binds (rem_binds : sourcespan bind list) (env : scope_info name_envt) =
match rem_binds with
| [] -> (env, [])
| BBlank _ :: rest -> process_binds rest env
| BTuple (binds, _) :: rest -> process_binds (binds @ rest) env
| BName (x, allow_shadow, xloc) :: rest ->
let shadow =
if allow_shadow
then []
else
match find_opt env x with
| None -> []
| Some (existing, _, _) ->
if xloc = existing then [] else [ShadowId (x, xloc, existing)]
in
let new_env = (x, (xloc, None, None)) :: env in
let newer_env, errs = process_binds rest new_env in
(newer_env, shadow @ errs)
in
let env, bind_errs = process_binds (List.map (fun (b, _, _) -> b) binds) env in
let rec process_bindings bindings env =
match bindings with
| [] -> (env, [])
| (b, e, _) :: rest ->
let env, errs = process_binds [b] env in
let errs_e = wf_E e env in
let env', errs' = process_bindings rest env in
(env', errs @ errs_e @ errs')
in
let new_env, binding_errs = process_bindings binds env in
let rhs_problems = List.map (fun (_, rhs, _) -> wf_E rhs new_env) binds in
let body_problems = wf_E body new_env in
nonfun_errs @ dupeIds @ bind_errs @ binding_errs @ List.flatten rhs_problems @ body_problems
| ELambda (binds, body, _) ->
let rec dupe x args =
match args with
| [] -> None
| BName (y, _, loc) :: _ when x = y -> Some loc
| BTuple (binds, _) :: rest -> dupe x (binds @ rest)
| _ :: rest -> dupe x rest
in
let rec process_args rem_args =
match rem_args with
| [] -> []
| BBlank _ :: rest -> process_args rest
| BName (x, _, loc) :: rest ->
( match dupe x rest with
| None -> []
| Some where -> [DuplicateId (x, where, loc)] )
@ process_args rest
| BTuple (binds, _) :: rest -> process_args (binds @ rest)
in
let rec flatten_bind (bind : sourcespan bind) : (string * scope_info) list =
match bind with
| BBlank _ -> []
| BName (x, _, xloc) -> [(x, (xloc, None, None))]
| BTuple (args, _) -> List.concat (List.map flatten_bind args)
in
process_args binds @ wf_E body (merge_envs (List.concat (List.map flatten_bind binds)) env)
and wf_D d (env : scope_info name_envt) =
match d with
| DFun (_, args, body, _) ->
let rec dupe x args =
match args with
| [] -> None
| BName (y, _, loc) :: _ when x = y -> Some loc
| BTuple (binds, _) :: rest -> dupe x (binds @ rest)
| _ :: rest -> dupe x rest
in
let rec process_args rem_args =
match rem_args with
| [] -> []
| BBlank _ :: rest -> process_args rest
| BName (x, _, loc) :: rest ->
( match dupe x rest with
| None -> []
| Some where -> [DuplicateId (x, where, loc)] )
@ process_args rest
| BTuple (binds, _) :: rest -> process_args (binds @ rest)
in
let rec arg_env args (env : scope_info name_envt) =
match args with
| [] -> env
| BBlank _ :: rest -> arg_env rest env
| BName (name, _, loc) :: rest -> (name, (loc, None, None)) :: arg_env rest env
| BTuple (binds, _) :: rest -> arg_env (binds @ rest) env
in
process_args args @ wf_E body (arg_env args env)
and wf_G (g : sourcespan decl list) (env : scope_info name_envt) =
let add_funbind (env : scope_info name_envt) d =
match d with
| DFun (name, args, _, loc) ->
(name, (loc, Some (List.length args), Some (List.length args))) :: env
in
let env = List.fold_left add_funbind env g in
let errs = List.concat (List.map (fun d -> wf_D d env) g) in
(errs, env)
in
match p with
| Program (decls, body, _) -> (
let initial_env = initial_val_env in
let initial_env =
List.fold_left
(fun env (name, (_, arg_count)) ->
(name, (dummy_span, Some arg_count, Some arg_count)) :: env )
initial_fun_env initial_env
in
let rec find name (decls : 'a decl list) =
match decls with
| [] -> None
| DFun (n, _, _, loc) :: _ when n = name -> Some loc
| _ :: rest -> find name rest
in
let rec dupe_funbinds decls =
match decls with
| [] -> []
| DFun (name, _, _, loc) :: rest ->
( match find name rest with
| None -> []
| Some where -> [DuplicateFun (name, where, loc)] )
@ dupe_funbinds rest
in
let all_decls = List.flatten decls in
let help_G (env, exns) g =
let g_exns, funbinds = wf_G g env in
(List.fold_left (fun xs x -> x :: xs) env funbinds, exns @ g_exns)
in
let env, exns = List.fold_left help_G (initial_env, dupe_funbinds all_decls) decls in
debug_printf "In wf_P: %s\n" (ExtString.String.join ", " (env_keys env));
let exns = exns @ wf_E body env in
match exns with
| [] -> Ok p
| _ -> Error exns )
;;
(* ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;; DESUGARING ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; *)
let desugar (p : sourcespan program) : sourcespan program =
let gensym =
let next = ref 0 in
fun name ->
next := !next + 1;
sprintf "%s_%d" name !next
in
let rec helpP (p : sourcespan program) =
match p with
| Program (decls, body, tag) ->
(* This particular desugaring will convert declgroups into ELetRecs *)
let merge_sourcespans ((s1, _) : sourcespan) ((_, s2) : sourcespan) : sourcespan =
(s1, s2)
in
let wrap_G g body =
match g with
| [] -> body
| f :: r ->
let span = List.fold_left merge_sourcespans (get_tag_D f) (List.map get_tag_D r) in
ELetRec (helpG g, body, span)
in
Program ([], List.fold_right wrap_G decls (helpE body), tag)
and helpG g = List.map helpD g
and helpD d =
match d with
| DFun (name, args, body, tag) ->
let helpArg a =
match a with
| BTuple (_, tag) ->
let name = gensym "argtup" in
let newbind = BName (name, false, tag) in
(newbind, [(a, EId (name, tag), tag)])
| _ -> (a, [])
in
let newargs, argbinds = List.split (List.map helpArg args) in
let newbody = ELet (List.flatten argbinds, body, tag) in
(BName (name, false, tag), ELambda (newargs, helpE newbody, tag), tag)
and helpBE bind =
let b, e, btag = bind in
let e = helpE e in
match b with
| BTuple (binds, ttag) -> (
match e with
| EId _ -> expandTuple binds ttag e
| _ ->
let newname = gensym "tup" in
(BName (newname, false, ttag), e, btag) :: expandTuple binds ttag (EId (newname, ttag)) )
| _ -> [(b, e, btag)]
and expandTuple binds tag source : sourcespan binding list =
let tupleBind i b =
match b with
| BBlank _ -> []
| BName (_, _, btag) ->
[(b, EGetItem (source, ENumber (Int64.of_int i, dummy_span), tag), btag)]
| BTuple (binds, tag) ->
let newname = gensym "tup" in
let newexpr = EId (newname, tag) in
( BName (newname, false, tag),
EGetItem (source, ENumber (Int64.of_int i, dummy_span), tag),
tag )
:: expandTuple binds tag newexpr
in
let size_check =
EPrim2 (CheckSize, source, ENumber (Int64.of_int (List.length binds), dummy_span), dummy_span)
in
let size_check_bind = (BBlank dummy_span, size_check, dummy_span) in
size_check_bind :: List.flatten (List.mapi tupleBind binds)
and helpE e =
match e with
| EString (str, tag) -> EString (str, tag)
| ESeq (e1, e2, tag) -> ELet ([(BBlank tag, helpE e1, tag)], helpE e2, tag)
| ETuple (exprs, tag) -> ETuple (List.map helpE exprs, tag)
| ESlice (str, s, en, step, tag) ->
ESlice (helpE str, Option.map helpE s, Option.map helpE en, Option.map helpE step, 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 (t, tag) -> ENil (t, tag)
| EInput t -> EInput t
| EPrim1 (op, e, tag) -> EPrim1 (op, helpE e, tag)
| EPrim2 (op, l, r, info) -> (
(* Desugaring AND and OR seems to mess with error messages for non-boolean values.
Here, we convert each side into a double negated version of itself to preserve
the boolean requirement, then we can translate into equivalent If expressions
*)
let double_negative (e : 'a expr) = EPrim1 (Not, EPrim1 (Not, e, info), info) in
let desugared_l = double_negative (helpE l) in
let desugared_r = double_negative (helpE r) in
match op with
| And -> EIf (desugared_l, desugared_r, EBool (false, info), info)
| Or -> EIf (desugared_l, EBool (true, info), desugared_r, info)
| _ -> EPrim2 (op, helpE l, helpE r, info) )
| ELet (binds, body, tag) ->
let newbinds = List.map helpBE binds in
List.fold_right (fun binds body -> ELet (binds, body, tag)) newbinds (helpE body)
| ELetRec (bindexps, body, tag) ->
(* ASSUMES well-formed letrec, so only BName bindings *)
let newbinds = List.map (fun (bind, e, tag) -> (bind, helpE e, tag)) bindexps in
ELetRec (newbinds, helpE body, tag)
| EIf (cond, thn, els, tag) -> EIf (helpE cond, helpE thn, helpE els, tag)
| EApp (name, args, native, tag) -> EApp (helpE name, List.map helpE args, native, tag)
| ELambda (binds, body, tag) ->
let expandBind bind =
match bind with
| BTuple (_, btag) ->
let newparam = gensym "tuparg" in
(BName (newparam, false, btag), helpBE (bind, EId (newparam, btag), btag))
| _ -> (bind, [])
in
let params, newbinds = List.split (List.map expandBind binds) in
let newbody =
List.fold_right (fun binds body -> ELet (binds, body, tag)) newbinds (helpE body)
in
ELambda (params, newbody, tag)
in
helpP p
;;
(* Returns the stack-index (in words) of the deepest stack index used for any
of the variables in this expression *)
let rec deepest_stack (e : 'a aexpr) (env : arg name_envt) : tag =
let rec helpA e =
match e with
| ALet (name, bind, body, _) ->
List.fold_left max 0 [name_to_offset name; helpC bind; helpA body]
| ALetRec (binds, body, _) ->
List.fold_left max (helpA body) (List.map (fun (_, bind) -> helpC bind) binds)
| ASeq (first, rest, _) -> max (helpC first) (helpA rest)
| ACExpr e -> helpC e
and helpC e =
match e with
| CIf (c, t, f, _) -> List.fold_left max 0 [helpI c; helpA t; helpA f]
| CInput _ -> 0
| CPrim1 (_, i, _) -> helpI i
| CPrim2 (_, i1, i2, _) -> max (helpI i1) (helpI i2)
| CApp (_, args, _, _) -> List.fold_left max 0 (List.map helpI args)
| CTuple (vals, _) -> List.fold_left max 0 (List.map helpI vals)
| CGetItem (t, _, _) -> helpI t
| CSetItem (t, _, v, _) -> max (helpI t) (helpI v)
| CLambda (args, body, _) ->
let new_env = List.mapi (fun i a -> (a, RegOffset (word_size * (i + 3), RBP))) args @ env in
deepest_stack body new_env
| CString _ -> 0
| CSlice (str, _, _, _, _) -> helpI str
| CImmExpr i -> helpI i
and helpI i =
match i with
| ImmNil _ -> 0
| ImmNum _ -> 0
| ImmBool _ -> 0
| ImmId (name, _) -> name_to_offset name
and name_to_offset name =
match find_opt env name with
| Some (RegOffset (bytes, RBP)) -> bytes / ~-word_size (* negative because stack direction *)
| Some _ -> 0 (* if it's not on the stack, we don't need to make room for it *)
| None -> 0
(* if it's not in the environment, it's in an inner lambda that will make room for itself *)
in
max (helpA e) 0 (* if only parameters are used, helpA might return a negative value *)
;;
(* ASSUMES desugaring is complete *)
let rename_and_tag (p : tag program) : tag program =
let rec rename env p =
match p with
| Program (decls, body, tag) ->
Program (List.map (fun group -> List.map (helpD env) group) decls, helpE env body, 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 _ -> (b, env)
| BName (name, allow_shadow, tag) ->
let name' = sprintf "%s_%d" name tag in
(BName (name', allow_shadow, 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)
| ESlice (str, s, en, step, tag) ->
ESlice
( helpE env str,
Option.map (helpE env) s,
Option.map (helpE env) en,
Option.map (helpE env) step,
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)
| EInput _ -> e
| 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)
| EString _ -> e
| ENumber _ -> e
| EBool _ -> e
| ENil _ -> e
| EId (name, tag) -> ( try EId (find env name, tag) with InternalCompilerError _ -> e )
| EApp (func, args, _, tag) -> (
match func with
| EId (name, _) when find_one c_global_function_names 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
;;
(* ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;; ANFING ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; *)
type 'a anf_bind =
| BSeq of 'a cexpr
| BLet of string * 'a cexpr
| BLetRec of (string * 'a cexpr) list
let anf (p : tag program) : unit aprogram =
let rec helpP (p : tag program) : unit aprogram =
match p with
| Program ([], body, _) -> AProgram (helpA body, ())
| Program _ -> raise (InternalCompilerError "decls should have been desugared away")
and helpC (e : tag expr) : unit cexpr * unit anf_bind list =
match e with
| EInput _ -> (CInput (), [])
| EPrim1 (op, arg, _) ->
let arg_imm, arg_setup = helpI arg in
(CPrim1 (op, arg_imm, ()), arg_setup)
| EPrim2 (op, left, right, _) ->
let left_imm, left_setup = helpI left in
let right_imm, right_setup = helpI right in
(CPrim2 (op, left_imm, right_imm, ()), left_setup @ right_setup)
| EIf (cond, _then, _else, _) ->
let cond_imm, cond_setup = helpI cond in
(CIf (cond_imm, helpA _then, helpA _else, ()), cond_setup)
| ELet ([], body, _) -> helpC body
| ELet ((BBlank _, exp, _) :: rest, body, pos) ->
let exp_ans, exp_setup = helpC exp in
let body_ans, body_setup = helpC (ELet (rest, body, pos)) in
(body_ans, exp_setup @ [BSeq exp_ans] @ body_setup)
| ELet ((BName (bind, _, _), exp, _) :: rest, body, pos) ->
let exp_ans, exp_setup = helpC exp in
let body_ans, body_setup = helpC (ELet (rest, body, pos)) in
(body_ans, exp_setup @ [BLet (bind, exp_ans)] @ body_setup)
| ELetRec (binds, body, _) ->
let processBind (bind, rhs, _) =
match bind with
| BName (name, _, _) -> (name, helpC rhs)
| _ ->
raise
(InternalCompilerError
(sprintf "Encountered a non-simple binding in ANFing a let-rec: %s"
(string_of_bind bind) ) )
in
let names, new_binds_setup = List.split (List.map processBind binds) in
let new_binds, _ = List.split new_binds_setup in
let body_ans, body_setup = helpC body in
(body_ans, BLetRec (List.combine names new_binds) :: body_setup)
| ELambda (args, body, _) ->
let processBind bind =
match bind with
| BName (name, _, _) -> name
| _ ->
raise
(InternalCompilerError
(sprintf "Encountered a non-simple binding in ANFing a lambda: %s"
(string_of_bind bind) ) )
in
(CLambda (List.map processBind args, helpA body, ()), [])
| ELet ((BTuple (_, _), _, _) :: _, _, _) ->
raise (InternalCompilerError "Tuple bindings should have been desugared away")
| EApp (func, args, native, _) ->
let func_ans, func_setup = helpI func in
let new_args, new_setup = List.split (List.map helpI args) in
(CApp (func_ans, new_args, native, ()), func_setup @ List.concat new_setup)
| ESeq (e1, e2, _) ->
let e1_ans, e1_setup = helpC e1 in
let e2_ans, e2_setup = helpC e2 in
(e2_ans, e1_setup @ [BSeq e1_ans] @ e2_setup)
| EString (s, _) -> (CString (s, ()), [])
| ETuple (args, _) ->
let new_args, new_setup = List.split (List.map helpI args) in
(CTuple (new_args, ()), List.concat new_setup)
| EGetItem (tup, idx, _) ->
let tup_imm, tup_setup = helpI tup in
let idx_imm, idx_setup = helpI idx in
(CGetItem (tup_imm, idx_imm, ()), tup_setup @ idx_setup)
| ESetItem (tup, idx, newval, _) ->
let tup_imm, tup_setup = helpI tup in
let idx_imm, idx_setup = helpI idx in
let new_imm, new_setup = helpI newval in
(CSetItem (tup_imm, idx_imm, new_imm, ()), tup_setup @ idx_setup @ new_setup)
| _ ->
let imm, setup = helpI e in
(CImmExpr imm, setup)
and helpI (e : tag expr) : unit immexpr * unit anf_bind list =
match e with
| ENumber (n, _) -> (ImmNum (n, ()), [])
| EBool (b, _) -> (ImmBool (b, ()), [])
| EId (name, _) -> (ImmId (name, ()), [])
| ENil _ -> (ImmNil (), [])
| ESeq (e1, e2, _) ->
let _, e1_setup = helpI e1 in
let e2_imm, e2_setup = helpI e2 in
(e2_imm, e1_setup @ e2_setup)
| ETuple (args, tag) ->
let tmp = sprintf "tup_%d" tag in
let new_args, new_setup = List.split (List.map helpI args) in
(ImmId (tmp, ()), List.concat new_setup @ [BLet (tmp, CTuple (new_args, ()))])
| EString (str, tag) ->
let tmp = sprintf "str_%d" tag in
(ImmId (tmp, ()), [BLet (tmp, CString (str, ()))])
| ESlice (str, s, en, step, tag) ->
let help_slice e =
match e with
| Some x ->
let e_imm, e_setup = helpI x in
(Some e_imm, e_setup)
| None -> (None, [])
in
let tmp = sprintf "slice_%d" tag in
let str_imm, str_setup = helpI str in
let s_imm, s_setup = help_slice s in
let e_imm, e_setup = help_slice en in
let step_imm, step_setup = help_slice step in
( ImmId (tmp, ()),
str_setup @ s_setup @ e_setup @ step_setup
@ [BLet (tmp, CSlice (str_imm, s_imm, e_imm, step_imm, ()))] )
| EGetItem (tup, idx, tag) ->
let tmp = sprintf "get_%d" tag in
let tup_imm, tup_setup = helpI tup in
let idx_imm, idx_setup = helpI idx in
(ImmId (tmp, ()), tup_setup @ idx_setup @ [BLet (tmp, CGetItem (tup_imm, idx_imm, ()))])
| ESetItem (tup, idx, newval, tag) ->
let tmp = sprintf "set_%d" tag in
let tup_imm, tup_setup = helpI tup in
let idx_imm, idx_setup = helpI idx in
let new_imm, new_setup = helpI newval in
( ImmId (tmp, ()),
tup_setup @ idx_setup @ new_setup @ [BLet (tmp, CSetItem (tup_imm, idx_imm, new_imm, ()))]
)
| EInput tag ->
let tmp = sprintf "input_%d" tag in
(ImmId (tmp, ()), [BLet (tmp, CInput ())])
| EPrim1 (op, arg, tag) ->
let tmp = sprintf "unary_%d" tag in
let arg_imm, arg_setup = helpI arg in
(ImmId (tmp, ()), arg_setup @ [BLet (tmp, CPrim1 (op, arg_imm, ()))])
| EPrim2 (op, left, right, tag) ->
let tmp = sprintf "binop_%d" tag in
let left_imm, left_setup = helpI left in
let right_imm, right_setup = helpI right in
( ImmId (tmp, ()),
left_setup @ right_setup @ [BLet (tmp, CPrim2 (op, left_imm, right_imm, ()))] )
| EIf (cond, _then, _else, tag) ->
let tmp = sprintf "if_%d" tag in
let cond_imm, cond_setup = helpI cond in
(ImmId (tmp, ()), cond_setup @ [BLet (tmp, CIf (cond_imm, helpA _then, helpA _else, ()))])
| EApp (func, args, native, tag) ->
let tmp = sprintf "app_%d" tag in
let new_func, func_setup = helpI func in
let new_args, new_setup = List.split (List.map helpI args) in
( ImmId (tmp, ()),
func_setup @ List.concat new_setup @ [BLet (tmp, CApp (new_func, new_args, native, ()))]
)
| ELet ([], body, _) -> helpI body
| ELet ((BBlank _, exp, _) :: rest, body, pos) ->
let exp_ans, exp_setup = helpC exp in
let body_ans, body_setup = helpI (ELet (rest, body, pos)) in
(body_ans, exp_setup @ [BSeq exp_ans] @ body_setup)
| ELetRec (binds, body, tag) ->
let tmp = sprintf "lam_%d" tag in
let processBind (bind, rhs, _) =
match bind with
| BName (name, _, _) -> (name, helpC rhs)
| _ ->
raise
(InternalCompilerError
(sprintf "Encountered a non-simple binding in ANFing a let-rec: %s"
(string_of_bind bind) ) )
in
let names, new_binds_setup = List.split (List.map processBind binds) in
let new_binds, new_setup = List.split new_binds_setup in
let body_ans, body_setup = helpC body in
( ImmId (tmp, ()),
List.concat new_setup
@ [BLetRec (List.combine names new_binds)]
@ body_setup
@ [BLet (tmp, body_ans)] )
| ELambda (args, body, tag) ->
let tmp = sprintf "lam_%d" tag in
let processBind bind =
match bind with
| BName (name, _, _) -> name
| _ ->
raise
(InternalCompilerError
(sprintf "Encountered a non-simple binding in ANFing a lambda: %s"
(string_of_bind bind) ) )
in
(ImmId (tmp, ()), [BLet (tmp, CLambda (List.map processBind args, helpA body, ()))])
| ELet ((BName (bind, _, _), exp, _) :: rest, body, pos) ->
let exp_ans, exp_setup = helpC exp in
let body_ans, body_setup = helpI (ELet (rest, body, pos)) in
(body_ans, exp_setup @ [BLet (bind, exp_ans)] @ body_setup)
| ELet ((BTuple (_, _), _, _) :: _, _, _) ->
raise (InternalCompilerError "Tuple bindings should have been desugared away")
and helpA e : unit aexpr =
let ans, ans_setup = helpC e in
List.fold_right
(fun bind body ->
match bind with
| BSeq exp -> ASeq (exp, body, ())
| BLet (name, exp) -> ALet (name, exp, body, ())
| BLetRec names -> ALetRec (names, body, ()) )
ans_setup (ACExpr ans)
in
helpP p
;;
let free_vars (e : 'a aexpr) : StringSet.t =
let rec free_vars_C (e : 'a cexpr) (bound : StringSet.t) : StringSet.t =
let free_vars_I_list (es : 'a immexpr list) (bound : StringSet.t) : StringSet.t =
List.fold_left
(fun free curr -> StringSet.union free (free_vars_I curr bound))
StringSet.empty es
in
match e with
| CIf (c, t, e, _) ->
let c_free = free_vars_I c bound in
let t_free = free_vars_A t bound in
let e_free = free_vars_A e bound in
StringSet.union (StringSet.union c_free t_free) e_free
| CInput _ -> StringSet.empty
| CPrim1 (_, op, _) -> free_vars_I op bound
| CPrim2 (_, op1, op2, _) ->
let op1_free = free_vars_I op1 bound in
let op2_free = free_vars_I op2 bound in
StringSet.union op1_free op2_free
| CApp (_, args, Native, _) -> free_vars_I_list args bound
| CApp (func, args, _, _) ->
let func_free = free_vars_I func bound in
let args_free = free_vars_I_list args bound in
StringSet.union func_free args_free
| CTuple (els, _) -> free_vars_I_list els bound
| CSlice (str, s, en, step, _) ->