forked from HaxeFoundation/haxe
-
Notifications
You must be signed in to change notification settings - Fork 3
/
genrb.ml
1792 lines (1699 loc) · 53 KB
/
genrb.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 Type
open Common
(* let s_expr = s_expr (s_type (print_context()))
let s_expr_pretty = s_expr_pretty "" (s_type (print_context()))
let debug e = print_endline (s_expr e)
let debug_pretty s e = Printf.printf "%s %s\n" s (s_expr_pretty e) *)
type context_infos = {
com : Common.context;
}
type context = {
inf : context_infos;
ch : out_channel;
buf : Buffer.t;
path : path;
mutable get_sets : (string * bool,string) Hashtbl.t;
mutable curclass : tclass;
mutable tabs : string;
mutable in_value : tvar option;
mutable in_static : bool;
mutable handle_break : bool;
mutable imports : (string,string list list) Hashtbl.t;
mutable gen_uid : int;
mutable local_types : t list;
mutable constructor_block : bool;
mutable block_inits : (unit -> unit) option;
mutable in_expression : bool;
mutable in_block_consumer : bool;
mutable protected_mode : bool;
mutable newlined : bool;
mutable dirty_line : bool;
mutable field_names : (string,bool) Hashtbl.t;
mutable has_statics : bool;
mutable has_inlines : bool;
mutable in_call : bool;
}
let is_var_field f =
match f with
| FStatic (_,f2) | FInstance (_,_,f2) ->
(match f2.cf_kind with Var _ -> true | _ -> false)
| _ ->
false
let is_autocall_field f =
match f with
| FStatic (_,f2) | FInstance (_,_,f2) ->
(match f2.cf_kind with
| Method MethDynamic -> false
| Method _ -> true
| _ -> false)
| _ ->
false
let is_special_compare e1 e2 =
match e1.eexpr, e2.eexpr with
| TConst TNull, _ | _ , TConst TNull -> None
| _ ->
match follow e1.etype, follow e2.etype with
| TInst ({ cl_path = [],"Xml" } as c,_) , _ | _ , TInst ({ cl_path = [],"Xml" } as c,_) -> Some c
| _ -> None
let is_known_nonzero e =
match e.eexpr with
| TConst(TInt i) -> (Int32.compare i Int32.zero <> 0)
| _ -> false
let is_known_positive e =
match e.eexpr with
| TConst(TInt i) -> (Int32.compare i Int32.zero >= 0)
| _ -> false
let protect name =
match name with
| "Namespace" -> "_" ^ name
| _ -> name
let this ctx = if ctx.in_value <> None then "_this_" else "self"
let has_feature ctx = Common.has_feature ctx.inf.com
let add_feature ctx = Common.add_feature ctx.inf.com
let reserved =
let h = Hashtbl.create 0 in
List.iter (fun l -> Hashtbl.add h l ())
(* these ones are defined in order to prevent recursion in some Std functions *)
["is";"as";"int";"uint";"const";"getTimer";"typeof";"parseInt";"parseFloat";
(* AS3 keywords which are not Haxe ones *)
"finally";"with";"final";"internal";"native";"namespace";"include";"delete";
(* some globals give some errors with Flex SDK as well *)
"print";"trace";
(* we don't include get+set since they are not 'real' keywords, but they can't be used as method names *)
"function";"class";"var";"if";"else";"while";"do";"for";"break";"next";"return";"extends";"implements";
"import";"switch";"case";"default";"static";"public";"private";"try";"catch";"new";"this";"throw";"interface";
"override";"package";"nil";"true";"false";"void";
"begin";"rescue";"end";
"Sys";"File";
"next";
];
h
(* "each", "label" : removed (actually allowed in locals and fields accesses) *)
let tweak_class_name n =
if Hashtbl.mem reserved n then "Hx" ^ (String.capitalize n) else if (n.[0] == '_') then ("X" ^ (String.capitalize n)) else (String.capitalize n)
let tweak_package_name n =
(tweak_class_name n)
let camel_to_underscore n =
let r = Str.regexp "\\([a-z]\\)\\([A-Z]\\)" in
String.lowercase (Str.global_replace r "\\1_\\2" n)
let camel_to_underscore_tweaked n =
(camel_to_underscore (tweak_package_name n))
let tweak_s_type_path (p,s) = match p with [] -> (tweak_class_name s) | _ -> "::" ^ String.concat "::" (List.map tweak_package_name p) ^ "::" ^ (tweak_class_name s)
let req_path (p,s) = match p with [] -> camel_to_underscore_tweaked(s) | _ -> String.concat "/" (List.map camel_to_underscore_tweaked(p)) ^ "/" ^ camel_to_underscore_tweaked(s)
let s_path ctx stat path p =
match path with
| ([],name) ->
(match name with
| "Int" -> "Fixnum"
| "Float" -> "Float"
| "Dynamic" -> "Object"
| "Bool" -> "TrueClass"
| "Enum" -> "Class"
| "EnumValue" -> "enum"
| "Date" ->
add_feature ctx "use.date";
"Date"
| "Array" -> "Array" (* BUT negative indices will break *)
| _ -> (tweak_class_name name))
| (["flash"],"FlashXml__") ->
"Xml"
| (["flash";"errors"],"Error") ->
"Error"
| (["flash"],"Vector") ->
"Vector"
| (["flash";"xml"],"XML") ->
"XML"
| (["flash";"xml"],"XMLList") ->
"XMLList"
| ["flash";"utils"],"QName" ->
"QName"
| ["flash";"utils"],"Namespace" ->
"Namespace"
| (["haxe"],"Int32") when not stat ->
"int"
| (pack,name) ->
let name = protect name in
let packs = (try Hashtbl.find ctx.imports name with Not_found -> []) in
if not (List.mem pack packs) then Hashtbl.replace ctx.imports name (pack :: packs);
tweak_s_type_path (pack,name)
let s_ident m =
let n = camel_to_underscore m in
let ch = (String.get n 0) in
if ch >= 'A' && ch <= 'Z' then
"_" ^ n
else if n = "to_string" then
"to_s"
else
if Hashtbl.mem reserved n then "_" ^ n else n
let s_ident_hash m =
let r = Str.regexp "^[_a-zA-Z0-9]+$" in
if (Str.string_match r m 0) then (s_ident m)^":" else "\""^m^"\""^" =>"
let s_ident_local ctx m =
(* not quite sure if collision is an issue; ruby local vars may be
indistinguishable from a setter in certain cases, need to think
about this *)
(* if Hashtbl.mem ctx.field_names m then
s_ident "__" ^ m
else *)
s_ident m
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
| TAbstract ({ a_path = [],_ },pl) ->
false
| TAbstract (a,pl) ->
is_anonym_type (Abstract.get_underlying_type a pl)
| _ -> 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 (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.inf.com "_hx_str" e.epos; e])) ctx.inf.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.inf.com "_hx_str" e.epos; e])) ctx.inf.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_str" | "_hx_str_or_null"))}]) -> e
| _ when not (is_string_expr e) -> to_string ctx e
| _ -> to_string_null ctx e
(*
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_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 =
match e.eexpr with
| TConst TNull -> false
| _ -> is_string_type e.etype
*)
let rec create_dir acc = function
| [] -> ()
| d :: l ->
let dir = String.concat "/" (List.rev (d :: acc)) in
if not (Sys.file_exists dir) then Unix.mkdir dir 0o755;
create_dir (d :: acc) l
let init infos path main =
let fst_path = if main then (fst path) else ("lib" :: (fst path)) in
let dir = (infos.com.file :: (List.map camel_to_underscore_tweaked fst_path)) in
create_dir [] dir;
let ch = open_out (String.concat "/" dir ^ "/" ^ (camel_to_underscore_tweaked (snd path)) ^ ".rb") in
let imports = Hashtbl.create 0 in
Hashtbl.add imports (snd path) [fst path];
{
inf = infos;
tabs = "";
ch = ch;
path = path;
buf = Buffer.create (1 lsl 14);
in_value = None;
in_static = false;
handle_break = false;
imports = imports;
curclass = null_class;
gen_uid = 0;
local_types = [];
get_sets = Hashtbl.create 0;
constructor_block = false;
block_inits = None;
in_expression = false;
in_block_consumer = false;
protected_mode = false;
newlined = true;
dirty_line = false;
field_names = Hashtbl.create 0;
has_statics = false;
has_inlines = false;
in_call = false;
}
let close ctx =
let module_names = (List.map tweak_package_name (fst ctx.path)) in
(* let module_name = (String.concat "::" (List.map tweak_package_name (fst ctx.path))) in *)
output_string ctx.ch "#!/usr/bin/env ruby\n";
output_string ctx.ch "# encoding: utf-8\n\n";
if (List.length module_names) > 0 then begin
List.iter (fun name ->
output_string ctx.ch (Printf.sprintf "module %s\n" name)) module_names;
end;
output_string ctx.ch (Buffer.contents ctx.buf);
if (List.length module_names) > 0 then begin
List.iter (fun name ->
output_string ctx.ch "\nend") module_names;
end;
output_string ctx.ch "\n";
close_out ctx.ch
let gen_local ctx l =
ctx.gen_uid <- ctx.gen_uid + 1;
if ctx.gen_uid = 1 then l else l ^ string_of_int ctx.gen_uid
let spr ctx s =
ctx.newlined <- false;
ctx.dirty_line <- true;
Buffer.add_string ctx.buf s
let print ctx =
ctx.newlined <- false;
ctx.dirty_line <- true;
Printf.kprintf (fun s -> Buffer.add_string ctx.buf s)
let unsupported p = error "This expression cannot be generated to Ruby" p
let newline ctx =
if not ctx.newlined then
ctx.newlined <- not ctx.dirty_line;
let nl = ctx.newlined in
let rec loop p =
match Buffer.nth ctx.buf p with
| '}' | '{' | ':' | ';' -> print ctx "\n%s" ctx.tabs
| '\n' | '\t' -> loop (p - 1)
| _ -> print ctx "\n%s" ctx.tabs
in
loop (Buffer.length ctx.buf - 1);
ctx.newlined <- nl;
ctx.dirty_line <- false
let soft_newline ctx =
if not ctx.newlined then newline ctx
let softest_newline ctx =
if ctx.dirty_line then newline ctx
let block_newline ctx = match Buffer.nth ctx.buf (Buffer.length ctx.buf - 1) with
| '}' -> print ctx "\n%s" ctx.tabs
| _ -> softest_newline ctx
let force_block e =
match e.eexpr with
| TBlock _ -> e
| _ ->
mk (TBlock [e]) e.etype e.epos
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 <- " " ^ ctx.tabs;
(fun() -> ctx.tabs <- oldt)
let parent e =
match e.eexpr with
| TParenthesis _ -> e
| _ -> mk (TParenthesis e) e.etype e.epos
let deparent e =
match e.eexpr with
| TParenthesis e2 -> e2
| _ -> e
let default_value tstr =
match tstr with
| "int" | "uint" -> "0"
| "Number" -> "NaN"
| "Boolean" -> "false"
| _ -> "nil"
let rec type_str ctx t p =
match t with
| TEnum _ | TInst _ when List.memq t ctx.local_types ->
"*"
| TAbstract ({ a_impl = Some _ } as a,pl) ->
type_str ctx (apply_params a.a_params pl a.a_this) p
| TAbstract (a,_) ->
(match a.a_path with
| [], "Void" -> "void"
| [], "UInt" -> "uint"
| [], "Int" -> "int"
| [], "Float" -> "Number"
| [], "Bool" -> "Boolean"
| _ -> s_path ctx true a.a_path p)
| TEnum (e,_) ->
if e.e_extern then (match e.e_path with
| [], "Void" -> "void"
| [], "Bool" -> "Boolean"
| _ ->
let rec loop = function
| [] -> "Object"
| (Ast.Meta.FakeEnum,[Ast.EConst (Ast.Ident n),_],_) :: _ ->
(match n with
| "Int" -> "int"
| "UInt" -> "uint"
| _ -> n)
| _ :: l -> loop l
in
loop e.e_meta
) else
s_path ctx true e.e_path p
| TInst ({ cl_path = ["flash"],"Vector" },[pt]) ->
(match pt with
| TInst({cl_kind = KTypeParameter _},_) -> "*"
| _ -> "Vector.<" ^ type_str ctx pt p ^ ">")
| TInst (c,_) ->
(match c.cl_kind with
| KNormal | KGeneric | KGenericInstance _ | KAbstractImpl _ | KGenericBuild _ -> s_path ctx false c.cl_path p
| KTypeParameter _ | KExtension _ | KExpr _ | KMacroType -> "*")
| TFun _ ->
"Function"
| TMono r ->
(match !r with None -> "*" | Some t -> type_str ctx t p)
| TAnon _ | TDynamic _ ->
"*"
| TType (t,args) ->
(match t.t_path with
| [], "UInt" -> "uint"
| [] , "Null" ->
(match args with
| [t] ->
(match follow t with
| TAbstract ({ a_path = [],"UInt" },_)
| TAbstract ({ a_path = [],"Int" },_)
| TAbstract ({ a_path = [],"Float" },_)
| TAbstract ({ a_path = [],"Bool" },_)
| TInst ({ cl_path = [],"Int" },_)
| TInst ({ cl_path = [],"Float" },_)
| TEnum ({ e_path = [],"Bool" },_) -> "*"
| _ -> type_str ctx t p)
| _ -> assert false);
| _ -> type_str ctx (apply_params t.t_params args t.t_type) p)
| TLazy f ->
type_str ctx ((!f)()) p
let rec iter_switch_break in_switch e =
match e.eexpr with
| TFunction _ | TWhile _ | TFor _ -> ()
| TSwitch _ when not in_switch -> iter_switch_break true e
| TBreak when in_switch -> raise Exit
| _ -> iter (iter_switch_break in_switch) e
let handle_break ctx e =
let old_handle = ctx.handle_break in
try
iter_switch_break false e;
ctx.handle_break <- false;
(fun() -> ctx.handle_break <- old_handle)
with
Exit ->
spr ctx "catch :__break__ do";
let b = open_block ctx in
newline ctx;
ctx.handle_break <- true;
(fun() ->
b();
ctx.handle_break <- old_handle;
newline ctx;
spr ctx "end";
newline ctx;
)
let is_dynamic_iterator ctx e =
let check x =
(*has_feature ctx "HxOverrides.iter" &&*) (match follow x.etype with TInst ({ cl_path = [],"Array" },_) | TAnon _ | TDynamic _ | TMono _ -> true | _ -> false)
in
match e.eexpr with
| TField (x,f) when field_name f = "iterator" -> check x
| _ ->
false
let gen_constant ctx p = function
| TInt i -> print ctx "%ld" i
| TFloat s ->
if (s.[0] == '.') then spr ctx "0";
spr ctx s;
if (s.[(String.length s)-1] == '.') then spr ctx "0"
| TString s -> print ctx "\"%s\"" (Ast.s_escape s)
| TBool b -> spr ctx (if b then "true" else "false")
| TNull -> spr ctx "nil"
| TThis -> spr ctx (this ctx)
| TSuper -> spr ctx "super"
let gen_function_header ctx name f params p in_expression =
let old = ctx.in_value in
let old_t = ctx.local_types in
let old_bi = ctx.block_inits in
let old_ie = ctx.in_expression in
let old_ibc = ctx.in_block_consumer in
ctx.in_value <- None;
ctx.in_expression <- in_expression;
ctx.local_types <- List.map snd params @ ctx.local_types;
let init () =
(*
List.iter (fun (v,o) -> match o with
| Some c when is_nullable v.v_type && c <> TNull ->
newline ctx;
print ctx "if(%s==nil) %s=" v.v_name v.v_name;
gen_constant ctx p c;
| _ -> ()
) f.tf_args; *)
ctx.block_inits <- None;
in
ctx.block_inits <- Some init;
let str_def = (if in_expression then (if ctx.in_block_consumer then "" else "lambda") else "def") in
let str_pre = (if in_expression then "{|" else "(") in
let str_pre0 = (if in_expression then "{" else " ") in
let str_post = (if in_expression then "|" else ")") in
if not in_expression then begin
soft_newline ctx;
soft_newline ctx;
end;
if ctx.constructor_block then
print ctx "def initialize%s" (if (List.length f.tf_args)>0 then "(" else "")
else
print ctx "%s%s%s%s" str_def (if ctx.in_static && not(in_expression) then (" " ^ (tweak_class_name (snd ctx.curclass.cl_path)) ^ ".") else " ") (match name with None -> "" | Some (n,meta) ->
let rec loop = function
| [] -> n
| (Ast.Meta.Getter,[Ast.EConst (Ast.Ident i),_],_) :: _ -> "get " ^ i
| (Ast.Meta.Setter,[Ast.EConst (Ast.Ident i),_],_) :: _ -> "set " ^ i
| _ :: l -> loop l
in
"" ^ loop meta) (if (List.length f.tf_args)>0 then str_pre else str_pre0);
ctx.constructor_block <- false;
concat ctx "," (fun (v,c) ->
let tstr = type_str ctx v.v_type p in
print ctx "%s" (s_ident_local ctx v.v_name);
match c with
| None ->
if ctx.constructor_block then print ctx " = %s" (default_value tstr);
| Some c ->
spr ctx " = ";
gen_constant ctx p c
) f.tf_args;
if (List.length f.tf_args)>0 then print ctx "%s" str_post;
(fun () ->
ctx.in_value <- old;
ctx.local_types <- old_t;
ctx.block_inits <- old_bi;
ctx.in_expression <- old_ie;
ctx.in_block_consumer <- old_ibc;
)
let rec gen_call ctx e el r =
match e.eexpr , el with
| TCall (x,_) , el ->
spr ctx "(";
gen_value ctx e;
spr ctx ").call";
show_args ctx el;
| TLocal { v_name = "__is__" } , [e1;e2] ->
gen_value ctx e1;
spr ctx " is ";
gen_value ctx e2;
| TLocal { v_name = "__assign__" } , [e1;e2] ->
gen_value ctx e1;
spr ctx " = ";
gen_value ctx e2;
| TLocal { v_name = "__in__" } , [e1;e2] ->
gen_value ctx e1;
spr ctx " in ";
gen_value ctx e2;
| TLocal { v_name = "__pow__" }, [e1;e2] ->
gen_value ctx e1;
spr ctx " ** ";
gen_value ctx e2;
| TLocal { v_name = "__int__" }, [e] ->
spr ctx "int(";
gen_value ctx e;
spr ctx ")";
| TLocal { v_name = "__float__" }, [e] ->
spr ctx "Number(";
gen_value ctx e;
spr ctx ")";
| TLocal { v_name = "__typeof__" }, [e] ->
spr ctx "typeof ";
gen_value ctx e;
| TLocal { v_name = "__dotcall__" }, eo :: { eexpr = TConst (TString code) } :: el ->
gen_value_nest ctx eo;
spr ctx ".";
spr ctx code;
show_args ctx el;
| TLocal { v_name = "__coloncoloncall__" }, eo :: { eexpr = TConst (TString code) } :: el ->
gen_value_nest ctx eo;
spr ctx "::";
spr ctx code;
show_args ctx el;
| TLocal { v_name = "__rescue__" }, [e1;e2] ->
spr ctx "(";
gen_value ctx e1;
spr ctx " rescue ";
gen_value ctx e2;
spr ctx ")";
| TLocal { v_name = "__call__" }, { eexpr = TConst (TString code) } :: el ->
spr ctx code;
show_args ctx el;
| TLocal { v_name = "__pass_block__" }, [e0;e1;{ eexpr = TFunction _ } as e2] ->
gen_value ctx e0;
spr ctx ".";
gen_value ctx e1;
ctx.in_block_consumer <- true;
gen_value ctx e2;
ctx.in_block_consumer <- false;
| TLocal { v_name = "__pass_block__" }, [e0;e1;e2] ->
gen_value ctx e0;
spr ctx ".";
gen_value ctx e1;
spr ctx "{|a,b| ";
call_expr_begin ctx e2;
spr ctx "(a,b)}";
| TLocal { v_name = "__rb__" }, [{ eexpr = TConst (TString code) }] ->
spr ctx (String.concat "\n" (ExtString.String.nsplit code "\r\n"))
| TLocal { v_name = "__js__" }, [{ eexpr = TConst (TString code) }] ->
spr ctx (String.concat "\n" (ExtString.String.nsplit code "\r\n"))
| TLocal { v_name = "__keys__" }, [e] ->
let ret = (match ctx.in_value with None -> assert false | Some r -> r) in
print ctx "%s = new Array()" ret.v_name;
newline ctx;
let tmp = gen_local ctx "$k" in
print ctx "for(var %s : String in " tmp;
gen_value ctx e;
print ctx ") %s.push(%s)" ret.v_name tmp;
| TLocal { v_name = "__hkeys__" }, [e] ->
let ret = (match ctx.in_value with None -> assert false | Some r -> r) in
print ctx "%s = new Array()" ret.v_name;
newline ctx;
let tmp = gen_local ctx "$k" in
print ctx "for(var %s : String in " tmp;
gen_value ctx e;
print ctx ") %s.push(%s.substr(1))" ret.v_name tmp;
| TLocal { v_name = "__foreach__" }, [e] ->
let ret = (match ctx.in_value with None -> assert false | Some r -> r) in
print ctx "%s = new Array()" ret.v_name;
newline ctx;
let tmp = gen_local ctx "$k" in
print ctx "for each(var %s : * in " tmp;
gen_value ctx e;
print ctx ") %s.push(%s)" ret.v_name tmp;
| TLocal { v_name = "__new__" }, e :: args ->
gen_value ctx e;
spr ctx ".new";
show_args ctx args;
| TLocal { v_name = "__delete__" }, [e;f] ->
spr ctx "delete(";
gen_value ctx e;
spr ctx "[";
gen_value ctx f;
spr ctx "]";
spr ctx ")";
| TLocal { v_name = "__set__" }, [e;k;v] ->
gen_value ctx e;
spr ctx "[";
gen_value ctx k;
spr ctx "] = ";
gen_value ctx v;
| TLocal { v_name = "__get__" }, [e;k] ->
gen_value ctx e;
spr ctx "[";
gen_value ctx k;
spr ctx "]";
| TLocal { v_name = "__get2__" }, [e;k1;k2] ->
gen_value ctx e;
spr ctx "[";
gen_value ctx k1;
(match k2.eexpr with
| TConst TNull ->
spr ctx "..";
spr ctx "-1";
| _ ->
spr ctx ",";
gen_value ctx k2);
spr ctx "]";
| TLocal { v_name = "__paren__" }, [e] ->
spr ctx "(";
gen_value ctx e;
spr ctx ")";
| TLocal { v_name = "__unprotect__" }, [e] ->
gen_value ctx e
| TLocal { v_name = "__vector__" }, [e] ->
spr ctx (type_str ctx r e.epos);
spr ctx "(";
gen_value ctx e;
spr ctx ")"
| TLocal { v_name = "`trace" }, [e;infos] ->
spr ctx "puts ";
gen_value ctx e
| TLocal x, el when (match x.v_type with TFun _ -> true | TAnon _ -> true | _ -> false) ->
spr ctx "(";
gen_value ctx e;
spr ctx ").call";
show_args ctx el
| TField (_, FStatic ({ cl_path = (["flash"],"Vector") }, cf)), args ->
(match cf.cf_name, args with
| "ofArray", [e] | "convert", [e] ->
(match follow r with
| TInst ({ cl_path = (["flash"],"Vector") },[t]) ->
print ctx "Vector.<%s>(" (type_str ctx t e.epos);
gen_value ctx e;
print ctx ")";
| _ -> assert false)
| _ -> assert false)
| TField (ee,f), args when is_var_field f ->
spr ctx "(";
gen_value ctx e;
spr ctx ")";
spr ctx ".call";
show_args ctx el;
| _ ->
let is_super = (match e.eexpr with | TField ({ eexpr = TConst TSuper },_) -> true | _ -> false) in
if is_super then begin
spr ctx "super"; (* incomplete; covers common case though of super.samename() *)
show_args ctx el;
end else call_expr ctx e el;
and call_expr ctx e el =
call_expr_begin ctx e;
show_args ctx el
and call_expr_begin ctx e =
ctx.in_call <- true;
gen_value ctx e;
ctx.in_call <- false;
if (match e.eexpr with
| TField (_,FStatic(_,f)) when (match f.cf_kind with | Var _ -> true | Method MethDynamic -> true | _ -> false) ->
true
| TField (x,f) when field_name f = "iterator" && is_dynamic_iterator ctx e ->
false
| TField (e2,_) when (is_anonym_type e2.etype) ->
true
| TField (_,_) -> false
| TFunction _ -> true
| TArray _ -> true
| TParenthesis _ -> true
| TConst TSuper -> false
| _ -> true) then spr ctx ".call"
and show_args ctx el =
if (List.length el)>0 then spr ctx "(";
concat ctx "," (gen_value ctx) el;
if (List.length el)>0 then spr ctx ")"
and gen_value_op ctx e =
match e.eexpr with
| TBinop (op,_,_) when op = Ast.OpAnd || op = Ast.OpOr || op = Ast.OpXor ->
spr ctx "(";
gen_value ctx e;
spr ctx ")";
| _ ->
gen_value ctx e
and gen_value_op_string ctx e =
if (is_uncertain_expr e) || not(is_string_expr e) then begin
spr ctx "_hx_str(";
gen_value ctx e;
spr ctx ")";
(* (match e.eexpr with
| TBinop (op,_,_) ->
spr ctx "(";
gen_value ctx e;
spr ctx ")";
| _ ->
gen_value ctx e);
spr ctx ".to_s";*)
end else
gen_value_op ctx e
and gen_value_nest ctx e =
match e.eexpr with
| TBinop (op,_,_) ->
spr ctx "(";
gen_value ctx e;
spr ctx ")";
| _ ->
gen_value ctx e
and gen_field_access ctx t s f e =
(*Printf.printf "field access for %s --- %s\n" (Type.s_expr (fun(t) -> Type.s_type (print_context()) t) e) s;*)
let field c =
match fst c.cl_path, snd c.cl_path, s with
(* | [], "Math", "NaN"
| [], "Math", "NEGATIVE_INFINITY"
| [], "Math", "POSITIVE_INFINITY"
| [], "Math", "isFinite"
| [], "Math", "isNaN"
| [], "Date", "now"
| [], "Date", "fromTime"
| [], "Date", "fromString"
->
print ctx "[\"%s\"]" s
| [], "String", "charCodeAt" ->
spr ctx "[\"charCodeAtHX\"]"
| [], "Array", "map" ->
spr ctx "[\"mapHX\"]"
| [], "Array", "filter" ->
spr ctx "[\"filterHX\"]"
| [], "Date", "toString" ->
print ctx "[\"toStringHX\"]"
| [], "String", "cca" ->
print ctx ".charCodeAt"
| ["flash";"xml"], "XML", "namespace" ->
print ctx ".namespace" *)
| _ ->
print ctx ".%s"(s_ident s)
in
match follow t with
| TInst (c,_) -> field c
| TDynamic _ -> print ctx "[:%s]" (s_ident s)
| TAnon a ->
(match !(a.a_status) with
| Statics c ->
if ((is_autocall_field f) && (not(ctx.in_call))) then print ctx "[:%s]" (s_ident s) else field c
| EnumStatics _ -> print ctx ".%s" (s_ident s)
| _ -> print ctx "[:%s]" (s_ident s))
| TAbstract ({ a_path = [],_ },pl) ->
print ctx ".%s" (s_ident s)
| TAbstract (a,pl) ->
gen_field_access ctx (Abstract.get_underlying_type a pl) s f e
| _ ->
print ctx ".%s" (s_ident s)
and gen_expr ?(toplevel=false) ?(preblocked=false) ?(postblocked=false) ?(shortenable=true) ?(weakreturn=false) ctx e =
let in_expression = ctx.in_expression in
ctx.in_expression <- false;
(match e.eexpr with
| TConst c ->
gen_constant ctx e.epos c
| TLocal v ->
spr ctx (s_ident_local ctx v.v_name)
| TArray ({ eexpr = TLocal { v_name = "__global__" } },{ eexpr = TConst (TString s) }) ->
let path = Ast.parse_path s in
spr ctx (s_path ctx false path e.epos)
| TArray (e1,e2) ->
gen_value ctx e1;
spr ctx "[";
gen_value ctx e2;
spr ctx "]";
| TBinop (Ast.OpMod,e1,e2) when is_known_positive(e1) ->
gen_value ctx e1;
spr ctx " % ";
gen_value ctx e2;
| TBinop (Ast.OpMod,e1,e2) when is_known_nonzero(e2) ->
gen_value_nest ctx e1;
spr ctx ".remainder(";
gen_value ctx e2;
spr ctx ")";
| TBinop (Ast.OpMod,e1,e2) ->
spr ctx "(";
gen_value_nest ctx e1;
spr ctx ".remainder(";
gen_value ctx e2;
spr ctx ") rescue Float::NAN)";
| TBinop (Ast.OpAssignOp(Ast.OpMod),e1,e2) ->
gen_value ctx e1;
spr ctx " = ";
gen_expr ctx (mk (TBinop (Ast.OpMod, e1, e2)) e1.etype e1.epos);
| TBinop (Ast.OpAssignOp(Ast.OpUShr),e1,e2) ->
gen_value ctx e1;
spr ctx " = ";
gen_expr ctx (mk (TBinop (Ast.OpUShr, e1, e2)) e1.etype e1.epos);
| TBinop (Ast.OpEq,e1,e2) when (match is_special_compare e1 e2 with Some c -> true | None -> false) ->
let c = match is_special_compare e1 e2 with Some c -> c | None -> assert false in
gen_expr ctx (mk (TCall (mk (TField (mk (TTypeExpr (TClassDecl c)) t_dynamic e.epos,FDynamic "compare")) t_dynamic e.epos,[e1;e2])) ctx.inf.com.basic.tbool e.epos);
| TBinop (Ast.OpAdd,e1,e2) when (is_uncertain_expr e1 && is_uncertain_expr e2) ->
spr ctx "_hx_add(";
gen_value_op ctx e1;
spr ctx ", ";
gen_value_op ctx e2;
spr ctx ")";
| TBinop (Ast.OpAdd,e1,e2) when (is_string_expr e1 || is_string_expr e2) ->
(* gen_value_op_string ctx e1; *)
gen_value_op ctx (as_string_expr ctx e1);
spr ctx " + ";
gen_value_op ctx (as_string_expr ctx e2);
(* gen_value_op_string ctx e2; *)
| TBinop (Ast.OpUShr,e1,e2) ->
spr ctx "_hx_ushr(";
gen_value_op ctx e1;
spr ctx ",";
gen_value_op ctx e2;
spr ctx ")";
(* what is this used for? *)
(* | TBinop (op,{ eexpr = TField (e1,s) },e2) ->
gen_value_op ctx e1;
gen_field_access ctx e1.etype s;
print ctx " %s " (Ast.s_binop op);
gen_value_op ctx e2; *)
| TField (x,f) when field_name f = "iterator" && is_dynamic_iterator ctx e ->
add_feature ctx "use.$iterator";
print ctx "Rb::RubyIterator.new(";
gen_value ctx x;
print ctx ")";
| TBinop (op,e1,e2) ->
gen_value_op ctx e1;
print ctx " %s " (Ast.s_binop op);
gen_value_op ctx e2;
(* variable fields on interfaces are generated as (class["field"] as class) *)
(*
| TField ({etype = TInst({cl_interface = true} as c,_)} as e,FInstance (_,{ cf_name = s }))
when (try (match (PMap.find s c.cl_fields).cf_kind with Var _ -> true | _ -> false) with Not_found -> false) ->
spr ctx "(";
gen_value ctx e;
print ctx "[\"%s\"]" s;
print ctx " as %s)" (type_str ctx e.etype e.epos); *)
(* | TField({eexpr = TArrayDecl _} as e1,s) ->
spr ctx "(";
gen_expr ctx e1;
spr ctx ")";
gen_field_access ctx e1.etype (field_name s) *)
| TEnumParameter (e,_,i) ->
gen_value ctx e;
print ctx ".params[%i]" i;
| TField ({ eexpr = TConst (TThis) },s) when is_var_field s ->
spr ctx "@";
spr ctx (s_ident (field_name s))