forked from ocaml-flambda/flambda-backend
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtranslmod.ml
2166 lines (2034 loc) · 82.4 KB
/
translmod.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
(**************************************************************************)
(* *)
(* OCaml *)
(* *)
(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
(* *)
(* Copyright 1996 Institut National de Recherche en Informatique et *)
(* en Automatique. *)
(* *)
(* All rights reserved. This file is distributed under the terms of *)
(* the GNU Lesser General Public License version 2.1, with the *)
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
(* Translation from typed abstract syntax to lambda terms,
for the module language *)
open Misc
open Asttypes
open Types
open Typedtree
open Lambda
open Translobj
open Translcore
open Translclass
open Debuginfo.Scoped_location
type unsafe_component =
| Unsafe_module_binding
| Unsafe_functor
| Unsafe_non_function
| Unsafe_typext
| Unsafe_non_value_arg
type unsafe_info =
| Unsafe of { reason:unsafe_component; loc:Location.t; subid:Ident.t }
| Unnamed
type error =
Circular_dependency of (Ident.t * unsafe_info) list
| Conflicting_inline_attributes
| Non_value_jkind of type_expr * Jkind.sort
| Instantiating_packed of Compilation_unit.t
exception Error of Location.t * error
(* CR layouts v7: This is used as part of the "void safety check" in the case of
[Tstr_eval], where we want to allow any sort (see comment on that case of
typemod). Remove when we remove the safety check.
We still default to value before checking for void, to allow for sort
variables arising in situations like a module that is just:
exit 1;;
When this sanity check is removed, consider whether it must be replaced with
some defaulting. *)
let sort_must_not_be_void loc ty sort =
if Jkind.Sort.is_void_defaulting sort then
raise (Error (loc, Non_value_jkind (ty, sort)))
let cons_opt x_opt xs =
match x_opt with
| None -> xs
| Some x -> x :: xs
(* Keep track of the root path (from the root of the namespace to the
currently compiled module expression). Useful for naming extensions. *)
let longident_of_comp_unit cu =
let rec of_names names_rev =
match names_rev with
| [] -> fatal_error "empty sequence of names"
| [name] -> Longident.Lident name
| name :: names_rev -> Longident.Ldot (of_names names_rev, name)
in
let names_rev =
Compilation_unit.full_path cu
|> List.rev_map Compilation_unit.Name.to_string
in
of_names names_rev
let global_path cu =
Some(longident_of_comp_unit cu)
let functor_path path param =
match path with
None -> None
| Some p -> Some(Longident.Lapply(p, Lident (Ident.name param)))
let field_path path field =
match path with
None -> None
| Some p -> Some(Longident.Ldot(p, Ident.name field))
(* Compile type extensions *)
let transl_type_extension ~scopes env rootpath tyext body =
List.fold_right
(fun ext body ->
let lam =
transl_extension_constructor ~scopes env
(field_path rootpath ext.ext_id) ext
in
Llet(Strict, Lambda.layout_block, ext.ext_id, lam, body))
tyext.tyext_constructors
body
(* Compile a coercion *)
let rec apply_coercion loc strict restr arg =
match restr with
Tcoerce_none ->
arg
| Tcoerce_structure(pos_cc_list, id_pos_list) ->
name_lambda strict arg Lambda.layout_module (fun id ->
let get_field pos =
if pos < 0 then lambda_unit
else
Lprim(mod_field pos,[Lvar id], loc)
in
let lam =
Lprim(Pmakeblock(0, Immutable, None, alloc_heap),
List.map (apply_coercion_field loc get_field) pos_cc_list,
loc)
in
wrap_id_pos_list loc id_pos_list get_field lam)
| Tcoerce_functor(cc_arg, cc_res) ->
let param = Ident.create_local "funarg" in
let carg = apply_coercion loc Alias cc_arg (Lvar param) in
apply_coercion_result loc strict arg
[{name = param; layout = Lambda.layout_module;
attributes = Lambda.default_param_attribute; mode = alloc_heap}]
[carg] cc_res
| Tcoerce_primitive { pc_desc; pc_env; pc_type; pc_poly_mode; pc_poly_sort } ->
Translprim.transl_primitive loc pc_desc pc_env pc_type
~poly_mode:pc_poly_mode
~poly_sort:pc_poly_sort
None
| Tcoerce_alias (env, path, cc) ->
let lam = transl_module_path loc env path in
name_lambda strict arg Lambda.layout_module
(fun _ -> apply_coercion loc Alias cc lam)
and apply_coercion_field loc get_field (pos, cc) =
apply_coercion loc Alias cc (get_field pos)
and apply_coercion_result loc strict funct params args cc_res =
match cc_res with
| Tcoerce_functor(cc_arg, cc_res) ->
let param = Ident.create_local "funarg" in
let arg = apply_coercion loc Alias cc_arg (Lvar param) in
apply_coercion_result loc strict funct
({ name = param;
layout = Lambda.layout_module;
attributes = Lambda.default_param_attribute;
mode = alloc_heap } :: params)
(arg :: args) cc_res
| _ ->
name_lambda strict funct Lambda.layout_functor
(fun id ->
lfunction
~kind:(Curried {nlocal=0})
~params:(List.rev params)
~return:Lambda.layout_module
~attr:{ default_function_attribute with
is_a_functor = true;
zero_alloc = Default_zero_alloc;
stub = true;
may_fuse_arity = true; }
~loc
~mode:alloc_heap
~ret_mode:alloc_heap
~region:true
~body:(apply_coercion
loc Strict cc_res
(Lapply{
ap_loc=loc;
ap_func=Lvar id;
ap_args=List.rev args;
ap_result_layout=Lambda.layout_module;
ap_region_close=Rc_normal;
ap_mode=alloc_heap;
ap_tailcall=Default_tailcall;
ap_inlined=Default_inlined;
ap_specialised=Default_specialise;
ap_probe=None;
})))
and wrap_id_pos_list loc id_pos_list get_field lam =
let fv = free_variables lam in
(*Format.eprintf "%a@." Printlambda.lambda lam;
Ident.Set.iter (fun id -> Format.eprintf "%a " Ident.print id) fv;
Format.eprintf "@.";*)
let (lam, _fv, s) =
List.fold_left (fun (lam, fv, s) (id',pos,c) ->
if Ident.Set.mem id' fv then
let id'' = Ident.create_local (Ident.name id') in
let rhs = apply_coercion loc Alias c (get_field pos) in
let fv_rhs = free_variables rhs in
(Llet(Alias, Lambda.layout_module_field, id'', rhs, lam),
Ident.Set.union fv fv_rhs,
Ident.Map.add id' id'' s)
else (lam, fv, s))
(lam, fv, Ident.Map.empty) id_pos_list
in
if s == Ident.Map.empty then lam else Lambda.rename s lam
(* Compose two coercions
apply_coercion c1 (apply_coercion c2 e) behaves like
apply_coercion (compose_coercions c1 c2) e. *)
let rec compose_coercions c1 c2 =
match (c1, c2) with
(Tcoerce_none, c2) -> c2
| (c1, Tcoerce_none) -> c1
| (Tcoerce_structure (pc1, ids1), Tcoerce_structure (pc2, ids2)) ->
let v2 = Array.of_list pc2 in
let ids1 =
List.map (fun (id,pos1,c1) ->
if pos1 < 0 then (id, pos1, c1)
else
let (pos2,c2) = v2.(pos1) in
(id, pos2, compose_coercions c1 c2))
ids1
in
Tcoerce_structure
(List.map
(fun pc ->
match pc with
| _, (Tcoerce_primitive _ | Tcoerce_alias _) ->
(* These cases do not take an argument (the position is -1),
so they do not need adjusting. *)
pc
| (p1, c1) ->
let (p2, c2) = v2.(p1) in
(p2, compose_coercions c1 c2))
pc1,
ids1 @ ids2)
| (Tcoerce_functor(arg1, res1), Tcoerce_functor(arg2, res2)) ->
Tcoerce_functor(compose_coercions arg2 arg1,
compose_coercions res1 res2)
| (c1, Tcoerce_alias (env, path, c2)) ->
Tcoerce_alias (env, path, compose_coercions c1 c2)
| (_, _) ->
fatal_error "Translmod.compose_coercions"
let dump_coercions = Option.is_some (Sys.getenv_opt "DUMP_COERCIONS")
let apply_coercion a b c d =
if dump_coercions then
Format.eprintf "@[<2>apply_coercion@ %a@]@." Includemod.print_coercion c;
let ans = apply_coercion a b c d in
if dump_coercions then
Format.eprintf "@[<2>apply_coercion@ %a@ = %a@]@."
Includemod.print_coercion c
Printlambda.lambda ans;
ans
(* Record the primitive declarations occurring in the module compiled *)
let primitive_declarations = ref ([] : Primitive.description list)
let record_primitive = function
| {val_kind=Val_prim p;val_loc} ->
Translprim.check_primitive_arity val_loc p;
primitive_declarations := p :: !primitive_declarations
| _ -> ()
(* Utilities for compiling "module rec" definitions *)
let mod_prim = Lambda.transl_prim "CamlinternalMod"
let undefined_location loc =
let (fname, line, char) = Location.get_pos_info loc.Location.loc_start in
Lconst(Const_block(0,
[Const_base(Const_string (fname, loc, None));
const_int line;
const_int char]))
exception Initialization_failure of unsafe_info
let init_shape id modl =
let rec init_shape_mod subid loc env mty =
match Mtype.scrape env mty with
Mty_ident _
| Mty_alias _
| Mty_strengthen _ ->
raise (Initialization_failure
(Unsafe {reason=Unsafe_module_binding;loc;subid}))
| Mty_signature sg ->
Const_block(0, [Const_block(0, init_shape_struct env sg)])
| Mty_functor _ ->
(* can we do better? *)
raise (Initialization_failure
(Unsafe {reason=Unsafe_functor;loc;subid}))
and init_shape_struct env sg =
match sg with
[] -> []
| Sig_value(subid, {val_kind=Val_reg; val_type=ty; val_loc=loc},_) :: rem ->
let init_v =
match get_desc (Ctype.expand_head env ty) with
Tarrow(_,ty_arg,_,_) -> begin
(* CR layouts: We should allow any representable layout here. It
will require reworking [camlinternalMod.init_mod]. *)
let jkind = Jkind.Builtin.value ~why:Recmod_fun_arg in
let ty_arg = Ctype.correct_levels ty_arg in
match Ctype.check_type_jkind env ty_arg jkind with
| Ok _ -> const_int 0 (* camlinternalMod.Function *)
| Error _ ->
let unsafe = Unsafe {reason=Unsafe_non_value_arg; loc; subid} in
raise (Initialization_failure unsafe)
end
| Tconstr(p, _, _) when Path.same p Predef.path_lazy_t ->
const_int 1 (* camlinternalMod.Lazy *)
| _ ->
let not_a_function =
Unsafe {reason=Unsafe_non_function; loc; subid }
in
raise (Initialization_failure not_a_function) in
init_v :: init_shape_struct env rem
| Sig_value(_, {val_kind=Val_prim _}, _) :: rem ->
init_shape_struct env rem
| Sig_value _ :: _rem ->
assert false
| Sig_type(id, tdecl, _, _) :: rem ->
init_shape_struct (Env.add_type ~check:false id tdecl env) rem
| Sig_typext (subid, {ext_loc=loc},_,_) :: _ ->
raise (Initialization_failure (Unsafe {reason=Unsafe_typext;loc;subid}))
| Sig_module(id, Mp_present, md, _, _) :: rem ->
init_shape_mod id md.md_loc env md.md_type ::
init_shape_struct (Env.add_module_declaration ~check:false
id Mp_present md env) rem
| Sig_module(id, Mp_absent, md, _, _) :: rem ->
init_shape_struct
(Env.add_module_declaration ~check:false
id Mp_absent md env) rem
| Sig_modtype(id, minfo, _) :: rem ->
init_shape_struct (Env.add_modtype id minfo env) rem
| Sig_class _ :: rem ->
const_int 2 (* camlinternalMod.Class *)
:: init_shape_struct env rem
| Sig_class_type _ :: rem ->
init_shape_struct env rem
in
try
Ok(undefined_location modl.mod_loc,
Lconst(init_shape_mod id modl.mod_loc modl.mod_env modl.mod_type))
with Initialization_failure reason -> Result.Error(reason)
(* Reorder bindings to honor dependencies. *)
type binding_status =
| Undefined
| Inprogress of int option (** parent node *)
| Defined
type id_or_ignore_loc =
| Id of Ident.t
| Ignore_loc of Lambda.scoped_location
let extract_unsafe_cycle id status init cycle_start =
let info i = match init.(i) with
| Result.Error r ->
begin match id.(i) with
| Id id -> id, r
| Ignore_loc _ ->
assert false (* Can't refer to something without a name. *)
end
| Ok _ -> assert false in
let rec collect stop l i = match status.(i) with
| Inprogress None | Undefined | Defined -> assert false
| Inprogress Some i when i = stop -> info i :: l
| Inprogress Some i -> collect stop (info i::l) i in
collect cycle_start [] cycle_start
let reorder_rec_bindings bindings =
let id = Array.of_list (List.map (fun (id,_,_,_) -> id) bindings)
and loc = Array.of_list (List.map (fun (_,loc,_,_) -> loc) bindings)
and init = Array.of_list (List.map (fun (_,_,init,_) -> init) bindings)
and rhs = Array.of_list (List.map (fun (_,_,_,rhs) -> rhs) bindings) in
let fv = Array.map Lambda.free_variables rhs in
let num_bindings = Array.length id in
let status = Array.make num_bindings Undefined in
let res = ref [] in
let is_unsafe i = match init.(i) with
| Ok _ -> false
| Result.Error _ -> true in
let init_res i = match init.(i) with
| Result.Error _ -> None
| Ok(a,b) -> Some(a,b) in
let rec emit_binding parent i =
match status.(i) with
Defined -> ()
| Inprogress _ ->
status.(i) <- Inprogress parent;
let cycle = extract_unsafe_cycle id status init i in
raise(Error(loc.(i), Circular_dependency cycle))
| Undefined ->
if is_unsafe i then begin
status.(i) <- Inprogress parent;
for j = 0 to num_bindings - 1 do
match id.(j) with
| Id id when Ident.Set.mem id fv.(i) -> emit_binding (Some i) j
| _ -> ()
done
end;
res := (id.(i), init_res i, rhs.(i)) :: !res;
status.(i) <- Defined in
for i = 0 to num_bindings - 1 do
match status.(i) with
Undefined -> emit_binding None i
| Inprogress _ -> assert false
| Defined -> ()
done;
List.rev !res
(* Generate lambda-code for a reordered list of bindings *)
let eval_rec_bindings bindings cont =
let rec bind_inits = function
[] ->
bind_strict bindings
| (Ignore_loc _, _, _) :: rem
| (_, None, _) :: rem ->
bind_inits rem
| (Id id, Some(loc, shape), _rhs) :: rem ->
Llet(Strict, Lambda.layout_module, id,
Lapply{
ap_loc=Loc_unknown;
ap_func=mod_prim "init_mod";
ap_result_layout = Lambda.layout_module;
ap_args=[loc; shape];
ap_region_close=Rc_normal;
ap_mode=alloc_heap;
ap_tailcall=Default_tailcall;
ap_inlined=Default_inlined;
ap_specialised=Default_specialise;
ap_probe=None;
},
bind_inits rem)
and bind_strict = function
[] ->
patch_forwards bindings
| (Ignore_loc loc, None, rhs) :: rem ->
Lsequence(Lprim(Pignore, [rhs], loc), bind_strict rem)
| (Id id, None, rhs) :: rem ->
Llet(Strict, Lambda.layout_module, id, rhs, bind_strict rem)
| (_id, Some _, _rhs) :: rem ->
bind_strict rem
and patch_forwards = function
[] ->
cont
| (Ignore_loc _, _, _rhs) :: rem
| (_, None, _rhs) :: rem ->
patch_forwards rem
| (Id id, Some(_loc, shape), rhs) :: rem ->
Lsequence(
Lapply {
ap_loc=Loc_unknown;
ap_func=mod_prim "update_mod";
ap_result_layout = Lambda.layout_unit;
ap_args=[shape; Lvar id; rhs];
ap_region_close=Rc_normal;
ap_mode=alloc_heap;
ap_tailcall=Default_tailcall;
ap_inlined=Default_inlined;
ap_specialised=Default_specialise;
ap_probe=None;
},
patch_forwards rem)
in
bind_inits bindings
let compile_recmodule ~scopes compile_rhs bindings cont =
eval_rec_bindings
(reorder_rec_bindings
(List.map
(fun {mb_id=id; mb_name; mb_expr=modl; _} ->
let id_or_ignore_loc, shape =
match id with
| None ->
let loc = of_location ~scopes mb_name.loc in
Ignore_loc loc, Result.Error Unnamed
| Some id -> Id id, init_shape id modl
in
(id_or_ignore_loc, modl.mod_loc, shape, compile_rhs id modl))
bindings))
cont
(* Code to translate class entries in a structure *)
let transl_class_bindings ~scopes cl_list =
let ids = List.map (fun (ci, _) -> ci.ci_id_class) cl_list in
(ids,
List.map
(fun ({ci_id_class=id; ci_expr=cl; ci_virt=vf}, meths) ->
let def, rkind = transl_class ~scopes ids id meths cl vf in
(id, rkind, def))
cl_list)
(* Compile one or more functors, merging curried functors to produce
multi-argument functors. Any [@inline] attribute on a functor that is
merged must be consistent with any other [@inline] attribute(s) on the
functor(s) being merged with. Such an attribute will be placed on the
resulting merged functor. *)
let merge_inline_attributes attr1 attr2 loc =
match Lambda.merge_inline_attributes attr1 attr2 with
| Some attr -> attr
| None -> raise (Error (to_location loc, Conflicting_inline_attributes))
let merge_functors ~scopes mexp coercion root_path =
let rec merge ~scopes mexp coercion path acc inline_attribute =
let finished = acc, mexp, path, coercion, inline_attribute in
match mexp.mod_desc with
| Tmod_functor (param, body) ->
let inline_attribute' =
Translattribute.get_inline_attribute mexp.mod_attributes
in
let arg_coercion, res_coercion =
match coercion with
| Tcoerce_none -> Tcoerce_none, Tcoerce_none
| Tcoerce_functor (arg_coercion, res_coercion) ->
arg_coercion, res_coercion
| _ -> fatal_error "Translmod.merge_functors: bad coercion"
in
let loc = of_location ~scopes mexp.mod_loc in
let path, param =
match param with
| Unit -> None, Ident.create_local "*"
| Named (None, _, _) ->
let id = Ident.create_local "_" in
functor_path path id, id
| Named (Some id, _, _) -> functor_path path id, id
in
let inline_attribute =
merge_inline_attributes inline_attribute inline_attribute' loc
in
merge ~scopes body res_coercion path ((param, loc, arg_coercion) :: acc)
inline_attribute
| _ -> finished
in
merge ~scopes mexp coercion root_path [] Default_inline
let rec compile_functor ~scopes mexp coercion root_path loc =
let functor_params_rev, body, body_path, res_coercion, inline_attribute =
merge_functors ~scopes mexp coercion root_path
in
assert (List.length functor_params_rev >= 1); (* cf. [transl_module] *)
let params, body =
List.fold_left (fun (params, body) (param, loc, arg_coercion) ->
let param' = Ident.rename param in
let arg = apply_coercion loc Alias arg_coercion (Lvar param') in
let params = {
name = param';
layout = Lambda.layout_module;
attributes = Lambda.default_param_attribute;
mode = alloc_heap
} :: params in
let body = Llet (Alias, Lambda.layout_module, param, arg, body) in
params, body)
([], transl_module ~scopes res_coercion body_path body)
functor_params_rev
in
lfunction
~kind:(Curried {nlocal=0})
~params
~return:Lambda.layout_module
~attr:{
inline = inline_attribute;
specialise = Default_specialise;
local = Default_local;
poll = Default_poll;
loop = Never_loop;
is_a_functor = true;
is_opaque = false;
zero_alloc = Default_zero_alloc;
stub = false;
tmc_candidate = false;
may_fuse_arity = true;
unbox_return = false;
}
~loc
~mode:alloc_heap
~ret_mode:alloc_heap
~region:true
~body
(* Compile a module expression *)
and transl_module ~scopes cc rootpath mexp =
let loc = of_location ~scopes mexp.mod_loc in
match mexp.mod_desc with
| Tmod_ident (path,_) ->
apply_coercion loc Strict cc
(transl_module_path loc mexp.mod_env path)
| Tmod_structure str ->
fst (transl_struct ~scopes loc [] cc rootpath str)
| Tmod_functor _ ->
oo_wrap mexp.mod_env true (fun () ->
compile_functor ~scopes mexp cc rootpath loc) ()
| Tmod_apply(funct, arg, ccarg) ->
let translated_arg = transl_module ~scopes ccarg None arg in
transl_apply ~scopes ~loc ~cc mexp.mod_env funct translated_arg
| Tmod_apply_unit funct ->
transl_apply ~scopes ~loc ~cc mexp.mod_env funct lambda_unit
| Tmod_constraint(arg, _, _, ccarg) ->
transl_module ~scopes (compose_coercions cc ccarg) rootpath arg
| Tmod_unpack(arg, _) ->
apply_coercion loc Strict cc
(Translcore.transl_exp ~scopes Jkind.Sort.for_module arg)
and transl_apply ~scopes ~loc ~cc mod_env funct translated_arg =
let inlined_attribute =
Translattribute.get_inlined_attribute_on_module funct
in
oo_wrap mod_env true
(apply_coercion loc Strict cc)
(Lapply{
ap_loc=loc;
ap_func=transl_module ~scopes Tcoerce_none None funct;
ap_args=[translated_arg];
ap_result_layout = Lambda.layout_module;
ap_region_close=Rc_normal;
ap_mode=alloc_heap;
ap_tailcall=Default_tailcall;
ap_inlined=inlined_attribute;
ap_specialised=Default_specialise;
ap_probe=None;})
and transl_struct ~scopes loc fields cc rootpath {str_final_env; str_items; _} =
transl_structure ~scopes loc fields cc rootpath str_final_env str_items
(* The function transl_structure is called by the bytecode compiler.
Some effort is made to compile in top to bottom order, in order to display
warning by increasing locations. *)
and transl_structure ~scopes loc fields cc rootpath final_env = function
[] ->
let body, size =
match cc with
Tcoerce_none ->
Lprim(Pmakeblock(0, Immutable, None, alloc_heap),
List.map (fun id -> Lvar id) (List.rev fields), loc),
List.length fields
| Tcoerce_structure(pos_cc_list, id_pos_list) ->
(* Do not ignore id_pos_list ! *)
(*Format.eprintf "%a@.@[" Includemod.print_coercion cc;
List.iter (fun l -> Format.eprintf "%a@ " Ident.print l)
fields;
Format.eprintf "@]@.";*)
let v = Array.of_list (List.rev fields) in
let get_field pos =
if pos < 0 then lambda_unit
else Lvar v.(pos)
in
let ids = List.fold_right Ident.Set.add fields Ident.Set.empty in
let lam =
Lprim(Pmakeblock(0, Immutable, None, alloc_heap),
List.map
(fun (pos, cc) ->
match cc with
| Tcoerce_primitive p ->
let loc = of_location ~scopes p.pc_loc in
Translprim.transl_primitive
loc p.pc_desc p.pc_env p.pc_type
~poly_mode:p.pc_poly_mode
~poly_sort:p.pc_poly_sort
None
| _ -> apply_coercion loc Strict cc (get_field pos))
pos_cc_list, loc)
and id_pos_list =
List.filter (fun (id,_,_) -> not (Ident.Set.mem id ids))
id_pos_list
in
wrap_id_pos_list loc id_pos_list get_field lam,
List.length pos_cc_list
| _ ->
fatal_error "Translmod.transl_structure"
in
(* This debugging event provides information regarding the structure
items. It is ignored by the OCaml debugger but is used by
Js_of_ocaml to preserve variable names. *)
(if !Clflags.debug && not !Clflags.native_code then
Levent(body,
{lev_loc = loc;
lev_kind = Lev_pseudo;
lev_repr = None;
lev_env = final_env})
else
body),
size
| item :: rem ->
match item.str_desc with
| Tstr_eval (expr, sort, _) ->
let body, size =
transl_structure ~scopes loc fields cc rootpath final_env rem
in
sort_must_not_be_void expr.exp_loc expr.exp_type sort;
Lsequence(transl_exp ~scopes sort expr, body), size
| Tstr_value(rec_flag, pat_expr_list) ->
(* Translate bindings first *)
let mk_lam_let =
transl_let ~scopes ~return_layout:Lambda.layout_module_field
~in_structure:true rec_flag pat_expr_list
in
let ext_fields =
List.rev_append (let_bound_idents pat_expr_list) fields in
(* Then, translate remainder of struct *)
let body, size =
transl_structure ~scopes loc ext_fields cc rootpath final_env rem
in
mk_lam_let body, size
| Tstr_primitive descr ->
record_primitive descr.val_val;
transl_structure ~scopes loc fields cc rootpath final_env rem
| Tstr_type _ ->
transl_structure ~scopes loc fields cc rootpath final_env rem
| Tstr_typext(tyext) ->
let ids = List.map (fun ext -> ext.ext_id) tyext.tyext_constructors in
let body, size =
transl_structure ~scopes loc (List.rev_append ids fields)
cc rootpath final_env rem
in
transl_type_extension ~scopes item.str_env rootpath tyext body, size
| Tstr_exception ext ->
let id = ext.tyexn_constructor.ext_id in
let path = field_path rootpath id in
let body, size =
transl_structure ~scopes loc (id::fields) cc rootpath final_env rem
in
Llet(Strict, Lambda.layout_block, id,
transl_extension_constructor ~scopes
item.str_env
path
ext.tyexn_constructor, body),
size
| Tstr_module ({mb_presence=Mp_present} as mb) ->
let id = mb.mb_id in
(* Translate module first *)
let subscopes = match id with
| None -> scopes
| Some id -> enter_module_definition ~scopes id in
let module_body =
transl_module ~scopes:subscopes Tcoerce_none
(Option.bind id (field_path rootpath)) mb.mb_expr
in
let module_body =
Translattribute.add_inline_attribute module_body mb.mb_loc
mb.mb_attributes
in
(* Translate remainder second *)
let body, size =
transl_structure ~scopes loc (cons_opt id fields)
cc rootpath final_env rem
in
begin match id with
| None ->
Lsequence (Lprim(Pignore, [module_body],
of_location ~scopes mb.mb_name.loc), body),
size
| Some id ->
Llet(pure_module mb.mb_expr, Lambda.layout_module, id, module_body, body), size
end
| Tstr_module ({mb_presence=Mp_absent}) ->
transl_structure ~scopes loc fields cc rootpath final_env rem
| Tstr_recmodule bindings ->
let ext_fields =
List.rev_append (List.filter_map (fun mb -> mb.mb_id) bindings)
fields
in
let body, size =
transl_structure ~scopes loc ext_fields cc rootpath final_env rem
in
let lam =
compile_recmodule ~scopes (fun id modl ->
match id with
| None -> transl_module ~scopes Tcoerce_none None modl
| Some id ->
transl_module
~scopes:(enter_module_definition ~scopes id)
Tcoerce_none (field_path rootpath id) modl
) bindings body
in
lam, size
| Tstr_class cl_list ->
let (ids, class_bindings) = transl_class_bindings ~scopes cl_list in
let body, size =
transl_structure ~scopes loc (List.rev_append ids fields)
cc rootpath final_env rem
in
Value_rec_compiler.compile_letrec class_bindings body, size
| Tstr_include incl ->
let ids = bound_value_identifiers incl.incl_type in
let modl = incl.incl_mod in
let mid = Ident.create_local "include" in
let rec rebind_idents pos newfields = function
[] ->
transl_structure ~scopes loc newfields cc rootpath final_env rem
| id :: ids ->
let body, size =
rebind_idents (pos + 1) (id :: newfields) ids
in
Llet(Alias, Lambda.layout_module_field, id,
Lprim(mod_field pos, [Lvar mid],
of_location ~scopes incl.incl_loc), body),
size
in
let body, size = rebind_idents 0 fields ids in
let loc = of_location ~scopes incl.incl_loc in
let let_kind, modl =
match incl.incl_kind with
| Tincl_structure ->
pure_module modl, transl_module ~scopes Tcoerce_none None modl
| Tincl_functor ccs ->
Strict, transl_include_functor ~generative:false modl ccs
scopes loc
| Tincl_gen_functor ccs ->
Strict, transl_include_functor ~generative:true modl ccs
scopes loc
in
Llet(let_kind, Lambda.layout_module, mid, modl, body),
size
| Tstr_open od ->
let pure = pure_module od.open_expr in
(* this optimization shouldn't be needed because Simplif would
actually remove the [Llet] when it's not used.
But since [scan_used_globals] runs before Simplif, we need to do
it. *)
begin match od.open_bound_items with
| [] when pure = Alias ->
transl_structure ~scopes loc fields cc rootpath final_env rem
| _ ->
let ids = bound_value_identifiers od.open_bound_items in
let mid = Ident.create_local "open" in
let rec rebind_idents pos newfields = function
[] -> transl_structure
~scopes loc newfields cc rootpath final_env rem
| id :: ids ->
let body, size =
rebind_idents (pos + 1) (id :: newfields) ids
in
Llet(Alias, Lambda.layout_module_field, id,
Lprim(mod_field pos, [Lvar mid],
of_location ~scopes od.open_loc), body),
size
in
let body, size = rebind_idents 0 fields ids in
Llet(pure, Lambda.layout_module, mid,
transl_module ~scopes Tcoerce_none None od.open_expr, body),
size
end
| Tstr_modtype _
| Tstr_class_type _
| Tstr_attribute _ ->
transl_structure ~scopes loc fields cc rootpath final_env rem
(* construct functor application in "include functor" case *)
and transl_include_functor ~generative modl params scopes loc =
let inlined_attribute =
Translattribute.get_inlined_attribute_on_module modl
in
let modl = transl_module ~scopes Tcoerce_none None modl in
let params = if generative then [params;[]] else [params] in
let params = List.map (fun coercion ->
Lprim(Pmakeblock(0, Immutable, None, alloc_heap),
List.map (fun (name, cc) ->
apply_coercion loc Strict cc (Lvar name))
coercion,
loc))
params
in
Lapply {
ap_loc = loc;
ap_func = modl;
ap_args = params;
ap_result_layout = Lambda.layout_module;
ap_region_close=Rc_normal;
ap_mode = alloc_heap;
ap_tailcall = Default_tailcall;
ap_inlined = inlined_attribute;
ap_specialised = Default_specialise;
ap_probe = None;}
(* Update forward declaration in Translcore *)
let _ =
Translcore.transl_module := transl_module
(* Introduce dependencies on modules referenced only by "external". *)
let scan_used_globals lam =
let globals = ref Compilation_unit.Set.empty in
let rec scan lam =
Lambda.iter_head_constructor scan lam;
match lam with
Lprim ((Pgetglobal cu | Psetglobal cu), _, _) ->
globals := Compilation_unit.Set.add cu !globals
| _ -> ()
in
scan lam; !globals
let required_globals ~flambda body =
let globals = scan_used_globals body in
let add_global comp_unit req =
if not flambda && Compilation_unit.Set.mem comp_unit globals then
req
else
Compilation_unit.Set.add comp_unit req
in
let required =
List.fold_left
(fun acc cu -> add_global cu acc)
(if flambda then globals else Compilation_unit.Set.empty)
(Translprim.get_units_with_used_primitives ())
in
let required =
List.fold_right add_global (Env.get_required_globals ()) required
in
Env.reset_required_globals ();
Translprim.clear_used_primitives ();
required
let add_arg_block_to_module_block primary_block_lam size restr =
let primary_block_id = Ident.create_local "*primary-block*" in
let arg_block_id = Ident.create_local "*arg-block*" in
let arg_block_lam =
apply_coercion Loc_unknown Strict restr (Lvar primary_block_id)
in
let get_field i = Lprim (mod_field i, [Lvar primary_block_id], Loc_unknown) in
let all_fields = List.init size get_field @ [Lvar arg_block_id] in
let arg_block_field = size in
let new_size = size + 1 in
Llet(Strict, layout_module, primary_block_id, primary_block_lam,
Llet(Strict, layout_module, arg_block_id, arg_block_lam,
Lprim(Pmakeblock(0, Immutable, None, alloc_heap),
all_fields,
Loc_unknown))),
new_size,
Some arg_block_field
let add_runtime_parameters lam params =
let params =
List.map
(fun name ->
{ name;
layout = Pvalue Lambda.generic_value;
attributes = Lambda.default_param_attribute;
mode = Lambda.alloc_heap })
params
in
let inline =
(* We want to inline the functor so that [-instantiate] compiles away the
function call and actually substitutes. *)
Always_inline
in
lfunction
~params
~kind:(Curried { nlocal = 0 })
~return:(Pvalue Lambda.generic_value)
~attr:{ default_function_attribute with is_a_functor = true; inline }
~loc:Loc_unknown
~body:lam
~mode:alloc_heap
~ret_mode:alloc_heap
~region:true
let transl_implementation_module ~scopes module_id (str, cc, cc2) =
let path = global_path module_id in
let lam, size =
transl_struct ~scopes Loc_unknown [] cc path str
in
match cc2 with
| None -> lam, size, None
| Some cc2 -> add_arg_block_to_module_block lam size cc2
let wrap_toplevel_functor_in_struct code =
Lprim(Pmakeblock(0, Immutable, None, Lambda.alloc_heap),
[ code ],
Loc_unknown)
(* Convert an flambda-style implementation (module block only) to a
non-flambda-style one (set global as side effect) *)
let wrap_in_setglobal implementation =
let code =
Lprim (Psetglobal implementation.compilation_unit, [implementation.code],
Loc_unknown)
in
{ implementation with code }
(* Compile an implementation *)
type compilation_unit_style =
| Plain_block
| Set_global_to_block
| Set_individual_fields
let has_parameters () =
Env.parameters () <> []
let transl_implementation_plain_block compilation_unit impl =