forked from HaxeFoundation/haxe
-
Notifications
You must be signed in to change notification settings - Fork 1
/
genphp.ml
2335 lines (2180 loc) · 64.3 KB
/
genphp.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)2005-2013 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*)
open Ast
open Type
open Common
type method_name = {
mutable mpath : path;
mutable mname : string;
}
type inline_method = {
iname : string;
iindex : int;
iexpr : texpr;
ihasthis : bool;
iin_block : bool;
iarguments : string list;
ilocals : (string,string) PMap.t;
iinv_locals : (string,string) PMap.t;
}
type context = {
com : Common.context;
ch : out_channel;
buf : Buffer.t;
path : path;
stack : Codegen.stack_context;
mutable nested_loops : int;
mutable inline_index : int;
mutable curclass : tclass;
mutable curmethod : string;
mutable tabs : string;
mutable in_value : string option;
mutable in_loop : bool;
mutable in_block : bool;
mutable in_instance_method : bool;
mutable imports : (string,string list list) Hashtbl.t;
mutable extern_required_paths : (string list * string) list;
mutable extern_classes_with_init : path list;
mutable locals : (string,string) PMap.t;
mutable inv_locals : (string,string) PMap.t;
mutable local_types : t list;
mutable inits : texpr list;
mutable constructor_block : bool;
mutable all_dynamic_methods: method_name list;
mutable dynamic_methods: tclass_field list;
mutable is_call : bool;
mutable cwd : string;
mutable inline_methods : inline_method list;
mutable lib_path : string;
}
let join_class_path path separator =
let result = match fst path, snd path with
| [], s -> s
| el, s -> String.concat separator el ^ separator ^ s in
if (String.contains result '+') then begin
let idx = String.index result '+' in
(String.sub result 0 idx) ^ (String.sub result (idx+1) ((String.length result) - idx -1 ) )
end else
result;;
(* Get a string to represent a type.
The "suffix" will be nothing or "_obj", depending if we want the name of the
pointer class or the pointee (_obj class *)
let rec class_string klass suffix params =
(match klass.cl_path with
(* Array class *)
| ([],"Array") -> (snd klass.cl_path) ^ suffix ^ "<" ^ (String.concat ","
(List.map type_string params) ) ^ " >"
| _ when (match klass.cl_kind with KTypeParameter _ -> true | _ -> false) -> "Dynamic"
| ([],"#Int") -> "/* # */int"
| (["haxe";"io"],"Unsigned_char__") -> "unsigned char"
| ([],"Class") -> "Class"
| ([],"Null") -> (match params with
| [t] ->
(match follow t with
| TInst ({ cl_path = [],"Int" },_)
| TInst ({ cl_path = [],"Float" },_)
| TEnum ({ e_path = [],"Bool" },_) -> "Dynamic"
| _ -> "/*NULL*/" ^ (type_string t) )
| _ -> assert false);
(* Normal class *)
| _ -> (join_class_path klass.cl_path "::") ^ suffix
)
and type_string_suff suffix haxe_type =
(match haxe_type with
| TMono r -> (match !r with None -> "Dynamic" | Some t -> type_string_suff suffix t)
| TAbstract ({ a_path = [],"Int" },[]) -> "int"
| TAbstract ({ a_path = [],"Float" },[]) -> "double"
| TAbstract ({ a_path = [],"Bool" },[]) -> "bool"
| TAbstract ({ a_path = [],"Void" },[]) -> "Void"
| TEnum ({ e_path = ([],"Void") },[]) -> "Void"
| TEnum ({ e_path = ([],"Bool") },[]) -> "bool"
| TInst ({ cl_path = ([],"Float") },[]) -> "double"
| TInst ({ cl_path = ([],"Int") },[]) -> "int"
| TEnum (enum,params) -> (join_class_path enum.e_path "::") ^ suffix
| TInst (klass,params) -> (class_string klass suffix params)
| TAbstract (abs,params) -> (join_class_path abs.a_path "::") ^ suffix
| TType (type_def,params) ->
(match type_def.t_path with
| [] , "Null" ->
(match params with
| [t] ->
(match follow t with
| TInst ({ cl_path = [],"Int" },_)
| TInst ({ cl_path = [],"Float" },_)
| TEnum ({ e_path = [],"Bool" },_) -> "Dynamic"
| _ -> type_string_suff suffix t)
| _ -> assert false);
| [] , "Array" ->
(match params with
| [t] -> "Array<" ^ (type_string (follow t) ) ^ " >"
| _ -> assert false)
| _ -> type_string_suff suffix (apply_params type_def.t_types params type_def.t_type)
)
| TFun (args,haxe_type) -> "Dynamic"
| TAnon anon -> "Dynamic"
| TDynamic haxe_type -> "Dynamic"
| TLazy func -> type_string_suff suffix ((!func)())
)
and type_string haxe_type =
type_string_suff "" haxe_type;;
let debug_expression expression type_too =
"/* " ^ Type.s_expr_kind expression ^ (if (type_too) then " = " ^ (type_string (follow expression.etype)) else "") ^ " */";;
let rec register_extern_required_path ctx path =
if (List.exists(fun p -> p = path) ctx.extern_classes_with_init) && not (List.exists(fun p -> p = path) ctx.extern_required_paths) then
ctx.extern_required_paths <- path :: ctx.extern_required_paths
let s_expr_expr = Type.s_expr_kind
let s_expr_name e =
s_type (print_context()) (follow e.etype)
let s_type_name t =
s_type (print_context()) t
and start_with s test =
let len = String.length test in
(String.length s > len && String.sub s 0 len = test)
let rec is_uncertain_type t =
match follow t with
| TInst (c, _) -> c.cl_interface
| TMono _ -> true
| TAnon a ->
(match !(a.a_status) with
| Statics _
| EnumStatics _ -> false
| _ -> true)
| TDynamic _ -> true
| _ -> false
let is_uncertain_expr e =
is_uncertain_type e.etype
let rec is_anonym_type t =
match follow t with
| TAnon a ->
(match !(a.a_status) with
| Statics _
| EnumStatics _ -> false
| _ -> true)
| TDynamic _ -> true
| _ -> false
let is_anonym_expr e = is_anonym_type e.etype
let rec is_unknown_type t =
match follow t with
| TMono r ->
(match !r with
| None -> true
| Some t -> is_unknown_type t)
| _ -> false
let is_unknown_expr e = is_unknown_type e.etype
let rec is_string_type t =
match follow t with
| TInst ({cl_path = ([], "String")}, _) -> true
| TAnon a ->
(match !(a.a_status) with
| Statics ({cl_path = ([], "String")}) -> true
| _ -> false)
| TAbstract (a,pl) -> is_string_type (Codegen.Abstract.get_underlying_type a pl)
| _ -> false
let is_string_expr e = is_string_type e.etype
let to_string ctx e =
let v = alloc_var "__call__" t_dynamic in
let f = mk (TLocal v) t_dynamic e.epos in
mk (TCall (f, [ Codegen.string ctx.com "_hx_string_rec" e.epos; e; Codegen.string ctx.com "" e.epos])) ctx.com.basic.tstring e.epos
let as_string_expr ctx e =
match e.eexpr with
| TConst (TNull) ->
to_string ctx e
| _ when not (is_string_expr e) ->
to_string ctx e
| _ -> e
(* for known String type that could have null value *)
let to_string_null ctx e =
let v = alloc_var "__call__" t_dynamic in
let f = mk (TLocal v) t_dynamic e.epos in
mk (TCall (f, [ Codegen.string ctx.com "_hx_string_or_null" e.epos; e])) ctx.com.basic.tstring e.epos
let as_string_expr ctx e = match e.eexpr with
| TConst (TNull) -> to_string ctx e
| TConst (TString s) -> e
| TBinop (op,_,_) when (is_string_expr e)-> e
| TCall ({eexpr = TField({eexpr = TTypeExpr(TClassDecl {cl_path = ([],"Std")})},FStatic(c,f) )}, [_]) when (f.cf_name="string") -> e
| TCall ({eexpr = TLocal _}, [{eexpr = TConst (TString ("_hx_string_rec" | "_hx_str_or_null"))}]) -> e
| _ when not (is_string_expr e) -> to_string ctx e
| _ -> to_string_null ctx e
let spr ctx s = Buffer.add_string ctx.buf s
let print ctx = Printf.kprintf (fun s -> Buffer.add_string ctx.buf s)
(*--php-prefix - added by skial bainn*)
let prefix_class com name =
match com.php_prefix with
| Some prefix_class (* when not (String.length name <= 2 || String.sub name 0 2 = "__") *) ->
prefix_class ^ name
| _ ->
name
let prefix_init_replace com code =
let r = Str.regexp "php_Boot" in
Str.global_replace r ("php_" ^ (prefix_class com "Boot")) code
let s_path ctx path isextern p =
if isextern then begin
register_extern_required_path ctx path;
snd path
end else begin
(match path with
(*--php-prefix*)
| ([],"List") -> (prefix_class ctx.com "HList")
(*--php-prefix*)
| ([],name) -> (prefix_class ctx.com name)
| (pack,name) ->
(try
(match Hashtbl.find ctx.imports name with
| [p] when p = pack ->
()
| packs ->
if not (List.mem pack packs) then Hashtbl.replace ctx.imports name (pack :: packs))
with Not_found ->
Hashtbl.add ctx.imports name [pack]);
(*--php-prefix*)
String.concat "_" pack ^ "_" ^ (prefix_class ctx.com name))
end
let s_path_haxe path =
match fst path, snd path with
| [], s -> s
| el, s -> String.concat "." el ^ "." ^ s
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('\\') or c = Char.code('"') or 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
(*
haxe reserved words that match php ones: break, case, class, continue, default, do, else, extends, for, function, if, new, return, static, switch, var, while, interface, implements, public, private, try, catch, throw
*)
(* PHP only (for future use): cfunction, old_function *)
let is_keyword n =
match String.lowercase n with
| "and" | "or" | "xor" | "__file__" | "exception" | "__line__" | "array"
| "as" | "const" | "declare" | "die" | "echo"| "elseif" | "empty"
| "enddeclare" | "endfor" | "endforeach" | "endif" | "endswitch"
| "endwhile" | "eval" | "exit" | "foreach"| "global" | "include"
| "include_once" | "isset" | "list" | "namespace" | "print" | "require" | "require_once"
| "unset" | "use" | "__function__" | "__class__" | "__method__" | "final"
| "php_user_filter" | "protected" | "abstract" | "__set" | "__get" | "__call"
| "clone" | "instanceof" | "break" | "case" | "class" | "continue" | "default" | "do" | "else" | "extends" | "for" | "function" | "if" | "new" | "return" | "static" | "switch" | "var" | "while" | "interface" | "implements" | "public" | "private" | "try" | "catch" | "throw" -> true
| "goto"
| _ -> false
let s_ident n =
let suf = "h" in
if (is_keyword n) then (suf ^ n) else n
let s_ident_field n =
if (is_keyword n) then ("{\"" ^ (escape_bin n) ^ "\"}") else n
let s_ident_local n =
let suf = "h" in
match String.lowercase n with
| "globals" | "_server" | "_get" | "_post" | "_cookie" | "_files"
| "_env" | "_request" | "_session" -> suf ^ n
| _ -> n
let create_directory com ldir =
let atm_path = ref (String.create 0) in
atm_path := com.file;
if not (Sys.file_exists com.file) then (Unix.mkdir com.file 0o755);
(List.iter (fun p -> atm_path := !atm_path ^ "/" ^ p; if not (Sys.file_exists !atm_path) then (Unix.mkdir !atm_path 0o755);) ldir)
let write_resource dir name data =
let i = ref 0 in
String.iter (fun c ->
if c = '\\' || c = '/' || c = ':' || c = '*' || c = '?' || c = '"' || c = '<' || c = '>' || c = '|' then String.blit "_" 0 name !i 1;
incr i
) name;
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 ch = open_out_bin (rdir ^ "/" ^ name) in
output_string ch data;
close_out ch
let stack_init com use_add =
Codegen.stack_context_init com "GLOBALS['%s']" "GLOBALS['%e']" "__hx__spos" "tmp" use_add null_pos
let init com cwd path def_type =
let rec create acc = function
| [] -> ()
| d :: l ->
let pdir = String.concat "/" (List.rev (d :: acc)) in
if not (Sys.file_exists pdir) then Unix.mkdir pdir 0o755;
create (d :: acc) l
in
let dir = if cwd <> "" then com.file :: (cwd :: fst path) else com.file :: fst path; in
create [] dir;
let filename path =
prefix_class com (match path with
| [], "List" -> "HList";
| _, s -> s) in
(*--php-prefix*)
let ch = open_out (String.concat "/" dir ^ "/" ^ (filename path) ^ (if def_type = 0 then ".class" else if def_type = 1 then ".enum" else if def_type = 2 then ".interface" else ".extern") ^ ".php") in
let imports = Hashtbl.create 0 in
Hashtbl.add imports (snd path) [fst path];
{
com = com;
stack = stack_init com false;
tabs = "";
ch = ch;
path = path;
buf = Buffer.create (1 lsl 14);
in_value = None;
in_loop = false;
in_instance_method = false;
imports = imports;
extern_required_paths = [];
extern_classes_with_init = [];
curclass = null_class;
curmethod = "";
locals = PMap.empty;
inv_locals = PMap.empty;
local_types = [];
inits = [];
constructor_block = false;
dynamic_methods = [];
all_dynamic_methods = [];
is_call = false;
cwd = cwd;
inline_methods = [];
nested_loops = 0;
inline_index = 0;
in_block = false;
lib_path = match com.php_lib with None -> "lib" | Some s -> s;
}
let unsupported msg p = error ("This expression cannot be generated to PHP: " ^ msg) p
let newline ctx =
match Buffer.nth ctx.buf (Buffer.length ctx.buf - 1) with
| '{' | ':' | ' '
| '}' when Buffer.nth ctx.buf (Buffer.length ctx.buf - 2) != '"' ->
print ctx "\n%s" ctx.tabs
| _ ->
print ctx ";\n%s" ctx.tabs
let rec concat ctx s f = function
| [] -> ()
| [x] -> f x
| x :: l ->
f x;
spr ctx s;
concat ctx s f l
let open_block ctx =
let oldt = ctx.tabs in
ctx.tabs <- "\t" ^ ctx.tabs;
(fun() -> ctx.tabs <- oldt)
let parent e =
match e.eexpr with
| TParenthesis _ -> e
| _ -> mk (TParenthesis e) e.etype e.epos
let inc_extern_path ctx path =
let rec slashes n =
if n = 0 then "" else ("../" ^ slashes (n-1))
in
let pre = if ctx.cwd = "" then ctx.lib_path ^ "/" else "" in
match path with
| ([],name) ->
pre ^ (slashes (List.length (fst ctx.path))) ^ (prefix_class ctx.com name) ^ ".extern.php"
| (pack,name) ->
pre ^ (slashes (List.length (fst ctx.path))) ^ String.concat "/" pack ^ "/" ^ (prefix_class ctx.com name) ^ ".extern.php"
let close ctx =
output_string ctx.ch "<?php\n";
List.iter (fun path ->
if path <> ctx.path then output_string ctx.ch ("require_once dirname(__FILE__).'/" ^ (inc_extern_path ctx path) ^ "';\n");
) (List.rev ctx.extern_required_paths);
output_string ctx.ch "\n";
output_string ctx.ch (Buffer.contents ctx.buf);
close_out ctx.ch
let save_locals ctx =
let old = ctx.locals in
let old_inv = ctx.inv_locals in
(fun() -> ctx.locals <- old; ctx.inv_locals <- old_inv)
let define_local ctx l =
let rec loop n =
let name = (if n = 1 then s_ident_local l else s_ident_local (l ^ string_of_int n)) in
if PMap.mem name ctx.inv_locals then
loop (n+1)
else begin
ctx.locals <- PMap.add l name ctx.locals;
ctx.inv_locals <- PMap.add name l ctx.inv_locals;
name
end
in
loop 1
let this ctx =
if ctx.in_value <> None then "$__hx__this" else "$this"
let gen_constant ctx p = function
| TInt i -> print ctx "%ld" i
| TFloat s -> spr ctx s
| TString s ->
print ctx "\"%s\"" (escape_bin s)
| TBool b -> spr ctx (if b then "true" else "false")
| TNull -> spr ctx "null"
| TThis -> spr ctx (this ctx)
| TSuper -> spr ctx "ERROR /* unexpected call to super in gen_constant */"
let arg_is_opt c =
match c with
| Some _ -> true
| None -> false
let s_funarg ctx arg t p o =
let byref = if (String.length arg > 7 && String.sub arg 0 7 = "byref__") then "&" else "" in
print ctx "%s$%s" byref (s_ident_local arg);
if o then spr ctx " = null"
(*
match c with
| _, Some _ -> spr ctx " = null"
| _, None -> ()
*)
let is_in_dynamic_methods ctx e s =
List.exists (fun dm ->
(* TODO: I agree, this is a mess ... but after hours of trials and errors I gave up; maybe in a calmer day *)
((String.concat "." ((fst dm.mpath) @ ["#" ^ (snd dm.mpath)])) ^ "." ^ dm.mname) = (s_type_name e.etype ^ "." ^ s)
) ctx.all_dynamic_methods
let is_dynamic_method f =
(match f.cf_kind with
| Var _ -> true
| Method MethDynamic -> true
| _ -> false)
let fun_block ctx f p =
let e = (match f.tf_expr with { eexpr = TBlock [{ eexpr = TBlock _ } as e] } -> e | e -> e) in
let e = List.fold_left (fun e (v,c) ->
match c with
| None | Some TNull -> e
| Some c -> Codegen.concat (Codegen.set_default ctx.com v c p) e
) e f.tf_args in
if ctx.com.debug then begin
Codegen.stack_block ctx.stack ctx.curclass ctx.curmethod e
end else
mk_block e
let rec gen_array_args ctx lst =
match lst with
| [] -> ()
| h :: t ->
spr ctx "[";
gen_value ctx h;
spr ctx "]";
gen_array_args ctx t
and gen_call ctx e el =
let rec genargs lst =
(match lst with
| [] -> ()
| h :: [] ->
spr ctx " = ";
gen_value ctx h;
| h :: t ->
spr ctx "[";
gen_value ctx h;
spr ctx "]";
genargs t)
in
match e.eexpr , el with
| TConst TSuper , params ->
(match ctx.curclass.cl_super with
| None -> assert false
| Some (c,_) ->
spr ctx "parent::__construct(";
concat ctx "," (gen_value ctx) params;
spr ctx ")";
);
| TField ({ eexpr = TConst TSuper },f) , params ->
(match ctx.curclass.cl_super with
| None -> assert false
| Some (c,_) ->
print ctx "parent::%s(" (s_ident (field_name f));
concat ctx "," (gen_value ctx) params;
spr ctx ")";
);
| TLocal { v_name = "__set__" }, { eexpr = TConst (TString code) } :: el ->
print ctx "$%s" code;
genargs el;
| TLocal { v_name = "__set__" }, e :: el ->
gen_value ctx e;
genargs el;
| TLocal { v_name = "__setfield__" }, e :: (f :: el) ->
gen_value ctx e;
spr ctx "->{";
gen_value ctx f;
spr ctx "}";
genargs el;
| TLocal { v_name = "__field__" }, e :: ({ eexpr = TConst (TString code) } :: el) ->
gen_value ctx e;
spr ctx "->";
spr ctx code;
gen_array_args ctx el;
| TLocal { v_name = "__field__" }, e :: (f :: el) ->
gen_value ctx e;
spr ctx "->";
gen_value ctx f;
gen_array_args ctx el;
| TLocal { v_name = "__prefix__" }, [] ->
(match ctx.com.php_prefix with
| Some prefix ->
print ctx "\"%s\"" prefix
| None ->
spr ctx "null")
| TLocal { v_name = "__var__" }, { eexpr = TConst (TString code) } :: el ->
print ctx "$%s" code;
gen_array_args ctx el;
| TLocal { v_name = "__var__" }, e :: el ->
gen_value ctx e;
gen_array_args ctx el;
| TLocal { v_name = "__call__" }, { eexpr = TConst (TString code) } :: el ->
spr ctx code;
spr ctx "(";
concat ctx ", " (gen_value ctx) el;
spr ctx ")";
| TLocal { v_name = "__php__" }, [{ eexpr = TConst (TString code) }] ->
(*--php-prefix*)
spr ctx (prefix_init_replace ctx.com code)
| TLocal { v_name = "__instanceof__" }, [e1;{ eexpr = TConst (TString t) }] ->
gen_value ctx e1;
print ctx " instanceof %s" t;
| TLocal { v_name = "__physeq__" }, [e1;e2] ->
spr ctx "(";
gen_value ctx e1;
spr ctx " === ";
gen_value ctx e2;
spr ctx ")"
| TLocal _, []
| TFunction _, []
| TCall _, []
| TParenthesis _, []
| TMeta _, []
| TBlock _, [] ->
ctx.is_call <- true;
spr ctx "call_user_func(";
gen_value ctx e;
ctx.is_call <- false;
spr ctx ")";
| TLocal _, el
| TFunction _, el
| TCall _, el
| TParenthesis _, el
| TMeta _, el
| TBlock _, el ->
ctx.is_call <- true;
spr ctx "call_user_func_array(";
gen_value ctx e;
ctx.is_call <- false;
spr ctx ", array(";
concat ctx ", " (gen_value ctx) el;
spr ctx "))"
(*
| TCall (x,_), el when (match x.eexpr with | TLocal _ -> false | _ -> true) ->
ctx.is_call <- true;
spr ctx "call_user_func_array(";
gen_value ctx e;
ctx.is_call <- false;
spr ctx ", array(";
concat ctx ", " (gen_value ctx) el;
spr ctx "))"
*)
| _ ->
ctx.is_call <- true;
gen_value ctx e;
ctx.is_call <- false;
spr ctx "(";
concat ctx ", " (gen_value ctx) el;
spr ctx ")";
and could_be_string_var s =
s = "length"
and gen_uncertain_string_var ctx s e =
match s with
| "length" ->
spr ctx "_hx_len(";
gen_value ctx e;
spr ctx ")"
| _ ->
gen_field_access ctx true e s;
and gen_string_var ctx s e =
match s with
| "length" ->
spr ctx "strlen(";
gen_value ctx e;
spr ctx ")"
| _ ->
unsupported "gen_string_var " e.epos;
and gen_string_static_call ctx s e el =
match s with
| "fromCharCode" ->
spr ctx "chr(";
concat ctx ", " (gen_value ctx) el;
spr ctx ")";
| _ -> unsupported "gen_string_static_call " e.epos;
and could_be_string_call s =
s = "substr" || s = "substring" || s = "charAt" || s = "charCodeAt" || s = "indexOf" ||
s = "lastIndexOf" || s = "split" || s = "toLowerCase" || s = "toString" || s = "toUpperCase"
and gen_string_call ctx s e el =
match s with
| "substr" ->
spr ctx "_hx_substr(";
gen_value ctx e;
spr ctx ", ";
concat ctx ", " (gen_value ctx) el;
spr ctx ")"
| "substring" ->
spr ctx "_hx_substring(";
gen_value ctx e;
spr ctx ", ";
concat ctx ", " (gen_value ctx) el;
spr ctx ")"
| "charAt" ->
spr ctx "_hx_char_at(";
gen_value ctx e;
spr ctx ", ";
concat ctx ", " (gen_value ctx) el;
spr ctx ")"
| "cca" ->
spr ctx "ord(substr(";
gen_value ctx e;
spr ctx ",";
concat ctx ", " (gen_value ctx) el;
spr ctx ",1))"
| "charCodeAt" ->
spr ctx "_hx_char_code_at(";
gen_value ctx e;
spr ctx ", ";
concat ctx ", " (gen_value ctx) el;
spr ctx ")"
| "indexOf" ->
spr ctx "_hx_index_of(";
gen_value ctx e;
spr ctx ", ";
concat ctx ", " (gen_value ctx) el;
spr ctx ")"
| "lastIndexOf" ->
spr ctx "_hx_last_index_of(";
gen_value ctx e;
spr ctx ", ";
concat ctx ", " (gen_value ctx) el;
spr ctx ")"
| "split" ->
spr ctx "_hx_explode(";
concat ctx ", " (gen_value ctx) el;
spr ctx ", ";
gen_value ctx e;
spr ctx ")"
| "toLowerCase" ->
spr ctx "strtolower(";
gen_value ctx e;
spr ctx ")"
| "toUpperCase" ->
spr ctx "strtoupper(";
gen_value ctx e;
spr ctx ")"
| "toString" ->
gen_value ctx e;
| _ ->
unsupported "gen_string_call" e.epos;
and gen_uncertain_string_call ctx s e el =
spr ctx "_hx_string_call(";
gen_value ctx e;
print ctx ", \"%s\", array(" s;
concat ctx ", " (gen_value ctx) el;
spr ctx "))"
and gen_field_op ctx e =
match e.eexpr with
| TField (f,s) ->
(match follow e.etype with
| TFun _ ->
gen_field_access ctx true f (field_name s)
| _ ->
gen_value_op ctx e)
| _ ->
gen_value_op ctx e
and gen_value_op ctx e =
match e.eexpr with
| TBinop (op,_,_) when op = Ast.OpAnd || op = Ast.OpOr || op = Ast.OpXor ->
gen_value ctx e;
| _ ->
gen_value ctx e
and is_static t =
match follow t with
| TAnon a -> (match !(a.a_status) with
| Statics c -> true
| _ -> false)
| _ -> false
and gen_member_access ctx isvar e s =
match follow e.etype with
| TAnon a ->
(match !(a.a_status) with
| EnumStatics _ ->
print ctx "::%s%s" (if isvar then "$" else "") (s_ident s)
| Statics _ ->
print ctx "::%s%s" (if isvar then "$" else "") (s_ident s)
| _ -> print ctx "->%s" (if isvar then s_ident_field s else s_ident s))
| _ -> print ctx "->%s" (if isvar then s_ident_field s else s_ident s)
and gen_field_access ctx isvar e s =
match e.eexpr with
| TTypeExpr t ->
spr ctx (s_path ctx (t_path t) false e.epos);
gen_member_access ctx isvar e s
| TLocal _ ->
gen_expr ctx e;
print ctx "->%s" (if isvar then s_ident_field s else s_ident s)
| TArray (e1,e2) ->
spr ctx "_hx_array_get(";
gen_value ctx e1;
spr ctx ", ";
gen_value ctx e2;
spr ctx ")";
gen_member_access ctx isvar e s
| TBlock _
| TParenthesis _
| TMeta _
| TObjectDecl _
| TArrayDecl _
| TNew _ ->
spr ctx "_hx_deref(";
ctx.is_call <- false;
gen_value ctx e;
spr ctx ")";
gen_member_access ctx isvar e s
| TCast (ec, _) when (match ec.eexpr with | TNew _ | TArrayDecl _ -> true | _ -> false) ->
spr ctx "_hx_deref(";
ctx.is_call <- false;
gen_value ctx e;
spr ctx ")";
gen_member_access ctx isvar e s
| _ ->
gen_expr ctx e;
gen_member_access ctx isvar e s
and gen_dynamic_function ctx isstatic name f params p =
let old = ctx.in_value in
let old_l = ctx.locals in
let old_li = ctx.inv_locals in
let old_t = ctx.local_types in
ctx.in_value <- None;
ctx.local_types <- List.map snd params @ ctx.local_types;
let byref = if (String.length name > 9 && String.sub name 0 9 = "__byref__") then "&" else "" in
print ctx "function %s%s(" byref name;
concat ctx ", " (fun (v,c) ->
let arg = define_local ctx v.v_name in
s_funarg ctx arg v.v_type p (arg_is_opt c);
) f.tf_args;
spr ctx ") {";
if (List.length f.tf_args) > 0 then begin
if isstatic then
print ctx " return call_user_func_array(self::$%s, array(" name
else
print ctx " return call_user_func_array($this->%s, array(" name;
concat ctx ", " (fun (v,_) ->
spr ctx ("$" ^ v.v_name)
) f.tf_args;
print ctx ")); }";
end else if isstatic then
print ctx " return call_user_func(self::$%s); }" name
else
print ctx " return call_user_func($this->%s); }" name;
newline ctx;
if isstatic then
print ctx "public static $%s = null" name
else
print ctx "public $%s = null" name;
ctx.in_value <- old;
ctx.locals <- old_l;
ctx.inv_locals <- old_li;
ctx.local_types <- old_t
and gen_function ctx name f params p =
let old = ctx.in_value in
let old_l = ctx.locals in
let old_li = ctx.inv_locals in
let old_t = ctx.local_types in
ctx.in_value <- None;
ctx.local_types <- List.map snd params @ ctx.local_types;
let byref = if (String.length name > 9 && String.sub name 0 9 = "__byref__") then "&" else "" in
print ctx "function %s%s(" byref name;
concat ctx ", " (fun (v,o) ->
let arg = define_local ctx v.v_name in
s_funarg ctx arg v.v_type p (arg_is_opt o);
) f.tf_args;
print ctx ") ";
gen_expr ctx (fun_block ctx f p);
ctx.in_value <- old;
ctx.locals <- old_l;
ctx.inv_locals <- old_li;
ctx.local_types <- old_t
and gen_inline_function ctx f hasthis p =
ctx.nested_loops <- ctx.nested_loops - 1;
let old = ctx.in_value in
let old_l = ctx.locals in
let old_li = ctx.inv_locals in
let old_t = ctx.local_types in
ctx.in_value <- Some "closure";
let args a = List.map (fun (v,_) -> v.v_name) a in
let arguments = ref [] in
if hasthis then begin arguments := "this" :: !arguments end;
PMap.iter (fun n _ -> arguments := !arguments @ [n]) old_li;
spr ctx "array(new _hx_lambda(array(";
let c = ref 0 in
List.iter (fun a ->
if !c > 0 then spr ctx ", ";
incr c;
print ctx "&$%s" a;
) (remove_internals !arguments);
spr ctx "), \"";
spr ctx (inline_function ctx (args f.tf_args) hasthis (fun_block ctx f p));
print ctx "\"), 'execute')";
ctx.in_value <- old;
ctx.locals <- old_l;
ctx.inv_locals <- old_li;
ctx.local_types <- old_t;
ctx.nested_loops <- ctx.nested_loops + 1;
and unset_locals ctx old_l =
let lst = ref [] in
PMap.iter (fun n _ ->
if not (PMap.exists n old_l) then
lst := ["$" ^ n] @ !lst;
) ctx.inv_locals;
if (List.length !lst) > 0 then begin
newline ctx;
spr ctx "unset(";
concat ctx "," (fun (s) -> spr ctx s; ) !lst;
spr ctx ")"
end
and gen_while_expr ctx e =
let old_loop = ctx.in_loop in
ctx.in_loop <- true;
let old_nested_loops = ctx.nested_loops in
ctx.nested_loops <- 1;
let old_l = ctx.inv_locals in
let b = save_locals ctx in
(match e.eexpr with
| TBlock (el) ->
List.iter (fun e -> newline ctx; gen_expr ctx e) el;
| _ ->
newline ctx;
gen_expr ctx e);
unset_locals ctx old_l;
b();
ctx.nested_loops <- old_nested_loops;
ctx.in_loop <- old_loop
and gen_tfield ctx e e1 s =
match follow e.etype with
| TFun (args, _) ->
(if ctx.is_call then begin
gen_field_access ctx false e1 s
end else if is_in_dynamic_methods ctx e1 s then begin
gen_field_access ctx true e1 s;
end else begin
let ob ex =
(match ex with
| TTypeExpr t ->
print ctx "\"";
spr ctx (s_path ctx (t_path t) false e1.epos);
print ctx "\""
| _ ->
gen_expr ctx e1) in
spr ctx "(isset(";
gen_field_access ctx true e1 s;
spr ctx ") ? ";
gen_field_access ctx true e1 s;
spr ctx ": array(";
ob e1.eexpr;
print ctx ", \"%s\"))" (s_ident s);
end)
| TMono _ ->
if ctx.is_call then
gen_field_access ctx false e1 s
else
gen_uncertain_string_var ctx s e1
| _ ->
if is_string_expr e1 then
gen_string_var ctx s e1
else if is_uncertain_expr e1 then
gen_uncertain_string_var ctx s e1
else
gen_field_access ctx true e1 s
and gen_expr ctx e =
let in_block = ctx.in_block in
ctx.in_block <- false;
let restore_in_block ctx inb =
if inb then ctx.in_block <- true
in
match e.eexpr with
| TConst c ->
gen_constant ctx e.epos c