-
Notifications
You must be signed in to change notification settings - Fork 464
/
Copy pathlam_compile.ml
1756 lines (1678 loc) · 69.5 KB
/
lam_compile.ml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(* 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 args_either_function_or_const (args : Lam.t list) =
Ext_list.for_all args (fun x ->
match x with Lfunction _ | Lconst _ -> true | _ -> false)
let call_info_of_ap_status (ap_status : Lam.apply_status) : Js_call_info.t =
(* XXX *)
match ap_status with
| App_infer_full -> { arity = Full; call_info = Call_ml }
| App_uncurry -> { arity = Full; call_info = Call_na }
| App_na -> { arity = NA; call_info = Call_ml }
let rec apply_with_arity_aux (fn : J.expression) (arity : int list)
(args : E.t list) (len : int) : E.t =
if len = 0 then fn (* All arguments consumed so far *)
else
match arity with
| x :: rest ->
let x = if x = 0 then 1 else x in
(* Relax when x = 0 *)
if len >= x then
let first_part, continue = Ext_list.split_at args x in
apply_with_arity_aux
(E.call ~info:{ arity = Full; call_info = Call_ml } fn first_part)
rest continue (len - x)
else if
(* GPR #1423 *)
Ext_list.for_all args Js_analyzer.is_okay_to_duplicate
then
let params =
Ext_list.init (x - len) (fun _ -> Ext_ident.create "param")
in
E.ocaml_fun params ~return_unit:false (* unknown info *) ~async:false ~one_unit_arg:false
[
S.return_stmt
(E.call
~info:{ arity = Full; call_info = Call_ml }
fn
(Ext_list.append args @@ Ext_list.map params E.var));
]
else E.call ~info:Js_call_info.dummy fn args
(* alpha conversion now? --
Since we did an alpha conversion before so it is not here
*)
| [] ->
(* can not happen, unless it's an exception ? *)
E.call ~info:Js_call_info.dummy fn args
let apply_with_arity ~arity fn args =
apply_with_arity_aux fn arity args (List.length args)
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 : Lam.t) :
Lam_compile_context.handler list * Lam.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 : Lam.t) : Lam_compile_context.handler list * Lam.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 ~merge_cases cases callback =
Ext_list.flat_map
(Ext_list.stable_group cases (fun (tag1, lam) (tag2, lam1) ->
merge_cases tag1 tag2 && Lam.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 Lam.t | Complete | NonComplete
let default_action ~saturated failaction =
match failaction with
| None -> Complete
| Some x -> if saturated then Complete else Default x
let get_const_tag i (sw_names : Ast_untagged_variants.switch_names option) =
match sw_names with None -> None | Some { consts } -> Some consts.(i)
let get_block i (sw_names : Ast_untagged_variants.switch_names option) =
match sw_names with None -> None | Some { blocks } -> Some blocks.(i)
let get_tag_name (sw_names : Ast_untagged_variants.switch_names option) =
match sw_names with
| None -> Js_dump_lit.tag
| Some { blocks } ->
(match Array.find_opt (fun {Ast_untagged_variants.tag_name} -> tag_name <> None) blocks with
| Some {tag_name = Some s} -> s
| _ -> Js_dump_lit.tag
)
let get_block_cases (sw_names : Ast_untagged_variants.switch_names option) =
let res = ref [] in
(match sw_names with
| None -> res := []
| Some { blocks } ->
Ext_array.iter blocks (function
| {block_type = Some block_type} -> res := block_type :: !res
| {block_type = None} -> ()
)
);
!res
let get_literal_cases (sw_names : Ast_untagged_variants.switch_names option) =
let res = ref [] in
(match sw_names with
| None -> res := []
| Some { consts } ->
Ext_array.iter consts (function
| {tag_type = Some t} -> res := t :: !res
| {name; tag_type = None} -> res := String name :: !res
)
);
!res
let has_null_undefined_other (sw_names : Ast_untagged_variants.switch_names option) =
let (null, undefined, other) = (ref false, ref false, ref false) in
(match sw_names with
| None -> ()
| Some { consts; blocks } ->
Ext_array.iter consts (fun x -> match x.tag_type with
| Some Undefined -> undefined := true
| Some Null -> null := true
| _ -> other := true);
);
(!null, !undefined, !other)
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
*)
let compile output_prefix =
let rec compile_external_field (* Like [List.empty]*)
?(dynamic_import = false) (lamba_cxt : Lam_compile_context.t) (id : Ident.t) name : Js_output.t =
match Lam_compile_env.query_external_id_info ~dynamic_import 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 ~dynamic_import 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 ?(dynamic_import = false) (appinfo : Lam.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 ~dynamic_import 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 && Lam_analysis.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
compile_lambda lambda_cxt
(Lam_beta_reduce.propagate_beta_reduce_with_map lambda_cxt.meta
param_map params body ap_args)
| _ ->
let args_code, args =
let dummy = ([], []) in
if ap_args = [] then dummy
else
let arg_cxt = { lambda_cxt with continuation = NeedValue Not_tail } in
Ext_list.fold_right ap_args dummy (fun arg_lambda (args_code, args) ->
match compile_lambda arg_cxt arg_lambda with
| { block; value = Some b } ->
(Ext_list.append block args_code, b :: args)
| _ -> assert false)
in
let fn = E.ml_var_dot ~dynamic_import module_id ident_info.name in
let expression =
match appinfo.ap_info.ap_status with
| (App_infer_full | App_uncurry) as ap_status ->
E.call ~info:(call_info_of_ap_status ap_status) fn args
| App_na -> (
match ident_info.arity with
| Submodule _ | Single Arity_na ->
E.call ~info:Js_call_info.dummy fn args
| Single x ->
apply_with_arity fn ~arity:(Lam_arity.extract_arity x) args)
in
Js_output.output_of_block_and_expression lambda_cxt.continuation args_code
expression
(*
The second return values are values which need to be wrapped using
[update_dummy]
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 : Lam.t) : Js_output.t * initialization =
match arg with
| Lfunction { params; body; attr = { return_unit; async; one_unit_arg; directive } } ->
(* TODO: Think about recursive value
{[
let rec v = ref (fun _ ...
)
]}
[Alias] may not be exact
*)
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;
}
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 ->
Map_ident.find_default ret.new_params x x))
[
S.while_ E.true_
(Map_ident.fold ret.new_params body_block
(fun old new_param acc ->
S.define_variable ~kind:Alias old (E.var new_param) :: acc));
]
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
( 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 xs.(i)
| Blk_record_inlined xs ->
Fld_record_inline_set 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 Js_runtime_modules.obj_runtime
"update_dummy" [ 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 : Lam_scc.bindings) : 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
| _ -> (
let id_args_group = Lam_scc.scc_bindings id_args in
match id_args_group with
| [] -> assert false
| first :: rest ->
let acc = compile_recursive_lets_aux cxt first in
Ext_list.fold_left rest acc (fun acc x ->
Js_output.append_output acc (compile_recursive_lets_aux cxt x)))
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:Lam_compat.let_kind * Ident.t ->
_ -> ('a * J.case_clause) list -> J.statement) ->
switch_exp: J.expression ->
default: default_case ->
?merge_cases: ('a -> 'a -> bool) ->
('a * Lam.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:Lam_compat.let_kind * Ident.t ->
_ -> (a * J.case_clause) list -> J.statement
)
~(switch_exp : J.expression)
~(default : default_case)
?(merge_cases = fun _ _ -> true)
(cases : (a * Lam.t) list) ->
match (cases, default) with
| [], Default lam -> Js_output.output_as_block (compile_lambda cxt lam)
| [], (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
*)
Js_output.output_as_block (compile_lambda 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))
(Js_output.output_as_block (compile_lambda cxt lam));
])
| [ (id, lam) ], Default x | [ (id, lam); (_, x) ], Complete ->
morph_declare_to_assign cxt (fun cxt define ->
let else_block = Js_output.output_as_block (compile_lambda cxt x) in
let then_block = Js_output.output_as_block (compile_lambda 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 (Lam.eq_approx lam lam1)) cases
| _ -> cases
in
let default =
match default with
| Complete -> None
| NonComplete -> None
| Default lam ->
Some (Js_output.output_as_block (compile_lambda cxt lam))
in
let body =
group_apply ~merge_cases cases (fun last (switch_case, lam) ->
if last then
(* merge and shared *)
let switch_body, should_break =
Js_output.to_break_block (compile_lambda cxt lam)
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;
} )
else
( switch_case,
{
switch_body = [];
should_break = false;
comment = None;
} ))
(* 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 ~(get_tag : _ -> Ast_untagged_variants.tag option) =
List.fold_right (fun (i, lam) acc ->
match get_tag i, acc with
| Some {Ast_untagged_variants.tag_type = Some t}, Some string_table ->
Some ((t, lam) :: string_table)
| Some {name; tag_type = None}, Some string_table -> Some ((String name, lam) :: string_table)
| _, _ -> None
) table (Some [])
and compile_cases
?(untagged=false) ~cxt ~(switch_exp : E.t) ?(default = NonComplete)
?(get_tag = fun _ -> None) ?(block_cases=[]) cases : initialization =
match use_compile_literal_cases cases ~get_tag with
| Some string_cases ->
if untagged
then compile_untagged_cases ~cxt ~switch_exp ~block_cases ~default string_cases
else compile_string_cases ~cxt ~switch_exp ~default string_cases
| None ->
cases |> compile_general_cases
~make_exp:(fun i -> match get_tag i with
| None -> E.small_int i
| Some {tag_type = Some(String s)} -> E.str s
| Some {name} -> E.str name)
~eq_exp: (fun _ x _ y -> E.int_equal x y)
~cxt
~switch: (fun ?default ?declaration e clauses ->
S.int_switch ?default ?declaration e clauses)
~switch_exp
~default
and compile_switch (switch_arg : Lam.t) (sw : Lam.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_names;
}
: Lam.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 get_const_tag i = get_const_tag i sw_names in
let get_block i = get_block i sw_names in
let block_cases = get_block_cases sw_names in
let get_block_tag i : Ast_untagged_variants.tag option = match get_block i with
| None -> None
| Some ({tag = {name}; block_type = Some block_type}) ->
Some {name; tag_type = Some (Untagged block_type)} (* untagged block *)
| Some ({block_type = None; tag}) -> (* tagged block *)
Some tag in
let tag_name = get_tag_name sw_names in
let untagged = block_cases <> [] 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 } -> (
block
@
if sw_consts_full && sw_consts = [] then
compile_cases ~block_cases
~untagged ~cxt
~switch_exp:(if untagged then e else E.tag ~name:tag_name e)
~default:sw_blocks_default
~get_tag:get_block_tag sw_blocks
else if sw_blocks_full && sw_blocks = [] then
compile_cases ~cxt ~switch_exp:e ~block_cases ~default:sw_num_default ~get_tag:get_const_tag sw_consts
else
(* [e] will be used twice *)
let dispatch e =
let is_a_literal_case =
if block_cases <> []
then
E.is_a_literal_case ~literal_cases:(get_literal_cases sw_names) ~block_cases e
else
E.is_int_tag ~has_null_undefined_other:(has_null_undefined_other sw_names) e in
S.if_ is_a_literal_case
(compile_cases ~cxt ~switch_exp:e ~block_cases ~default:sw_num_default ~get_tag:get_const_tag sw_consts)
~else_:
(compile_cases
~untagged ~cxt
~switch_exp:(if untagged then e else E.tag ~name:tag_name e)
~block_cases
~default:sw_blocks_default
~get_tag:get_block_tag sw_blocks)
in
match e.expression_desc with
| J.Var _ -> [ dispatch e ]
| _ ->
let v = Ext_ident.create_tmp () in
(* Necessary avoid duplicated computation*)
[ S.define_variable ~kind:Variable v e; dispatch (E.var v) ])
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_cases ~cxt ~switch_exp ~default ~block_cases cases =
let mk_eq (i : Ast_untagged_variants.tag_type option) x j y =
let check = match i, j with
| Some tag_type, _ ->
Ast_untagged_variants.DynamicChecks.add_runtime_type_check ~tag_type ~block_cases (Expr x) (Expr y)
| _, Some tag_type ->
Ast_untagged_variants.DynamicChecks.add_runtime_type_check ~tag_type ~block_cases (Expr y) (Expr x)
| _ ->
Ast_untagged_variants.DynamicChecks.(==) (Expr x) (Expr y)
in
E.emit_check check
in
let tag_is_not_typeof = function
| Ast_untagged_variants.Untagged (InstanceType _) -> true
| _ -> false in
let clause_is_not_typeof (tag, _) = tag_is_not_typeof tag in
let switch ?default ?declaration e clauses =
let (not_typeof_clauses, typeof_clauses) = List.partition clause_is_not_typeof clauses in
let rec build_if_chain remaining_clauses = (match remaining_clauses with
| (Ast_untagged_variants.Untagged (InstanceType instance_type), {J.switch_body}) :: rest ->
S.if_ (E.emit_check (IsInstanceOf (instance_type, Expr e)))
(switch_body)
~else_:([build_if_chain rest])
| _ -> S.string_switch ?default ?declaration (E.typeof e) typeof_clauses) in
build_if_chain not_typeof_clauses in
let merge_cases tag1 tag2 = (* only merge typeof cases, as instanceof cases are pulled out into if-then-else *)
not (tag_is_not_typeof tag1 || tag_is_not_typeof tag2) in
cases |> compile_general_cases
~make_exp: E.tag_type
~eq_exp: mk_eq
~cxt
~switch
~switch_exp
~default
~merge_cases
and compile_stringswitch l cases default (lambda_cxt : Lam_compile_context.t) =
(* TODO might better optimization according to the number of cases
Be careful: we should avoid multiple evaluation of l,
The [gen] can be elimiated when number of [cases] is less than 3
*)
let cases = cases |> List.map (fun (s,l) -> Ast_untagged_variants.String s, l) in
match
compile_lambda { lambda_cxt with continuation = NeedValue Not_tail } l
with
| { value = None } -> assert false
| { block; value = Some e } -> (
(* when should_return is true -- it's passed down
otherwise it's ok *)
let default =
match default with Some x -> Default x | None -> Complete
in
match lambda_cxt.continuation with
(* TODO: can be avoided when cases are less than 3 *)
| NeedValue _ ->
let v = Ext_ident.create_tmp () in
Js_output.make
(Ext_list.append block
(compile_string_cases
~cxt: { lambda_cxt with continuation = Declare (Variable, v) }
~switch_exp:e ~default cases))
~value:(E.var v)
| _ ->
Js_output.make
(Ext_list.append block
(compile_string_cases ~cxt:lambda_cxt ~switch_exp:e ~default cases )))
(*
This should be optimized in lambda layer
(let (match/1038 = (apply g/1027 x/1028))
(catch
(stringswitch match/1038
case "aabb": 0
case "bbc": 1
default: (exit 1))
with (1) 2))
*)
and compile_staticraise i (largs : Lam.t list)
(lambda_cxt : Lam_compile_context.t) =
(* [i] is the jump table, [largs] is the arguments passed to [Lstaticcatch]*)
match Lam_compile_context.find_exn lambda_cxt i with
| { exit_id; bindings; order_id } ->
Ext_list.fold_right2 largs bindings
(Js_output.make
(if order_id >= 0 then [ S.assign exit_id (E.small_int order_id) ]
else []))
(fun larg bind acc ->
let new_output =
match larg with
| Lvar id -> Js_output.make [ S.assign bind (E.var id) ]
| _ ->
(* TODO: should be Assign -- Assign is an optimization *)
compile_lambda
{ lambda_cxt with continuation = Assign bind }
larg
in
Js_output.append_output new_output acc)
(* Invariant: exit_code can not be reused
(catch l with (32)
(handler))
32 should not be used in another catch
Invariant:
This is true in current ocaml compiler
currently exit only appears in should_return position relative to staticcatch
if not we should use ``javascript break`` or ``continue``
if exit_code_id == code
handler -- ids are not useful, since
when compiling `largs` we will do the binding there
- when exit_code is undefined internally,
it should PRESERVE ``tail`` property
- if it uses `staticraise` only once
or handler is minimal, we can inline
- always inline also seems to be ok, but it might bloat the code
- another common scenario is that we have nested catch
(catch (catch (catch ..))
checkout example {!Digest.file}, you can not inline handler there,
we can spot such patten and use finally there?
{[
let file filename =
let ic = open_in_bin filename in
match channel ic (-1) with
| d -> close_in ic; d
| exception e -> close_in ic; raise e
]}
*)
and compile_staticcatch (lam : Lam.t) (lambda_cxt : Lam_compile_context.t) =
let code_table, body = flatten_nested_caches lam in
let exit_id = Ext_ident.create_tmp ~name:"exit" () in
match (lambda_cxt.continuation, code_table) with
| ( EffectCall
(Maybe_tail_is_return (Tail_with_name { in_staticcatch = false }) as
tail_type),
[ code_table ] )
(* tail position and only one exit code *)
when Lam_compile_context.no_static_raise_in_handler code_table ->
let jmp_table, handler =
Lam_compile_context.add_pseudo_jmp lambda_cxt.jmp_table exit_id
code_table
in
let new_cxt =
{
lambda_cxt with
jmp_table;
continuation = EffectCall (in_staticcatch tail_type);
}
in
let lbody = compile_lambda new_cxt body in
let declares =
Ext_list.map code_table.bindings (fun x ->
S.declare_variable ~kind:Variable x)
in
Js_output.append_output (Js_output.make declares)
(Js_output.append_output lbody (compile_lambda lambda_cxt handler))
| _ -> (
let exit_expr = E.var exit_id in
let jmp_table, handlers =
Lam_compile_context.add_jmps lambda_cxt.jmp_table exit_id code_table
in
(* Declaration First, body and handler have the same value *)
let declares =
S.define_variable ~kind:Variable exit_id E.zero_int_literal
:: (* we should always make it zero here, since [zero] is reserved in our mapping*)
Ext_list.flat_map code_table (fun { bindings } ->
Ext_list.map bindings (fun x ->
S.declare_variable ~kind:Variable x))
in
match lambda_cxt.continuation with
(* could be optimized when cases are less than 3 *)
| NeedValue _ ->
let v = Ext_ident.create_tmp () in
let new_cxt =
{ lambda_cxt with jmp_table; continuation = Assign v }
in
let lbody = compile_lambda new_cxt body in
Js_output.append_output
(Js_output.make (S.declare_variable ~kind:Variable v :: declares))
(Js_output.append_output lbody
(Js_output.make
(compile_cases ~cxt:new_cxt ~switch_exp:exit_expr handlers)
~value:(E.var v)))
| Declare (kind, id) (* declare first this we will do branching*) ->
let declares = S.declare_variable ~kind id :: declares in
let new_cxt =
{ lambda_cxt with jmp_table; continuation = Assign id }
in
let lbody = compile_lambda new_cxt body in
Js_output.append_output (Js_output.make declares)
(Js_output.append_output lbody
(Js_output.make
(compile_cases ~cxt:new_cxt ~switch_exp:exit_expr handlers)))
(* place holder -- tell the compiler that
we don't know if it's complete
*)
| EffectCall tail_type as cont ->
let continuation =
let new_tail_type = in_staticcatch tail_type in
if new_tail_type == tail_type then cont
else EffectCall new_tail_type
in
let new_cxt = { lambda_cxt with jmp_table; continuation } in
let lbody = compile_lambda new_cxt body in
Js_output.append_output (Js_output.make declares)
(Js_output.append_output lbody
(Js_output.make
(compile_cases ~cxt:new_cxt ~switch_exp:exit_expr handlers)))
| Assign _ ->
let new_cxt = { lambda_cxt with jmp_table } in
let lbody = compile_lambda new_cxt body in
Js_output.append_output (Js_output.make declares)
(Js_output.append_output lbody
(Js_output.make
(compile_cases ~cxt:new_cxt ~switch_exp:exit_expr handlers))))
and compile_sequand (l : Lam.t) (r : Lam.t) (lambda_cxt : Lam_compile_context.t)
=
if Lam_compile_context.continuation_is_return lambda_cxt.continuation then
compile_lambda lambda_cxt (Lam.sequand l r)
else
let new_cxt = { lambda_cxt with continuation = NeedValue Not_tail } in
match compile_lambda new_cxt l with
| { value = None } -> assert false
| { block = l_block; value = Some l_expr } -> (
match compile_lambda new_cxt r with
| { value = None } -> assert false
| { block = []; value = Some r_expr } ->
Js_output.output_of_block_and_expression lambda_cxt.continuation
l_block (E.and_ l_expr r_expr)
| { block = r_block; value = Some r_expr } -> (
match lambda_cxt.continuation with
| Assign v ->
(* Refernece Js_output.output_of_block_and_expression *)
Js_output.make
(l_block
@ [
S.if_ l_expr
(r_block @ [ S.assign v r_expr ])
~else_:[ S.assign v E.false_ ];
])