forked from HaxeFoundation/haxe
-
Notifications
You must be signed in to change notification settings - Fork 0
/
genjs.ml
1472 lines (1373 loc) · 43.9 KB
/
genjs.ml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(*
The Haxe Compiler
Copyright (C) 2005-2015 Haxe Foundation
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*)
open Ast
open Type
open Common
type pos = Ast.pos
type sourcemap = {
sources : (string) DynArray.t;
sources_hash : (string, int) Hashtbl.t;
mappings : Rbuffer.t;
mutable source_last_line : int;
mutable source_last_col : int;
mutable source_last_file : int;
mutable print_comma : bool;
mutable output_last_col : int;
mutable output_current_col : int;
}
type ctx = {
com : Common.context;
buf : Rbuffer.t;
chan : out_channel;
packages : (string list,unit) Hashtbl.t;
smap : sourcemap;
js_modern : bool;
js_flatten : bool;
mutable current : tclass;
mutable statics : (tclass * string * texpr) list;
mutable inits : texpr list;
mutable tabs : string;
mutable in_value : tvar option;
mutable in_loop : bool;
mutable handle_break : bool;
mutable id_counter : int;
mutable type_accessor : module_type -> string;
mutable separator : bool;
mutable found_expose : bool;
}
type object_store = {
os_name : string;
mutable os_fields : object_store list;
}
let get_exposed ctx path meta =
try
let (_, args, pos) = Meta.get Meta.Expose meta in
(match args with
| [ EConst (String s), _ ] -> [s]
| [] -> [path]
| _ -> error "Invalid @:expose parameters" pos)
with Not_found -> []
let dot_path = Ast.s_type_path
let flat_path (p,s) =
(* Replace _ with _$ in paths to prevent name collisions. *)
let escape str = String.concat "_$" (ExtString.String.nsplit str "_") in
match p with
| [] -> escape s
| _ -> String.concat "_" (List.map escape p) ^ "_" ^ (escape s)
let s_path ctx = if ctx.js_flatten then flat_path else dot_path
let kwds =
let h = Hashtbl.create 0 in
List.iter (fun s -> Hashtbl.add h s ()) [
"abstract"; "as"; "boolean"; "break"; "byte"; "case"; "catch"; "char"; "class"; "continue"; "const";
"debugger"; "default"; "delete"; "do"; "double"; "else"; "enum"; "export"; "extends"; "false"; "final";
"finally"; "float"; "for"; "function"; "goto"; "if"; "implements"; "import"; "in"; "instanceof"; "int";
"interface"; "is"; "let"; "long"; "namespace"; "native"; "new"; "null"; "package"; "private"; "protected";
"public"; "return"; "short"; "static"; "super"; "switch"; "synchronized"; "this"; "throw"; "throws";
"transient"; "true"; "try"; "typeof"; "use"; "var"; "void"; "volatile"; "while"; "with"; "yield"
];
h
(* Identifiers Haxe reserves to make the JS output cleaner. These can still be used in untyped code (TLocal),
but are escaped upon declaration. *)
let kwds2 =
let h = Hashtbl.create 0 in
List.iter (fun s -> Hashtbl.add h s ()) [
(* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects *)
"Infinity"; "NaN"; "decodeURI"; "decodeURIComponent"; "encodeURI"; "encodeURIComponent";
"escape"; "eval"; "isFinite"; "isNaN"; "parseFloat"; "parseInt"; "undefined"; "unescape";
"JSON"; "Number"; "Object"; "console"; "window"; "require";
];
h
let valid_js_ident s =
String.length s > 0 && try
for i = 0 to String.length s - 1 do
match String.unsafe_get s i with
| 'a'..'z' | 'A'..'Z' | '$' | '_' -> ()
| '0'..'9' when i > 0 -> ()
| _ -> raise Exit
done;
true
with Exit ->
false
let field s = if Hashtbl.mem kwds s || not (valid_js_ident s) then "[\"" ^ s ^ "\"]" else "." ^ s
let ident s = if Hashtbl.mem kwds s then "$" ^ s else s
let check_var_declaration v = if Hashtbl.mem kwds2 v.v_name then v.v_name <- "$" ^ v.v_name
let anon_field s = if Hashtbl.mem kwds s || not (valid_js_ident s) then "'" ^ s ^ "'" else s
let static_field c s =
match s with
| "length" | "name" when not c.cl_extern || Meta.has Meta.HxGen c.cl_meta-> ".$" ^ s
| s -> field s
let has_feature ctx = Common.has_feature ctx.com
let add_feature ctx = Common.add_feature ctx.com
let handle_newlines ctx str =
if ctx.com.debug then
let rec loop from =
try begin
let next = String.index_from str from '\n' + 1 in
Rbuffer.add_char ctx.smap.mappings ';';
ctx.smap.output_last_col <- 0;
ctx.smap.print_comma <- false;
loop next
end with Not_found ->
ctx.smap.output_current_col <- String.length str - from
in
loop 0
else ()
let flush ctx =
Rbuffer.output_buffer ctx.chan ctx.buf;
Rbuffer.clear ctx.buf
let spr ctx s =
ctx.separator <- false;
handle_newlines ctx s;
Rbuffer.add_string ctx.buf s
let print ctx =
ctx.separator <- false;
Printf.kprintf (fun s -> begin
handle_newlines ctx s;
Rbuffer.add_string ctx.buf s
end)
let unsupported p = error "This expression cannot be compiled to Javascript" p
let add_mapping ctx e =
if not ctx.com.debug || e.epos.pmin < 0 then () else
let pos = e.epos in
let smap = ctx.smap in
let file = try
Hashtbl.find smap.sources_hash pos.pfile
with Not_found ->
let length = DynArray.length smap.sources in
Hashtbl.replace smap.sources_hash pos.pfile length;
DynArray.add smap.sources pos.pfile;
length
in
let line, col = Lexer.find_pos pos in
let line = line - 1 in
let col = col - 1 in
if smap.source_last_file != file || smap.source_last_line != line || smap.source_last_col != col then begin
if smap.print_comma then
Rbuffer.add_char smap.mappings ','
else
smap.print_comma <- true;
let base64_vlq number =
let encode_digit digit =
let chars = [|
'A';'B';'C';'D';'E';'F';'G';'H';'I';'J';'K';'L';'M';'N';'O';'P';
'Q';'R';'S';'T';'U';'V';'W';'X';'Y';'Z';'a';'b';'c';'d';'e';'f';
'g';'h';'i';'j';'k';'l';'m';'n';'o';'p';'q';'r';'s';'t';'u';'v';
'w';'x';'y';'z';'0';'1';'2';'3';'4';'5';'6';'7';'8';'9';'+';'/'
|] in
Array.unsafe_get chars digit
in
let to_vlq number =
if number < 0 then
((-number) lsl 1) + 1
else
number lsl 1
in
let rec loop vlq =
let shift = 5 in
let base = 1 lsl shift in
let mask = base - 1 in
let continuation_bit = base in
let digit = vlq land mask in
let next = vlq asr shift in
Rbuffer.add_char smap.mappings (encode_digit (
if next > 0 then digit lor continuation_bit else digit));
if next > 0 then loop next else ()
in
loop (to_vlq number)
in
base64_vlq (smap.output_current_col - smap.output_last_col);
base64_vlq (file - smap.source_last_file);
base64_vlq (line - smap.source_last_line);
base64_vlq (col - smap.source_last_col);
smap.source_last_file <- file;
smap.source_last_line <- line;
smap.source_last_col <- col;
smap.output_last_col <- smap.output_current_col
end
let write_mappings ctx =
let basefile = Filename.basename ctx.com.file in
print ctx "\n//# sourceMappingURL=%s.map" basefile;
let channel = open_out_bin (ctx.com.file ^ ".map") in
let sources = DynArray.to_list ctx.smap.sources in
let to_url file =
ExtString.String.map (fun c -> if c == '\\' then '/' else c) (Common.get_full_path file)
in
output_string channel "{\n";
output_string channel "\"version\":3,\n";
output_string channel ("\"file\":\"" ^ (String.concat "\\\\" (ExtString.String.nsplit basefile "\\")) ^ "\",\n");
output_string channel ("\"sourceRoot\":\"file:///\",\n");
output_string channel ("\"sources\":[" ^
(String.concat "," (List.map (fun s -> "\"" ^ to_url s ^ "\"") sources)) ^
"],\n");
if Common.defined ctx.com Define.SourceMapContent then begin
output_string channel ("\"sourcesContent\":[" ^
(String.concat "," (List.map (fun s -> try "\"" ^ Ast.s_escape (Std.input_file ~bin:true s) ^ "\"" with _ -> "null") sources)) ^
"],\n");
end;
output_string channel "\"names\":[],\n";
output_string channel "\"mappings\":\"";
Rbuffer.output_buffer channel ctx.smap.mappings;
output_string channel "\"\n";
output_string channel "}";
close_out channel
let newline ctx =
match Rbuffer.nth ctx.buf (Rbuffer.length ctx.buf - 1) with
| '}' | '{' | ':' | ';' when not ctx.separator -> print ctx "\n%s" ctx.tabs
| _ -> print ctx ";\n%s" ctx.tabs
let newprop ctx =
match Rbuffer.nth ctx.buf (Rbuffer.length ctx.buf - 1) with
| '{' -> print ctx "\n%s" ctx.tabs
| _ -> print ctx "\n%s," ctx.tabs
let semicolon ctx =
match Rbuffer.nth ctx.buf (Rbuffer.length ctx.buf - 1) with
| '}' when not ctx.separator -> ()
| _ -> spr ctx ";"
let rec concat ctx s f = function
| [] -> ()
| [x] -> f x
| x :: l ->
f x;
spr ctx s;
concat ctx s f l
let fun_block ctx f p =
let e = List.fold_left (fun e (a,c) ->
match c with
| None | Some TNull -> e
| Some c -> Type.concat (Codegen.set_default ctx.com a c p) e
) f.tf_expr f.tf_args in
e
let open_block ctx =
let oldt = ctx.tabs in
ctx.tabs <- "\t" ^ ctx.tabs;
(fun() -> ctx.tabs <- oldt)
let rec has_return e =
match e.eexpr with
| TBlock [] -> false
| TBlock el -> has_return (List.hd (List.rev el))
| TReturn _ -> true
| _ -> false
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 = ctx.in_loop, ctx.handle_break in
ctx.in_loop <- true;
try
iter_switch_break false e;
ctx.handle_break <- false;
(fun() ->
ctx.in_loop <- fst old;
ctx.handle_break <- snd old;
)
with
Exit ->
spr ctx "try {";
let b = open_block ctx in
newline ctx;
ctx.handle_break <- true;
(fun() ->
b();
ctx.in_loop <- fst old;
ctx.handle_break <- snd old;
newline ctx;
spr ctx "} catch( e ) { if( e != \"__break__\" ) throw e; }";
)
let this ctx = match ctx.in_value with None -> "this" | Some _ -> "$this"
let is_dynamic_iterator ctx e =
let check x =
has_feature ctx "HxOverrides.iter" && (match follow x.etype with
| TInst ({ cl_path = [],"Array" },_)
| TInst ({ cl_kind = KTypeParameter _}, _)
| 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 -> spr ctx s
| TString s -> print ctx "\"%s\"" (Ast.s_escape s)
| TBool b -> spr ctx (if b then "true" else "false")
| TNull -> spr ctx "null"
| TThis -> spr ctx (this ctx)
| TSuper -> assert false
let rec gen_call ctx e el in_value =
match e.eexpr , el with
| TConst TSuper , params ->
(match ctx.current.cl_super with
| None -> error "Missing api.setCurrentClass" e.epos
| Some (c,_) ->
print ctx "%s.call(%s" (ctx.type_accessor (TClassDecl c)) (this ctx);
List.iter (fun p -> print ctx ","; gen_value ctx p) params;
spr ctx ")";
);
| TField ({ eexpr = TConst TSuper },f) , params ->
(match ctx.current.cl_super with
| None -> error "Missing api.setCurrentClass" e.epos
| Some (c,_) ->
let name = field_name f in
print ctx "%s.prototype%s.call(%s" (ctx.type_accessor (TClassDecl c)) (field name) (this ctx);
List.iter (fun p -> print ctx ","; gen_value ctx p) params;
spr ctx ")";
);
| TCall (x,_) , el when (match x.eexpr with TLocal { v_name = "__js__" } -> false | _ -> true) ->
spr ctx "(";
gen_value ctx e;
spr ctx ")";
spr ctx "(";
concat ctx "," (gen_value ctx) el;
spr ctx ")";
| TLocal { v_name = "__new__" }, { eexpr = TConst (TString cl) } :: params ->
print ctx "new %s(" cl;
concat ctx "," (gen_value ctx) params;
spr ctx ")";
| TLocal { v_name = "__new__" }, e :: params ->
spr ctx "new ";
gen_value ctx e;
spr ctx "(";
concat ctx "," (gen_value ctx) params;
spr ctx ")";
| TLocal { v_name = "__js__" }, [{ eexpr = TConst (TString "this") }] ->
spr ctx (this ctx)
| TLocal { v_name = "__js__" }, [{ eexpr = TConst (TString code) }] ->
spr ctx (String.concat "\n" (ExtString.String.nsplit code "\r\n"))
| TLocal { v_name = "__js__" }, { eexpr = TConst (TString code); epos = p } :: tl ->
Codegen.interpolate_code ctx.com code tl (spr ctx) (gen_expr ctx) p
| TLocal { v_name = "__instanceof__" }, [o;t] ->
spr ctx "(";
gen_value ctx o;
print ctx " instanceof ";
gen_value ctx t;
spr ctx ")";
| TLocal { v_name = "__typeof__" }, [o] ->
spr ctx "typeof(";
gen_value ctx o;
spr ctx ")";
| TLocal { v_name = "__strict_eq__" } , [x;y] ->
(* add extra parenthesis here because of operator precedence *)
spr ctx "((";
gen_value ctx x;
spr ctx ") === ";
gen_value ctx y;
spr ctx ")";
| TLocal { v_name = "__strict_neq__" } , [x;y] ->
(* add extra parenthesis here because of operator precedence *)
spr ctx "((";
gen_value ctx x;
spr ctx ") !== ";
gen_value ctx y;
spr ctx ")";
| TLocal ({v_name = "__define_feature__"}), [_;e] ->
gen_expr ctx e
| TLocal { v_name = "__feature__" }, { eexpr = TConst (TString f) } :: eif :: eelse ->
(if has_feature ctx f then
gen_value ctx eif
else match eelse with
| [] -> ()
| e :: _ -> gen_value ctx e)
| TLocal { v_name = "__rethrow__" }, [] ->
spr ctx "throw $hx_rethrow";
| TLocal { v_name = "__resources__" }, [] ->
spr ctx "[";
concat ctx "," (fun (name,data) ->
spr ctx "{ ";
spr ctx "name : ";
gen_constant ctx e.epos (TString name);
spr ctx ", data : ";
gen_constant ctx e.epos (TString (Codegen.bytes_serialize data));
spr ctx "}"
) (Hashtbl.fold (fun name data acc -> (name,data) :: acc) ctx.com.resources []);
spr ctx "]";
| TLocal { v_name = "`trace" }, [e;infos] ->
if has_feature ctx "haxe.Log.trace" then begin
let t = (try List.find (fun t -> t_path t = (["haxe"],"Log")) ctx.com.types with _ -> assert false) in
spr ctx (ctx.type_accessor t);
spr ctx ".trace(";
gen_value ctx e;
spr ctx ",";
gen_value ctx infos;
spr ctx ")";
end else begin
spr ctx "console.log(";
gen_value ctx e;
spr ctx ")";
end
| _ ->
gen_value ctx e;
spr ctx "(";
concat ctx "," (gen_value ctx) el;
spr ctx ")"
and gen_expr ctx e =
add_mapping ctx e;
match e.eexpr with
| TConst c -> gen_constant ctx e.epos c
| TLocal v -> spr ctx (ident v.v_name)
| TArray (e1,{ eexpr = TConst (TString s) }) when valid_js_ident s && (match e1.eexpr with TConst (TInt _|TFloat _) -> false | _ -> true) ->
gen_value ctx e1;
spr ctx (field s)
| TArray (e1,e2) ->
gen_value ctx e1;
spr ctx "[";
gen_value ctx e2;
spr ctx "]";
| TBinop (op,{ eexpr = TField (x,f) },e2) when field_name f = "iterator" ->
gen_value ctx x;
spr ctx (field "iterator");
print ctx " %s " (Ast.s_binop op);
gen_value ctx e2;
| TBinop (op,e1,e2) ->
gen_value ctx e1;
print ctx " %s " (Ast.s_binop op);
gen_value ctx e2;
| TField (x,f) when field_name f = "iterator" && is_dynamic_iterator ctx e ->
add_feature ctx "use.$iterator";
print ctx "$iterator(";
gen_value ctx x;
print ctx ")";
| TField (x,FClosure (Some ({cl_path=[],"Array"},_), {cf_name="push"})) ->
(* see https://github.com/HaxeFoundation/haxe/issues/1997 *)
add_feature ctx "use.$arrayPushClosure";
print ctx "$arrayPushClosure(";
gen_value ctx x;
print ctx ")"
| TField (x,FClosure (_,f)) ->
add_feature ctx "use.$bind";
(match x.eexpr with
| TConst _ | TLocal _ ->
print ctx "$bind(";
gen_value ctx x;
print ctx ",";
gen_value ctx x;
print ctx "%s)" (field f.cf_name)
| _ ->
print ctx "($_=";
gen_value ctx x;
print ctx ",$bind($_,$_%s))" (field f.cf_name))
| TEnumParameter (x,_,i) ->
gen_value ctx x;
print ctx "[%i]" (i + 2)
| TField ({ eexpr = TConst (TInt _ | TFloat _) } as x,f) ->
gen_expr ctx { e with eexpr = TField(mk (TParenthesis x) x.etype x.epos,f) }
| TField (x, (FInstance(_,_,f) | FStatic(_,f) | FAnon(f))) when Meta.has Meta.SelfCall f.cf_meta ->
gen_value ctx x;
| TField (x,f) ->
gen_value ctx x;
let name = field_name f in
spr ctx (match f with FStatic(c,_) -> static_field c name | FEnum _ | FInstance _ | FAnon _ | FDynamic _ | FClosure _ -> field name)
| TTypeExpr t ->
spr ctx (ctx.type_accessor t)
| TParenthesis e ->
spr ctx "(";
gen_value ctx e;
spr ctx ")";
| TMeta (_,e) ->
gen_expr ctx e
| TReturn eo ->
if ctx.in_value <> None then unsupported e.epos;
(match eo with
| None ->
spr ctx "return"
| Some e ->
spr ctx "return ";
gen_value ctx e);
| TBreak ->
if not ctx.in_loop then unsupported e.epos;
if ctx.handle_break then spr ctx "throw \"__break__\"" else spr ctx "break"
| TContinue ->
if not ctx.in_loop then unsupported e.epos;
spr ctx "continue"
| TBlock el ->
print ctx "{";
let bend = open_block ctx in
List.iter (gen_block_element ctx) el;
bend();
newline ctx;
print ctx "}";
| TFunction f ->
let old = ctx.in_value, ctx.in_loop in
ctx.in_value <- None;
ctx.in_loop <- false;
print ctx "function(%s) " (String.concat "," (List.map ident (List.map arg_name f.tf_args)));
gen_expr ctx (fun_block ctx f e.epos);
ctx.in_value <- fst old;
ctx.in_loop <- snd old;
ctx.separator <- true
| TCall (e,el) ->
gen_call ctx e el false
| TArrayDecl el ->
spr ctx "[";
concat ctx "," (gen_value ctx) el;
spr ctx "]"
| TThrow e ->
spr ctx "throw ";
gen_value ctx e;
| TVar (v,eo) ->
spr ctx "var ";
check_var_declaration v;
spr ctx (ident v.v_name);
begin match eo with
| None -> ()
| Some e ->
spr ctx " = ";
gen_value ctx e
end
| TNew ({ cl_path = [],"Array" },_,[]) ->
print ctx "[]"
| TNew (c,_,el) ->
(match c.cl_constructor with
| Some cf when Meta.has Meta.SelfCall cf.cf_meta -> ()
| _ -> print ctx "new ");
print ctx "%s(" (ctx.type_accessor (TClassDecl c));
concat ctx "," (gen_value ctx) el;
spr ctx ")"
| TIf (cond,e,eelse) ->
spr ctx "if";
gen_value ctx cond;
spr ctx " ";
gen_expr ctx e;
(match eelse with
| None -> ()
| Some e2 ->
(match e.eexpr with
| TObjectDecl _ -> ctx.separator <- false
| _ -> ());
semicolon ctx;
spr ctx " else ";
gen_expr ctx e2);
| TUnop (op,Ast.Prefix,e) ->
spr ctx (Ast.s_unop op);
gen_value ctx e
| TUnop (op,Ast.Postfix,e) ->
gen_value ctx e;
spr ctx (Ast.s_unop op)
| TWhile (cond,e,Ast.NormalWhile) ->
let handle_break = handle_break ctx e in
spr ctx "while";
gen_value ctx cond;
spr ctx " ";
gen_expr ctx e;
handle_break();
| TWhile (cond,e,Ast.DoWhile) ->
let handle_break = handle_break ctx e in
spr ctx "do ";
gen_expr ctx e;
semicolon ctx;
spr ctx " while";
gen_value ctx cond;
handle_break();
| TObjectDecl fields ->
spr ctx "{ ";
concat ctx ", " (fun (f,e) -> (match e.eexpr with
| TMeta((Meta.QuotedField,_,_),e) -> print ctx "'%s' : " f;
| _ -> print ctx "%s : " (anon_field f));
gen_value ctx e
) fields;
spr ctx "}";
ctx.separator <- true
| TFor (v,it,e) ->
check_var_declaration v;
let handle_break = handle_break ctx e in
let it = ident (match it.eexpr with
| TLocal v -> v.v_name
| _ ->
let id = ctx.id_counter in
ctx.id_counter <- ctx.id_counter + 1;
let name = "$it" ^ string_of_int id in
print ctx "var %s = " name;
gen_value ctx it;
newline ctx;
name
) in
print ctx "while( %s.hasNext() ) {" it;
let bend = open_block ctx in
newline ctx;
print ctx "var %s = %s.next()" (ident v.v_name) it;
gen_block_element ctx e;
bend();
newline ctx;
spr ctx "}";
handle_break();
| TTry (e,catchs) ->
spr ctx "try ";
gen_expr ctx e;
let vname = (match catchs with [(v,_)] -> check_var_declaration v; v.v_name | _ ->
let id = ctx.id_counter in
ctx.id_counter <- ctx.id_counter + 1;
"$e" ^ string_of_int id
) in
print ctx " catch( %s ) {" vname;
let bend = open_block ctx in
let last = ref false in
let else_block = ref false in
if (has_feature ctx "haxe.CallStack.exceptionStack") then begin
newline ctx;
print ctx "%s.lastException = %s" (ctx.type_accessor (TClassDecl { null_class with cl_path = ["haxe"],"CallStack" })) vname
end;
if (has_feature ctx "js.Lib.rethrow") then begin
let has_rethrow (_,e) =
let rec loop e = match e.eexpr with
| TCall({eexpr = TLocal {v_name = "__rethrow__"}}, []) -> raise Exit
| _ -> Type.iter loop e
in
try (loop e; false) with Exit -> true
in
if List.exists has_rethrow catchs then begin
newline ctx;
print ctx "var $hx_rethrow = %s" vname;
end
end;
if (has_feature ctx "js.Boot.HaxeError") then begin
newline ctx;
print ctx "if (%s instanceof %s) %s = %s.val" vname (ctx.type_accessor (TClassDecl { null_class with cl_path = ["js";"_Boot"],"HaxeError" })) vname vname;
end;
List.iter (fun (v,e) ->
if !last then () else
let t = (match follow v.v_type with
| TEnum (e,_) -> Some (TEnumDecl e)
| TInst (c,_) -> Some (TClassDecl c)
| TAbstract (a,_) -> Some (TAbstractDecl a)
| TFun _
| TLazy _
| TType _
| TAnon _ ->
assert false
| TMono _
| TDynamic _ ->
None
) in
match t with
| None ->
last := true;
if !else_block then print ctx "{";
if vname <> v.v_name then begin
newline ctx;
print ctx "var %s = %s" v.v_name vname;
end;
gen_block_element ctx e;
if !else_block then begin
newline ctx;
print ctx "}";
end
| Some t ->
if not !else_block then newline ctx;
print ctx "if( %s.__instanceof(%s," (ctx.type_accessor (TClassDecl { null_class with cl_path = ["js"],"Boot" })) vname;
gen_value ctx (mk (TTypeExpr t) (mk_mono()) e.epos);
spr ctx ") ) {";
let bend = open_block ctx in
if vname <> v.v_name then begin
newline ctx;
print ctx "var %s = %s" v.v_name vname;
end;
gen_block_element ctx e;
bend();
newline ctx;
spr ctx "} else ";
else_block := true
) catchs;
if not !last then print ctx "throw(%s)" vname;
bend();
newline ctx;
spr ctx "}";
| TSwitch (e,cases,def) ->
spr ctx "switch";
gen_value ctx e;
spr ctx " {";
newline ctx;
List.iter (fun (el,e2) ->
List.iter (fun e ->
match e.eexpr with
| TConst(c) when c = TNull ->
spr ctx "case null: case undefined:";
| _ ->
spr ctx "case ";
gen_value ctx e;
spr ctx ":"
) el;
let bend = open_block ctx in
gen_block_element ctx e2;
if not (has_return e2) then begin
newline ctx;
print ctx "break";
end;
bend();
newline ctx;
) cases;
(match def with
| None -> ()
| Some e ->
spr ctx "default:";
let bend = open_block ctx in
gen_block_element ctx e;
bend();
newline ctx;
);
spr ctx "}"
| TCast (e,None) ->
gen_expr ctx e
| TCast (e1,Some t) ->
print ctx "%s.__cast(" (ctx.type_accessor (TClassDecl { null_class with cl_path = ["js"],"Boot" }));
gen_expr ctx e1;
spr ctx " , ";
spr ctx (ctx.type_accessor t);
spr ctx ")"
and gen_block_element ?(after=false) ctx e =
match e.eexpr with
| TBlock el ->
List.iter (gen_block_element ~after ctx) el
| TCall ({ eexpr = TLocal { v_name = "__feature__" } }, { eexpr = TConst (TString f) } :: eif :: eelse) ->
if has_feature ctx f then
gen_block_element ~after ctx eif
else (match eelse with
| [] -> ()
| [e] -> gen_block_element ~after ctx e
| _ -> assert false)
| TFunction _ ->
gen_block_element ~after ctx (mk (TParenthesis e) e.etype e.epos)
| TObjectDecl fl ->
List.iter (fun (_,e) -> gen_block_element ~after ctx e) fl
| _ ->
if not after then newline ctx;
gen_expr ctx e;
if after then newline ctx
and gen_value ctx e =
add_mapping ctx e;
let assign e =
mk (TBinop (Ast.OpAssign,
mk (TLocal (match ctx.in_value with None -> assert false | Some v -> v)) t_dynamic e.epos,
e
)) e.etype e.epos
in
let value() =
let old = ctx.in_value, ctx.in_loop in
let r = alloc_var "$r" t_dynamic in
ctx.in_value <- Some r;
ctx.in_loop <- false;
spr ctx "(function($this) ";
spr ctx "{";
let b = open_block ctx in
newline ctx;
spr ctx "var $r";
newline ctx;
(fun() ->
newline ctx;
spr ctx "return $r";
b();
newline ctx;
spr ctx "}";
ctx.in_value <- fst old;
ctx.in_loop <- snd old;
print ctx "(%s))" (this ctx)
)
in
match e.eexpr with
| TConst _
| TLocal _
| TArray _
| TBinop _
| TField _
| TEnumParameter _
| TTypeExpr _
| TParenthesis _
| TObjectDecl _
| TArrayDecl _
| TNew _
| TUnop _
| TFunction _ ->
gen_expr ctx e
| TMeta (_,e1) ->
gen_value ctx e1
| TCall (e,el) ->
gen_call ctx e el true
| TReturn _
| TBreak
| TContinue ->
unsupported e.epos
| TCast (e1, None) ->
gen_value ctx e1
| TCast (e1, Some t) ->
print ctx "%s.__cast(" (ctx.type_accessor (TClassDecl { null_class with cl_path = ["js"],"Boot" }));
gen_value ctx e1;
spr ctx " , ";
spr ctx (ctx.type_accessor t);
spr ctx ")"
| TVar _
| TFor _
| TWhile _
| TThrow _ ->
(* value is discarded anyway *)
let v = value() in
gen_expr ctx e;
v()
| TBlock [e] ->
gen_value ctx e
| TBlock el ->
let v = value() in
let rec loop = function
| [] ->
spr ctx "return null";
| [e] ->
gen_expr ctx (assign e);
| e :: l ->
gen_expr ctx e;
newline ctx;
loop l
in
loop el;
v();
| TIf (cond,e,eo) ->
(* remove parenthesis unless it's an operation with higher precedence than ?: *)
let cond = (match cond.eexpr with
| TParenthesis { eexpr = TBinop ((Ast.OpAssign | Ast.OpAssignOp _),_,_) | TIf _ } -> cond
| TParenthesis e -> e
| _ -> cond
) in
gen_value ctx cond;
spr ctx "?";
gen_value ctx e;
spr ctx ":";
(match eo with
| None -> spr ctx "null"
| Some e -> gen_value ctx e);
| TSwitch (cond,cases,def) ->
let v = value() in
gen_expr ctx (mk (TSwitch (cond,
List.map (fun (e1,e2) -> (e1,assign e2)) cases,
match def with None -> None | Some e -> Some (assign e)
)) e.etype e.epos);
v()
| TTry (b,catchs) ->
let v = value() in
let block e = mk (TBlock [e]) e.etype e.epos in
gen_expr ctx (mk (TTry (block (assign b),
List.map (fun (v,e) -> v, block (assign e)) catchs
)) e.etype e.epos);
v()
let generate_package_create ctx (p,_) =
let rec loop acc = function
| [] -> ()
| p :: l when Hashtbl.mem ctx.packages (p :: acc) -> loop (p :: acc) l
| p :: l ->
Hashtbl.add ctx.packages (p :: acc) ();
(match acc with
| [] ->
if ctx.js_modern then
print ctx "var %s = {}" p
else
print ctx "var %s = %s || {}" p p
| _ ->
let p = String.concat "." (List.rev acc) ^ (field p) in
if ctx.js_modern then
print ctx "%s = {}" p
else
print ctx "if(!%s) %s = {}" p p
);
ctx.separator <- true;
newline ctx;
loop (p :: acc) l
in
match p with
| [] -> print ctx "var "
| _ -> loop [] p
let check_field_name c f =
match f.cf_name with
| "prototype" | "__proto__" | "constructor" ->
error ("The field name '" ^ f.cf_name ^ "' is not allowed in JS") (match f.cf_expr with None -> c.cl_pos | Some e -> e.epos);
| _ -> ()
(* convert a.b.c to ["a"]["b"]["c"] *)
let path_to_brackets path =
let parts = ExtString.String.nsplit path "." in
"[\"" ^ (String.concat "\"][\"" parts) ^ "\"]"
let gen_class_static_field ctx c f =
match f.cf_expr with
| None | Some { eexpr = TConst TNull } when not (has_feature ctx "Type.getClassFields") ->
()
| None when is_extern_field f ->
()
| None ->
print ctx "%s%s = null" (s_path ctx c.cl_path) (static_field c f.cf_name);
newline ctx
| Some e ->
match e.eexpr with
| TFunction _ ->
let path = (s_path ctx c.cl_path) ^ (static_field c f.cf_name) in
let dot_path = (dot_path c.cl_path) ^ (static_field c f.cf_name) in
ctx.id_counter <- 0;
print ctx "%s = " path;
(match (get_exposed ctx dot_path f.cf_meta) with [s] -> print ctx "$hx_exports%s = " (path_to_brackets s) | _ -> ());
gen_value ctx e;
newline ctx;
| _ ->
ctx.statics <- (c,f.cf_name,e) :: ctx.statics
let can_gen_class_field ctx = function
| { cf_expr = (None | Some { eexpr = TConst TNull }) } when not (has_feature ctx "Type.getInstanceFields") ->
false
| f ->
not (is_extern_field f)
let gen_class_field ctx c f =
check_field_name c f;
match f.cf_expr with
| None ->
newprop ctx;
print ctx "%s: " (anon_field f.cf_name);
print ctx "null";
| Some e ->
newprop ctx;
print ctx "%s: " (anon_field f.cf_name);
ctx.id_counter <- 0;
gen_value ctx e;
ctx.separator <- false
let generate_class___name__ ctx c =