forked from HaxeFoundation/haxe
-
Notifications
You must be signed in to change notification settings - Fork 3
/
codegen.ml
1863 lines (1756 loc) · 62 KB
/
codegen.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
open Typecore
(* -------------------------------------------------------------------------- *)
(* TOOLS *)
let field e name t p =
mk (TField (e,try quick_field e.etype name with Not_found -> assert false)) t p
let fcall e name el ret p =
let ft = tfun (List.map (fun e -> e.etype) el) ret in
mk (TCall (field e name ft p,el)) ret p
let mk_parent e =
mk (TParenthesis e) e.etype e.epos
let string com str p =
mk (TConst (TString str)) com.basic.tstring p
let binop op a b t p =
mk (TBinop (op,a,b)) t p
let index com e index t p =
mk (TArray (e,mk (TConst (TInt (Int32.of_int index))) com.basic.tint p)) t p
let type_constant com c p =
let t = com.basic in
match c with
| Int s ->
if String.length s > 10 && String.sub s 0 2 = "0x" then error "Invalid hexadecimal integer" p;
(try mk (TConst (TInt (Int32.of_string s))) t.tint p
with _ -> mk (TConst (TFloat s)) t.tfloat p)
| Float f -> mk (TConst (TFloat f)) t.tfloat p
| String s -> mk (TConst (TString s)) t.tstring p
| Ident "true" -> mk (TConst (TBool true)) t.tbool p
| Ident "false" -> mk (TConst (TBool false)) t.tbool p
| Ident "null" -> mk (TConst TNull) (t.tnull (mk_mono())) p
| Ident t -> error ("Invalid constant : " ^ t) p
| Regexp _ -> error "Invalid constant" p
let rec type_constant_value com (e,p) =
match e with
| EConst c ->
type_constant com c p
| EParenthesis e ->
type_constant_value com e
| EObjectDecl el ->
mk (TObjectDecl (List.map (fun (n,e) -> n, type_constant_value com e) el)) (TAnon { a_fields = PMap.empty; a_status = ref Closed }) p
| EArrayDecl el ->
mk (TArrayDecl (List.map (type_constant_value com) el)) (com.basic.tarray t_dynamic) p
| _ ->
error "Constant value expected" p
let rec has_properties c =
List.exists (fun f ->
match f.cf_kind with
| Var { v_read = AccCall } -> true
| Var { v_write = AccCall } -> true
| _ when Meta.has Meta.Accessor f.cf_meta -> true
| _ -> false
) c.cl_ordered_fields || (match c.cl_super with Some (c,_) -> has_properties c | _ -> false)
let get_properties fields =
List.fold_left (fun acc f ->
if Meta.has Meta.Accessor f.cf_meta then
(f.cf_name, f.cf_name) :: acc
else
let acc = (match f.cf_kind with
| Var { v_read = AccCall } -> ("get_" ^ f.cf_name , "get_" ^ f.cf_name) :: acc
| _ -> acc) in
match f.cf_kind with
| Var { v_write = AccCall } -> ("set_" ^ f.cf_name , "set_" ^ f.cf_name) :: acc
| _ -> acc
) [] fields
let add_property_field com c =
let p = c.cl_pos in
let props = get_properties (c.cl_ordered_statics @ c.cl_ordered_fields) in
match props with
| [] -> ()
| _ ->
let fields,values = List.fold_left (fun (fields,values) (n,v) ->
let cf = mk_field n com.basic.tstring p in
PMap.add n cf fields,(n, string com v p) :: values
) (PMap.empty,[]) props in
let t = mk_anon fields in
let e = mk (TObjectDecl values) t p in
let cf = mk_field "__properties__" t p in
cf.cf_expr <- Some e;
c.cl_statics <- PMap.add cf.cf_name cf c.cl_statics;
c.cl_ordered_statics <- cf :: c.cl_ordered_statics
let is_removable_field ctx f =
Meta.has Meta.Extern f.cf_meta || Meta.has Meta.Generic f.cf_meta
|| (match f.cf_kind with
| Var {v_read = AccRequire (s,_)} -> true
| Method MethMacro -> not ctx.in_macro
| _ -> false)
(* -------------------------------------------------------------------------- *)
(* REMOTING PROXYS *)
let extend_remoting ctx c t p async prot =
if c.cl_super <> None then error "Cannot extend several classes" p;
(* remove forbidden packages *)
let rules = ctx.com.package_rules in
ctx.com.package_rules <- PMap.foldi (fun key r acc -> match r with Forbidden -> acc | _ -> PMap.add key r acc) rules PMap.empty;
(* parse module *)
let path = (t.tpackage,t.tname) in
let new_name = (if async then "Async_" else "Remoting_") ^ t.tname in
(* check if the proxy already exists *)
let t = (try
Typeload.load_type_def ctx p { tpackage = fst path; tname = new_name; tparams = []; tsub = None }
with
Error (Module_not_found _,p2) when p == p2 ->
(* build it *)
Common.log ctx.com ("Building proxy for " ^ s_type_path path);
let file, decls = (try
Typeload.parse_module ctx path p
with
| Not_found -> ctx.com.package_rules <- rules; error ("Could not load proxy module " ^ s_type_path path ^ (if fst path = [] then " (try using absolute path)" else "")) p
| e -> ctx.com.package_rules <- rules; raise e) in
ctx.com.package_rules <- rules;
let base_fields = [
{ cff_name = "__cnx"; cff_pos = p; cff_doc = None; cff_meta = []; cff_access = []; cff_kind = FVar (Some (CTPath { tpackage = ["haxe";"remoting"]; tname = if async then "AsyncConnection" else "Connection"; tparams = []; tsub = None }),None) };
{ cff_name = "new"; cff_pos = p; cff_doc = None; cff_meta = []; cff_access = [APublic]; cff_kind = FFun { f_args = ["c",false,None,None]; f_type = None; f_expr = Some (EBinop (OpAssign,(EConst (Ident "__cnx"),p),(EConst (Ident "c"),p)),p); f_params = [] } };
] in
let tvoid = CTPath { tpackage = []; tname = "Void"; tparams = []; tsub = None } in
let build_field is_public acc f =
if f.cff_name = "new" then
acc
else match f.cff_kind with
| FFun fd when (is_public || List.mem APublic f.cff_access) && not (List.mem AStatic f.cff_access) ->
if List.exists (fun (_,_,t,_) -> t = None) fd.f_args then error ("Field " ^ f.cff_name ^ " type is not complete and cannot be used by RemotingProxy") p;
let eargs = [EArrayDecl (List.map (fun (a,_,_,_) -> (EConst (Ident a),p)) fd.f_args),p] in
let ftype = (match fd.f_type with Some (CTPath { tpackage = []; tname = "Void" }) -> None | _ -> fd.f_type) in
let fargs, eargs = if async then match ftype with
| Some tret -> fd.f_args @ ["__callb",true,Some (CTFunction ([tret],tvoid)),None], eargs @ [EConst (Ident "__callb"),p]
| _ -> fd.f_args, eargs @ [EConst (Ident "null"),p]
else
fd.f_args, eargs
in
let id = (EConst (String f.cff_name), p) in
let id = if prot then id else ECall ((EConst (Ident "__unprotect__"),p),[id]),p in
let expr = ECall (
(EField (
(ECall ((EField ((EConst (Ident "__cnx"),p),"resolve"),p),[id]),p),
"call")
,p),eargs),p
in
let expr = if async || ftype = None then expr else (EReturn (Some expr),p) in
let fd = {
f_params = fd.f_params;
f_args = fargs;
f_type = if async then None else ftype;
f_expr = Some (EBlock [expr],p);
} in
{ cff_name = f.cff_name; cff_pos = p; cff_doc = None; cff_meta = []; cff_access = [APublic]; cff_kind = FFun fd } :: acc
| _ -> acc
in
let decls = List.map (fun d ->
match d with
| EClass c, p when c.d_name = t.tname ->
let is_public = List.mem HExtern c.d_flags || List.mem HInterface c.d_flags in
let fields = List.rev (List.fold_left (build_field is_public) base_fields c.d_data) in
(EClass { c with d_flags = []; d_name = new_name; d_data = fields },p)
| _ -> d
) decls in
let m = Typeload.type_module ctx (t.tpackage,new_name) file decls p in
add_dependency ctx.m.curmod m;
try
List.find (fun tdecl -> snd (t_path tdecl) = new_name) m.m_types
with Not_found ->
error ("Module " ^ s_type_path path ^ " does not define type " ^ t.tname) p
) in
match t with
| TClassDecl c2 when c2.cl_params = [] -> c2.cl_build(); c.cl_super <- Some (c2,[]);
| _ -> error "Remoting proxy must be a class without parameters" p
(* -------------------------------------------------------------------------- *)
(* HAXE.RTTI.GENERIC *)
exception Generic_Exception of string * Ast.pos
type generic_context = {
ctx : typer;
subst : (t * t) list;
name : string;
p : pos;
mutable mg : module_def option;
}
let make_generic ctx ps pt p =
let rec loop l1 l2 =
match l1, l2 with
| [] , [] -> []
| (x,TLazy f) :: l1, _ -> loop ((x,(!f)()) :: l1) l2
| (_,t1) :: l1 , t2 :: l2 -> (t1,t2) :: loop l1 l2
| _ -> assert false
in
let name =
String.concat "_" (List.map2 (fun (s,_) t ->
let s_type_path_underscore (p,s) = match p with [] -> s | _ -> String.concat "_" p ^ "_" ^ s in
let rec loop top t = match follow t with
| TInst(c,tl) -> (s_type_path_underscore c.cl_path) ^ (loop_tl tl)
| TEnum(en,tl) -> (s_type_path_underscore en.e_path) ^ (loop_tl tl)
| TAbstract(a,tl) -> (s_type_path_underscore a.a_path) ^ (loop_tl tl)
| _ when not top -> "_" (* allow unknown/incompatible types as type parameters to retain old behavior *)
| TMono _ -> raise (Generic_Exception (("Could not determine type for parameter " ^ s), p))
| t -> raise (Generic_Exception (("Type parameter must be a class or enum instance (found " ^ (s_type (print_context()) t) ^ ")"), p))
and loop_tl tl = match tl with
| [] -> ""
| tl -> "_" ^ String.concat "_" (List.map (loop false) tl)
in
loop true t
) ps pt)
in
{
ctx = ctx;
subst = loop ps pt;
name = name;
p = p;
mg = None;
}
let rec generic_substitute_type gctx t =
match t with
| TInst ({ cl_kind = KGeneric } as c2,tl2) ->
(* maybe loop, or generate cascading generics *)
let _, _, f = gctx.ctx.g.do_build_instance gctx.ctx (TClassDecl c2) gctx.p in
let t = f (List.map (generic_substitute_type gctx) tl2) in
(match follow t,gctx.mg with TInst(c,_), Some m -> add_dependency m c.cl_module | _ -> ());
t
| _ ->
try
generic_substitute_type gctx (List.assq t gctx.subst)
with Not_found ->
Type.map (generic_substitute_type gctx) t
let generic_substitute_expr gctx e =
let vars = Hashtbl.create 0 in
let build_var v =
try
Hashtbl.find vars v.v_id
with Not_found ->
let v2 = alloc_var v.v_name (generic_substitute_type gctx v.v_type) in
v2.v_meta <- v.v_meta;
Hashtbl.add vars v.v_id v2;
v2
in
let rec build_expr e =
match e.eexpr with
| TField(e1, FInstance({cl_kind = KGeneric} as c,tl,cf)) ->
let _, _, f = gctx.ctx.g.do_build_instance gctx.ctx (TClassDecl c) gctx.p in
let t = f (List.map (generic_substitute_type gctx) tl) in
build_expr {e with eexpr = TField(e1,quick_field t cf.cf_name)}
| _ ->
map_expr_type build_expr (generic_substitute_type gctx) build_var e
in
build_expr e
let has_ctor_constraint c = match c.cl_kind with
| KTypeParameter tl ->
List.exists (fun t -> match follow t with
| TAnon a when PMap.mem "new" a.a_fields -> true
| _ -> false
) tl;
| _ -> false
let get_short_name =
let i = ref (-1) in
(fun () ->
incr i;
Printf.sprintf "__hx_type_%i" !i
)
let rec build_generic ctx c p tl =
let pack = fst c.cl_path in
let recurse = ref false in
let rec check_recursive t =
match follow t with
| TInst (c2,tl) ->
(match c2.cl_kind with
| KTypeParameter tl ->
if not (Typeload.is_generic_parameter ctx c2) && has_ctor_constraint c2 then
error "Type parameters with a constructor cannot be used non-generically" p;
recurse := true
| _ -> ());
List.iter check_recursive tl;
| _ ->
()
in
List.iter check_recursive tl;
if !recurse then begin
TInst (c,tl) (* build a normal instance *)
end else begin
let gctx = make_generic ctx c.cl_params tl p in
let name = (snd c.cl_path) ^ "_" ^ gctx.name in
try
Typeload.load_instance ctx { tpackage = pack; tname = name; tparams = []; tsub = None } p false
with Error(Module_not_found path,_) when path = (pack,name) ->
let m = (try Hashtbl.find ctx.g.modules (Hashtbl.find ctx.g.types_module c.cl_path) with Not_found -> assert false) in
let ctx = { ctx with m = { ctx.m with module_types = m.m_types @ ctx.m.module_types } } in
c.cl_build(); (* make sure the super class is already setup *)
let mg = {
m_id = alloc_mid();
m_path = (pack,name);
m_types = [];
m_extra = module_extra (s_type_path (pack,name)) m.m_extra.m_sign 0. MFake;
} in
gctx.mg <- Some mg;
let cg = mk_class mg (pack,name) c.cl_pos in
mg.m_types <- [TClassDecl cg];
Hashtbl.add ctx.g.modules mg.m_path mg;
add_dependency mg m;
add_dependency ctx.m.curmod mg;
(* ensure that type parameters are set in dependencies *)
let dep_stack = ref [] in
let rec loop t =
if not (List.memq t !dep_stack) then begin
dep_stack := t :: !dep_stack;
match t with
| TInst (c,tl) -> add_dep c.cl_module tl
| TEnum (e,tl) -> add_dep e.e_module tl
| TType (t,tl) -> add_dep t.t_module tl
| TAbstract (a,tl) -> add_dep a.a_module tl
| TMono r ->
(match !r with
| None -> ()
| Some t -> loop t)
| TLazy f ->
loop ((!f)());
| TDynamic t2 ->
if t == t2 then () else loop t2
| TAnon a ->
PMap.iter (fun _ f -> loop f.cf_type) a.a_fields
| TFun (args,ret) ->
List.iter (fun (_,_,t) -> loop t) args;
loop ret
end
and add_dep m tl =
add_dependency mg m;
List.iter loop tl
in
List.iter loop tl;
let build_field cf_old =
let cf_new = {cf_old with cf_pos = cf_old.cf_pos} in (* copy *)
let f () =
let t = generic_substitute_type gctx cf_old.cf_type in
ignore (follow t);
begin try (match cf_old.cf_expr with
| None ->
begin match cf_old.cf_kind with
| Method _ when not c.cl_interface && not c.cl_extern ->
display_error ctx (Printf.sprintf "Field %s has no expression (possible typing order issue)" cf_new.cf_name) cf_new.cf_pos;
display_error ctx (Printf.sprintf "While building %s" (s_type_path cg.cl_path)) p;
| _ ->
()
end
| Some e ->
cf_new.cf_expr <- Some (generic_substitute_expr gctx e)
) with Unify_error l ->
error (error_msg (Unify l)) cf_new.cf_pos
end;
t
in
let r = exc_protect ctx (fun r ->
let t = mk_mono() in
r := (fun() -> t);
unify_raise ctx (f()) t p;
t
) "build_generic" in
delay ctx PForce (fun() -> ignore ((!r)()));
cf_new.cf_type <- TLazy r;
cf_new
in
if c.cl_init <> None || c.cl_dynamic <> None then error "This class can't be generic" p;
List.iter (fun cf -> match cf.cf_kind with
| Method MethMacro when not ctx.in_macro -> ()
| _ -> error "A generic class can't have static fields" cf.cf_pos
) c.cl_ordered_statics;
cg.cl_super <- (match c.cl_super with
| None -> None
| Some (cs,pl) ->
let find_class subst =
let rec loop subst = match subst with
| (TInst(c,[]),t) :: subst when c == cs -> t
| _ :: subst -> loop subst
| [] -> raise Not_found
in
try
if pl <> [] then raise Not_found;
let t = loop subst in
(* extended type parameter: concrete type must have a constructor, but generic base class must not have one *)
begin match follow t,c.cl_constructor with
| TInst(cs,_),None ->
cs.cl_build();
begin match cs.cl_constructor with
| None -> error ("Cannot use " ^ (s_type_path cs.cl_path) ^ " as type parameter because it is extended and has no constructor") p
| _ -> ()
end;
| _,Some cf -> error "Generics extending type parameters cannot have constructors" cf.cf_pos
| _ -> ()
end;
t
with Not_found ->
apply_params c.cl_params tl (TInst(cs,pl))
in
let ts = follow (find_class gctx.subst) in
let cs,pl = Typeload.check_extends ctx c ts p in
match cs.cl_kind with
| KGeneric ->
(match build_generic ctx cs p pl with
| TInst (cs,pl) -> Some (cs,pl)
| _ -> assert false)
| _ -> Some(cs,pl)
);
Typeload.add_constructor ctx cg false p;
cg.cl_kind <- KGenericInstance (c,tl);
cg.cl_interface <- c.cl_interface;
cg.cl_constructor <- (match cg.cl_constructor, c.cl_constructor, c.cl_super with
| _, Some cf, _ -> Some (build_field cf)
| Some ctor, _, _ -> Some ctor
| None, None, None -> None
| _ -> error "Please define a constructor for this class in order to use it as generic" c.cl_pos
);
cg.cl_implements <- List.map (fun (i,tl) ->
(match follow (generic_substitute_type gctx (TInst (i, List.map (generic_substitute_type gctx) tl))) with
| TInst (i,tl) -> i, tl
| _ -> assert false)
) c.cl_implements;
cg.cl_ordered_fields <- List.map (fun f ->
let f = build_field f in
cg.cl_fields <- PMap.add f.cf_name f cg.cl_fields;
f
) c.cl_ordered_fields;
(* In rare cases the class name can become too long, so let's shorten it (issue #3090). *)
if String.length (snd cg.cl_path) > 254 then begin
let n = get_short_name () in
let tp = fst cg.cl_path,n in
cg.cl_meta <- (Meta.Native,[EConst(String (s_type_path tp)),p],p) :: cg.cl_meta;
end;
TInst (cg,[])
end
(* -------------------------------------------------------------------------- *)
(* HAXE.XML.PROXY *)
let extend_xml_proxy ctx c t file p =
let t = Typeload.load_complex_type ctx p t in
let file = (try Common.find_file ctx.com file with Not_found -> file) in
add_dependency c.cl_module (create_fake_module ctx file);
let used = ref PMap.empty in
let print_results() =
PMap.iter (fun id used ->
if not used then ctx.com.warning (id ^ " is not used") p;
) (!used)
in
let check_used = Common.defined ctx.com Define.CheckXmlProxy in
if check_used then ctx.g.hook_generate <- print_results :: ctx.g.hook_generate;
try
let rec loop = function
| Xml.Element (_,attrs,childs) ->
(try
let id = List.assoc "id" attrs in
if PMap.mem id c.cl_fields then error ("Duplicate id " ^ id) p;
let t = if not check_used then t else begin
used := PMap.add id false (!used);
let ft() = used := PMap.add id true (!used); t in
TLazy (ref ft)
end in
let f = {
cf_name = id;
cf_type = t;
cf_public = true;
cf_pos = p;
cf_doc = None;
cf_meta = no_meta;
cf_kind = Var { v_read = AccResolve; v_write = AccNo };
cf_params = [];
cf_expr = None;
cf_overloads = [];
} in
c.cl_fields <- PMap.add id f c.cl_fields;
with
Not_found -> ());
List.iter loop childs;
| Xml.PCData _ -> ()
in
loop (Xml.parse_file file)
with
| Xml.Error e -> error ("XML error " ^ Xml.error e) p
| Xml.File_not_found f -> error ("XML File not found : " ^ f) p
(* -------------------------------------------------------------------------- *)
(* BUILD META DATA OBJECT *)
let build_metadata com t =
let api = com.basic in
let p, meta, fields, statics = (match t with
| TClassDecl c ->
let fields = List.map (fun f -> f.cf_name,f.cf_meta) (c.cl_ordered_fields @ (match c.cl_constructor with None -> [] | Some f -> [{ f with cf_name = "_" }])) in
let statics = List.map (fun f -> f.cf_name,f.cf_meta) c.cl_ordered_statics in
(c.cl_pos, ["",c.cl_meta],fields,statics)
| TEnumDecl e ->
(e.e_pos, ["",e.e_meta],List.map (fun n -> n, (PMap.find n e.e_constrs).ef_meta) e.e_names, [])
| TTypeDecl t ->
(t.t_pos, ["",t.t_meta],(match follow t.t_type with TAnon a -> PMap.fold (fun f acc -> (f.cf_name,f.cf_meta) :: acc) a.a_fields [] | _ -> []),[])
| TAbstractDecl a ->
(a.a_pos, ["",a.a_meta],[],[])
) in
let filter l =
let l = List.map (fun (n,ml) -> n, ExtList.List.filter_map (fun (m,el,p) -> match m with Meta.Custom s when String.length s > 0 && s.[0] <> ':' -> Some (s,el,p) | _ -> None) ml) l in
List.filter (fun (_,ml) -> ml <> []) l
in
let meta, fields, statics = filter meta, filter fields, filter statics in
let make_meta_field ml =
let h = Hashtbl.create 0 in
mk (TObjectDecl (List.map (fun (f,el,p) ->
if Hashtbl.mem h f then error ("Duplicate metadata '" ^ f ^ "'") p;
Hashtbl.add h f ();
f, mk (match el with [] -> TConst TNull | _ -> TArrayDecl (List.map (type_constant_value com) el)) (api.tarray t_dynamic) p
) ml)) (api.tarray t_dynamic) p
in
let make_meta l =
mk (TObjectDecl (List.map (fun (f,ml) -> f,make_meta_field ml) l)) t_dynamic p
in
if meta = [] && fields = [] && statics = [] then
None
else
let meta_obj = [] in
let meta_obj = (if fields = [] then meta_obj else ("fields",make_meta fields) :: meta_obj) in
let meta_obj = (if statics = [] then meta_obj else ("statics",make_meta statics) :: meta_obj) in
let meta_obj = (try ("obj", make_meta_field (List.assoc "" meta)) :: meta_obj with Not_found -> meta_obj) in
Some (mk (TObjectDecl meta_obj) t_dynamic p)
(* -------------------------------------------------------------------------- *)
(* MACRO TYPE *)
let get_macro_path ctx e args p =
let rec loop e =
match fst e with
| EField (e,f) -> f :: loop e
| EConst (Ident i) -> [i]
| _ -> error "Invalid macro call" p
in
let path = match e with
| (EConst(Ident i)),_ ->
let path = try
if not (PMap.mem i ctx.curclass.cl_statics) then raise Not_found;
ctx.curclass.cl_path
with Not_found -> try
(t_infos (fst (PMap.find i ctx.m.module_globals))).mt_path
with Not_found ->
error "Invalid macro call" p
in
i :: (snd path) :: (fst path)
| _ ->
loop e
in
(match path with
| meth :: cl :: path -> (List.rev path,cl), meth, args
| _ -> error "Invalid macro call" p)
let build_macro_type ctx pl p =
let path, field, args = (match pl with
| [TInst ({ cl_kind = KExpr (ECall (e,args),_) },_)]
| [TInst ({ cl_kind = KExpr (EArrayDecl [ECall (e,args),_],_) },_)] ->
get_macro_path ctx e args p
| _ ->
error "MacroType requires a single expression call parameter" p
) in
let old = ctx.ret in
let t = (match ctx.g.do_macro ctx MMacroType path field args p with
| None -> mk_mono()
| Some _ -> ctx.ret
) in
ctx.ret <- old;
t
let build_macro_build ctx c pl cfl p =
let path, field, args = match Meta.get Meta.GenericBuild c.cl_meta with
| _,[ECall(e,args),_],_ -> get_macro_path ctx e args p
| _ -> error "genericBuild requires a single expression call parameter" p
in
let old = ctx.ret,ctx.g.get_build_infos in
ctx.g.get_build_infos <- (fun() -> Some (TClassDecl c, pl, cfl));
let t = (match ctx.g.do_macro ctx MMacroType path field args p with
| None -> mk_mono()
| Some _ -> ctx.ret
) in
ctx.ret <- fst old;
ctx.g.get_build_infos <- snd old;
t
(* -------------------------------------------------------------------------- *)
(* API EVENTS *)
let build_instance ctx mtype p =
match mtype with
| TClassDecl c ->
if ctx.pass > PBuildClass then c.cl_build();
let build f s =
let r = exc_protect ctx (fun r ->
let t = mk_mono() in
r := (fun() -> t);
unify_raise ctx (f()) t p;
t
) s in
delay ctx PForce (fun() -> ignore ((!r)()));
TLazy r
in
let ft = (fun pl ->
match c.cl_kind with
| KGeneric ->
build (fun () -> build_generic ctx c p pl) "build_generic"
| KMacroType ->
build (fun () -> build_macro_type ctx pl p) "macro_type"
| KGenericBuild cfl ->
build (fun () -> build_macro_build ctx c pl cfl p) "generic_build"
| _ ->
TInst (c,pl)
) in
c.cl_params , c.cl_path , ft
| TEnumDecl e ->
e.e_params , e.e_path , (fun t -> TEnum (e,t))
| TTypeDecl t ->
t.t_params , t.t_path , (fun tl -> TType(t,tl))
| TAbstractDecl a ->
a.a_params, a.a_path, (fun tl -> TAbstract(a,tl))
let on_inherit ctx c p h =
match h with
| HExtends { tpackage = ["haxe";"remoting"]; tname = "Proxy"; tparams = [TPType(CTPath t)] } ->
extend_remoting ctx c t p false true;
false
| HExtends { tpackage = ["haxe";"remoting"]; tname = "AsyncProxy"; tparams = [TPType(CTPath t)] } ->
extend_remoting ctx c t p true true;
false
| HExtends { tpackage = ["haxe";"xml"]; tname = "Proxy"; tparams = [TPExpr(EConst (String file),p);TPType t] } ->
extend_xml_proxy ctx c t file p;
true
| _ ->
true
(* -------------------------------------------------------------------------- *)
(* ABSTRACT CASTS *)
module AbstractCast = struct
let cast_stack = ref []
let make_static_call ctx c cf a pl args t p =
make_static_call ctx c cf (apply_params a.a_params pl) args t p
let do_check_cast ctx tleft eright p =
let recurse cf f =
if cf == ctx.curfield || List.mem cf !cast_stack then error "Recursive implicit cast" p;
cast_stack := cf :: !cast_stack;
let r = f() in
cast_stack := List.tl !cast_stack;
r
in
let find a tl f =
let tcf,cf = f() in
if (Meta.has Meta.MultiType a.a_meta) then
mk_cast eright tleft p
else match a.a_impl with
| Some c -> recurse cf (fun () -> make_static_call ctx c cf a tl [eright] tleft p)
| None -> assert false
in
if type_iseq tleft eright.etype then
eright
else begin
let rec loop tleft tright = match follow tleft,follow tright with
| TAbstract(a1,tl1),TAbstract(a2,tl2) ->
begin try find a2 tl2 (fun () -> Abstract.find_to a2 tl2 tleft)
with Not_found -> try find a1 tl1 (fun () -> Abstract.find_from a1 tl1 eright.etype tleft)
with Not_found -> raise Not_found
end
| TAbstract(a,tl),_ ->
begin try find a tl (fun () -> Abstract.find_from a tl eright.etype tleft)
with Not_found ->
let rec loop2 tcl = match tcl with
| tc :: tcl ->
if not (type_iseq tc tleft) then loop (apply_params a.a_params tl tc) tright
else loop2 tcl
| [] -> raise Not_found
in
loop2 a.a_from
end
| _,TAbstract(a,tl) ->
begin try find a tl (fun () -> Abstract.find_to a tl tleft)
with Not_found ->
let rec loop2 tcl = match tcl with
| tc :: tcl ->
if not (type_iseq tc tright) then loop tleft (apply_params a.a_params tl tc)
else loop2 tcl
| [] -> raise Not_found
in
loop2 a.a_to
end
| _ ->
raise Not_found
in
loop tleft eright.etype
end
let cast_or_unify_raise ctx tleft eright p =
try
if ctx.com.display <> DMNone then raise Not_found;
do_check_cast ctx tleft eright p
with Not_found ->
unify_raise ctx eright.etype tleft p;
eright
let cast_or_unify ctx tleft eright p =
try
cast_or_unify_raise ctx tleft eright p
with Error (Unify _ as err,_) ->
if not ctx.untyped then display_error ctx (error_msg err) p;
eright
let find_array_access_raise ctx a pl e1 e2o p =
let is_set = e2o <> None in
let ta = apply_params a.a_params pl a.a_this in
let rec loop cfl = match cfl with
| [] -> raise Not_found
| cf :: cfl when not (Ast.Meta.has Ast.Meta.ArrayAccess cf.cf_meta) ->
loop cfl
| cf :: cfl ->
let monos = List.map (fun _ -> mk_mono()) cf.cf_params in
let map t = apply_params a.a_params pl (apply_params cf.cf_params monos t) in
let check_constraints () =
List.iter2 (fun m (name,t) -> match follow t with
| TInst ({ cl_kind = KTypeParameter constr },_) when constr <> [] ->
List.iter (fun tc -> match follow m with TMono _ -> raise (Unify_error []) | _ -> Type.unify m (map tc) ) constr
| _ -> ()
) monos cf.cf_params;
in
match follow (map cf.cf_type) with
| TFun([(_,_,tab);(_,_,ta1);(_,_,ta2)],r) as tf when is_set ->
begin try
Type.unify tab ta;
let e1 = cast_or_unify_raise ctx ta1 e1 p in
let e2o = match e2o with None -> None | Some e2 -> Some (cast_or_unify_raise ctx ta2 e2 p) in
check_constraints();
cf,tf,r,e1,e2o
with Unify_error _ | Error (Unify _,_) ->
loop cfl
end
| TFun([(_,_,tab);(_,_,ta1)],r) as tf when not is_set ->
begin try
Type.unify tab ta;
let e1 = cast_or_unify_raise ctx ta1 e1 p in
check_constraints();
cf,tf,r,e1,None
with Unify_error _ | Error (Unify _,_) ->
loop cfl
end
| _ -> loop cfl
in
loop a.a_array
let find_array_access ctx a tl e1 e2o p =
try find_array_access_raise ctx a tl e1 e2o p
with Not_found -> match e2o with
| None ->
error (Printf.sprintf "No @:arrayAccess function accepts argument of %s" (s_type (print_context()) e1.etype)) p
| Some e2 ->
error (Printf.sprintf "No @:arrayAccess function accepts arguments of %s and %s" (s_type (print_context()) e1.etype) (s_type (print_context()) e2.etype)) p
let find_multitype_specialization com a pl p =
let m = mk_mono() in
let tl = match Meta.get Meta.MultiType a.a_meta with
| _,[],_ -> pl
| _,el,_ ->
let relevant = Hashtbl.create 0 in
List.iter (fun e -> match fst e with
| EConst(Ident s) -> Hashtbl.replace relevant s true
| _ -> error "Type parameter expected" (pos e)
) el;
let tl = List.map2 (fun (n,_) t -> if Hashtbl.mem relevant n || not (has_mono t) then t else t_dynamic) a.a_params pl in
if com.platform = Js && a.a_path = ([],"Map") then begin match tl with
| t1 :: _ ->
let rec loop stack t =
if List.exists (fun t2 -> fast_eq t t2) stack then
t
else begin
let stack = t :: stack in
match follow t with
| TAbstract ({ a_path = [],"Class" },_) ->
error (Printf.sprintf "Cannot use %s as key type to Map because Class<T> is not comparable" (s_type (print_context()) t1)) p;
| TEnum(en,tl) ->
PMap.iter (fun _ ef -> ignore(loop stack ef.ef_type)) en.e_constrs;
Type.map (loop stack) t
| t ->
Type.map (loop stack) t
end
in
ignore(loop [] t1)
| _ -> assert false
end;
tl
in
let _,cf =
try
Abstract.find_to a tl m
with Not_found ->
let at = apply_params a.a_params pl a.a_this in
let st = s_type (print_context()) at in
if has_mono at then
error ("Type parameters of multi type abstracts must be known (for " ^ st ^ ")") p
else
error ("Abstract " ^ (s_type_path a.a_path) ^ " has no @:to function that accepts " ^ st) p;
in
cf, follow m
let handle_abstract_casts ctx e =
let rec loop ctx e = match e.eexpr with
| TNew({cl_kind = KAbstractImpl a} as c,pl,el) ->
(* a TNew of an abstract implementation is only generated if it is a multi type abstract *)
let cf,m = find_multitype_specialization ctx.com a pl e.epos in
let e = make_static_call ctx c cf a pl ((mk (TConst TNull) (TAbstract(a,pl)) e.epos) :: el) m e.epos in
{e with etype = m}
| TCall({eexpr = TField(_,FStatic({cl_path=[],"Std"},{cf_name = "string"}))},[e1]) when (match follow e1.etype with TAbstract({a_impl = Some _},_) -> true | _ -> false) ->
begin match follow e1.etype with
| TAbstract({a_impl = Some c} as a,tl) ->
begin try
let cf = PMap.find "toString" c.cl_statics in
make_static_call ctx c cf a tl [e1] ctx.t.tstring e.epos
with Not_found ->
e
end
| _ ->
assert false
end
| TCall(e1, el) ->
begin try
begin match e1.eexpr with
| TField(e2,fa) ->
begin match follow e2.etype with
| TAbstract(a,pl) when Meta.has Meta.MultiType a.a_meta ->
let m = Abstract.get_underlying_type a pl in
let fname = field_name fa in
let el = List.map (loop ctx) el in
begin try
let ef = mk (TField({e2 with etype = m},quick_field m fname)) e1.etype e2.epos in
make_call ctx ef el e.etype e.epos
with Not_found ->
(* quick_field raises Not_found if m is an abstract, we have to replicate the 'using' call here *)
match follow m with
| TAbstract({a_impl = Some c} as a,pl) ->
let cf = PMap.find fname c.cl_statics in
make_static_call ctx c cf a pl (e2 :: el) e.etype e.epos
| _ -> raise Not_found
end
| _ -> raise Not_found
end
| _ ->
raise Not_found
end
with Not_found ->
Type.map_expr (loop ctx) e
end
| _ ->
Type.map_expr (loop ctx) e
in
loop ctx e
end
module PatternMatchConversion = struct
type cctx = {
ctx : typer;
mutable eval_stack : ((tvar * pos) * texpr) list list;
dt_lookup : dt array;
}
let is_declared cctx v =
let rec loop sl = match sl with
| stack :: sl ->
List.exists (fun ((v2,_),_) -> v == v2) stack || loop sl
| [] ->
false
in
loop cctx.eval_stack
let group_cases cases =
let dt_eq dt1 dt2 = match dt1,dt2 with
| DTGoto i1, DTGoto i2 when i1 = i2 -> true
(* TODO equal bindings *)
| _ -> false
in
match List.rev cases with
| [] -> []
| [con,dt] -> [[con],dt]
| (con,dt) :: cases ->
let tmp,ldt,cases = List.fold_left (fun (tmp,ldt,acc) (con,dt) ->
if dt_eq dt ldt then
(con :: tmp,dt,acc)
else
([con],dt,(tmp,ldt) :: acc)
) ([con],dt,[]) cases in
match tmp with
| [] -> cases
| tmp -> ((tmp,ldt) :: cases)
let rec convert_dt cctx dt =
match dt with
| DTBind (bl,dt) ->
cctx.eval_stack <- bl :: cctx.eval_stack;
let e = convert_dt cctx dt in
cctx.eval_stack <- List.tl cctx.eval_stack;
let vl,el = List.fold_left (fun (vl,el) ((v,p),e) ->
if is_declared cctx v then
vl, (mk (TBinop(OpAssign,mk (TLocal v) v.v_type p,e)) e.etype e.epos) :: el
else
((v,p,Some e) :: vl), el
) ([],[e]) bl in
let el_v = List.map (fun (v,p,eo) -> mk (TVar (v,eo)) cctx.ctx.t.tvoid p) vl in
mk (TBlock (el_v @ el)) e.etype e.epos
| DTGoto i ->
convert_dt cctx (cctx.dt_lookup.(i))
| DTExpr e ->
e
| DTGuard(e,dt1,dt2) ->
let ethen = convert_dt cctx dt1 in
mk (TIf(e,ethen,match dt2 with None -> None | Some dt -> Some (convert_dt cctx dt))) ethen.etype (punion e.epos ethen.epos)
| DTSwitch({eexpr = TMeta((Meta.Exhaustive,_,_),_)},[_,dt],None) ->
convert_dt cctx dt
| DTSwitch(e_st,cl,dto) ->
let def = match dto with None -> None | Some dt -> Some (convert_dt cctx dt) in
let cases = group_cases cl in
let cases = List.map (fun (cl,dt) -> cl,convert_dt cctx dt) cases in
mk (TSwitch(e_st,cases,def)) (mk_mono()) e_st.epos
let to_typed_ast ctx dt p =
let first = dt.dt_dt_lookup.(dt.dt_first) in
let cctx = {
ctx = ctx;
dt_lookup = dt.dt_dt_lookup;
eval_stack = [];
} in
let e = convert_dt cctx first in
let e = { e with epos = p; etype = dt.dt_type} in
if dt.dt_var_init = [] then
e
else begin
let el_v = List.map (fun (v,eo) -> mk (TVar (v,eo)) cctx.ctx.t.tvoid p) dt.dt_var_init in
mk (TBlock (el_v @ [e])) dt.dt_type e.epos
end
end
(* -------------------------------------------------------------------------- *)
(* USAGE *)
let detect_usage com =
let usage = ref [] in
List.iter (fun t -> match t with
| TClassDecl c ->
let check_constructor c p =
try
let _,cf = get_constructor (fun cf -> cf.cf_type) c in
if Meta.has Meta.Usage cf.cf_meta then
usage := p :: !usage;
with Not_found ->
()
in
let rec expr e = match e.eexpr with
| TField(_,FEnum(_,ef)) when Meta.has Meta.Usage ef.ef_meta ->
let p = {e.epos with pmin = e.epos.pmax - (String.length ef.ef_name)} in
usage := p :: !usage;
Type.iter expr e
| TField(_,(FAnon cf | FInstance (_,_,cf) | FStatic (_,cf) | FClosure (_,cf))) when Meta.has Meta.Usage cf.cf_meta ->
let p = {e.epos with pmin = e.epos.pmax - (String.length cf.cf_name)} in