-
-
Notifications
You must be signed in to change notification settings - Fork 646
/
genphp7.ml
3398 lines (3308 loc) · 107 KB
/
genphp7.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
(**
Compatible with PHP 7+
*)
open Ast
open Type
open Common
open Meta
open Globals
let debug = ref false
(**
Escape string for constant strings generation.
Copy-pasted from genphp.
*)
let escape_bin s =
let b = Buffer.create 0 in
for i = 0 to String.length s - 1 do
match Char.code (String.unsafe_get s i) with
| c when c = Char.code('\\') || c = Char.code('"') || c = Char.code('$') ->
Buffer.add_string b "\\";
Buffer.add_char b (Char.chr c)
| c when c < 32 ->
Buffer.add_string b (Printf.sprintf "\\x%.2X" c)
| c ->
Buffer.add_char b (Char.chr c)
done;
Buffer.contents b
(**
Write resources passed to compiler via `-resource` flag
Copy-pasted from genphp
*)
let write_resource dir name data =
let rdir = dir ^ "/res" in
if not (Sys.file_exists dir) then Unix.mkdir dir 0o755;
if not (Sys.file_exists rdir) then Unix.mkdir rdir 0o755;
let name = Codegen.escape_res_name name false in
let ch = open_out_bin (rdir ^ "/" ^ name) in
output_string ch data;
close_out ch
(**
Get list of keys in Hashtbl
*)
let hashtbl_keys tbl = Hashtbl.fold (fun key _ lst -> key :: lst) tbl []
(**
@return List of items in `list1` which `list2` does not contain
*)
let diff_lists list1 list2 = List.filter (fun x -> not (List.mem x list2)) list1
(**
Type path for native PHP Exception class
*)
let native_exception_path = ([], "Throwable")
(**
Type path for Haxe exceptions wrapper
*)
let hxexception_type_path = (["php"; "_Boot"], "HxException")
(**
Type path of `php.Boot`
*)
let boot_type_path = (["php"], "Boot")
(**
Type path of the base class for all enums: `php.Boot.HxEnum`
*)
let hxenum_type_path = (["php"; "_Boot"], "HxEnum")
(**
Type path of the implementation class for `Class<Dynamic>`
*)
let hxclass_type_path = (["php"; "_Boot"], "HxClass")
(**
Type path of the implementation class for `String`
*)
let hxstring_type_path = (["php"; "_Boot"], "HxString")
(**
Type path of the special implementation class for `String`
which is used when Dynamic value is suspected to be a string
*)
let hxdynamicstr_type_path = (["php"; "_Boot"], "HxDynamicStr")
(**
Type path of the implementation class for anonymous objects
*)
let hxanon_type_path = (["php"; "_Boot"], "HxAnon")
(**
Type path of the implementation class for closures
*)
let hxclosure_type_path = (["php"; "_Boot"], "HxClosure")
(**
Type path for special PHP extern class to support specific language expressions
*)
let syntax_type_path = (["php"], "Syntax")
(**
Special abstract which enables passing function arguments and return value by reference
*)
let ref_type_path = (["php"], "Ref")
(**
Type path of the implementation class for `Array<T>`
*)
let array_type_path = ([], "Array")
(**
Type path of the implementation class for `Array<T>`
*)
let native_array_type_path = (["php"], "NativeArray")
(**
Type path of the `Void`
*)
let void_type_path = ([], "Void")
(**
Type path of the `Bool`
*)
let bool_type_path = ([], "Bool")
(**
Stub to use when you need a `Ast.pos` instance, but don't have one
*)
let dummy_pos = { pfile = ""; pmin = 0; pmax = 0 }
(**
Check if specified string is a reserved word in PHP
*)
let is_keyword str =
match String.lowercase str with
| "__halt_compiler" | "abstract" | "and" | "array" | "as" | "break" | "callable" | "case" | "catch" | "class"
| "clone" | "const" | "continue" | "declare" | "default" | "die" | "do" | "echo" | "else" | "elseif" | "empty"
| "enddeclare" | "endfor" | "endforeach" | "endif" | "endswitch" | "endwhile" | "eval" | "exit" | "extends"
| "final" | "finally" | "for" | "foreach" | "function" | "global" | "goto" | "if" | "implements" | "include"
| "include_once" | "instanceof" | "insteadof" | "interface" | "isset" | "list" | "namespace" | "new" | "or"
| "print" | "private" | "protected" | "public" | "require" | "require_once" | "return" | "static" | "switch"
| "throw" | "trait" | "try" | "unset" | "use" | "var" | "while" | "xor" | "yield" | "__class__" | "__dir__"
| "__file__" | "__function__" | "__line__" | "__method__" | "__trait__" | "__namespace__" | "int" | "float"
| "bool" | "string" | "true" | "false" | "null" | "parent" | "void" | "iterable"
-> true
| _ -> false
(**
Check if specified type is Void
*)
let is_void_type t = match follow t with TAbstract ({ a_path = void_type_path }, _) -> true | _ -> false
(**
Check if specified type is Bool
*)
let is_bool_type t = match follow t with TAbstract ({ a_path = bool_type_path }, _) -> true | _ -> false
(**
Check if specified type is php.NativeArray
*)
let is_native_array_type t = match follow t with TAbstract ({ a_path = native_array_type_path }, _) -> true | _ -> false
(**
If `name` is not a reserved word in PHP then `name` is returned as-is.
Otherwise this method returns another string, which can be used instead of `name`
*)
let get_real_name name = if is_keyword name then name ^ "_hx" else name
(**
If `path` contains some reserved in PHP words, they will be replaced with allowed words.
*)
let get_real_path path = List.map get_real_name path
(**
Resolve real type (bypass abstracts and typedefs)
*)
let rec follow = Abstract.follow_with_abstracts
let prefix = ref None
(**
Returns value of `--php-prefix` compiler flag
*)
let get_php_prefix ctx =
match !prefix with
| Some prefix -> prefix
| None ->
let lst =
match ctx.php_prefix with
| None -> []
| Some str ->
if String.length str = 0 then
[]
else
Str.split (Str.regexp "\\.") str
in
prefix := Some lst;
lst
(**
Adds packages specified by `--php-prefix` to `type_path`.
E.g. if `--php-prefix some.sub` and `type_path` is `(["pack"], "MyClass")`, then this function
will return `(["some", "sub", "pack"], "MyClass")`
*)
let add_php_prefix ctx type_path =
match type_path with
| (pack, name) -> ((get_php_prefix ctx) @ pack, name)
(**
If `expr` is a TCast or TMeta, then returns underlying expression (recursively bypassing nested casts).
Otherwise returns `expr` as is.
*)
let rec reveal_expr expr =
match expr.eexpr with
| TCast (e, _) -> reveal_expr e
| TMeta (_, e) -> reveal_expr e
| _ -> expr
(**
@return Error message with position information
*)
let error_message pos message = (Lexer.get_error_pos (Printf.sprintf "%s:%d:") pos) ^ ": " ^ message
(**
Terminates compiler process and prints user-friendly instructions about filing an issue in compiler repo.
*)
let fail hxpos mlpos =
match mlpos with
| (file, line, _) ->
Printf.printf "%s\n" (error_message hxpos "Unexpected expression. Please submit an issue with expression example and following information:");
Printf.printf "%s:%d\n" file line;
assert false
(**
Print compilation error message and abort compilation process.
*)
let error_and_exit pos message =
Printf.printf "%s" (error_message pos message);
exit 1
(**
Check if `target` is a `Dynamic` type
*)
let rec is_dynamic_type (target:Type.t) = match follow target with TDynamic _ -> true | _ -> false
(**
Check if `target` is `php.Ref`
*)
let is_ref (target:Type.t) = match target with TType ({ t_path = type_path }, _) -> type_path = ref_type_path | _ -> false
(**
Check if `field` is a `dynamic function`
*)
let rec is_dynamic_method (field:tclass_field) =
match field.cf_kind with
| Method MethDynamic -> true
| _ -> false
(**
Check if specified expression is of `Dynamic` type
*)
let is_dynamic expr = is_dynamic_type expr.etype
(**
Check if specified expression is of `Int` type
*)
let is_int expr = match follow expr.etype with TAbstract ({ a_path = ([], "Int") }, _) -> true | _ -> false
(**
Check if specified expression is of `Float` type
*)
let is_float expr = match follow expr.etype with TAbstract ({ a_path = ([], "Float") }, _) -> true | _ -> false
(**
Check if specified type is String
*)
let is_string_type t = match follow t with TInst ({ cl_path = ([], "String") }, _) -> true | _ -> false
(**
Check if specified expression is of String type
*)
let is_string expr = is_string_type expr.etype
(**
Check if `expr` is an access to a method of special `php.PHP` class
*)
let is_lang_extern expr =
match expr.eexpr with
| TField ({ eexpr = TTypeExpr (TClassDecl { cl_path = path }) }, _) when path = syntax_type_path -> true
| _ -> false
(**
Check if specified type is actually a generic parameter
*)
let is_generic_parameter (target:Type.t) =
match follow target with
| TInst ({ cl_kind = KTypeParameter _ }, _) -> true
| _ -> false
(**
Check if `target` type cannot be clarified on compilation
*)
let is_unknown_type (target:Type.t) = is_dynamic_type target || is_generic_parameter target
(**
@return `Type.t` instance for `Void`
*)
let void = ref None
let get_void ctx : Type.t =
match !void with
| Some value -> value
| None ->
let find com_type =
match com_type with
| TAbstractDecl ({ a_path = ([], "Void") } as abstr) -> void := Some (TAbstract (abstr, []));
| _ -> ()
in
List.iter find ctx.types;
match !void with
| Some value -> value
| None -> fail dummy_pos (try assert false with Assert_failure mlpos -> mlpos)
(**
@return `tclass` instance for `php.Boot`
*)
let boot = ref None
let get_boot ctx : tclass =
match !boot with
| Some value -> value
| None ->
let find com_type =
match com_type with
| TClassDecl ({ cl_path = path } as cls) when path = boot_type_path -> boot := Some cls;
| _ -> ()
in
List.iter find ctx.types;
match !boot with
| Some value -> value
| None -> fail dummy_pos (try assert false with Assert_failure mlpos -> mlpos)
(**
@return `expr` wrapped in parenthesis
*)
let parenthesis expr = {eexpr = TParenthesis expr; etype = expr.etype; epos = expr.epos}
(**
Check if `current` binary should be surrounded with parenthesis
*)
let need_parenthesis_for_binop current parent =
if current = parent then
false
else
match (current, parent) with
| (_, OpAssign) -> false
| (_, OpAssignOp _) -> false
| (OpAdd, OpSub) -> false
| (OpSub, OpAdd) -> false
| (OpMult, OpDiv) -> false
| (OpDiv, OpMult) -> false
| (OpMult, OpAdd) -> false
| (OpMult, OpSub) -> false
| (OpDiv, OpAdd) -> false
| (OpDiv, OpSub) -> false
| _ -> true
(**
Check if specified expression may require dereferencing if used as "temporary expression"
*)
let needs_dereferencing expr =
let rec is_create target_expr =
match target_expr.eexpr with
| TParenthesis e -> is_create e
| TCast (e, _) -> is_create e
| TNew _ -> true
| TArrayDecl _ -> true
| TObjectDecl _ -> true
| TConst TNull -> true
(* some of `php.Syntax` methods *)
| TCall ({ eexpr = TField (_, FStatic ({ cl_path = syntax_type_path }, { cf_name = name })) }, _) ->
(match name with
| "binop" | "object" | "array" -> true
| _ -> false
)
| _ -> false
in
match expr.eexpr with
| TField (target_expr, _) -> is_create target_expr
| TArray (target_expr, _) -> is_create target_expr
| _ -> false
(**
@return (arguments_list, return_type)
*)
let get_function_signature (field:tclass_field) : (string * bool * Type.t) list * Type.t =
match follow field.cf_type with
| TFun (args, return_type) -> (args, return_type)
| _ -> fail field.cf_pos (try assert false with Assert_failure mlpos -> mlpos)
(**
Check if `target` is 100% guaranteed to be a scalar type in PHP.
Inversion of `is_sure_scalar` does not guarantee `target` is not scalar.
*)
let is_sure_scalar (target:Type.t) =
match follow target with
| TInst ({ cl_path = ([], "String") }, _) -> true
| TAbstract (abstr, _) ->
(match abstr.a_path with
| ([],"Int") -> true
| ([],"Float") -> true
| ([],"Bool") -> true
| _ -> false
)
| _ -> false
(**
Indicates if `expr` is guaranteed to be an access to a `var` field.
*)
let is_sure_var_field_access expr =
match (reveal_expr expr).eexpr with
| TField (_, FStatic (_, { cf_kind = Var _ })) -> true
| TField (_, FInstance (_, _, { cf_kind = Var _ })) -> true
(* | TField (_, FAnon { cf_kind = Var _ }) -> true *) (* Sometimes we get anon access to non-anonymous objects *)
| _ -> false
(**
Check if specified unary operation modifies value in place
*)
let is_modifying_unop op =
match op with
| Increment
| Decrement -> true
| _ -> false
(**
Indicates whether `expr` is a field access which should be generated as global namespace function
*)
let is_php_global expr =
match expr.eexpr with
| TField (_, FStatic ({ cl_extern = true; cl_meta = meta }, _)) -> Meta.has Meta.PhpGlobal meta
| _ -> false
(**
Indicates whether `expr` is a field access which should be generated as class constant access
*)
let is_php_class_const expr =
match expr.eexpr with
| TField (_, FStatic ({ cl_extern = true }, { cf_meta = meta; cf_kind = Var _ })) ->
Meta.has Meta.PhpClassConst meta
| _ -> false
(**
Check if specified enum constructor has arguments
*)
let is_enum_constructor_with_args (constructor:tenum_field) =
match follow constructor.ef_type with
| TFun _ -> true
| _ -> false
(**
Check if `target` is 100% guaranteed to be or extend an extern class.
Inversion of `sure_extends_extern` does not guarantee `target` does not extend an extern class.
*)
let rec sure_extends_extern (target:Type.t) =
match follow target with
| TInst ({ cl_path = ([], "String") }, _) -> false
| TInst ({ cl_extern = true }, _) -> true
| TInst ({ cl_super = Some (tsuper, params) }, _) -> sure_extends_extern (TInst (tsuper,params))
| _ -> false
(**
@return `opt` value or `default` if `opt` is None
*)
let get_option_value (opt:'a option) default =
match opt with
| None -> default
| Some value -> value
(**
@param path Something like [ "/some/path/first_dir_to_create"; "nested_level1"; "nested_level2" ]
@return String representation of created path (E.g. "/some/path/first_dir_to_create/nested_level1/nested_level2")
*)
let create_dir_recursive (path:string list) =
let rec create dir nested_dirs =
if not (Sys.file_exists dir) then (Unix.mkdir dir 0o755);
match nested_dirs with
| [] -> ();
| next :: rest -> create (dir ^ "/" ^ next) rest
in
match path with
| [] -> "";
| root :: rest ->
create root rest;
(String.concat "/" path)
(**
@return String representation of specified type path. E.g. returns "\example\Test" for (["example"], "Test")
*)
let get_full_type_name ?escape ?omit_first_slash (type_path:path) =
let name =
match type_path with
| (module_path, type_name) ->
let parts =
match omit_first_slash with
| Some true -> get_real_path module_path
| _ -> "" :: get_real_path module_path
in
(String.concat "\\" parts) ^ "\\" ^ type_name
in
match escape with
| Some true -> String.escaped name
| _ -> name
(**
Check if `target` is or implements native PHP `Throwable` interface
*)
let rec is_native_exception (target:Type.t) =
match follow target with
| TInst ({ cl_path = path }, _) when path = native_exception_path -> true
| TInst ({ cl_super = parent ; cl_implements = interfaces ; cl_path = path }, _) ->
let (parent, params) =
match parent with
| Some (parent, params) -> (Some parent, params)
| None -> (None, [])
in
let found = ref false in
List.iter
(fun (cls, params) ->
if not !found then
found := is_native_exception (TInst (cls, params))
)
interfaces;
if !found then
true
else
(match parent with
| Some parent -> is_native_exception (TInst (parent, params))
| None -> false
)
| _ -> false
(**
@return Short type name. E.g. returns "Test" for (["example"], "Test")
*)
let get_type_name (type_path:path) = match type_path with (_, type_name) -> type_name
(**
@return E.g. returns ["example"] for (["example"], "Test")
*)
let get_module_path (type_path:path) = match type_path with (module_path, _) -> module_path
(**
@return PHP visibility keyword.
*)
let get_visibility (meta:metadata) = if Meta.has Meta.Protected meta then "protected" else "public"
(**
Writes arguments list to output buffer
*)
let rec write_args buffer arg_writer (args:'a) =
match args with
| [] -> ()
| [arg] -> arg_writer arg
| arg :: rest ->
arg_writer arg;
Buffer.add_string buffer ", ";
write_args buffer arg_writer rest
(**
Check if specified field is a var with non-constant expression
*)
let is_var_with_nonconstant_expr (field:tclass_field) =
match field.cf_kind with
| Var _ ->
(match field.cf_expr with
| None -> false
| Some ({eexpr = TConst _ }) -> false
| Some _ -> true
)
| Method _ -> false
(**
@return New TBlock expression which is composed of setting default values for optional arguments and function body.
*)
let inject_defaults (ctx:Common.context) (func:tfunc) =
let rec inject args body_exprs =
match args with
| [] -> body_exprs
| (_, None) :: rest -> inject rest body_exprs
| (_, Some TNull) :: rest -> inject rest body_exprs
| (var, Some const) :: rest ->
let expr = Codegen.set_default ctx var const func.tf_expr.epos in
expr :: (inject rest body_exprs)
in
let exprs =
match func.tf_expr.eexpr with
| TBlock exprs -> inject func.tf_args exprs
| _ -> inject func.tf_args [ func.tf_expr ]
in
{
eexpr = TBlock exprs;
etype = follow func.tf_expr.etype;
epos = func.tf_expr.epos;
}
(**
Check if `expr` is a constant string
*)
let is_constant_string expr =
match expr.eexpr with
| TConst (TString _) -> true
| _ -> false
(**
Check if `expr` is a constant null
*)
let is_constant_null expr =
match expr.eexpr with
| TConst TNull -> true
| _ -> false
(**
Check if `expr` is a constant
*)
let is_constant expr =
match expr.eexpr with
| TConst _ -> true
| _ -> false
(**
Check if `expr` is a concatenation
*)
let is_concatenation expr =
match expr.eexpr with
| TBinop (OpAdd, expr1, expr2) -> (is_string expr1) || (is_string expr2)
| _ -> false
(**
Check if provided expression is a binary operation
*)
let is_binop expr = match expr.eexpr with TBinop _ -> true | _ -> false
(**
Check if provided expression is an assignment binary operation
*)
let is_binop_assign expr =
match expr.eexpr with
| TBinop (operation, _, _) ->
(match operation with
| OpAssign | OpAssignOp _ -> true
| _ -> false
)
| _ -> false
(**
Check if specified expression is field access or array access
*)
let is_access expr =
match expr.eexpr with
| TField _ | TArray _ -> true
| _ -> false
(**
Indicates if `expr` is actually a call to Haxe->PHP magic function
@see http://old.haxe.org/doc/advanced/magic#php-magic
*)
let is_magic expr =
match expr.eexpr with
| TCall ({ eexpr = TLocal { v_name = name }}, _) ->
(match name with
| "__php__" -> true
| "__call__" -> true
| "__physeq__" -> true
| "__var__" -> true
| _ -> false
)
| _ -> false
(**
Check if `expr1` and `expr2` can be reliably checked for equality only with `Boot.equal()`
*)
let need_boot_equal expr1 expr2 =
if is_constant_null expr1 || is_constant_null expr2 then
false
else
(is_int expr1 && (is_float expr2 || is_unknown_type expr2.etype))
|| (is_float expr1 && (is_float expr2 || is_int expr2 || is_unknown_type expr2.etype))
|| (is_unknown_type expr1.etype && (is_int expr2 || is_float expr2))
|| (is_unknown_type expr1.etype && is_unknown_type expr2.etype)
(**
Adds `return` expression to block if it does not have one already
*)
let ensure_return_in_block block_expr =
match block_expr.eexpr with
| TBlock [] -> fail block_expr.epos (try assert false with Assert_failure mlpos -> mlpos)
| TBlock exprs ->
let reversed = List.rev exprs in
let last_expr = List.hd reversed in
let return_expr = { last_expr with eexpr = TReturn (Some last_expr) } in
let reversed = return_expr::(List.tl reversed) in
{ block_expr with eexpr = TBlock (List.rev reversed) }
| _ -> fail block_expr.epos (try assert false with Assert_failure mlpos -> mlpos)
(**
If `expr` is a block, then return list of expressions in that block.
Otherwise returns a list with `expr` as a single item.
*)
let unpack_block expr =
match expr.eexpr with
| TBlock exprs -> exprs
| _ -> [ expr ]
(**
If `expr` is a block of a single expression, then return that single expression.
If `expr` is a block with multiple expressions, fail compilation.
Otherwise return `expr` as-is.
*)
let unpack_single_expr_block expr =
match expr.eexpr with
| TBlock [ e ] -> e
| TBlock _ -> fail expr.epos (try assert false with Assert_failure mlpos -> mlpos)
| _ -> expr
(**
Check if specified type has rtti meta
*)
let has_rtti_meta ctx mtype =
match Codegen.build_metadata ctx mtype with
| None -> false
| Some _ -> true
(**
Check if this var accesses and meta combination should generate a variable
*)
let is_real_var field =
if Meta.has IsVar field.cf_meta then
true
else
match field.cf_kind with
| Var { v_read = read; v_write = write } -> read = AccNormal || write = AccNormal
| _ -> false
(**
Check if user-defined field has the same name as one of php magic methods, but with not compatible signature.
*)
let field_needs_rename field =
match field.cf_kind with
| Var _ -> false
| Method _ ->
match field.cf_name with
| "__construct" | "__destruct" | "__call" | "__callStatic" | "__get" | "__set" | "__isset"
| "__unset" | "__sleep" | "__wakeup" | "__toString" | "__invoke" | "__set_state" | "__clone"
| "__debugInfo" -> not (Meta.has Meta.PhpMagic field.cf_meta)
| _ -> false
(**
Get valid `field` name.
*)
let field_name field =
if field_needs_rename field then
"__hx__renamed" ^ field.cf_name
else
field.cf_name
(**
PHP DocBlock types
*)
type doc_type =
| DocVar of string * (string option) (* (type name, description) *)
| DocMethod of (string * bool * t) list * t * (string option) (* (arguments, return type, description) *)
| DocClass of string option
(**
Common interface for module_type instances
*)
class virtual type_wrapper (type_path:path) (meta:metadata) (needs_generation:bool) =
object (self)
(**
Indicates if this type should be rendered to corresponding php file
*)
method needs_generation = needs_generation
(**
Indicates if class initialization method should be executed upon class loaded
*)
method virtual needs_initialization : bool
(**
Returns hx source file name where this type was declared
*)
method virtual get_source_file : string
(**
Returns `Type.module_type` instance for this type
*)
method virtual get_module_type : module_type
(**
Returns expression of a user-defined static __init__ method
@see http://old.haxe.org/doc/advanced/magic#initialization-magic
*)
method get_magic_init : texpr option = None
(**
Namespace path. E.g. ["some"; "pack"] for "some.pack.MyType"
*)
method get_namespace = get_module_path type_path
(**
Short type name. E.g. `SomeType` for `pack.SomeType`
*)
method get_name = get_type_name type_path
(**
Full type path
*)
method get_type_path = type_path
end
(**
TClassDecl
*)
class class_wrapper (cls) =
object (self)
inherit type_wrapper cls.cl_path cls.cl_meta (not cls.cl_extern)
(**
Indicates if class initialization method should be executed upon class loaded
*)
method needs_initialization =
(* Interfaces may need initialization only for RTTI meta data.
But that meta is written in `class_wrapper#write_rtti_meta` *)
if cls.cl_interface then
false
else
match cls.cl_init with
| Some _ -> true
| None ->
let needs = ref false in
PMap.iter
(fun _ field ->
(* Check static vars with non-constant expressions *)
if not !needs then needs := is_var_with_nonconstant_expr field;
(* Check static dynamic functions *)
if not !needs then needs := is_dynamic_method field
)
cls.cl_statics;
!needs
(**
Returns expression of a user-defined static __init__ method
@see http://old.haxe.org/doc/advanced/magic#initialization-magic
*)
method get_magic_init = cls.cl_init
(**
Returns hx source file name where this type was declared
*)
method get_source_file = cls.cl_pos.pfile
(**
Returns `Type.module_type` instance for this type
*)
method get_module_type = TClassDecl cls
end
(**
TEnumDecl
*)
class enum_wrapper (enm) =
object (self)
inherit type_wrapper enm.e_path enm.e_meta (not enm.e_extern)
(**
Indicates if class initialization method should be executed upon class loaded
*)
method needs_initialization = false
(**
Returns hx source file name where this type was declared
*)
method get_source_file = enm.e_pos.pfile
(**
Returns `Type.module_type` instance for this type
*)
method get_module_type = TEnumDecl enm
end
(**
TTypeDecl
*)
class typedef_wrapper (tdef) =
object (self)
inherit type_wrapper tdef.t_path tdef.t_meta false
(**
Indicates if class initialization method should be executed upon class loaded
*)
method needs_initialization = false
(**
Returns hx source file name where this type was declared
*)
method get_source_file = tdef.t_pos.pfile
(**
Returns `Type.module_type` instance for this type
*)
method get_module_type = TTypeDecl tdef
end
(**
TAbstractDecl
*)
class abstract_wrapper (abstr) =
object (self)
inherit type_wrapper abstr.a_path abstr.a_meta false
(**
Indicates if class initialization method should be executed upon class loaded
*)
method needs_initialization = false
(**
Returns hx source file name where this type was declared
*)
method get_source_file = abstr.a_pos.pfile
(**
Returns `Type.module_type` instance for this type
*)
method get_module_type = TAbstractDecl abstr
end
(**
type_wrapper for classes
*)
let classes = Hashtbl.create 1000
let get_class_wrapper cls : type_wrapper =
try
let wrapper = Hashtbl.find classes cls in
wrapper
with
| Not_found ->
let wrapper = new class_wrapper cls in
Hashtbl.add classes cls wrapper;
wrapper
| e -> raise e
(**
type_wrapper for enums
*)
let enums = Hashtbl.create 200
let get_enum_wrapper enm : type_wrapper=
try
let wrapper = Hashtbl.find enums enm in
wrapper
with
| Not_found ->
let wrapper = new enum_wrapper enm in
Hashtbl.add enums enm wrapper;
wrapper
| e -> raise e
(**
type_wrapper for typedefs
*)
let typedefs = Hashtbl.create 200
let get_typedef_wrapper typedef : type_wrapper =
try
let wrapper = Hashtbl.find typedefs typedef in
wrapper
with
| Not_found ->
let wrapper = new typedef_wrapper typedef in
Hashtbl.add typedefs typedef wrapper;
wrapper
| e -> raise e
(**
type_wrapper for abstracts
*)
let abstracts = Hashtbl.create 200
let get_abstract_wrapper abstr : type_wrapper =
try
let wrapper = Hashtbl.find abstracts abstr in
wrapper
with
| Not_found ->
let wrapper = new abstract_wrapper abstr in
Hashtbl.add abstracts abstr wrapper;
wrapper
| e -> raise e
(**
Returns wrapper for module_type.
Caches wrappers so that each type will always return the same wrapper instance.
*)
let get_wrapper (mtype:module_type) : type_wrapper =
match mtype with
| TClassDecl cls -> get_class_wrapper cls
| TEnumDecl enm -> get_enum_wrapper enm
| TTypeDecl typedef -> get_typedef_wrapper typedef
| TAbstractDecl abstr -> get_abstract_wrapper abstr
(**
Drop cached instances of type_wrapper
*)
let clear_wrappers () =
Hashtbl.clear classes;
Hashtbl.clear enums;
Hashtbl.clear typedefs;
Hashtbl.clear abstracts
(**
Check if specified type name is used in specified namespace
*)
let namespaces_types_cache = Hashtbl.create 512
let type_name_used_in_namespace ctx name namespace =
let types = Hashtbl.find_all namespaces_types_cache namespace in
match types with
| [] ->
List.iter
(fun ctx_type ->
let wrapper = get_wrapper ctx_type in
Hashtbl.add namespaces_types_cache wrapper#get_namespace wrapper#get_name
)
ctx.types;
let types = Hashtbl.find_all namespaces_types_cache namespace in
List.mem name types
| _ ->