forked from HaxeFoundation/haxe
-
Notifications
You must be signed in to change notification settings - Fork 0
/
genpy.ml
2448 lines (2240 loc) · 84.6 KB
/
genpy.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
(*
The Haxe Compiler
Copyright (C) 2005-2015 Haxe Foundation
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*)
open Ast
open Type
open Common
module Utils = struct
let class_of_module_type mt = match mt with
| TClassDecl c -> c
| _ -> failwith ("Not a class: " ^ (s_type_path (t_infos mt).mt_path))
let find_type com path =
try
List.find (fun mt -> match mt with
| TAbstractDecl _ -> false
| _ -> (t_infos mt).mt_path = path
) com.types
with Not_found ->
error (Printf.sprintf "Could not find type %s\n" (s_type_path path)) null_pos
let mk_static_field c cf p =
let ta = TAnon { a_fields = c.cl_statics; a_status = ref (Statics c) } in
let ethis = mk (TTypeExpr (TClassDecl c)) ta p in
let t = monomorphs cf.cf_params cf.cf_type in
mk (TField (ethis,(FStatic (c,cf)))) t p
let mk_static_call c cf el p =
let ef = mk_static_field c cf p in
let tr = match follow ef.etype with
| TFun(args,tr) -> tr
| _ -> assert false
in
mk (TCall(ef,el)) tr p
let resolve_static_field c n =
try
PMap.find n c.cl_statics
with Not_found ->
failwith (Printf.sprintf "Class %s has no field %s" (s_type_path c.cl_path) n)
let mk_static_field_2 c n p =
mk_static_field c (resolve_static_field c n) p
let mk_static_call_2 c n el p =
mk_static_call c (resolve_static_field c n) el p
end
module KeywordHandler = struct
let kwds =
let h = Hashtbl.create 0 in
List.iter (fun s -> Hashtbl.add h s ()) [
"and"; "as"; "assert"; "break"; "class"; "continue"; "def"; "del"; "elif"; "else"; "except"; "exec"; "finally"; "for";
"from"; "global"; "if"; "import"; "in"; "is"; "lambda"; "not"; "or"; "pass"; " raise"; "return"; "try"; "while";
"with"; "yield"; "None"; "True"; "False";
];
h
let kwds2 =
let h = Hashtbl.create 0 in
List.iter (fun s -> Hashtbl.add h s ()) [
"len"; "int"; "float"; "list"; "bool"; "str"; "isinstance"; "print"; "min"; "max";
"hasattr"; "getattr"; "setattr"; "delattr"; "callable"; "type"; "ord"; "chr"; "iter"; "map"; "filter";
"tuple"; "dict"; "set"; "bytes"; "bytearray"
];
h
let handle_keywords s =
let l = String.length s in
if Hashtbl.mem kwds s then
"_hx_" ^ s
(*
handle special __ underscore behaviour (creates private fields for objects) for fields but only if the field doesn't
end with at least one underscores like __iter__ because these are special fields
*)
else if l > 2 && String.sub s 0 2 = "__" && String.sub s (l - 1) 1 <> "_" then
"_hx_" ^ s
else s
let check_var_declaration v =
if Hashtbl.mem kwds2 v.v_name then v.v_name <- "_hx_" ^ v.v_name
end
module Transformer = struct
type adjusted_expr = {
a_expr : texpr;
a_blocks : texpr list;
a_next_id : unit -> string;
a_is_value : bool;
}
let como = ref None
let t_bool = ref t_dynamic
let t_void = ref t_dynamic
let t_string = ref t_dynamic
let t_int = ref t_dynamic
let c_reflect = ref (fun () -> null_class)
let init com =
como := Some com;
t_bool := com.basic.tbool;
t_void := com.basic.tvoid;
t_string := com.basic.tstring;
t_int := com.basic.tint;
c_reflect := fun () -> Utils.class_of_module_type (Utils.find_type com ([],"Reflect"))
and debug_expr e =
let s_type = Type.s_type (print_context()) in
let s = Type.s_expr_pretty " " s_type e in
Printf.printf "%s\n" s
and debug_expr_with_type e =
let s_type = Type.s_type (print_context()) in
let es = Type.s_expr_pretty " " s_type e in
let t = s_type e.etype in
Printf.printf "%s : %s\n" es t
and debug_type t =
let s_type = Type.s_type (print_context()) in
let t = s_type t in
Printf.printf "%s\n" t
let new_counter () =
let n = ref (-1) in
(fun () ->
incr n;
Printf.sprintf "_hx_local_%i" !n
)
let to_expr ae =
match ae.a_blocks with
| [] ->
ae.a_expr
| el ->
match ae.a_expr.eexpr with
| TBlock el2 ->
{ ae.a_expr with eexpr = TBlock (el @ el2) }
| _ ->
{ ae.a_expr with eexpr = TBlock (el @ [ae.a_expr])}
let lift_expr ?(is_value = false) ?(next_id = None) ?(blocks = []) e =
let next_id = match next_id with
| None ->
new_counter()
| Some f ->
f
in
{
a_expr = e;
a_blocks = blocks;
a_next_id = next_id;
a_is_value = is_value
}
let lift_expr1 is_value next_id blocks e =
lift_expr ~is_value:is_value ~next_id:(Some next_id) ~blocks:blocks e
let to_tvar ?(capture = false) n t =
alloc_var n t
(* { v_name = n; v_type = t; v_id = 0; v_capture = capture; v_extra = None; v_meta = [] } *)
let create_non_local n pos =
let s = "nonlocal " ^ (KeywordHandler.handle_keywords n) in
(* TODO: this is a hack... *)
let id = mk (TLocal (to_tvar "python_Syntax._pythonCode" t_dynamic ) ) !t_void pos in
let id2 = mk (TLocal( to_tvar s t_dynamic )) !t_void pos in
mk (TCall(id, [id2])) t_dynamic pos
let to_tlocal_expr ?(capture = false) n t p =
mk (TLocal (to_tvar ~capture:capture n t)) t p
let check_unification e t = match follow e.etype,follow t with
| TAnon an1, TAnon an2 ->
PMap.iter (fun s cf ->
if not (PMap.mem s an1.a_fields) then an1.a_fields <- PMap.add s cf an1.a_fields
) an2.a_fields;
e
| _ ->
e
let dynamic_field_read e s t =
let e = Utils.mk_static_call_2 ((!c_reflect)()) "field" [e;mk (TConst (TString s)) !t_string e.epos] e.epos in
{ e with etype = t }
let dynamic_field_write e1 s e2 =
Utils.mk_static_call_2 ((!c_reflect)()) "setField" [e1;mk (TConst (TString s)) !t_string e1.epos;e2] e1.epos
let dynamic_field_read_write next_id e1 s op e2 t =
let id = next_id() in
let temp_var = to_tvar id e1.etype in
let temp_var_def = mk (TVar(temp_var,Some e1)) e1.etype e1.epos in
let temp_local = mk (TLocal temp_var) e1.etype e1.epos in
let e_field = dynamic_field_read temp_local s t in
let e_op = mk (TBinop(op,e_field,e2)) e_field.etype e_field.epos in
let e_set_field = dynamic_field_write temp_local s e_op in
mk (TBlock [
temp_var_def;
e_set_field;
]) e_set_field.etype e_set_field.epos
let add_non_locals_to_func e = match e.eexpr with
| TFunction tf ->
let cur = ref PMap.empty in
let save () =
let prev = !cur in
(fun () ->
cur := prev
)
in
let declare v =
cur := PMap.add v.v_id v !cur;
in
List.iter (fun (v,_) -> declare v) tf.tf_args;
let non_locals = Hashtbl.create 0 in
let rec it e = match e.eexpr with
| TVar(v,e1) ->
begin match e1 with
| Some e ->
maybe_continue e
| None ->
()
end;
declare v;
| TTry(e1,catches) ->
it e1;
List.iter (fun (v,e) ->
let restore = save() in
declare v;
it e;
restore()
) catches;
| TBinop( (OpAssign | OpAssignOp(_)), { eexpr = TLocal v }, e2) ->
if not (PMap.mem v.v_id !cur) then
Hashtbl.add non_locals v.v_id v;
maybe_continue e2;
| TFunction _ ->
()
| _ ->
Type.iter it e
and maybe_continue e = match e.eexpr with
| TFunction _ ->
()
| _ ->
it e
in
it tf.tf_expr;
let el = Hashtbl.fold (fun k v acc ->
(create_non_local v.v_name e.epos) :: acc
) non_locals [] in
let el = tf.tf_expr :: el in
let tf = { tf with tf_expr = { tf.tf_expr with eexpr = TBlock(List.rev el)}} in
{e with eexpr = TFunction tf}
| _ ->
assert false
let rec transform_function tf ae is_value =
let p = tf.tf_expr.epos in
let assigns = List.fold_left (fun acc (v,value) -> match value with
| None | Some TNull ->
acc
| Some ct ->
let a_local = mk (TLocal v) v.v_type p in
let a_null = mk (TConst TNull) v.v_type p in
let a_cmp = mk (TBinop(OpEq,a_local,a_null)) !t_bool p in
let a_value = mk (TConst(ct)) v.v_type p in
let a_assign = mk (TBinop(OpAssign,a_local,a_value)) v.v_type p in
let a_if = mk (TIf(a_cmp,a_assign,None)) !t_void p in
a_if :: acc
) [] tf.tf_args in
let body = match assigns with
| [] ->
tf.tf_expr
| _ ->
let eb = mk (TBlock (List.rev assigns)) t_dynamic p in
Type.concat eb tf.tf_expr
in
let e1 = to_expr (transform_expr ~next_id:(Some ae.a_next_id) body) in
let fn = mk (TFunction({
tf_expr = e1;
tf_args = tf.tf_args;
tf_type = tf.tf_type;
})) ae.a_expr.etype p in
let fn = add_non_locals_to_func fn in
if is_value then begin
let new_name = ae.a_next_id() in
let new_var = alloc_var new_name tf.tf_type in
let new_local = mk (TLocal new_var) fn.etype p in
let def = mk (TVar(new_var,Some fn)) fn.etype p in
lift_expr1 false ae.a_next_id [def] new_local
end else
lift_expr fn
and transform_var_expr ae eo v =
let b,new_expr = match eo with
| None ->
[],None
| Some e1 ->
let f = transform_expr1 true ae.a_next_id [] e1 in
let b = f.a_blocks in
b,Some(f.a_expr)
in
let e = mk (TVar(v,new_expr)) ae.a_expr.etype ae.a_expr.epos in
lift_expr ~next_id:(Some ae.a_next_id) ~blocks:b e
and transform_expr ?(is_value = false) ?(next_id = None) ?(blocks = []) (e : texpr) : adjusted_expr =
transform1 (lift_expr ~is_value ~next_id ~blocks e)
and transform_expr1 is_value next_id blocks e =
transform_expr ~is_value ~next_id:(Some next_id) ~blocks e
and transform_exprs_to_block el tb is_value p next_id =
match el with
| [e] ->
transform_expr ~is_value ~next_id:(Some next_id) e
| _ ->
let size = List.length el in
let res = DynArray.create () in
ExtList.List.iteri (fun i e ->
(* this removes len(x) calls which are reproduced by the inlined return
of Array.push even if the value is not used *)
let is_removable_statement e = (not is_value || i < size-1) &&
match e.eexpr with
| TField(_, FInstance({cl_path = [],"list"},_,{ cf_name = "length" })) -> true
| _ -> false
in
if not (is_removable_statement e) then
let ae = transform_expr ~is_value ~next_id:(Some next_id) e in
List.iter (DynArray.add res) ae.a_blocks;
DynArray.add res ae.a_expr
else
()
) el;
lift_expr (mk (TBlock (DynArray.to_list res)) tb p)
and transform_switch ae is_value e1 cases edef =
let case_functions = ref [] in
let case_to_if (el,e) eelse =
let val_reversed = List.rev el in
let mk_eq e = mk (TBinop(OpEq,e1,e)) !t_bool (punion e1.epos e.epos) in
let cond = match val_reversed with
| [] ->
assert false
| [e] ->
mk_eq e
| e :: el ->
List.fold_left (fun eelse e -> mk (TBinop(OpBoolOr,eelse,mk_eq e)) !t_bool (punion eelse.epos e.epos)) (mk_eq e) el
in
let eif = if is_value then begin
let name = ae.a_next_id() in
let func = exprs_to_func [e] name ae in
case_functions := !case_functions @ func.a_blocks;
let call = func.a_expr in
mk (TIf(cond,call,eelse)) ae.a_expr.etype ae.a_expr.epos
end else
mk (TIf(cond,e,eelse)) ae.a_expr.etype e.epos
in
eif
in
let rev_cases = List.rev cases in
let edef = Some (match edef with
| None ->
mk (TBlock []) ae.a_expr.etype ae.a_expr.epos
| Some e ->
e)
in
let res = match rev_cases,edef with
| [],Some edef ->
edef
| [],None ->
(* I don't think that can happen? *)
assert false
| [case],_ ->
case_to_if case edef
| case :: cases,_ ->
List.fold_left (fun acc case -> case_to_if case (Some acc)) (case_to_if case edef) cases
in
let res = if is_value then
mk (TBlock ((List.rev (res :: !case_functions)))) res.etype res.epos
else
res
in
forward_transform res ae
and transform_string_switch ae is_value e1 cases edef =
let length_map = Hashtbl.create 0 in
List.iter (fun (el,e) ->
List.iter (fun es ->
match es.eexpr with
| TConst (TString s) ->
let l = String.length s in
let sl = try
Hashtbl.find length_map l
with Not_found ->
let sl = ref [] in
Hashtbl.replace length_map l sl;
sl
in
sl := ([es],e) :: !sl;
| _ ->
()
) el
) cases;
if Hashtbl.length length_map < 2 then
transform_switch ae is_value e1 cases edef
else
let mk_eq e1 e2 = mk (TBinop(OpEq,e1,e2)) !t_bool (punion e1.epos e2.epos) in
let mk_or e1 e2 = mk (TBinop(OpOr,e1,e2)) !t_bool (punion e1.epos e2.epos) in
let mk_if (el,e) eo =
let eif = List.fold_left (fun eacc e -> mk_or eacc (mk_eq e1 e)) (mk_eq e1 (List.hd el)) (List.tl el) in
mk (TIf(Codegen.mk_parent eif,e,eo)) e.etype e.epos
in
let cases = Hashtbl.fold (fun i el acc ->
let eint = mk (TConst (TInt (Int32.of_int i))) !t_int e1.epos in
let fs = match List.fold_left (fun eacc ec -> Some (mk_if ec eacc)) edef !el with Some e -> e | None -> assert false in
([eint],fs) :: acc
) length_map [] in
let c_string = match !t_string with TInst(c,_) -> c | _ -> assert false in
let cf_length = PMap.find "length" c_string.cl_fields in
let ef = mk (TField(e1,FInstance(c_string,[],cf_length))) !t_int e1.epos in
let res_var = alloc_var (ae.a_next_id()) ef.etype in
let res_local = {ef with eexpr = TLocal res_var} in
let var_expr = {ef with eexpr = TVar(res_var,Some ef)} in
let e = mk (TBlock [
var_expr;
mk (TSwitch(res_local,cases,edef)) ae.a_expr.etype e1.epos
]) ae.a_expr.etype e1.epos in
forward_transform e ae
and transform_op_assign_op ae e1 op one is_value post =
let e1_ = transform_expr e1 ~is_value:true ~next_id:(Some ae.a_next_id) in
let handle_as_local temp_local =
let ex = ae.a_expr in
let res_var = alloc_var (ae.a_next_id()) ex.etype in
let res_local = {ex with eexpr = TLocal res_var} in
let plus = {ex with eexpr = TBinop(op,temp_local,one)} in
let var_expr = {ex with eexpr = TVar(res_var,Some temp_local)} in
let assign_expr = {ex with eexpr = TBinop(OpAssign,e1_.a_expr,plus)} in
let blocks = if post then
[var_expr;assign_expr;res_local]
else
[assign_expr;temp_local]
in
(* TODO: block is ignored in the else case? *)
let block = e1_.a_blocks @ blocks in
if is_value then begin
let f = exprs_to_func block (ae.a_next_id()) ae in
lift_expr f.a_expr ~is_value:true ~next_id:(Some ae.a_next_id) ~blocks:f.a_blocks
end else begin
let block = e1_.a_blocks @ [assign_expr] in
transform_exprs_to_block block ex.etype false ex.epos ae.a_next_id
end
in
match e1_.a_expr.eexpr with
| TArray({eexpr = TLocal _},{eexpr = TLocal _})
| TField({eexpr = TLocal _},_)
| TLocal _ ->
handle_as_local e1_.a_expr
| TArray(e1,e2) ->
let id = ae.a_next_id() in
let temp_var_l = alloc_var id e1.etype in
let temp_local_l = {e1 with eexpr = TLocal temp_var_l} in
let temp_var_l = {e1 with eexpr = TVar(temp_var_l,Some e1)} in
let id = ae.a_next_id() in
let temp_var_r = alloc_var id e2.etype in
let temp_local_r = {e2 with eexpr = TLocal temp_var_r} in
let temp_var_r = {e2 with eexpr = TVar(temp_var_r,Some e2)} in
let id = ae.a_next_id() in
let temp_var = alloc_var id e1_.a_expr.etype in
let temp_local = {e1_.a_expr with eexpr = TLocal temp_var} in
let temp_var_expr = {e1_.a_expr with eexpr = TArray(temp_local_l,temp_local_r)} in
let temp_var = {e1_.a_expr with eexpr = TVar(temp_var,Some temp_var_expr)} in
let plus = {ae.a_expr with eexpr = TBinop(op,temp_local,one)} in
let assign_expr = {ae.a_expr with eexpr = TBinop(OpAssign,temp_var_expr,plus)} in
let block = e1_.a_blocks @ [temp_var_l;temp_var_r;temp_var;assign_expr;if post then temp_local else temp_var_expr] in
if is_value then begin
let f = exprs_to_func block (ae.a_next_id()) ae in
lift_expr f.a_expr ~is_value:true ~next_id:(Some ae.a_next_id) ~blocks:f.a_blocks
end else
transform_exprs_to_block block ae.a_expr.etype false ae.a_expr.epos ae.a_next_id
| TField(e1,fa) ->
let temp_var_l = alloc_var (ae.a_next_id()) e1.etype in
let temp_local_l = {e1 with eexpr = TLocal temp_var_l} in
let temp_var_l = {e1 with eexpr = TVar(temp_var_l,Some e1)} in
let temp_var = alloc_var (ae.a_next_id()) e1_.a_expr.etype in
let temp_local = {e1_.a_expr with eexpr = TLocal temp_var} in
let temp_var_expr = {e1_.a_expr with eexpr = TField(temp_local_l,fa)} in
let temp_var = {e1_.a_expr with eexpr = TVar(temp_var,Some temp_var_expr)} in
let plus = {ae.a_expr with eexpr = TBinop(op,temp_local,one)} in
let assign_expr = {ae.a_expr with eexpr = TBinop(OpAssign,temp_var_expr,plus)} in
let block = e1_.a_blocks @ [temp_var_l;temp_var;assign_expr;if post then temp_local else temp_var_expr] in
if is_value then begin
let f = exprs_to_func block (ae.a_next_id()) ae in
lift_expr f.a_expr ~is_value:true ~next_id:(Some ae.a_next_id) ~blocks:f.a_blocks
end else
transform_exprs_to_block block ae.a_expr.etype false ae.a_expr.epos ae.a_next_id
| _ ->
debug_expr e1_.a_expr;
assert false
and var_to_treturn_expr ?(capture = false) n t p =
let x = mk (TLocal (to_tvar ~capture:capture n t)) t p in
mk (TReturn (Some x)) t p
and exprs_to_func exprs name base =
let convert_return_expr (expr:texpr) =
match expr.eexpr with
| TWhile(_,_,_) ->
let ret = { expr with eexpr = TReturn (None) } in
[expr; ret]
| TFunction(f) ->
let ret = var_to_treturn_expr name f.tf_type f.tf_expr.epos in
[expr;ret]
| TBinop(OpAssign, l, r) ->
let r = { l with eexpr = TReturn(Some l) } in
[expr; r]
| x ->
let ret_expr = { expr with eexpr = TReturn( Some(expr) )} in
[ret_expr]
in
let def =
(let ex = match exprs with
| [] -> assert false
| [x] ->
(let exs = convert_return_expr x in
match exs with
| [] -> assert false
| [x] -> x
| x ->
match List.rev x with
| x::xs ->
mk (TBlock exs) x.etype base.a_expr.epos
| _ -> assert false)
| x ->
match List.rev x with
| x::xs ->
(let ret = x in
let tail = List.rev xs in
let block = tail @ (convert_return_expr ret) in
match List.rev block with
| x::_ ->
mk (TBlock block) x.etype base.a_expr.epos
| _ -> assert false)
| _ -> assert false
in
let f1 = { tf_args = []; tf_type = TFun([],ex.etype); tf_expr = ex} in
let fexpr = mk (TFunction f1) ex.etype ex.epos in
let fvar = to_tvar name fexpr.etype in
let f = add_non_locals_to_func fexpr in
let assign = { ex with eexpr = TVar(fvar, Some(f))} in
let call_expr = (mk (TLocal fvar) fexpr.etype ex.epos ) in
let substitute = mk (TCall(call_expr, [])) ex.etype ex.epos in
lift_expr ~blocks:[assign] substitute)
in
match exprs with
| [{ eexpr = TFunction({ tf_args = []} as f) } as x] ->
let l = to_tlocal_expr name f.tf_type f.tf_expr.epos in
let substitute = mk (TCall(l, [])) f.tf_type f.tf_expr.epos in
lift_expr ~blocks:[x] substitute
| _ -> def
and transform_call is_value e params ae =
let trans is_value blocks e = transform_expr1 is_value ae.a_next_id blocks e in
let trans1 e params =
let e = trans true [] e in
let blocks = e.a_blocks @ (List.flatten (List.map (fun (p) -> p.a_blocks) params)) in
let params = List.map (fun (p) -> p.a_expr) params in
let e = { ae.a_expr with eexpr = TCall(e.a_expr, params) } in
lift_expr ~blocks:blocks e
in
match e, params with
(* the foreach block should not be handled as a value *)
| ({ eexpr = TField(_, FStatic({cl_path = ["python";],"Syntax"},{ cf_name = "_foreach" }))} as e, [e1;e2;e3]) ->
trans1 e [trans true [] e1; trans true [] e2; trans false [] e3]
| (e, params) ->
trans1 e (List.map (trans true []) params)
and transform1 ae : adjusted_expr =
let trans is_value blocks e = transform_expr1 is_value ae.a_next_id blocks e in
let lift is_value blocks e = lift_expr1 is_value ae.a_next_id blocks e in
let a_expr = ae.a_expr in
match ae.a_is_value,ae.a_expr.eexpr with
| (is_value,TBlock [x]) ->
trans is_value [] x
| (false,TBlock []) ->
lift_expr a_expr
| (true,TBlock []) ->
lift_expr (mk (TConst TNull) ae.a_expr.etype ae.a_expr.epos)
| (false,TBlock el) ->
transform_exprs_to_block el ae.a_expr.etype false ae.a_expr.epos ae.a_next_id
| (true,TBlock el) ->
let name = ae.a_next_id() in
let block,tr = match List.rev el with
| e :: el ->
List.rev ((mk (TReturn (Some e)) t_dynamic e.epos) :: el),e.etype
| [] ->
assert false
in
let my_block = transform_exprs_to_block block tr false ae.a_expr.epos ae.a_next_id in
let fn = mk (TFunction {
tf_args = [];
tf_type = tr;
tf_expr = my_block.a_expr;
}) ae.a_expr.etype ae.a_expr.epos in
let t_var = alloc_var name ae.a_expr.etype in
let f = add_non_locals_to_func fn in
let fn_assign = mk (TVar (t_var,Some f)) ae.a_expr.etype ae.a_expr.epos in
let ev = mk (TLocal t_var) ae.a_expr.etype ae.a_expr.epos in
let substitute = mk (TCall(ev,[])) ae.a_expr.etype ae.a_expr.epos in
lift_expr ~blocks:[fn_assign] substitute
| (is_value,TFunction(f)) ->
transform_function f ae is_value
| (_,TVar(v,None)) ->
transform_var_expr ae None v
| (false, TVar(v,Some({ eexpr = TUnop((Increment | Decrement as unop),post_fix,({eexpr = TLocal _ | TField({eexpr = TConst TThis},_)} as ve))} as e1))) ->
let one = {e1 with eexpr = TConst (TInt (Int32.of_int 1))} in
let op = if unop = Increment then OpAdd else OpSub in
let inc = {e1 with eexpr = TBinop(op,ve,one)} in
let inc_assign = {e1 with eexpr = TBinop(OpAssign,ve,inc)} in
let var_assign = {e1 with eexpr = TVar(v,Some ve)} in
if post_fix = Postfix then
lift true [var_assign] inc_assign
else
lift true [inc_assign] var_assign
| (_,TVar(v,eo)) ->
transform_var_expr ae eo v
| (_,TFor(v,e1,e2)) ->
let a1 = trans true [] e1 in
let a2 = to_expr (trans false [] e2) in
let name = (ae.a_next_id ()) in
let t_var = alloc_var name e1.etype in
let mk_local v p = { eexpr = TLocal v; etype = v.v_type; epos = p } in
let ev = mk_local t_var e1.epos in
let ehasnext = mk (TField(ev,quick_field e1.etype "hasNext")) (tfun [] (!t_bool) ) e1.epos in
let ehasnext = mk (TCall(ehasnext,[])) ehasnext.etype ehasnext.epos in
let enext = mk (TField(ev,quick_field e1.etype "next")) (tfun [] v.v_type) e1.epos in
let enext = mk (TCall(enext,[])) v.v_type e1.epos in
let var_assign = mk (TVar (v,Some enext)) v.v_type a_expr.epos in
let ebody = Type.concat var_assign (a2) in
let var_decl = mk (TVar (t_var,Some a1.a_expr)) (!t_void) e1.epos in
let twhile = mk (TWhile((mk (TParenthesis ehasnext) ehasnext.etype ehasnext.epos),ebody,NormalWhile)) (!t_void) e1.epos in
let blocks = a1.a_blocks @ [var_decl] in
lift_expr ~blocks: blocks twhile
| (_,TReturn None) ->
ae
| (_,TReturn (Some ({eexpr = TFunction f} as ef))) ->
let n = ae.a_next_id() in
let e1 = to_expr (trans false [] f.tf_expr) in
let f = mk (TFunction {
tf_args = f.tf_args;
tf_type = f.tf_type;
tf_expr = e1;
}) ef.etype ef.epos in
let f1 = add_non_locals_to_func f in
let var_n = alloc_var n ef.etype in
let f1_assign = mk (TVar(var_n,Some f1)) !t_void f1.epos in
let var_local = mk (TLocal var_n) ef.etype f1.epos in
let er = mk (TReturn (Some var_local)) t_dynamic ae.a_expr.epos in
lift true [f1_assign] er
| (_,TReturn Some(x)) ->
let x1 = trans true [] x in
(match x1.a_blocks with
| [] ->
lift true [] { ae.a_expr with eexpr = TReturn(Some x1.a_expr) }
| blocks ->
let f = exprs_to_func (blocks @ [x1.a_expr]) (ae.a_next_id()) ae in
lift true f.a_blocks {a_expr with eexpr = TReturn (Some f.a_expr)})
| (_, TParenthesis(e1)) ->
let e1 = trans true [] e1 in
let p = { ae.a_expr with eexpr = TParenthesis(e1.a_expr)} in
lift true e1.a_blocks p
| (_, TEnumParameter(e1,ef,i)) ->
let e1 = trans true [] e1 in
let p = { ae.a_expr with eexpr = TEnumParameter(e1.a_expr,ef,i)} in
lift true e1.a_blocks p
| (true, TIf(econd, eif, eelse)) ->
(let econd1 = trans true [] econd in
let eif1 = trans true [] eif in
let eelse1 = match eelse with
| Some x -> Some(trans true [] x)
| None -> None
in
let blocks = [] in
let eif2, blocks =
match eif1.a_blocks with
| [] -> eif1.a_expr, blocks
| x ->
let regular =
let fname = eif1.a_next_id () in
let f = exprs_to_func (List.append eif1.a_blocks [eif1.a_expr]) fname ae in
f.a_expr, List.append blocks f.a_blocks
in
match eif1.a_blocks with
| [{ eexpr = TVar(_, Some({ eexpr = TFunction(_)}))} as b] ->
eif1.a_expr, List.append blocks [b]
| _ -> regular
in
let eelse2, blocks =
match eelse1 with
| None -> None, blocks
| Some({ a_blocks = []} as x) -> Some(x.a_expr), blocks
| Some({ a_blocks = b} as eelse1) ->
let regular =
let fname = eelse1.a_next_id () in
let f = exprs_to_func (List.append eelse1.a_blocks [eelse1.a_expr]) fname ae in
Some(f.a_expr), List.append blocks f.a_blocks
in
match b with
| [{ eexpr = TVar(_, Some({ eexpr = TFunction(f)}))} as b] ->
Some(eelse1.a_expr), List.append blocks [b]
| _ -> regular
in
let blocks = List.append econd1.a_blocks blocks in
let new_if = { ae.a_expr with eexpr = TIf(econd1.a_expr, eif2, eelse2) } in
match blocks with
| [] ->
let meta = Meta.Custom(":ternaryIf"), [], ae.a_expr.epos in
let ternary = { ae.a_expr with eexpr = TMeta(meta, new_if) } in
lift_expr ~blocks:blocks ternary
| b ->
let f = exprs_to_func (List.append blocks [new_if]) (ae.a_next_id ()) ae in
lift_expr ~blocks:f.a_blocks f.a_expr)
| (false, TIf(econd, eif, eelse)) ->
let econd = trans true [] econd in
let eif = to_expr (trans false [] eif) in
let eelse = match eelse with
| Some(x) -> Some(to_expr (trans false [] x))
| None -> None
in
let new_if = { ae.a_expr with eexpr = TIf(econd.a_expr, eif, eelse) } in
lift false econd.a_blocks new_if
| (false, TWhile(econd, e1, NormalWhile)) ->
let econd1 = trans true [] econd in
let e11 = to_expr (trans false [] e1) in
let new_while = mk (TWhile(econd1.a_expr,e11,NormalWhile)) a_expr.etype a_expr.epos in
lift false econd1.a_blocks new_while
| (true, TWhile(econd, ebody, NormalWhile)) ->
let econd = trans true [] econd in
let ebody = to_expr (trans false [] ebody) in
let ewhile = { ae.a_expr with eexpr = TWhile(econd.a_expr, ebody, NormalWhile) } in
let eval = { ae.a_expr with eexpr = TConst(TNull) } in
let f = exprs_to_func (List.append econd.a_blocks [ewhile; eval]) (ae.a_next_id ()) ae in
lift true f.a_blocks f.a_expr
| (false, TWhile(econd, ebody, DoWhile)) ->
let not_expr = { econd with eexpr = TUnop(Not, Prefix, econd) } in
let break_expr = mk TBreak !t_void econd.epos in
let if_expr = mk (TIf(not_expr, break_expr, None)) (!t_void) econd.epos in
let new_e = match ebody.eexpr with
| TBlock(exprs) -> { econd with eexpr = TBlock( List.append exprs [if_expr]) }
| _ -> { econd with eexpr = TBlock( List.append [ebody] [if_expr]) }
in
let true_expr = mk (TConst(TBool(true))) econd.etype ae.a_expr.epos in
let new_expr = { ae.a_expr with eexpr = TWhile( true_expr, new_e, NormalWhile) } in
forward_transform new_expr ae
| (is_value, TSwitch(e, cases, edef)) ->
begin match follow e.etype with
| TInst({cl_path = [],"str"},_) ->
transform_string_switch ae is_value e cases edef
| _ ->
transform_switch ae is_value e cases edef
end
(* anon field access on optional params *)
| (is_value, TField(e,FAnon cf)) when Meta.has Meta.Optional cf.cf_meta ->
let e = dynamic_field_read e cf.cf_name ae.a_expr.etype in
transform_expr ~is_value:is_value e
| (is_value, TBinop(OpAssign,{eexpr = TField(e1,FAnon cf)},e2)) when Meta.has Meta.Optional cf.cf_meta ->
let e = dynamic_field_write e1 cf.cf_name e2 in
transform_expr ~is_value:is_value e
| (is_value, TBinop(OpAssignOp op,{eexpr = TField(e1,FAnon cf); etype = t},e2)) when Meta.has Meta.Optional cf.cf_meta ->
let e = dynamic_field_read_write ae.a_next_id e1 cf.cf_name op e2 t in
transform_expr ~is_value:is_value e
(* TODO we need to deal with Increment, Decrement too!
| (_, TUnop( (Increment | Decrement) as unop, op,{eexpr = TField(e1,FAnon cf)})) when Meta.has Meta.Optional cf.cf_meta ->
let = dynamic_field_read e cf.cf_name in
let e = dynamic_field_read_write_unop ae.a_next_id e1 cf.cf_name unop op in
Printf.printf "dyn read write\n";
transform_expr e
*)
(*
anon field access with non optional members like iterator, length, split must be handled too, we need to Reflect on them too when it's a runtime method
*)
| (is_value, TUnop( (Increment | Decrement) as unop, op, e)) ->
let one = { ae.a_expr with eexpr = TConst(TInt(Int32.of_int(1)))} in
let is_postfix = match op with
| Postfix -> true
| Prefix -> false in
let op = match unop with
| Increment -> OpAdd
| Decrement -> OpSub
| _ -> assert false in
transform_op_assign_op ae e op one is_value is_postfix
| (_, TUnop(op, Prefix, e)) ->
let e1 = trans true [] e in
let r = { a_expr with eexpr = TUnop(op, Prefix, e1.a_expr) } in
lift_expr ~blocks:e1.a_blocks r
| (is_value, TField(e,FDynamic s)) ->
let e = dynamic_field_read e s ae.a_expr.etype in
transform_expr ~is_value:is_value e
| (is_value, TBinop(OpAssign,{eexpr = TField(e1,FDynamic s)},e2)) ->
let e = dynamic_field_write e1 s e2 in
transform_expr ~is_value:is_value e
| (is_value, TBinop(OpAssignOp op,{eexpr = TField(e1,FDynamic s); etype = t},e2)) ->
let e = dynamic_field_read_write ae.a_next_id e1 s op e2 t in
transform_expr ~is_value:is_value e
| (is_value, TField(e1, FClosure(Some ({cl_path = [],("str" | "list")},_),cf))) ->
let e = dynamic_field_read e1 cf.cf_name ae.a_expr.etype in
transform_expr ~is_value:is_value e
| (is_value, TBinop(OpAssign, left, right))->
(let left = trans true [] left in
let right = trans true [] right in
let r = { a_expr with eexpr = TBinop(OpAssign, left.a_expr, right.a_expr)} in
if is_value then
(let blocks = List.concat [left.a_blocks; right.a_blocks; [r]] in
let f = exprs_to_func blocks (ae.a_next_id ()) ae in
lift true f.a_blocks f.a_expr)
else
lift false (List.append left.a_blocks right.a_blocks) r)
| (is_value, TBinop(OpAssignOp(x), left, right)) ->
let right = trans true [] right in
let v = right.a_expr in
let res = transform_op_assign_op ae left x v is_value false in
lift true (List.append right.a_blocks res.a_blocks) res.a_expr
| (_, TBinop(op, left, right))->
(let left = trans true [] left in
let right = trans true [] right in
let r = { a_expr with eexpr = TBinop(op, left.a_expr, right.a_expr)} in
lift false (List.append left.a_blocks right.a_blocks) r)
| (true, TThrow(x)) ->
let block = TBlock([a_expr; { a_expr with eexpr = TConst(TNull) }]) in
let r = { a_expr with eexpr = block } in
forward_transform r ae
| (false, TThrow(x)) ->
let x = trans true [] x in
let r = { a_expr with eexpr = TThrow(x.a_expr)} in
lift false x.a_blocks r
| (_, TNew(c, tp, params)) ->
let params = List.map (trans true []) params in
let blocks = List.flatten (List.map (fun (p) -> p.a_blocks) params) in
let params = List.map (fun (p) -> p.a_expr) params in
let e = { a_expr with eexpr = TNew(c, tp, params) } in
lift false blocks e
| (is_value, TCall(e,params)) ->
transform_call is_value e params ae
| (_, TArray(e1, e2)) ->
let e1 = trans true [] e1 in
let e2 = trans true [] e2 in
let r = { a_expr with eexpr = TArray(e1.a_expr, e2.a_expr)} in
let blocks = List.append e1.a_blocks e2.a_blocks in
lift_expr ~blocks:blocks r
| (false, TTry(etry, catches)) ->
let etry = trans false [] etry in
let catches = List.map (fun(v,e) -> v, trans false [] e) catches in
let blocks = List.flatten (List.map (fun (_,e) -> e.a_blocks) catches) in
let catches = List.map (fun(v,e) -> v, e.a_expr) catches in
let r = { a_expr with eexpr = TTry(etry.a_expr, catches)} in
let blocks = List.append etry.a_blocks blocks in
lift false blocks r
| (true, TTry(etry, catches)) ->
let id = ae.a_next_id () in
let temp_var = to_tvar id a_expr.etype in
let temp_var_def = { a_expr with eexpr = TVar(temp_var, None) } in
let temp_local = { a_expr with eexpr = TLocal(temp_var)} in
let mk_temp_assign right = { a_expr with eexpr = TBinop(OpAssign, temp_local, right)} in
let etry = mk_temp_assign etry in
let catches = List.map (fun (v,e)-> v, mk_temp_assign e) catches in
let new_try = { a_expr with eexpr = TTry(etry, catches)} in
let block = [temp_var_def; new_try; temp_local] in
let new_block = { a_expr with eexpr = TBlock(block)} in
forward_transform new_block ae
| (_, TObjectDecl(fields)) ->
let fields = List.map (fun (name,ex) -> name, trans true [] ex) fields in
let blocks = List.flatten (List.map (fun (_,ex) -> ex.a_blocks) fields) in
let fields = List.map (fun (name,ex) -> name, ex.a_expr) fields in
let r = { a_expr with eexpr = (TObjectDecl(fields) )} in
lift_expr ~blocks r
| (_, TArrayDecl(values)) ->
let values = List.map (trans true []) values in
let blocks = List.flatten (List.map (fun (v) -> v.a_blocks) values) in
let exprs = List.map (fun (v) -> v.a_expr) values in
let r = { a_expr with eexpr = TArrayDecl exprs } in
lift_expr ~blocks:blocks r
| (is_value, TCast(e1,Some mt)) ->
let e = Codegen.default_cast ~vtmp:(ae.a_next_id()) (match !como with Some com -> com | None -> assert false) e1 mt ae.a_expr.etype ae.a_expr.epos in
transform_expr ~is_value:is_value e
| (is_value, TCast(e,None)) ->
let e = trans is_value [] e in
let r = { a_expr with eexpr = TCast(e.a_expr, None)} in
lift_expr ~blocks:e.a_blocks r
| (_, TField(e,f)) ->
let e = trans true [] e in
let r = { a_expr with eexpr = TField(e.a_expr, f) } in
lift_expr ~blocks:e.a_blocks r
| (is_value, TMeta(m, e)) ->
let e = trans is_value [] e in
let r = { a_expr with eexpr = TMeta(m, e.a_expr); etype = e.a_expr.etype } in
lift_expr ~blocks:e.a_blocks r
| ( _, TLocal _ ) -> lift_expr a_expr
| ( _, TConst _ ) -> lift_expr a_expr
| ( _, TTypeExpr _ ) -> lift_expr a_expr
| ( _, TUnop _ ) -> assert false
| ( true, TWhile(econd, ebody, DoWhile) ) ->
let new_expr = trans false [] a_expr in
let f = exprs_to_func (new_expr.a_blocks @ [new_expr.a_expr]) (ae.a_next_id()) ae in
lift_expr ~is_value:true ~blocks:f.a_blocks f.a_expr
| ( _, TBreak ) | ( _, TContinue ) ->
lift_expr a_expr
and transform e =
to_expr (transform1 (lift_expr e))
and forward_transform e base =
transform1 (lift_expr1 base.a_is_value base.a_next_id base.a_blocks e)
let transform_to_value e =
to_expr (transform1 (lift_expr e ~is_value:true))
end
module Printer = struct
type print_context = {
pc_indent : string;
pc_next_anon_func : unit -> string;
pc_debug : bool;
pc_com : Common.context;
}
let has_feature pctx = Common.has_feature pctx.pc_com
let add_feature pctx = Common.add_feature pctx.pc_com
let create_context =
let n = ref (-1) in
(fun indent com debug -> {
pc_indent = indent;
pc_next_anon_func = (fun () -> incr n; Printf.sprintf "anon_%i" !n);
pc_debug = debug;
pc_com = com;
}
)
let tabs = ref ""
let opt o f s = match o with
| None -> ""
| Some v -> s ^ (f v)
(* TODO: both of these are crazy *)
let is_type p t =
(fun r ->
let x = t_infos r in
(String.concat "." (fst x.mt_path)) = p && (snd x.mt_path) = t
)
let is_type1 p s =
(fun t -> match follow t with