-
Notifications
You must be signed in to change notification settings - Fork 464
/
Copy pathtranslcore.ml
1280 lines (1232 loc) · 42.3 KB
/
translcore.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 core language *)
open Misc
open Asttypes
open Primitive
open Types
open Typedtree
open Typeopt
open Lambda
type error = Unknown_builtin_primitive of string
exception Error of Location.t * error
(* Forward declaration -- to be filled in by Translmod.transl_module *)
let transl_module =
ref
(fun _cc _rootpath _modl -> assert false
: module_coercion -> Path.t option -> module_expr -> lambda)
(* Compile an exception/extension definition *)
let transl_extension_constructor env path ext =
let name =
match path (*!Clflags.for_package*) with
| None -> Ident.name ext.ext_id
| Some p -> Path.name p
in
let loc = ext.ext_loc in
match ext.ext_kind with
| Text_decl _ -> Lprim (Pcreate_extension name, [], loc)
| Text_rebind (path, _lid) -> transl_extension_path ~loc env path
(* Translation of primitives *)
(** This is ad-hoc translation for unifying specific primitive operations
See [Unified_ops] module for detailed explanation.
*)
let translate_unified_ops (prim : Primitive.description) (env : Env.t)
(lhs_type : type_expr) : Lambda.primitive option =
(* lhs_type is already unified in type-level *)
let entry = Hashtbl.find_opt Unified_ops.index_by_name prim.prim_name in
match entry with
| Some {specialization} -> (
match specialization with
| {int}
when is_base_type env lhs_type Predef.path_int
|| maybe_pointer_type env lhs_type = Immediate ->
Some int
| {float = Some float} when is_base_type env lhs_type Predef.path_float ->
Some float
| {bigint = Some bigint} when is_base_type env lhs_type Predef.path_bigint
->
Some bigint
| {string = Some string} when is_base_type env lhs_type Predef.path_string
->
Some string
| {bool = Some bool} when is_base_type env lhs_type Predef.path_bool ->
Some bool
| {int} -> Some int)
| _ -> None
type specialized = {
objcomp: Lambda.primitive;
intcomp: Lambda.primitive;
boolcomp: Lambda.primitive;
floatcomp: Lambda.primitive;
stringcomp: Lambda.primitive;
bigintcomp: Lambda.primitive;
simplify_constant_constructor: bool;
}
let comparisons_table =
create_hashtable
[|
( "%equal",
{
objcomp = Pobjcomp Ceq;
intcomp = Pintcomp Ceq;
boolcomp = Pboolcomp Ceq;
floatcomp = Pfloatcomp Ceq;
stringcomp = Pstringcomp Ceq;
bigintcomp = Pbigintcomp Ceq;
simplify_constant_constructor = true;
} );
( "%notequal",
{
objcomp = Pobjcomp Cneq;
intcomp = Pintcomp Cneq;
boolcomp = Pboolcomp Cneq;
floatcomp = Pfloatcomp Cneq;
stringcomp = Pstringcomp Cneq;
bigintcomp = Pbigintcomp Cneq;
simplify_constant_constructor = true;
} );
( "%lessthan",
{
objcomp = Pobjcomp Clt;
intcomp = Pintcomp Clt;
boolcomp = Pboolcomp Clt;
floatcomp = Pfloatcomp Clt;
stringcomp = Pstringcomp Clt;
bigintcomp = Pbigintcomp Clt;
simplify_constant_constructor = false;
} );
( "%greaterthan",
{
objcomp = Pobjcomp Cgt;
intcomp = Pintcomp Cgt;
boolcomp = Pboolcomp Cgt;
floatcomp = Pfloatcomp Cgt;
stringcomp = Pstringcomp Cgt;
bigintcomp = Pbigintcomp Cgt;
simplify_constant_constructor = false;
} );
( "%lessequal",
{
objcomp = Pobjcomp Cle;
intcomp = Pintcomp Cle;
boolcomp = Pboolcomp Cle;
floatcomp = Pfloatcomp Cle;
stringcomp = Pstringcomp Cle;
bigintcomp = Pbigintcomp Cle;
simplify_constant_constructor = false;
} );
( "%greaterequal",
{
objcomp = Pobjcomp Cge;
intcomp = Pintcomp Cge;
boolcomp = Pboolcomp Cge;
floatcomp = Pfloatcomp Cge;
stringcomp = Pstringcomp Cge;
bigintcomp = Pbigintcomp Cge;
simplify_constant_constructor = false;
} );
( "%compare",
{
objcomp = Pobjorder;
intcomp = Pintorder;
boolcomp = Pboolorder;
floatcomp = Pfloatorder;
stringcomp = Pstringorder;
bigintcomp = Pbigintorder;
simplify_constant_constructor = false;
} );
( "%max",
{
objcomp = Pobjmax;
intcomp = Pintmax;
boolcomp = Pboolmax;
floatcomp = Pboolmax;
stringcomp = Pstringmax;
bigintcomp = Pbigintmax;
simplify_constant_constructor = false;
} );
( "%min",
{
objcomp = Pobjmin;
intcomp = Pintmin;
boolcomp = Pboolmin;
floatcomp = Pfloatmin;
stringcomp = Pstringmin;
bigintcomp = Pbigintmin;
simplify_constant_constructor = false;
} );
( "%equal_null",
{
objcomp = Pobjcomp Ceq;
intcomp = Pintcomp Ceq;
boolcomp = Pboolcomp Ceq;
floatcomp = Pfloatcomp Ceq;
stringcomp = Pstringcomp Ceq;
bigintcomp = Pbigintcomp Ceq;
simplify_constant_constructor = false;
} );
( "%equal_undefined",
{
objcomp = Pobjcomp Ceq;
intcomp = Pintcomp Ceq;
boolcomp = Pboolcomp Ceq;
floatcomp = Pfloatcomp Ceq;
stringcomp = Pstringcomp Ceq;
bigintcomp = Pbigintcomp Ceq;
simplify_constant_constructor = false;
} );
( "%equal_nullable",
{
objcomp = Pobjcomp Ceq;
intcomp = Pintcomp Ceq;
boolcomp = Pboolcomp Ceq;
floatcomp = Pfloatcomp Ceq;
stringcomp = Pstringcomp Ceq;
bigintcomp = Pbigintcomp Ceq;
simplify_constant_constructor = false;
} );
(* FIXME: Core compatibility *)
( "%bs_min",
{
objcomp = Pobjmax;
intcomp = Pintmax;
boolcomp = Pboolmax;
floatcomp = Pboolmax;
stringcomp = Pstringmax;
bigintcomp = Pbigintmax;
simplify_constant_constructor = false;
} );
( "%bs_max",
{
objcomp = Pobjmin;
intcomp = Pintmin;
boolcomp = Pboolmin;
floatcomp = Pfloatmin;
stringcomp = Pstringmin;
bigintcomp = Pbigintmin;
simplify_constant_constructor = false;
} );
|]
let primitives_table =
create_hashtable
[|
("%identity", Pidentity);
("%ignore", Pignore);
("%revapply", Prevapply);
("%apply", Pdirapply);
("%loc_LOC", Ploc Loc_LOC);
("%loc_FILE", Ploc Loc_FILE);
("%loc_LINE", Ploc Loc_LINE);
("%loc_POS", Ploc Loc_POS);
("%loc_MODULE", Ploc Loc_MODULE);
(* BEGIN Triples for ref data type *)
("%makeref", Pmakeblock Lambda.ref_tag_info);
("%refset", Psetfield (0, Lambda.ref_field_set_info));
("%refget", Pfield (0, Lambda.ref_field_info));
("%incr", Poffsetref 1);
("%decr", Poffsetref (-1));
(* Finish Triples for ref data type *)
("%field0", Pfield (0, Fld_tuple));
("%field1", Pfield (1, Fld_tuple));
("%obj_dup", Pduprecord);
("%obj_tag", Pobjtag);
("%obj_size", Pobjsize);
("%obj_get_field", Parrayrefu);
("%obj_set_field", Parraysetu);
("%raise", Praise Raise_regular);
(* bool primitives *)
("%sequand", Psequand);
("%sequor", Psequor);
("%boolnot", Pnot);
("%boolorder", Pboolorder);
("%boolmin", Pboolmin);
("%boolmax", Pboolmax);
(* int primitives *)
("%obj_is_int", Pisint);
("%negint", Pnegint);
("%succint", Poffsetint 1);
("%predint", Poffsetint (-1));
("%addint", Paddint);
("%subint", Psubint);
("%mulint", Pmulint);
("%divint", Pdivint Safe);
("%modint", Pmodint Safe);
("%andint", Pandint);
("%orint", Porint);
("%xorint", Pxorint);
("%lslint", Plslint);
("%lsrint", Plsrint);
("%asrint", Pasrint);
("%eq", Pintcomp Ceq);
("%noteq", Pintcomp Cneq);
("%ltint", Pintcomp Clt);
("%leint", Pintcomp Cle);
("%gtint", Pintcomp Cgt);
("%geint", Pintcomp Cge);
("%intorder", Pintorder);
("%intmin", Pintmin);
("%intmax", Pintmax);
(* float primitives *)
("%negfloat", Pnegfloat);
("%absfloat", Pabsfloat);
("%addfloat", Paddfloat);
("%subfloat", Psubfloat);
("%mulfloat", Pmulfloat);
("%divfloat", Pdivfloat);
("%modfloat", Pmodfloat);
("%eqfloat", Pfloatcomp Ceq);
("%noteqfloat", Pfloatcomp Cneq);
("%ltfloat", Pfloatcomp Clt);
("%lefloat", Pfloatcomp Cle);
("%gtfloat", Pfloatcomp Cgt);
("%gefloat", Pfloatcomp Cge);
("%floatorder", Pfloatorder);
("%floatmin", Pfloatmin);
("%floatmax", Pfloatmax);
(* bigint primitives *)
("%negbigint", Pnegbigint);
("%addbigint", Paddbigint);
("%subbigint", Psubbigint);
("%mulbigint", Pmulbigint);
("%divbigint", Pdivbigint);
("%powbigint", Ppowbigint);
("%modbigint", Pmodbigint);
("%eqbigint", Pbigintcomp Ceq);
("%noteqbigint", Pbigintcomp Cneq);
("%ltbigint", Pbigintcomp Clt);
("%lebigint", Pbigintcomp Cle);
("%gtbigint", Pbigintcomp Cgt);
("%gebigint", Pbigintcomp Cge);
("%andbigint", Pandbigint);
("%orbigint", Porbigint);
("%xorbigint", Pxorbigint);
("%lslbigint", Plslbigint);
("%asrbigint", Pasrbigint);
("%bigintorder", Pbigintorder);
("%bigintmin", Pbigintmin);
("%bigintmax", Pbigintmax);
(* string primitives *)
("%string_length", Pstringlength);
("%string_safe_get", Pstringrefs);
("%string_unsafe_get", Pstringrefu);
("%stringorder", Pstringorder);
("%stringmin", Pstringmin);
("%stringmax", Pstringmax);
("%string_concat", Pstringadd);
(* array primitives *)
("%array_length", Parraylength);
("%array_safe_get", Parrayrefs);
("%array_safe_set", Parraysets);
("%array_unsafe_get", Parrayrefu);
("%array_unsafe_set", Parraysetu);
(* dict primitives *)
("%makedict", Pmakedict);
(* promise *)
("%await", Pawait);
(* module *)
("%import", Pimport);
(* hash *)
("%hash", Phash);
("%hash_mix_int", Phash_mixint);
("%hash_mix_string", Phash_mixstring);
("%hash_final_mix", Phash_finalmix);
(* etc *)
("%typeof", Ptypeof);
("%debugger", Pdebugger);
("%intoffloat", Pintoffloat);
("%floatofint", Pfloatofint);
("%unsafe_eq", Pjscomp Ceq);
("%unsafe_neq", Pjscomp Cneq);
("%unsafe_lt", Pjscomp Clt);
("%unsafe_le", Pjscomp Cle);
("%unsafe_gt", Pjscomp Cgt);
("%unsafe_ge", Pjscomp Cge);
("%null", Pnull);
("%undefined", Pundefined);
("%is_nullable", Pisnullable);
("%undefined_to_opt", Pundefined_to_opt);
("%null_to_opt", Pnull_to_opt);
("%nullable_to_opt", Pnullable_to_opt);
("%function_arity", Pfn_arity);
("%wrap_exn", Pwrap_exn);
("%curry_apply1", Pcurry_apply 1);
("%curry_apply2", Pcurry_apply 2);
("%curry_apply3", Pcurry_apply 3);
("%curry_apply4", Pcurry_apply 4);
("%curry_apply5", Pcurry_apply 5);
("%curry_apply6", Pcurry_apply 6);
("%curry_apply7", Pcurry_apply 7);
("%curry_apply8", Pcurry_apply 8);
("%makemutablelist", Pmakelist Mutable);
("%unsafe_to_method", Pjs_fn_method);
(* Compiler internals, never expose to ReScript files *)
("#raw_expr", Pjs_raw_expr);
("#raw_stmt", Pjs_raw_stmt);
(* FIXME: Core compatibility *)
("#null", Pnull);
("#undefined", Pundefined);
("#typeof", Ptypeof);
("#is_nullable", Pisnullable);
("#null_to_opt", Pnull_to_opt);
("#nullable_to_opt", Pnullable_to_opt);
("#undefined_to_opt", Pundefined_to_opt);
("#makemutablelist", Pmakelist Mutable);
("#import", Pimport);
(* FIXME: Deprecated *)
("%obj_field", Parrayrefu);
|]
let find_primitive prim_name = Hashtbl.find primitives_table prim_name
let specialize_comparison
({objcomp; intcomp; floatcomp; stringcomp; bigintcomp; boolcomp} :
specialized) env ty =
match () with
| ()
when is_base_type env ty Predef.path_int
|| is_base_type env ty Predef.path_char
|| maybe_pointer_type env ty = Immediate ->
intcomp
| () when is_base_type env ty Predef.path_float -> floatcomp
| () when is_base_type env ty Predef.path_string -> stringcomp
| () when is_base_type env ty Predef.path_bigint -> bigintcomp
| () when is_base_type env ty Predef.path_bool -> boolcomp
| () -> objcomp
(* Specialize a primitive from available type information,
raise Not_found if primitive is unknown *)
let specialize_primitive p env ty (* ~has_constant_constructor *) =
let fn_expr = is_function_type env ty in
let unified =
match fn_expr with
| Some (lhs, _) -> translate_unified_ops p env lhs
| None -> None
in
match unified with
| Some primitive -> primitive
| None -> (
try
let table = Hashtbl.find comparisons_table p.prim_name in
match fn_expr with
| Some (lhs, _rhs) -> specialize_comparison table env lhs
| None -> table.objcomp
with Not_found -> find_primitive p.prim_name)
(* Eta-expand a primitive *)
let transl_primitive loc p env ty =
(* Printf.eprintf "----transl_primitive %s----\n" p.prim_name; *)
let prim =
try specialize_primitive p env ty (* ~has_constant_constructor:false *)
with Not_found -> Pccall p
in
match prim with
| Plazyforce ->
let parm = Ident.create "prim" in
Lfunction
{
params = [parm];
body = Matching.inline_lazy_force (Lvar parm) Location.none;
loc;
attr = default_function_attribute;
}
| Ploc kind -> (
let lam = lam_of_loc kind loc in
match p.prim_arity with
| 0 -> lam
| 1 ->
(* TODO: we should issue a warning ? *)
let param = Ident.create "prim" in
Lfunction
{
params = [param];
attr = default_function_attribute;
loc;
body = Lprim (Pmakeblock Blk_tuple, [lam; Lvar param], loc);
}
| _ -> assert false)
| _ ->
let rec make_params n total =
if n <= 0 then []
else
Ident.create ("prim" ^ string_of_int (total - n))
:: make_params (n - 1) total
in
let prim_arity = p.prim_arity in
if p.prim_from_constructor || prim_arity = 0 then Lprim (prim, [], loc)
else
let params =
if prim_arity = 1 then [Ident.create "prim"]
else make_params prim_arity prim_arity
in
Lfunction
{
params;
attr = default_function_attribute;
loc;
body = Lprim (prim, List.map (fun id -> Lvar id) params, loc);
}
let transl_primitive_application loc prim env ty args =
let prim_name = prim.prim_name in
let unified =
match args with
| [arg1] | [arg1; _] -> translate_unified_ops prim env arg1.exp_type
| _ -> None
in
match unified with
| Some primitive -> primitive
| None -> (
try
match args with
| [arg1; _]
when is_base_type env arg1.exp_type Predef.path_bool
&& Hashtbl.mem comparisons_table prim_name ->
(Hashtbl.find comparisons_table prim_name).boolcomp
| _ ->
let has_constant_constructor =
match args with
| [
_; {exp_desc = Texp_construct (_, {cstr_tag = Cstr_constant _}, _)};
]
| [
{exp_desc = Texp_construct (_, {cstr_tag = Cstr_constant _}, _)}; _;
]
| [_; {exp_desc = Texp_variant (_, None)}]
| [{exp_desc = Texp_variant (_, None)}; _] ->
true
| _ -> false
in
if has_constant_constructor then
match Hashtbl.find_opt comparisons_table prim_name with
| Some table when table.simplify_constant_constructor -> table.intcomp
| Some _ | None -> specialize_primitive prim env ty
(* ~has_constant_constructor*)
else specialize_primitive prim env ty
with Not_found ->
if String.length prim_name > 0 && prim_name.[0] = '%' then
raise (Error (loc, Unknown_builtin_primitive prim_name));
Pccall prim)
(* To propagate structured constants *)
exception Not_constant
let extract_constant = function
| Lconst sc -> sc
| _ -> raise_notrace Not_constant
(* Push the default values under the functional abstractions *)
(* Also push bindings of module patterns, since this sound *)
type binding =
| Bind_value of value_binding list
| Bind_module of Ident.t * string loc * module_expr
let rec push_defaults loc bindings case partial =
match case with
| {
c_lhs = pat;
c_guard = None;
c_rhs =
{exp_desc = Texp_function {arg_label; arity; param; case; partial}} as exp;
} ->
let case = push_defaults exp.exp_loc bindings case partial in
{
c_lhs = pat;
c_guard = None;
c_rhs =
{
exp with
exp_desc = Texp_function {arg_label; arity; param; case; partial};
};
}
| {
c_lhs = pat;
c_guard = None;
c_rhs =
{
exp_attributes = [({txt = "#default"}, _)];
exp_desc =
Texp_let (Nonrecursive, binds, ({exp_desc = Texp_function _} as e2));
};
} ->
push_defaults loc
(Bind_value binds :: bindings)
{c_lhs = pat; c_guard = None; c_rhs = e2}
partial
| {
c_lhs = pat;
c_guard = None;
c_rhs =
{
exp_attributes = [({txt = "#modulepat"}, _)];
exp_desc =
Texp_letmodule (id, name, mexpr, ({exp_desc = Texp_function _} as e2));
};
} ->
push_defaults loc
(Bind_module (id, name, mexpr) :: bindings)
{c_lhs = pat; c_guard = None; c_rhs = e2}
partial
| case ->
let exp =
List.fold_left
(fun exp binds ->
{
exp with
exp_desc =
(match binds with
| Bind_value binds -> Texp_let (Nonrecursive, binds, exp)
| Bind_module (id, name, mexpr) ->
Texp_letmodule (id, name, mexpr, exp));
})
case.c_rhs bindings
in
{case with c_rhs = exp}
(* Assertions *)
let assert_failed exp =
let fname, line, char =
Location.get_pos_info exp.exp_loc.Location.loc_start
in
let fname = Filename.basename fname in
Lprim
( Praise Raise_regular,
[
Lprim
( Pmakeblock Blk_extension,
[
transl_normal_path Predef.path_assert_failure;
Lconst
(Const_block
( Blk_tuple,
[
Const_base (Const_string (fname, None));
Const_base (Const_int line);
Const_base (Const_int char);
] ));
],
exp.exp_loc );
],
exp.exp_loc )
let rec cut n l =
if n = 0 then ([], l)
else
match l with
| [] -> failwith "Translcore.cut"
| a :: l ->
let l1, l2 = cut (n - 1) l in
(a :: l1, l2)
(* Translation of expressions *)
let try_ids = Hashtbl.create 8
let extract_directive_for_fn exp =
exp.exp_attributes
|> List.find_map (fun ({txt}, payload) ->
if txt = "directive" then Ast_payload.is_single_string payload
else None)
let rec transl_exp e =
List.iter (Translattribute.check_attribute e) e.exp_attributes;
transl_exp0 e
and transl_exp0 (e : Typedtree.expression) : Lambda.lambda =
match e.exp_desc with
| Texp_ident (_, _, {val_kind = Val_prim p}) ->
transl_primitive e.exp_loc p e.exp_env e.exp_type
| Texp_ident (path, _, {val_kind = Val_reg}) ->
transl_value_path ~loc:e.exp_loc e.exp_env path
| Texp_constant cst -> Lconst (Const_base cst)
| Texp_let (rec_flag, pat_expr_list, body) ->
transl_let rec_flag pat_expr_list (transl_exp body)
| Texp_function {arg_label = _; arity; param; case; partial} -> (
let async = Ast_async.has_async_payload e.exp_attributes in
let directive =
match extract_directive_for_fn e with
| None -> None
| Some (directive, _) -> Some directive
in
let params, body, return_unit =
let pl = push_defaults e.exp_loc [] case partial in
transl_function e.exp_loc partial param pl
in
let attr =
{
default_function_attribute with
inline = Translattribute.get_inline_attribute e.exp_attributes;
async;
return_unit;
directive;
}
in
let loc = e.exp_loc in
let lambda = Lfunction {params; body; attr; loc} in
match arity with
| Some arity ->
let prim =
let expanded = Ctype.expand_head e.exp_env e.exp_type in
match (Btype.repr expanded).desc with
| Tarrow (Nolabel, t, _, _, _) -> (
match (Ctype.expand_head e.exp_env t).desc with
| Tconstr (Pident {name = "unit"}, [], _) -> Pjs_fn_make_unit
| _ -> Pjs_fn_make arity)
| _ -> Pjs_fn_make arity
in
Lprim
( prim (* could be replaced with Opaque in the future except arity 0*),
[lambda],
loc )
| None -> lambda)
| Texp_apply
( ({
exp_desc = Texp_ident (_, _, {val_kind = Val_prim p});
exp_type = prim_type;
} as funct),
oargs )
when List.length oargs >= p.prim_arity
&& List.for_all (fun (_, arg) -> arg <> None) oargs -> (
let args, args' = cut p.prim_arity oargs in
let wrap f =
if args' = [] then f
else
let inlined, _ =
Translattribute.get_and_remove_inlined_attribute funct
in
transl_apply ~inlined f args' e.exp_loc
in
let args =
List.map
(function
| _, Some x -> x
| _ -> assert false)
args
in
let argl = transl_list args in
let prim =
transl_primitive_application e.exp_loc p e.exp_env prim_type args
in
match (prim, args) with
| Praise k, [_] ->
let targ = List.hd argl in
let k =
match (k, targ) with
| Raise_regular, Lvar id when Hashtbl.mem try_ids id -> Raise_reraise
| _ -> k
in
wrap (Lprim (Praise k, [targ], e.exp_loc))
| Ploc kind, [] -> lam_of_loc kind e.exp_loc
| Ploc kind, [arg1] ->
let lam = lam_of_loc kind arg1.exp_loc in
Lprim (Pmakeblock Blk_tuple, lam :: argl, e.exp_loc)
| Ploc _, _ -> assert false
| _, _ -> (
match (prim, argl) with
| Plazyforce, [a] -> wrap (Matching.inline_lazy_force a e.exp_loc)
| Plazyforce, _ -> assert false
| _ -> wrap (Lprim (prim, argl, e.exp_loc))))
| Texp_apply (funct, oargs) ->
let inlined, funct =
Translattribute.get_and_remove_inlined_attribute funct
in
let uncurried_partial_application =
(* In case of partial application foo(args, ...) when some args are missing,
get the arity *)
let uncurried_partial_app =
Ext_list.exists e.exp_attributes (fun ({txt}, _) -> txt = "res.partial")
in
if uncurried_partial_app then
let arity_opt = Ctype.get_arity funct.exp_env funct.exp_type in
match arity_opt with
| Some arity ->
let real_args = List.filter (fun (_, x) -> Option.is_some x) oargs in
if arity > List.length real_args then Some arity else None
| None -> None
else None
in
transl_apply ~inlined ~uncurried_partial_application (transl_exp funct)
oargs e.exp_loc
| Texp_match (arg, pat_expr_list, exn_pat_expr_list, partial) ->
transl_match e arg pat_expr_list exn_pat_expr_list partial
| Texp_try (body, pat_expr_list) ->
let id = Typecore.name_pattern "exn" pat_expr_list in
Ltrywith
( transl_exp body,
id,
Matching.for_trywith (Lvar id) (transl_cases_try pat_expr_list) )
| Texp_tuple el -> (
let ll = transl_list el in
try Lconst (Const_block (Blk_tuple, List.map extract_constant ll))
with Not_constant -> Lprim (Pmakeblock Blk_tuple, ll, e.exp_loc))
| Texp_construct ({txt = Lident "false"}, _, []) -> Lconst Const_false
| Texp_construct ({txt = Lident "true"}, _, []) -> Lconst Const_true
| Texp_construct (lid, cstr, args) -> (
let ll = transl_list args in
if cstr.cstr_inlined <> None then
match ll with
| [x] -> x
| _ -> assert false
else
match cstr.cstr_tag with
| Cstr_constant n ->
Lconst
(Const_pointer
( n,
match lid.txt with
| Longident.Ldot (Longident.Lident "*predef*", "None")
| Longident.Lident "None"
when Datarepr.constructor_has_optional_shape cstr ->
Pt_shape_none
| _ ->
if Datarepr.constructor_has_optional_shape cstr then
Pt_shape_none
else
Pt_constructor
{
name = cstr.cstr_name;
const = cstr.cstr_consts;
non_const = cstr.cstr_nonconsts;
attrs = cstr.cstr_attributes;
} ))
| Cstr_unboxed -> (
match ll with
| [v] -> v
| _ -> assert false)
| Cstr_block n -> (
let tag_info : Lambda.tag_info =
if Datarepr.constructor_has_optional_shape cstr then
match args with
| [arg]
when Typeopt.type_cannot_contain_undefined arg.exp_type
arg.exp_env ->
(* Format.fprintf Format.err_formatter "@[special boxingl@]@."; *)
Blk_some_not_nested
| _ -> Blk_some
else
Blk_constructor
{
name = cstr.cstr_name;
num_nonconst = cstr.cstr_nonconsts;
tag = n;
attrs = cstr.cstr_attributes;
}
in
try Lconst (Const_block (tag_info, List.map extract_constant ll))
with Not_constant -> Lprim (Pmakeblock tag_info, ll, e.exp_loc))
| Cstr_extension path ->
Lprim
( Pmakeblock Blk_extension,
transl_extension_path e.exp_env path :: ll,
e.exp_loc ))
| Texp_extension_constructor (_, path) -> transl_extension_path e.exp_env path
| Texp_variant (l, arg) -> (
let tag = Btype.hash_variant l in
match arg with
| None -> Lconst (Const_pointer (tag, Pt_variant {name = l}))
| Some arg -> (
let lam = transl_exp arg in
let tag_info = Blk_poly_var l in
try
Lconst
(Const_block
(tag_info, [Const_base (Const_int tag); extract_constant lam]))
with Not_constant ->
Lprim
( Pmakeblock tag_info,
[Lconst (Const_base (Const_int tag)); lam],
e.exp_loc )))
| Texp_record {fields; representation; extended_expression} ->
transl_record e.exp_loc e.exp_env fields representation extended_expression
| Texp_field (arg, _, lbl) -> (
let targ = transl_exp arg in
match lbl.lbl_repres with
| Record_float_unused -> assert false
| Record_regular ->
Lprim (Pfield (lbl.lbl_pos, Lambda.fld_record lbl), [targ], e.exp_loc)
| Record_inlined _ ->
Lprim
(Pfield (lbl.lbl_pos, Lambda.fld_record_inline lbl), [targ], e.exp_loc)
| Record_unboxed _ -> targ
| Record_extension ->
Lprim
( Pfield (lbl.lbl_pos + 1, Lambda.fld_record_extension lbl),
[targ],
e.exp_loc ))
| Texp_setfield (arg, _, lbl, newval) ->
let access =
match lbl.lbl_repres with
| Record_float_unused -> assert false
| Record_regular -> Psetfield (lbl.lbl_pos, Lambda.fld_record_set lbl)
| Record_inlined _ ->
Psetfield (lbl.lbl_pos, Lambda.fld_record_inline_set lbl)
| Record_unboxed _ -> assert false
| Record_extension ->
Psetfield (lbl.lbl_pos + 1, Lambda.fld_record_extension_set lbl)
in
Lprim (access, [transl_exp arg; transl_exp newval], e.exp_loc)
| Texp_array expr_list ->
let ll = transl_list expr_list in
Lprim (Pmakearray Mutable, ll, e.exp_loc)
| Texp_ifthenelse (cond, ifso, Some ifnot) ->
Lifthenelse (transl_exp cond, transl_exp ifso, transl_exp ifnot)
| Texp_ifthenelse (cond, ifso, None) ->
Lifthenelse (transl_exp cond, transl_exp ifso, lambda_unit)
| Texp_sequence (expr1, expr2) ->
Lsequence (transl_exp expr1, transl_exp expr2)
| Texp_while (cond, body) -> Lwhile (transl_exp cond, transl_exp body)
| Texp_for (param, _, low, high, dir, body) ->
Lfor (param, transl_exp low, transl_exp high, dir, transl_exp body)
| Texp_send (expr, Tmeth_name nm, _) ->
let obj = transl_exp expr in
Lsend (nm, obj, e.exp_loc)
| Texp_new _ | Texp_instvar _ | Texp_setinstvar _ | Texp_override _ ->
assert false
| Texp_letmodule (id, _loc, modl, body) ->
let defining_expr = !transl_module Tcoerce_none None modl in
Llet (Strict, Pgenval, id, defining_expr, transl_exp body)
| Texp_letexception (cd, body) ->
Llet
( Strict,
Pgenval,
cd.ext_id,
transl_extension_constructor e.exp_env None cd,
transl_exp body )
| Texp_pack modl -> !transl_module Tcoerce_none None modl
| Texp_assert {exp_desc = Texp_construct (_, {cstr_name = "false"}, _)} ->
if !Clflags.no_assert_false then Lambda.lambda_assert_false
else assert_failed e
| Texp_assert cond ->
if !Clflags.noassert then lambda_unit
else Lifthenelse (transl_exp cond, lambda_unit, assert_failed e)
| Texp_lazy e ->
(* when e needs no computation (constants, identifiers, ...), we
optimize the translation just as Lazy.lazy_from_val would
do *)
Lprim (Pmakeblock Blk_lazy_general, [transl_exp e], e.exp_loc)
and transl_list expr_list = List.map transl_exp expr_list
and transl_guard guard rhs =
let expr = transl_exp rhs in
match guard with
| None -> expr
| Some cond -> Lifthenelse (transl_exp cond, expr, staticfail)
and transl_case {c_lhs; c_guard; c_rhs} = (c_lhs, transl_guard c_guard c_rhs)
and transl_cases cases = List.map transl_case cases
and transl_case_try {c_lhs; c_guard; c_rhs} =
match c_lhs.pat_desc with
| Tpat_var (id, _) | Tpat_alias (_, id, _) ->
Hashtbl.replace try_ids id ();
Misc.try_finally
(fun () -> (c_lhs, transl_guard c_guard c_rhs))
(fun () -> Hashtbl.remove try_ids id)
| _ -> (c_lhs, transl_guard c_guard c_rhs)
and transl_cases_try cases = List.map transl_case_try cases
and transl_apply ?(inlined = Default_inline)
?(uncurried_partial_application = None) lam sargs loc =
let lapply ap_func ap_args =
Lapply {ap_loc = loc; ap_func; ap_args; ap_inlined = inlined}
in
let rec build_apply lam args = function
| (None, optional) :: l ->
let defs = ref [] in
let protect name lam =
match lam with
| Lvar _ | Lconst _ -> lam
| _ ->
let id = Ident.create name in
defs := (id, lam) :: !defs;
Lvar id
in
let args, args' =
if List.for_all (fun (_, opt) -> opt) args then ([], args)
else (args, [])
in
let lam = if args = [] then lam else lapply lam (List.rev_map fst args) in
let handle = protect "func" lam
and l = List.map (fun (arg, opt) -> (may_map (protect "arg") arg, opt)) l
and id_arg = Ident.create "param" in
let body =
match build_apply handle ((Lvar id_arg, optional) :: args') l with
| Lfunction {params = ids; body = lam; attr; loc} ->
Lfunction {params = id_arg :: ids; body = lam; attr; loc}
| lam ->
Lfunction
{
params = [id_arg];
body = lam;
attr = default_function_attribute;
loc;
}
in
List.fold_left
(fun body (id, lam) -> Llet (Strict, Pgenval, id, lam, body))
body !defs