Repository navigation
Expand file tree
/
Copy pathlam_compile.ml
More file actions
2146 lines (2087 loc) · 84.7 KB
/
Copy pathlam_compile.ml
File metadata and controls
2146 lines (2087 loc) · 84.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(* Copyright (C) 2015 - 2016 Bloomberg Finance L.P.
* Copyright (C) 2017 - Hongbo Zhang, Authors of ReScript
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* In addition to the permissions granted to you by the LGPL, you may combine
* or link a "work that uses the Library" with a publicly distributed version
* of this file to produce a combined library or application, then distribute
* that combined work under the terms of your choosing, with no requirement
* to comply with the obligations normally placed on you by section 4 of the
* LGPL version 3 (or the corresponding section of a later version of the LGPL
* should you choose to use a later version).
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *)
module E = Js_exp_make
module S = Js_stmt_make
let source_map_loc = Js_source_map.source_loc_of_loc
let with_source_loc loc (exp : J.expression) =
match (source_map_loc loc, exp.source_loc) with
| Some source_loc, None -> {exp with source_loc = Some source_loc}
| _ -> exp
let rec source_loc_of_lam (lam : Lambda.t) =
match lam with
| Lapply {ap_loc} -> Some ap_loc
| Lprim {loc} | Lfunction {loc} -> Some loc
| Llet (_, _, arg, body) -> (
match source_loc_of_lam arg with
| Some _ as loc -> loc
| None -> source_loc_of_lam body)
| Lletrec (_, body) | Lsequence (_, body) -> source_loc_of_lam body
| Lifthenelse (_, then_, _) -> source_loc_of_lam then_
| Lstaticcatch (body, _, _) | Ltrywith (body, _, _) | Ltryfinally (body, _) ->
source_loc_of_lam body
| Lstringswitch (_, cases, default) -> (
match cases with
| (_, body) :: _ -> source_loc_of_lam body
| [] -> (
match default with
| Some body -> source_loc_of_lam body
| None -> None))
| Lswitch (_, sw) -> (
match (sw.sw_consts, sw.sw_blocks, sw.sw_failaction) with
| (_, body) :: _, _, _ | _, (_, body) :: _, _ -> source_loc_of_lam body
| [], [], Some body -> source_loc_of_lam body
| [], [], None -> None)
| Lstaticraise (_, args) -> (
match args with
| arg :: _ -> source_loc_of_lam arg
| [] -> None)
| Lwhile (_, body)
| Lfor (_, _, _, _, body)
| Lfor_of (_, _, body)
| Lfor_await_of (_, _, body) ->
source_loc_of_lam body
| Lassign (_, body) -> source_loc_of_lam body
| Lvar _ | Lglobal_module _ | Lconst _ | Lbreak | Lcontinue -> None
let source_map_loc_of_lam lam =
match source_loc_of_lam lam with
| Some loc -> source_map_loc loc
| None -> None
let with_statement_source_loc source_loc (stmt : J.statement) =
match (source_loc, stmt.source_loc) with
| Some source_loc, None -> {stmt with source_loc = Some source_loc}
| _ -> stmt
let with_block_source_loc lam block =
match block with
| [] -> []
| stmt :: rest ->
with_statement_source_loc (source_map_loc_of_lam lam) stmt :: rest
let args_either_function_or_const (args : Lambda.t list) =
Ext_list.for_all args (fun x ->
match x with
| Lfunction _ | Lconst _ -> true
| _ -> false)
(* Whether the callee's arity is known and this call saturates it. The printer
uses it to decide whether a wrapper around the call may be eta reduced,
which is only sound for a ReScript value of exactly that arity - never for
an FFI name, whose wrapper carries argument adaptation. Looked up here
rather than stamped on the application by an earlier pass. *)
let call_info_of_apply (meta : Lam_stats.t) (appinfo : Lambda.lambda_apply) :
Js_call_info.t =
let saturated =
match
Lam_arity.extract_arity
(Lam_arity_analysis.get_arity meta appinfo.ap_func)
with
| x :: _ -> x = List.length appinfo.ap_args
| [] -> false
in
if saturated then Js_call_info.ml_full_call else Js_call_info.na_full_call
let change_tail_type_in_try (x : Lam_compile_context.tail_type) :
Lam_compile_context.tail_type =
match x with
| Maybe_tail_is_return (Tail_with_name _) -> Maybe_tail_is_return Tail_in_try
| Not_tail | Maybe_tail_is_return Tail_in_try -> x
let in_staticcatch (x : Lam_compile_context.tail_type) :
Lam_compile_context.tail_type =
match x with
| Maybe_tail_is_return (Tail_with_name ({in_staticcatch = false} as x)) ->
Maybe_tail_is_return (Tail_with_name {x with in_staticcatch = true})
| _ -> x
(* let change_tail_type_in_static
(x : Lam_compile_context.tail_type)
: Lam_compile_context.tail_type =
match x with
| Maybe_tail_is_return (Tail_with_name ({in_staticcatch=false} as z) ) ->
Maybe_tail_is_return (Tail_with_name {z with in_staticcatch=true})
| Maybe_tail_is_return (Tail_with_name {in_staticcatch=true} )
| Not_tail | Maybe_tail_is_return Tail_in_try
-> x *)
(* assume outer is [Lstaticcatch] *)
let rec flat_catches (acc : Lam_compile_context.handler list) (x : Lambda.t) :
Lam_compile_context.handler list * Lambda.t =
match x with
| Lstaticcatch (l, (label, bindings), handler)
when acc = []
|| not
(Lam_exit_code.has_exit_code handler (fun exit ->
Ext_list.exists acc (fun x -> x.label = exit))) ->
(* #1698 should not crush exit code here without checking *)
flat_catches ({label; handler; bindings} :: acc) l
| _ -> (acc, x)
let flatten_nested_caches (x : Lambda.t) :
Lam_compile_context.handler list * Lambda.t =
flat_catches [] x
let morph_declare_to_assign (cxt : Lam_compile_context.t) k =
match cxt.continuation with
| Declare (kind, did) ->
k {cxt with continuation = Assign did} (Some (kind, did))
| _ -> k cxt None
let group_apply cases callback =
Ext_list.flat_map
(Ext_list.stable_group cases (fun (_, lam) (_, lam1) ->
Lambda.eq_approx lam lam1))
(fun group -> Ext_list.map_last group callback)
(* TODO:
for expression generation,
name, should_return is not needed,
only jmp_table and env needed
*)
type default_case = Default of Lambda.t | Complete | NonComplete
let default_action ~saturated failaction =
match failaction with
| None -> Complete
| Some x -> if saturated then Complete else Default x
let tag_of_switch_key : _ -> Variant_runtime.tag_type option = function
| Lambda.Switch_int _ -> None
| Switch_constructor (Constant {literal} | Block (Tagged {tag = {literal}}))
->
Some (Literal literal)
| Switch_constructor (Block (Untagged {block_type})) ->
Some (Payload_shape block_type)
let dispatch_info = function
| Lambda.Switch_direct -> (Js_dump_lit.tag, [])
| Switch_variant {Variant_runtime.tag_name; literal_tags} ->
(Option.value tag_name ~default:Js_dump_lit.tag, literal_tags)
let no_effects_const = lazy true
(* let has_effects_const = lazy false *)
(* We drop the ability of cross-compiling
the compiler has to be the same running
*)
type initialization = J.block
(* since it's only for alias, there is no arguments,
we should not inline function definition here, even though
it is very small
TODO: add comment here, we should try to add comment for
cross module inlining
if we do too agressive inlining here:
if we inline {!List.length} which will call {!A_list.length},
then we if we try inline {!A_list.length}, this means if {!A_list}
is rebuilt, this module should also be rebuilt,
But if the build system is content-based, suppose {!A_list}
is changed, cmj files in {!List} is unchnaged, however,
{!List.length} call {!A_list.length} which is changed, since
[ocamldep] only detect that we depend on {!List}, it will not
get re-built, then we are screwed.
This is okay for stamp based build system.
Another solution is that we add dependencies in the compiler
-: we should not do functor application inlining in a
non-toplevel, it will explode code very quickly
*)
(* Semantic SCC already ran in [Lambda_scc.bind_rec]. JS still wants
functions before values so dummy / updateDummy init is well-ordered. *)
let functions_before_values (group : (Ident.t * Lambda.t) list) =
if
Ext_list.for_all group (fun (_, x) ->
match x with
| Lfunction _ -> true
| _ -> false)
then group
else
List.sort
(fun (_, lama) (_, lamb) ->
match ((lama : Lambda.t), (lamb : Lambda.t)) with
| Lfunction _, Lfunction _ -> 0
| Lfunction _, _ -> -1
| _, Lfunction _ -> 1
| _, _ -> 0)
group
(* Whether evaluating [e] later, after other code, gives the same value and
the same effects as evaluating it now: constants, functions, immutable
local variables and pure operations on them. [assignable] are the local
variables some [Lassign] assigns; the other code, or a closure it calls,
may assign them. JS globals ([@val]) and reads of the heap (fields, array
elements, lengths) may change as well. *)
let rec delay_safe ~assignable (e : J.expression) =
match e.expression_desc with
| Undefined _ | Null | Bool _ | Number _ | Str _ | Template_literal _
| Json_literal _ | Fun _
| Var (Qualified _) ->
true
| Var (Id id) ->
(not (Ext_ident.is_js id)) && not (Set_ident.mem id assignable)
| Bin (Eq, _, _) -> false
| Bin (_, a, b) ->
Js_analyzer.no_side_effect_expression e
&& delay_safe ~assignable a && delay_safe ~assignable b
| String_append (a, b) -> delay_safe ~assignable a && delay_safe ~assignable b
| Js_not a
| Js_bnot a
| Typeof a
| Is_null_or_undefined a
| Optional_block (a, _) ->
delay_safe ~assignable a
| Cond (a, b, c) ->
delay_safe ~assignable a && delay_safe ~assignable b
&& delay_safe ~assignable c
| Interpolated_template {values} ->
Ext_list.for_all values (delay_safe ~assignable)
| Array xs | Caml_block (xs, _, _) ->
Ext_list.for_all xs (delay_safe ~assignable)
| Object entries ->
Ext_list.for_all entries (function
| J.Object_property (_, v) -> delay_safe ~assignable v
| Record_spread _ | Object_spread _ -> false)
| _ -> false
(* Statements that evaluate [e] now, and the expression that stands for its
value afterwards. A sequence's leading expressions become statements of
their own, and the last one gets a temporary unless it is [delay_safe].
Building an array, block or object literal is pure, so a literal stays in
place and its elements are evaluated now instead. That also keeps the
literal visible to translations that look into their arguments, such as
the rows of a dict literal or a [@variadic] array. So does an
[Optional_block], which keeps an optional argument known to be present. *)
let rec evaluate_now ~assignable (e : J.expression) : J.block * J.expression =
match e.expression_desc with
| _ when delay_safe ~assignable e -> ([], e)
| Seq (a, b) ->
let rest, b = evaluate_now ~assignable b in
if Js_analyzer.no_side_effect_expression a then (rest, b)
else
({J.statement_desc = Exp a; comment = None; source_loc = None} :: rest, b)
| Optional_block (a, identity) ->
let held, a = evaluate_now ~assignable a in
(held, {e with expression_desc = Optional_block (a, identity)})
| Array xs ->
let held, xs = evaluate_all_now ~assignable xs in
(held, {e with expression_desc = Array xs})
| Caml_block (xs, mutable_flag, tag) ->
let held, xs = evaluate_all_now ~assignable xs in
(held, {e with expression_desc = Caml_block (xs, mutable_flag, tag)})
| Object entries
when Ext_list.for_all entries (function
| J.Object_property _ -> true
| Record_spread _ | Object_spread _ -> false) ->
let held, values =
evaluate_all_now ~assignable
(Ext_list.filter_map entries (function
| J.Object_property (_, v) -> Some v
| Record_spread _ | Object_spread _ -> None))
in
let entries =
List.map2
(fun entry v ->
match entry with
| J.Object_property (k, _) -> J.Object_property (k, v)
| Record_spread _ | Object_spread _ -> assert false)
entries values
in
(held, {e with expression_desc = Object entries})
| _ ->
let tmp = Ext_ident.create_tmp () in
([S.define_variable ~kind:Strict tmp e], E.var tmp)
(* [evaluate_now] on each of [xs], left to right. The elements left in place
are [delay_safe], so no other element's statements can change them. *)
and evaluate_all_now ~assignable (xs : J.expression list) :
J.block * J.expression list =
let blocks, xs = Ext_list.split_map xs (evaluate_now ~assignable) in
(List.concat blocks, xs)
(* Whether evaluating [e] runs no code: it has no side effects and reads no JS
property, which may run a getter. A record field counts. *)
let runs_no_code (e : J.expression) =
Js_analyzer.is_okay_to_duplicate ~property_reads:false e
(* Whether [block] only defines variables as values that run no code, as a
temporary bound to a record field does *)
let defines_pure_values (block : J.block) =
Ext_list.for_all block (fun (s : J.statement) ->
match s.statement_desc with
| Variable {value = None} -> true
| Variable {value = Some e} -> runs_no_code e
| _ -> false)
(* Assembles compiled arguments for a call or a literal that evaluates them
left to right. Each argument comes with the statements that have to run
before its value is read. Putting all statements first and then the
values would move the statements of an argument in front of the values of
the arguments to its left, so when an argument has statements, every
argument to its left is evaluated before them with [evaluate_now]. An
argument that runs no code stays in place when the statements after it
only define values that run none either, since then neither can change
the other.
With [~method_callee:true], the first argument is a JS method read
[obj.m] being called: the object is held and the property read stays in
the call, so the call still passes the object as [this]. *)
let sequence_arguments ?(method_callee = false) ~assignable
(args : (J.block * J.expression) list) : J.block * J.expression list =
let later_statements =
match args with
| [] -> false
| _ :: rest -> Ext_list.exists_fst rest (fun block -> block <> [])
in
if not later_statements then (List.concat_map fst args, Ext_list.map args snd)
else
let last = List.length args - 1 in
let _, code, values =
Ext_list.fold_right args (last, [], [])
(fun (block, value) (i, code, values) ->
let held, value =
if code = [] || (runs_no_code value && defines_pure_values code)
then ([], value)
else
match value.expression_desc with
| Static_index (obj, name, pos) when method_callee && i = 0 ->
let held, obj = evaluate_now ~assignable obj in
( held,
{value with expression_desc = Static_index (obj, name, pos)}
)
| _ -> evaluate_now ~assignable value
in
( i - 1,
Ext_list.append block (Ext_list.append held code),
value :: values ))
in
(code, values)
let compile output_prefix =
(* When compiling a read from another module, a nested source path like
Other.A.B.make reaches this point as nested module-field reads:
Pfield "make" (Pfield "B" (Pfield "A" (Lglobal_module Other)))
Every nested [make] is also exported under a flat name (see
[Translmod.implementation]), so it is read as Other.A$B$make rather
than through the module objects. The same holds below a local bound to
the awaited module, [let d = await import(Other)]. Other reads query
only the first field, "A", and emit the remaining fields as JS property
access. *)
let rec extract_field_path awaited_units segments primitive args =
match (primitive, args) with
| Lambda.Pfield (_, Fld_module {name}), [Lambda.Lprim {primitive; args; _}]
->
extract_field_path awaited_units (name :: segments) primitive args
| Lambda.Pfield (_, Fld_module {name}), [Lambda.Lglobal_module id] ->
Some (E.ml_var_dot id, name :: segments)
| Lambda.Pfield (_, Fld_module {name}), [Lambda.Lvar id]
when Set_ident.mem id awaited_units ->
Some (E.dot (E.var id), name :: segments)
| _ -> None
in
let flat_make_field (lambda_cxt : Lam_compile_context.t) primitive args =
match
extract_field_path lambda_cxt.meta.awaited_units [] primitive args
with
| Some (read, segments) ->
Translmod.flat_make_name segments |> Option.map read
| None -> None
in
let rec compile_external_field (* Like [List.empty]*)
(lamba_cxt : Lam_compile_context.t) (id : Ident.t) name : Js_output.t =
match Lam_compile_env.query_external_id_info id name with
| {persistent_closed_lambda = Some lam} when Lam_util.not_function lam ->
compile_lambda lamba_cxt lam
| _ ->
Js_output.output_of_expression lamba_cxt.continuation
~no_effects:no_effects_const (E.ml_var_dot id name)
(* TODO: how nested module call would behave,
In the future, we should keep in track of if
it is fully applied from [Lapply]
Seems that the module dependency is tricky..
should we depend on [Pervasives] or not?
we can not do this correctly for the return value,
however we can inline the definition in Pervasives
TODO:
[Pervasives.print_endline]
[Pervasives.prerr_endline]
@param id external module id
@param number the index of the external function
@param env typing environment
@param args arguments
*)
(* This can not happen since this id should be already consulted by type checker
Worst case
{[
E.array_index_by_int m pos
]}
*)
(* when module is passed as an argument - unpack to an array
for the function, generative module or functor can be a function,
however it can not be global -- global can only module
*)
and compile_external_field_apply (appinfo : Lambda.lambda_apply)
(module_id : Ident.t) (field_name : string)
(lambda_cxt : Lam_compile_context.t) : Js_output.t =
let ident_info =
Lam_compile_env.query_external_id_info module_id field_name
in
let ap_args = appinfo.ap_args in
match ident_info.persistent_closed_lambda with
| Some (Lfunction ({params; body; _} as lfunction))
when Ext_list.same_length params ap_args
&& Lambda.lfunction_can_be_inlined lfunction ->
(* TODO: serialize it when exporting to save compile time *)
let _, param_map =
Lam_closure.is_closed_with_map Set_ident.empty params body
in
let inlined =
Lam_beta_reduce.propagate_beta_reduce_with_map lambda_cxt.meta param_map
params body ap_args
in
(* The inlined body comes from another module, so the variables it
assigns are not in [meta.assignable] yet. *)
let meta =
{
lambda_cxt.meta with
assignable =
Set_ident.union lambda_cxt.meta.assignable
(Lambda_traverse.assigned_variables inlined);
}
in
compile_lambda {lambda_cxt with meta} inlined
| _ ->
let args_code, args = compile_arguments lambda_cxt ap_args in
let fn = E.ml_var_dot module_id ident_info.name in
let expression =
E.call ~info:(call_info_of_apply lambda_cxt.meta appinfo) fn args
in
let expression = with_source_loc appinfo.ap_loc expression in
Js_output.output_of_block_and_expression lambda_cxt.continuation args_code
expression
(*
The second return value holds declarations, such as [dummy_obj]
placeholders, that are emitted before the bindings
Invariant: jmp_table can not across function boundary,
here we share env
*)
and compile_recursive_let ~all_bindings (cxt : Lam_compile_context.t)
(id : Ident.t) (arg : Lambda.t) : Js_output.t * initialization =
match arg with
| Lfunction
{
params;
body;
attr = {return_unit; async; one_unit_arg; directive};
loc;
} ->
(* TODO: Think about recursive value
{[
let rec v = ref (fun _ ...
)
]}
[Alias] may not be exact
*)
let params = if one_unit_arg then [] else params in
let ret : Lam_compile_context.return_label =
{
id;
params;
immutable_mask = Array.make (List.length params) true;
new_params = Map_ident.empty;
triggered = false;
}
in
let output =
compile_lambda
{
cxt with
continuation =
EffectCall
(Maybe_tail_is_return
(Tail_with_name {label = Some ret; in_staticcatch = false}));
jmp_table = Lam_compile_context.empty_handler_map;
switch_depth = 0;
loop_stack = [];
}
body
in
let result =
if ret.triggered then
let body_block = Js_output.output_as_block output in
E.ocaml_fun
(* TODO: save computation of length several times
Here we always create [ocaml_fun],
it will be renamed into [method]
when it is detected by a primitive
*)
~return_unit ~async ~one_unit_arg ?directive
~immutable_mask:ret.immutable_mask
(Ext_list.map params (fun x ->
match Map_ident.find_opt x ret.new_params with
| Some y -> y
| None -> x))
[
S.while_ E.true_
(Map_ident.fold
(fun old new_param acc ->
S.define_variable ~kind:Alias old (E.var new_param) :: acc)
ret.new_params body_block);
]
else
(* TODO: save computation of length several times *)
E.ocaml_fun params
(Js_output.output_as_block output)
~return_unit ~async ~one_unit_arg ?directive
in
let result = with_source_loc loc result in
( Js_output.output_of_expression
(Declare (Alias, id))
result
~no_effects:(lazy (Lam_analysis.no_side_effects arg)),
[] )
| Lprim {primitive = Pmakeblock _; args}
when args_either_function_or_const args ->
(compile_lambda {cxt with continuation = Declare (Alias, id)} arg, [])
(* case of lazy blocks, treat it as usual *)
| Lprim
{
primitive =
Pmakeblock
(( Blk_record _
| Blk_constructor {num_nonconst = 1}
| Blk_record_inlined {num_nonconst = 1} ) as tag_info);
args = ls;
}
when Ext_list.for_all ls (fun x ->
match x with
| Lvar pid ->
Ident.same pid id
|| not
@@ Ext_list.exists all_bindings (fun (other, _) ->
Ident.same other pid)
| Lconst _ -> true
| _ -> false) ->
(* capture cases like for {!Queue}
{[let rec cell = { content = x; next = cell} ]}
#1716: be careful not to optimize such cases:
{[ let rec a = { b} and b = { a} ]} they are indeed captured
and need to be declared first
TODO: this should be inlined based on tag info
*)
( Js_output.make
(S.define_variable ~kind:Variable id (E.dummy_obj tag_info)
:: Ext_list.mapi ls (fun i x ->
S.exp
(Js_of_lam_block.set_field
(match tag_info with
| Blk_record {fields = xs} -> Fld_record_set (fst xs.(i))
| Blk_record_inlined xs ->
Fld_record_inline_set (fst xs.fields.(i))
| Blk_constructor p -> (
let is_cons = p.name = Literals.cons in
match (is_cons, i) with
| true, 0 -> Fld_record_inline_set Literals.hd
| true, 1 -> Fld_record_inline_set Literals.tl
| _, _ -> Fld_record_inline_set ("_" ^ string_of_int i))
| _ -> assert false)
(E.var id) (Int32.of_int i)
(match x with
| Lvar lid -> E.var lid
| Lconst x -> Lam_compile_const.translate x
| _ -> assert false)))),
[] )
| Lprim {primitive = Pmakeblock tag_info} -> (
(* Lconst should not appear here if we do [scc]
optimization, since it's faked recursive value,
however it would affect scope issues, we have to declare it first
*)
match compile_lambda {cxt with continuation = NeedValue Not_tail} arg with
| {block = b; value = Some v} ->
(* TODO: check recursive value ..
could be improved for simple cases
*)
( Js_output.make
(Ext_list.append b
[
S.exp
(E.runtime_call Primitive_modules.object_ "updateDummy"
[E.var id; v]);
]),
[S.define_variable ~kind:Variable id (E.dummy_obj tag_info)] )
| _ -> assert false)
| _ ->
(* pathological case:
fail to capture taill call?
{[ let rec a =
if g > 30 then .. fun () -> a ()
]}
Neither below is not allowed in ocaml:
{[
let rec v =
if sum 0 10 > 20 then
1::v
else 2:: v
]}
{[
let rec v =
if sum 0 10 > 20 then
fun _ -> print_endline "hi"; v ()
else
fun _-> print_endline "hey"; v ()
]}
*)
(compile_lambda {cxt with continuation = Declare (Alias, id)} arg, [])
and compile_recursive_lets_aux cxt (id_args : (Ident.t * Lambda.t) list) :
Js_output.t =
(* #1716 *)
let output_code, ids =
Ext_list.fold_right id_args (Js_output.dummy, [])
(fun (ident, arg) (acc, ids) ->
let code, declare_ids =
compile_recursive_let ~all_bindings:id_args cxt ident arg
in
(Js_output.append_output code acc, Ext_list.append declare_ids ids))
in
match ids with
| [] -> output_code
| _ -> Js_output.append_output (Js_output.make ids) output_code
and compile_recursive_lets cxt id_args : Js_output.t =
match id_args with
| [] -> Js_output.dummy
| _ -> compile_recursive_lets_aux cxt (functions_before_values id_args)
and compile_general_cases :
'a.
make_exp:('a -> J.expression) ->
eq_exp:
('a option -> J.expression -> 'a option -> J.expression -> J.expression) ->
cxt:Lam_compile_context.t ->
switch:
(?default:J.block ->
?declaration:Lambda.let_kind * Ident.t ->
_ ->
('a * J.case_clause) list ->
J.statement) ->
switch_exp:J.expression ->
default:default_case ->
('a * Lambda.t) list ->
J.block =
fun (type a) ~(make_exp : a -> J.expression)
~(eq_exp :
a option -> J.expression -> a option -> J.expression -> J.expression)
~(cxt : Lam_compile_context.t)
~(switch :
?default:J.block ->
?declaration:Lambda.let_kind * Ident.t ->
_ ->
(a * J.case_clause) list ->
J.statement) ~(switch_exp : J.expression) ~(default : default_case)
(cases : (a * Lambda.t) list) ->
let output_block_with_source_loc cxt lam =
compile_lambda cxt lam |> Js_output.output_as_block
|> with_block_source_loc lam
in
let output_default cxt = function
| Default lam -> output_block_with_source_loc cxt lam
| Complete | NonComplete -> []
in
match (cases, default) with
| [], Default _ -> output_default cxt default
| [], (Complete | NonComplete) -> []
| [(_, lam)], Complete ->
(* To take advantage of such optimizations,
when we generate code using switch,
we should always have a default,
otherwise the compiler engine would think that
it's also complete
*)
output_block_with_source_loc cxt lam
| [(id, lam)], NonComplete ->
morph_declare_to_assign cxt (fun cxt define ->
[
S.if_ ?declaration:define
(eq_exp None switch_exp (Some id) (make_exp id))
(output_block_with_source_loc cxt lam);
])
| [(id, lam)], Default _ ->
morph_declare_to_assign cxt (fun cxt define ->
let else_block = output_default cxt default in
let then_block = output_block_with_source_loc cxt lam in
[
S.if_ ?declaration:define
(eq_exp None switch_exp (Some id) (make_exp id))
then_block ~else_:else_block;
])
| [(id, lam); (_, x)], Complete ->
morph_declare_to_assign cxt (fun cxt define ->
let else_block = output_block_with_source_loc cxt x in
let then_block = output_block_with_source_loc cxt lam in
[
S.if_ ?declaration:define
(eq_exp None switch_exp (Some id) (make_exp id))
then_block ~else_:else_block;
])
| _, _ ->
(* TODO: this is not relevant to switch case
however, in a subset of switch-case if we can analysis
its branch are the same, we can propogate which
might encourage better inlining strategey
---
TODO: grouping can be delayed untile JS IR
see #2413
In general, we know it is last call,
there is no need to print [break];
But we need make sure the last call lambda does not
have `(exit ..)` due to we pass should_return from Lstaticcath downwards
Since this is a rough approximation, some `(exit ..)` does not destroy
last call property, we use exiting should_break to improve preciseness
(and it indeed help catch
- tailcall or not does not matter, if it is the tailcall
break still should not be printed (it will be continuned)
TOOD: disabled temporarily since it's not perfect yet *)
morph_declare_to_assign cxt (fun cxt declaration ->
(* Exclude cases that are the same as the default if the default is defined *)
let cases =
match default with
| Default lam ->
List.filter
(fun (_, lam1) -> not (Lambda.eq_approx lam lam1))
cases
| _ -> cases
in
let switch_cxt = Lam_compile_context.enter_switch cxt in
let default =
match output_default switch_cxt default with
| [] -> None
| statements -> Some statements
in
let body =
group_apply cases (fun last (switch_case, lam) ->
if last then
(* merge and shared *)
let switch_body, should_break =
Js_output.to_break_block (compile_lambda switch_cxt lam)
in
let switch_body = with_block_source_loc lam switch_body in
let should_break =
if
not
@@ Lam_compile_context.continuation_is_return
cxt.continuation
then should_break
else should_break && Lam_exit_code.has_exit lam
in
( switch_case,
J.
{
switch_body;
should_break;
comment = None;
source_loc = source_map_loc_of_lam lam;
} )
else
( switch_case,
{
switch_body = [];
should_break = false;
comment = None;
source_loc = source_map_loc_of_lam lam;
} ))
(* TODO: we should also group default *)
(* The last clause does not need [break]
common break through, *)
in
[switch ?default ?declaration switch_exp body])
and use_compile_literal_cases table =
List.fold_right
(fun (key, lam) acc ->
match (tag_of_switch_key key, acc) with
| Some tag_type, Some string_table ->
Some ((tag_type, lam) :: string_table)
| _, _ -> None)
table (Some [])
and compile_cases ~cxt ~(switch_exp : E.t) ?(default = NonComplete) cases :
initialization =
match use_compile_literal_cases cases with
| Some string_cases ->
compile_string_cases ~cxt ~switch_exp ~default string_cases
| None ->
cases
|> compile_general_cases
~make_exp:(function
| Lambda.Switch_int i -> E.small_int i
| Switch_constructor _ -> assert false)
~eq_exp:(fun _ x _ y -> E.int_equal x y)
~cxt
~switch:(fun ?default ?declaration e clauses ->
S.int_switch ?default ?declaration e
(List.map
(fun (key, clause) ->
match key with
| Lambda.Switch_int i -> (i, clause)
| Switch_constructor _ -> assert false)
clauses))
~switch_exp ~default
and compile_switch (switch_arg : Lambda.t) (sw : Lambda.lambda_switch)
(lambda_cxt : Lam_compile_context.t) =
(* TODO: if default is None, we can do some optimizations
Use switch vs if/then/else
TODO: switch based optimiztion - hash, group, or using array,
also if last statement is throw -- should we drop remaining
statement?
*)
let ({
sw_consts_full;
sw_consts;
sw_blocks_full;
sw_blocks;
sw_failaction;
sw_dispatch;
}
: Lambda.lambda_switch) =
sw
in
let sw_num_default =
default_action ~saturated:sw_consts_full sw_failaction
in
let sw_blocks_default =
default_action ~saturated:sw_blocks_full sw_failaction
in
let tag_name, literal_cases = dispatch_info sw_dispatch in
let payload_only = sw_consts_full && sw_consts = [] in
let compile_whole (cxt : Lam_compile_context.t) =
match
compile_lambda {cxt with continuation = NeedValue Not_tail} switch_arg
with
| {value = None; _} -> assert false
| {block; value = Some e} -> (
(* [e] is used more than once *)
let with_variable dispatch =
match e.expression_desc with
| J.Var _ -> dispatch e
| _ ->
let v = Ext_ident.create_tmp () in
S.define_variable ~kind:Variable v e :: dispatch (E.var v)
in
block
@
match Lambda.untagged_plan sw with
| Some plan ->
let compile e =
compile_untagged_plan ~cxt ~switch_exp:e ~fallback:sw_failaction
plan
in
if payload_only then compile e else with_variable compile
| None ->
if payload_only then
compile_cases ~cxt ~switch_exp:(E.tag ~name:tag_name e)
~default:sw_blocks_default sw_blocks
else if sw_blocks_full && sw_blocks = [] then
compile_cases ~cxt ~switch_exp:e ~default:sw_num_default sw_consts
else
with_variable (fun e ->
[
S.if_
(E.is_int_tag ~literal_tags:literal_cases e)
(compile_cases ~cxt ~switch_exp:e ~default:sw_num_default
sw_consts)
~else_:
(compile_cases ~cxt ~switch_exp:(E.tag ~name:tag_name e)
~default:sw_blocks_default sw_blocks);
]))
in
match lambda_cxt.continuation with
(* Needs declare first *)
| NeedValue _ ->
(* Necessary since switch is a statement, we need they return
the same value for different branches -- can be optmized
when branches are minimial (less than 2)
*)
let v = Ext_ident.create_tmp () in
Js_output.make
(S.declare_variable ~kind:Variable v
:: compile_whole {lambda_cxt with continuation = Assign v})
~value:(E.var v)
| Declare (kind, id) ->
Js_output.make
(S.declare_variable ~kind id
:: compile_whole {lambda_cxt with continuation = Assign id})
| EffectCall _ | Assign _ -> Js_output.make (compile_whole lambda_cxt)
and compile_string_cases ~cxt ~switch_exp ~default cases : initialization =
cases
|> compile_general_cases ~make_exp:E.tag_type
~eq_exp:(fun _ x _ y -> E.string_equal x y)
~cxt
~switch:(fun ?default ?declaration e clauses ->
S.string_switch ?default ?declaration e clauses)
~switch_exp ~default
and compile_untagged_plan ~(cxt : Lam_compile_context.t) ~switch_exp ~fallback
(plan : Lambda.t Untagged_dispatch.tree) : J.block =
(* Prints the plan: each node is one statement. A body in a [switch]
statement is compiled in a [switch] context, a body of an [if] is
not *)
let e = switch_exp in
let rec test_exp : Untagged_dispatch.test -> J.expression = function
| Equals literal -> E.string_equal e (E.tag_type (Literal literal))
| Typeof block_type -> (
match Variant_runtime.typeof_name block_type with
| Some name -> E.string_equal (E.typeof e) (E.str name)
| None -> assert false)
| Instance instance -> E.is_instance_of instance e
| Not_null -> E.not (E.is_null e)
| Not test -> E.not (test_exp test)
| And (test1, test2) -> E.and_ (test_exp test1) (test_exp test2)
| Or (test1, test2) -> E.or_ (test_exp test1) (test_exp test2)
in
let output_block cxt lam =
compile_lambda cxt lam |> Js_output.output_as_block
|> with_block_source_loc lam
in
(* The default action is compiled once and shared by every path to it *)
let fallback_blocks = ref [] in
let fallback_block (cxt : Lam_compile_context.t) =
let in_switch = cxt.switch_depth > 0 in
match List.assoc_opt in_switch !fallback_blocks with
| Some block -> block
| None ->
let block =
match fallback with
| Some lam -> output_block cxt lam
| None -> assert false
in
fallback_blocks := (in_switch, block) :: !fallback_blocks;
block
in
let rec emit ~cxt (tree : Lambda.t Untagged_dispatch.tree) : J.block =
match tree with
| Run lam -> output_block cxt lam