-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcompile.ml
2158 lines (2079 loc) · 88.9 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 = 0x000000000000000fL
let bool_tag_mask = 0x000000000000000fL
let num_tag = 0x0000000000000000L
let num_tag_mask = 0x0000000000000001L
let closure_tag = 0x0000000000000005L
let closure_tag_mask = 0x000000000000000fL
let tuple_tag = 0x0000000000000001L
let tuple_tag_mask = 0x000000000000000fL
let str_tag = 0x0000000000000009L
let str_tag_mask = 0x000000000000000fL
let const_nil = HexConst(tuple_tag)
let err_COMP_NOT_NUM = 1L
let err_ARITH_NOT_NUM = 2L
let err_NOT_BOOL = 3L
let err_DESTRUCTURE_INVALID_LEN = 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_NOT_STR = 17L
let err_INVALID_CONVERSION = 18L
let err_SUBSTRING_NOT_NUM = 19L
let err_SUBSTRING_OUT_OF_BOUNDS = 20L
(* label names for errors *)
let label_COMP_NOT_NUM = "error_comp_not_num"
let label_ARITH_NOT_NUM = "error_arith_not_num"
let label_TUPLE_ACCESS_NOT_NUM = "error_tuple_access_not_num"
let label_SUBSTRING_NOT_NUM = "error_substring_not_num"
let label_NOT_BOOL = "error_not_bool"
let label_NOT_STR = "error_not_str"
let label_NOT_TUPLE = "error_not_tuple"
let label_OVERFLOW = "error_overflow"
let label_GET_LOW_INDEX = "error_get_low_index"
let label_GET_HIGH_INDEX = "error_get_high_index"
let label_NIL_DEREF = "error_nil_deref"
let label_DESTRUCTURE_INVALID_LEN = "destructure_invalid_len"
let label_SHOULD_BE_FUN = "error_should_be_fun"
let label_ARITY = "error_arity"
let label_INVALID_CONVERSION = "invalid_conversion"
(* label names for conditionals *)
let label_IS_NOT_BOOL = "is_not_bool"
let label_IS_NOT_NUM = "is_not_num"
let label_IS_NOT_TUPLE = "is_not_tuple"
let label_DONE = "done"
let dummy_span = (Lexing.dummy_pos, Lexing.dummy_pos);;
let first_six_args_registers = [RDI; RSI; RDX; RCX; R8; R9]
let register_allocation_registers = [R12;R13;R14;RBX]
let caller_saved_regs : arg list =
[ Reg RDI
; Reg RSI
; Reg RDX
; Reg RCX
; Reg R8
; Reg R9
; Reg R10
; Reg R13
]
;;
let callee_saved_regs : arg list =
[ Reg R12
; Reg R14
; Reg RBX
]
;;
let heap_reg = R15
let scratch_reg = R10
let scratch_reg_2 = R11
let stack_filler = Const(62L)
let nil = HexConst(tuple_tag)
let prim_bindings = [];;
let native_fun_bindings = [
("input", (Native, 0));
("equal", (Native, 2));
("print_heap", (Native, 0));
("format", (Native, 1));
("ascii_tuple_to_str", (Native, 1));
("str_to_ascii_tuple", (Native, 1));
("get_ascii_char", (Native, 2));
("len", (Native, 1));
("contains", (Native, 2));
];;
let initial_fun_env = prim_bindings @ native_fun_bindings;;
let stringset_of_list : (string list -> StringSet.t) =
List.fold_left
(fun acc arg -> StringSet.add arg acc)
StringSet.empty
;;
let rec find_helper orig_ls ls x =
match ls with
| [] -> raise (InternalCompilerError (sprintf "Name %s not found in %s" x (List.fold_right (fun (s, _) acc -> acc ^ " " ^ s) orig_ls "")))
| (y,v)::rest ->
if y = x then v else find_helper orig_ls rest x
let rec find ls x =
find_helper ls ls 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 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;;
(* 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 (env: arg name_envt name_envt) current_env =
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(expr1, expr2, _) -> helpC expr1 + helpA expr2
| 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]
| CPrim1(_, i, _) -> helpI i
| CPrim2(_, i1, i2, _) -> max (helpI i1) (helpI i2)
| CApp(name, args, _, _) -> List.fold_left max (helpI name) (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)
| CSubstring(t, _, f, _) -> max (helpI t) (helpI f)
| CLambda(_, _, _) -> 1
| CImmExpr i -> helpI i
| CStr _ -> 0
and helpI i =
match i with
| ImmNil _ -> 0
| ImmNum _ -> 0
| ImmBool _ -> 0
| ImmId(name, _) -> name_to_offset name
and name_to_offset name =
try (match find (find env current_env) name with
| RegOffset(bytes, RBP) -> bytes / (-1 * word_size) (* negative because stack direction *)
| _ -> 0)
with InternalCompilerError _ -> 0
in max (helpA e) 0 (* if only parameters are used, helpA might return a negative value *)
;;
(* 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
| ESeq(e1, e2, _) -> wf_E e1 env @ wf_E e2 env
| ETuple(es, _) -> List.concat (List.map (fun e -> wf_E e env) es)
| EGetItem(e, idx, pos) ->
wf_E e env @ wf_E idx env
| ESetItem(e, idx, newval, pos) ->
wf_E e env @ wf_E idx env @ wf_E newval env
| ESubstring(e, start, finish, pos) ->
wf_E e env @ wf_E start env @ wf_E finish env
| ENil _ -> []
| EStr (s, pos) -> if String.exists (fun c -> ((Char.code c) > 127)) s then [(StringIllegalChar(s, pos))] else []
| 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)]
| 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, loc)::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, native, loc) ->
let rec_errors = List.concat (List.map (fun e -> wf_E e env) (func :: args)) in
(match func with
| EId("format", _) -> []
| 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, loc)::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, loc)::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) (tyenv : StringSet.t) =
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, loc)::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) (tyenv : StringSet.t) =
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 tyenv) g) in
(errs, env)
in
match p with
| Program(decls, body, _) ->
let initial_env = List.fold_left
(fun env (name, (_, arg_count)) -> (name, (dummy_span, Some arg_count, Some arg_count))::env)
[] initial_fun_env in
let rec find name (decls : 'a decl list) =
match decls with
| [] -> None
| DFun(n, args, _, loc)::rest when n = name -> Some(loc)
| _::rest -> find name rest in
let rec dupe_funbinds decls =
match decls with
| [] -> []
| DFun(name, args, _, 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 initial_tyenv = StringSet.of_list ["Int"; "Bool"] in
let help_G (env, exns) g =
let (g_exns, funbinds) = wf_G g env initial_tyenv 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 btag -> []
| 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
| ESeq(e1, e2, tag) -> ELet([(BBlank(tag), helpE e1, tag)], helpE e2, tag)
| ETuple(exprs, tag) -> ETuple(List.map helpE exprs, tag)
| EGetItem(e, idx, tag) -> EGetItem(helpE e, helpE idx, tag)
| ESetItem(e, idx, newval, tag) -> ESetItem(helpE e, helpE idx, helpE newval, tag)
| ESubstring(e, start, finish, tag) -> ESubstring(helpE e, helpE start, helpE finish, 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)
| EStr(s, tag) -> EStr(s, tag)
| EPrim1(op, e, tag) ->
EPrim1(op, helpE e, tag)
| EPrim2(op, e1, e2, tag) ->
begin
match op with
| And -> EIf(
helpE e1,
EIf(
helpE e2,
EBool(true, tag),
EBool(false, tag),
tag),
EBool(false, tag),
tag)
| Or -> EIf(
helpE e1,
EBool(true, tag),
EIf(
helpE e2,
EBool(true, tag),
EBool(false, tag),
tag),
tag)
| p -> EPrim2(p, helpE e1, helpE e2, tag)
end
| 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(EId("format", id_tag), args, native, tag) ->
let new_args = List.map (fun arg -> EPrim1(ToStr, arg, tag)) args in
EApp(EId("format", id_tag), [helpE (ETuple(new_args, tag))], native, 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
;;
(* 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 tag -> (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)
| 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)
| ESubstring(e, start, finish, tag) -> ESubstring(helpE env e, helpE env start, helpE env finish, 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)
| EStr(s, tag) -> EStr(s, tag)
| EApp(func, args, Snake, tag) ->
let func = helpE env func in
EApp(func, List.map (helpE env) args, Snake, tag)
| EApp(func, args, Native, tag) ->
EApp(func, List.map (helpE env) args, Native, tag)
| EApp(func, args, call_type, tag) ->
let func = helpE env func in
EApp(func, List.map (helpE env) args, call_type, 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
| 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, new_setup) = 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(binds, _), exp, _)::rest, body, pos) ->
raise (InternalCompilerError("Tuple bindings should have been desugared away"))
| EApp(func, args, native, _) ->
let ct = if native = Native
then Native
else Snake in
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, ct, ()), 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)
| 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)
| ESubstring(string, start, finish, _) ->
let (string_imm, string_setup) = helpI string in
let (start_imm, start_setup) = helpI start in
let (finish_imm, finish_setup) = helpI finish in
(CSubstring(string_imm, start_imm, finish_imm, ()), string_setup @ start_setup @ finish_setup)
| EStr(s, _) -> (CStr(s, ()), [])
| _ -> 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(), [])
| EStr(s, tag) ->
let tmp = sprintf "str_%d" tag in
(ImmId(tmp, ()), [BLet(tmp, CStr(s, ()))])
| ESeq(e1, e2, _) ->
let (e1_imm, 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, ()))])
| 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,()))])
| ESubstring(string, start, finish, tag) ->
let tmp = sprintf "substr_%d" tag in
let (string_imm, string_setup) = helpI string in
let (start_imm, start_setup) = helpI start in
let (finish_imm, finish_setup) = helpI finish in
(ImmId(tmp, ()), string_setup @ start_setup @ finish_setup @ [BLet (tmp, CSubstring(string_imm, start_imm, finish_imm, ()))])
| 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 ct = if native = Native
then Native
else Snake in
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, ct, ()))])
| 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(binds, _), exp, _)::rest, body, pos) ->
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
;;
(* IMPLEMENT THIS FROM YOUR PREVIOUS ASSIGNMENT *)
let free_vars (e: 'a aexpr) (args : string list) : string list =
let rec help_imm (e : 'a immexpr) (env : StringSet.t) : StringSet.t =
match e with
| ImmId(name, _) ->
if StringSet.mem name env
then StringSet.empty
else StringSet.singleton name
| _ -> StringSet.empty
and help_cexpr (e : 'a cexpr) (env : StringSet.t) : StringSet.t =
match e with
| CIf(cnd, thn, els, _) ->
StringSet.(union (help_imm cnd env) (help_aexpr thn env)
|> union (help_aexpr els env))
| CPrim1(_, e, _) -> help_imm e env
| CPrim2(_, e1, e2, _) ->
StringSet.union (help_imm e1 env) (help_imm e2 env)
| CApp(func, args, _, _) ->
StringSet.union
(help_imm func env)
(List.fold_left
(fun acc arg -> StringSet.union acc (help_imm arg env))
StringSet.empty
args)
| CImmExpr(e) -> help_imm e env
| CTuple(exprs, _) ->
List.fold_left
(fun acc arg -> StringSet.union acc (help_imm arg env))
StringSet.empty
exprs
| CGetItem(tuple, pos, _) ->
StringSet.union (help_imm tuple env) (help_imm pos env)
| CSetItem(tuple, pos, value, _) ->
StringSet.(union (help_imm tuple env) (help_imm pos env)
|> union (help_imm value env))
| CSubstring(string, start, finish, _) ->
StringSet.(union (help_imm string env) (help_imm start env)
|> union (help_imm finish env))
| CLambda(args, body, _) ->
let newenv = StringSet.union (stringset_of_list args) env in
help_aexpr body newenv
| CStr(s, _) -> StringSet.empty
and help_aexpr (e : 'a aexpr) (env : StringSet.t) : StringSet.t =
match e with
| ASeq(expr1, expr2, _) -> StringSet.union (help_cexpr expr1 env) (help_aexpr expr2 env)
| ALet(name, bind, body, _) ->
let newenv = StringSet.add name env in
StringSet.union (help_cexpr bind newenv) (help_aexpr body newenv)
| ALetRec(name_binds, body, _) ->
(* Add all the binds *)
let env = List.fold_right (fun (bind, _) acc -> StringSet.add bind acc) name_binds env in
let newenv, bind_frees =
List.fold_left
(fun (newenv, frees) (name, bind) ->
(StringSet.add name newenv,
StringSet.union (help_cexpr bind newenv) frees))
(env, StringSet.empty)
name_binds
in
StringSet.union bind_frees (help_aexpr body newenv)
| ACExpr(e) ->
help_cexpr e env
in
let new_args = List.map (fun (name, _) -> sprintf "?%s" name) native_fun_bindings @ args in
let arg_set = stringset_of_list new_args in
StringSet.(diff (help_aexpr e arg_set) arg_set |> elements)
;;
let free_vars_cache (prog: 'a aprogram) : (StringSet.t * tag) aprogram =
let native_env = stringset_of_list (List.map (fun (name, _) -> sprintf "?%s" name) native_fun_bindings) in
let rec help_imm (e : 'a immexpr) : (StringSet.t * tag) immexpr * StringSet.t =
match e with
| ImmId(name, tag) ->
if StringSet.mem name native_env
then ImmId(name, (StringSet.empty, tag)), StringSet.empty
else
let frees = StringSet.singleton name in
ImmId(name, (frees, tag)), frees
| ImmNum(e, tag) -> ImmNum(e, (StringSet.empty, tag)), StringSet.empty
| ImmBool(e, tag) -> ImmBool(e, (StringSet.empty, tag)), StringSet.empty
| ImmNil(tag) -> ImmNil(StringSet.empty, tag), StringSet.empty
and help_cexpr (e : 'a cexpr) (env : StringSet.t) : (StringSet.t * tag) cexpr * StringSet.t =
match e with
| CIf(cnd, thn, els, tag) ->
let cnd, cnd_frees = help_imm cnd in
let thn, thn_frees = help_aexpr thn env in
let els, els_frees = help_aexpr els env in
let frees = StringSet.(union cnd_frees thn_frees |> union els_frees) in
CIf(cnd, thn, els, (frees, tag)), frees
| CPrim1(prim, e, tag) ->
let e, frees = help_imm e in
CPrim1(prim, e, (frees, tag)), frees
| CPrim2(prim, e1, e2, tag) ->
let e1, e1_frees = help_imm e1 in
let e2, e2_frees = help_imm e2 in
let frees = StringSet.union e1_frees e2_frees in
CPrim2(prim, e1, e2, (frees, tag)), frees
| CApp(func, args, ct, tag) ->
let func, func_frees = help_imm func in
let args, args_frees =
(List.fold_left
(fun (args, frees) arg ->
let arg, arg_frees = help_imm arg in
(arg :: args, StringSet.union frees arg_frees))
([], StringSet.empty)
args)
in
let frees = StringSet.union func_frees args_frees in
CApp(func, args, ct, (frees, tag)), frees
| CImmExpr(e) ->
let e, frees = help_imm e in
CImmExpr(e), frees
| CTuple(exprs, tag) ->
let exprs, frees =
List.fold_left
(fun (exprs, frees) arg ->
let arg, arg_frees = help_imm arg in
(arg :: exprs, StringSet.union frees arg_frees))
([], StringSet.empty)
exprs
in
CTuple(exprs, (frees, tag)), frees
| CGetItem(tuple, pos, tag) ->
let tuple, tuple_frees = help_imm tuple in
let pos, pos_frees = help_imm pos in
let frees = StringSet.union tuple_frees pos_frees in
CGetItem(tuple, pos, (frees, tag)), frees
| CSetItem(tuple, pos, value, tag) ->
let tuple, tuple_frees = help_imm tuple in
let pos, pos_frees = help_imm pos in
let value, value_frees = help_imm value in
let frees = StringSet.(union tuple_frees pos_frees |> union value_frees) in
CSetItem(tuple, pos, value, (frees, tag)), frees
| CSubstring(string, start, finish, tag) ->
let string, string_frees = help_imm string in
let start, start_frees = help_imm start in
let finish, finish_frees = help_imm finish in
let frees = StringSet.(union string_frees start_frees |> union finish_frees) in
CSubstring(string, start, finish, (frees, tag)), frees
| CLambda(args, body, tag) ->
let body, body_frees = help_aexpr body (StringSet.union env (stringset_of_list args)) in
let frees = StringSet.inter body_frees env in
CLambda(args, body, (frees, tag)), frees
| CStr(s, tag) -> CStr(s, (StringSet.empty, tag)), StringSet.empty
and help_aexpr (e : 'a aexpr) (env : StringSet.t) : (StringSet.t * tag) aexpr * StringSet.t =
match e with
| ASeq(e1, e2, tag) ->
let e1, e1_frees = help_cexpr e1 env in
let e2, e2_frees = help_aexpr e2 env in
let frees = StringSet.union e1_frees e2_frees in
ASeq(e1, e2, (frees, tag)), frees
| ALet(name, bind, body, tag) ->
let bind, bind_frees = help_cexpr bind env in
let body, body_frees = help_aexpr body (StringSet.add name env) in