forked from HaxeFoundation/haxe
-
Notifications
You must be signed in to change notification settings - Fork 0
/
typer.ml
5152 lines (5023 loc) · 176 KB
/
typer.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
open Typecore
(* ---------------------------------------------------------------------- *)
(* TOOLS *)
type switch_mode =
| CMatch of (tenum_field * (string * t) option list option * pos)
| CExpr of texpr
type access_mode =
| MGet
| MSet
| MCall
type identifier_type =
| ITLocal of tvar
| ITMember of tclass * tclass_field
| ITStatic of tclass * tclass_field
| ITEnum of tenum * tenum_field
| ITGlobal of module_type * string * t
| ITType of module_type
| ITPackage of string
(* order of these variants affects output sorting *)
type display_field_kind =
| FKVar
| FKMethod
| FKType
| FKPackage
exception DisplayFields of (string * t * display_field_kind option * documentation) list
exception DisplayToplevel of identifier_type list
exception WithTypeError of unify_error list * pos
type access_kind =
| AKNo of string
| AKExpr of texpr
| AKSet of texpr * t * tclass_field
| AKInline of texpr * tclass_field * tfield_access * t
| AKMacro of texpr * tclass_field
| AKUsing of texpr * tclass * tclass_field * texpr
| AKAccess of tabstract * tparams * tclass * texpr * texpr
let build_call_ref : (typer -> access_kind -> expr list -> with_type -> pos -> texpr) ref = ref (fun _ _ _ _ _ -> assert false)
let mk_infos ctx p params =
let file = if ctx.in_macro then p.pfile else if Common.defined ctx.com Define.AbsolutePath then Common.get_full_path p.pfile else Filename.basename p.pfile in
(EObjectDecl (
("fileName" , (EConst (String file) , p)) ::
("lineNumber" , (EConst (Int (string_of_int (Lexer.get_error_line p))),p)) ::
("className" , (EConst (String (s_type_path ctx.curclass.cl_path)),p)) ::
if ctx.curfield.cf_name = "" then
params
else
("methodName", (EConst (String ctx.curfield.cf_name),p)) :: params
) ,p)
let check_assign ctx e =
match e.eexpr with
| TLocal {v_extra = None} | TArray _ | TField _ ->
()
| TConst TThis | TTypeExpr _ when ctx.untyped ->
()
| _ ->
error "Invalid assign" e.epos
type type_class =
| KInt
| KFloat
| KString
| KUnk
| KDyn
| KOther
| KParam of t
| KAbstract of tabstract * t list
let rec classify t =
match follow t with
| TInst ({ cl_path = ([],"String") },[]) -> KString
| TAbstract({a_impl = Some _} as a,tl) -> KAbstract (a,tl)
| TAbstract ({ a_path = [],"Int" },[]) -> KInt
| TAbstract ({ a_path = [],"Float" },[]) -> KFloat
| TAbstract (a,[]) when List.exists (fun t -> match classify t with KInt | KFloat -> true | _ -> false) a.a_to -> KParam t
| TInst ({ cl_kind = KTypeParameter ctl },_) when List.exists (fun t -> match classify t with KInt | KFloat -> true | _ -> false) ctl -> KParam t
| TMono r when !r = None -> KUnk
| TDynamic _ -> KDyn
| _ -> KOther
let get_iterator_param t =
match follow t with
| TAnon a ->
if !(a.a_status) <> Closed then raise Not_found;
(match follow (PMap.find "hasNext" a.a_fields).cf_type, follow (PMap.find "next" a.a_fields).cf_type with
| TFun ([],tb), TFun([],t) when (match follow tb with TAbstract ({ a_path = [],"Bool" },[]) -> true | _ -> false) ->
if PMap.fold (fun _ acc -> acc + 1) a.a_fields 0 <> 2 then raise Not_found;
t
| _ ->
raise Not_found)
| _ ->
raise Not_found
let get_iterable_param t =
match follow t with
| TAnon a ->
if !(a.a_status) <> Closed then raise Not_found;
(match follow (PMap.find "iterator" a.a_fields).cf_type with
| TFun ([],it) ->
let t = get_iterator_param it in
if PMap.fold (fun _ acc -> acc + 1) a.a_fields 0 <> 1 then raise Not_found;
t
| _ ->
raise Not_found)
| _ -> raise Not_found
(*
temporally remove the constant flag from structures to allow larger unification
*)
let remove_constant_flag t callb =
let tmp = ref [] in
let rec loop t =
match follow t with
| TAnon a ->
if !(a.a_status) = Const then begin
a.a_status := Closed;
tmp := a :: !tmp;
end;
PMap.iter (fun _ f -> loop f.cf_type) a.a_fields;
| _ ->
()
in
let restore() =
List.iter (fun a -> a.a_status := Const) (!tmp)
in
try
loop t;
let ret = callb (!tmp <> []) in
restore();
ret
with e ->
restore();
raise e
let rec is_pos_infos = function
| TMono r ->
(match !r with
| Some t -> is_pos_infos t
| _ -> false)
| TLazy f ->
is_pos_infos (!f())
| TType ({ t_path = ["haxe"] , "PosInfos" },[]) ->
true
| TType (t,tl) ->
is_pos_infos (apply_params t.t_params tl t.t_type)
| _ ->
false
let check_constraints ctx tname tpl tl map delayed p =
List.iter2 (fun m (name,t) ->
match follow t with
| TInst ({ cl_kind = KTypeParameter constr },_) when constr <> [] ->
let f = (fun() ->
List.iter (fun ct ->
try
Type.unify (map m) (map ct)
with Unify_error l ->
let l = Constraint_failure (tname ^ "." ^ name) :: l in
raise (Unify_error l)
) constr
) in
if delayed then
delay ctx PCheckConstraint (fun () -> try f() with Unify_error l -> display_error ctx (error_msg (Unify l)) p)
else
f()
| _ ->
()
) tl tpl
let enum_field_type ctx en ef tl_en tl_ef p =
let map t = apply_params en.e_params tl_en (apply_params ef.ef_params tl_ef t) in
begin try
check_constraints ctx (s_type_path en.e_path) en.e_params tl_en map true p;
check_constraints ctx ef.ef_name ef.ef_params tl_ef map true p;
with Unify_error l ->
display_error ctx (error_msg (Unify l)) p
end;
map ef.ef_type
let add_constraint_checks ctx ctypes pl f tl p =
List.iter2 (fun m (name,t) ->
match follow t with
| TInst ({ cl_kind = KTypeParameter constr },_) when constr <> [] ->
let constr = List.map (fun t ->
let t = apply_params f.cf_params tl t in
(* only apply params if not static : in that case no param is passed *)
let t = (if pl = [] then t else apply_params ctypes pl t) in
t
) constr in
delay ctx PCheckConstraint (fun() ->
List.iter (fun ct ->
try
(* if has_mono m then raise (Unify_error [Unify_custom "Could not resolve full type for constraint checks"; Unify_custom ("Type was " ^ (s_type (print_context()) m))]); *)
Type.unify m ct
with Unify_error l ->
display_error ctx (error_msg (Unify (Constraint_failure (f.cf_name ^ "." ^ name) :: l))) p;
) constr
);
| _ -> ()
) tl f.cf_params
let field_type ctx c pl f p =
match f.cf_params with
| [] -> f.cf_type
| l ->
let monos = List.map (fun _ -> mk_mono()) l in
if not (Meta.has Meta.Generic f.cf_meta) then add_constraint_checks ctx c.cl_params pl f monos p;
apply_params l monos f.cf_type
let class_field ctx c tl name p =
raw_class_field (fun f -> field_type ctx c tl f p) c tl name
(* checks if we can access to a given class field using current context *)
let rec can_access ctx ?(in_overload=false) c cf stat =
if cf.cf_public then
true
else if not in_overload && ctx.com.config.pf_overload && Meta.has Meta.Overload cf.cf_meta then
true
else
(* TODO: should we add a c == ctx.curclass short check here? *)
(* has metadata path *)
let rec make_path c f = match c.cl_kind with
| KAbstractImpl a -> fst a.a_path @ [snd a.a_path; f.cf_name]
| KGenericInstance(c,_) -> make_path c f
| _ when c.cl_private -> List.rev (f.cf_name :: snd c.cl_path :: (List.tl (List.rev (fst c.cl_path))))
| _ -> fst c.cl_path @ [snd c.cl_path; f.cf_name]
in
let rec expr_path acc e =
match fst e with
| EField (e,f) -> expr_path (f :: acc) e
| EConst (Ident n) -> n :: acc
| _ -> []
in
let rec chk_path psub pfull =
match psub, pfull with
| [], _ -> true
| a :: l1, b :: l2 when a = b -> chk_path l1 l2
| _ -> false
in
let has m c f path =
let rec loop = function
| (m2,el,_) :: l when m = m2 ->
List.exists (fun e ->
let p = expr_path [] e in
(p <> [] && chk_path p path)
) el
|| loop l
| _ :: l -> loop l
| [] -> false
in
loop c.cl_meta || loop f.cf_meta
in
let cur_paths = ref [] in
let rec loop c =
cur_paths := make_path c ctx.curfield :: !cur_paths;
begin match c.cl_super with
| Some (csup,_) -> loop csup
| None -> ()
end;
List.iter (fun (c,_) -> loop c) c.cl_implements;
in
loop ctx.curclass;
let is_constr = cf.cf_name = "new" in
let rec loop c =
(try
(* if our common ancestor declare/override the field, then we can access it *)
let f = if is_constr then (match c.cl_constructor with None -> raise Not_found | Some c -> c) else PMap.find cf.cf_name (if stat then c.cl_statics else c.cl_fields) in
is_parent c ctx.curclass || (List.exists (has Meta.Allow c f) !cur_paths)
with Not_found ->
false
)
|| (match c.cl_super with
| Some (csup,_) -> loop csup
| None -> false)
|| has Meta.Access ctx.curclass ctx.curfield (make_path c cf)
in
let b = loop c
(* access is also allowed of we access a type parameter which is constrained to our (base) class *)
|| (match c.cl_kind with
| KTypeParameter tl ->
List.exists (fun t -> match follow t with TInst(c,_) -> loop c | _ -> false) tl
| _ -> false)
|| (Meta.has Meta.PrivateAccess ctx.meta) in
(* TODO: find out what this does and move it to genas3 *)
if b && Common.defined ctx.com Common.Define.As3 && not (Meta.has Meta.Public cf.cf_meta) then cf.cf_meta <- (Meta.Public,[],cf.cf_pos) :: cf.cf_meta;
b
(* removes the first argument of the class field's function type and all its overloads *)
let prepare_using_field cf = match cf.cf_type with
| TFun((_,_,tf) :: args,ret) ->
let rec loop acc overloads = match overloads with
| ({cf_type = TFun((_,_,tfo) :: args,ret)} as cfo) :: l ->
let tfo = apply_params cfo.cf_params (List.map snd cfo.cf_params) tfo in
(* ignore overloads which have a different first argument *)
if Type.type_iseq tf tfo then loop ({cfo with cf_type = TFun(args,ret)} :: acc) l else loop acc l
| _ :: l ->
loop acc l
| [] ->
acc
in
{cf with cf_overloads = loop [] cf.cf_overloads; cf_type = TFun(args,ret)}
| _ -> cf
let parse_string com s p inlined =
let old = Lexer.save() in
let old_file = (try Some (Hashtbl.find Lexer.all_files p.pfile) with Not_found -> None) in
let old_display = !Parser.resume_display in
let old_de = !Parser.display_error in
let restore() =
(match old_file with
| None -> ()
| Some f -> Hashtbl.replace Lexer.all_files p.pfile f);
if not inlined then Parser.resume_display := old_display;
Lexer.restore old;
Parser.display_error := old_de
in
Lexer.init p.pfile true;
Parser.display_error := (fun e p -> raise (Parser.Error (e,p)));
if not inlined then Parser.resume_display := null_pos;
let pack, decls = try
Parser.parse com (Lexing.from_string s)
with Parser.Error (e,pe) ->
restore();
error (Parser.error_msg e) (if inlined then pe else p)
| Lexer.Error (e,pe) ->
restore();
error (Lexer.error_msg e) (if inlined then pe else p)
in
restore();
pack,decls
let eval ctx s =
let p = { pfile = "--eval"; pmin = 0; pmax = String.length s; } in
let pack,decls = parse_string ctx.com s p false in
let rec find_main current decls = match decls with
| (EClass c,_) :: decls ->
let path = pack,c.d_name in
begin try
let cff = List.find (fun cff -> cff.cff_name = "main") c.d_data in
if ctx.com.main_class <> None then error "Multiple main" cff.cff_pos;
ctx.com.main_class <- Some path;
Some path
with Not_found ->
find_main (if current = None then Some path else current) decls
end
| ((EEnum {d_name = s} | ETypedef {d_name = s} | EAbstract {d_name = s}),_) :: decls when current = None ->
find_main (Some (pack,s)) decls
| _ :: decls ->
find_main current decls
| [] ->
current
in
let path_module = match find_main None decls with
| None -> error "Evaluated string did not define any types" p
| Some path -> path
in
ignore(Typeload.type_module ctx path_module "eval" decls p);
flush_pass ctx PBuildClass "eval"
let parse_expr_string ctx s p inl =
let head = "class X{static function main() " in
let head = (if p.pmin > String.length head then head ^ String.make (p.pmin - String.length head) ' ' else head) in
let rec loop e = let e = Ast.map_expr loop e in (fst e,p) in
match parse_string ctx.com (head ^ s ^ ";}") p inl with
| _,[EClass { d_data = [{ cff_name = "main"; cff_kind = FFun { f_expr = Some e } }]},_] -> if inl then e else loop e
| _ -> raise Interp.Invalid_expr
let collect_toplevel_identifiers ctx =
let acc = DynArray.create () in
(* locals *)
PMap.iter (fun _ v ->
if not (is_gen_local v) then
DynArray.add acc (ITLocal v)
) ctx.locals;
(* member vars *)
if ctx.curfun <> FunStatic then begin
let rec loop c =
List.iter (fun cf ->
DynArray.add acc (ITMember(ctx.curclass,cf))
) c.cl_ordered_fields;
match c.cl_super with
| None ->
()
| Some (csup,tl) ->
loop csup; (* TODO: type parameters *)
in
loop ctx.curclass;
(* TODO: local using? *)
end;
(* statics *)
List.iter (fun cf ->
DynArray.add acc (ITStatic(ctx.curclass,cf))
) ctx.curclass.cl_ordered_statics;
(* enum constructors *)
let rec enum_ctors t =
match t with
| TClassDecl _ | TAbstractDecl _ ->
()
| TTypeDecl t ->
begin match follow t.t_type with
| TEnum (e,_) -> enum_ctors (TEnumDecl e)
| _ -> ()
end
| TEnumDecl e ->
PMap.iter (fun _ ef ->
DynArray.add acc (ITEnum(e,ef))
) e.e_constrs;
in
List.iter enum_ctors ctx.m.curmod.m_types;
List.iter enum_ctors ctx.m.module_types;
(* imported globals *)
PMap.iter (fun _ (mt,s) ->
try
let t = match Typeload.resolve_typedef mt with
| TClassDecl c -> (PMap.find s c.cl_statics).cf_type
| TEnumDecl en -> (PMap.find s en.e_constrs).ef_type
| TAbstractDecl {a_impl = Some c} -> (PMap.find s c.cl_statics).cf_type
| _ -> raise Not_found
in
DynArray.add acc (ITGlobal(mt,s,t))
with Not_found ->
()
) ctx.m.module_globals;
let module_types = ref [] in
let add_type mt =
match mt with
| TClassDecl {cl_kind = KAbstractImpl _} -> ()
| _ ->
let path = (t_infos mt).mt_path in
if not (List.exists (fun mt2 -> (t_infos mt2).mt_path = path) !module_types) then module_types := mt :: !module_types
in
(* module types *)
List.iter add_type ctx.m.curmod.m_types;
(* module imports *)
List.iter add_type ctx.m.module_types;
(* module using *)
List.iter (fun c ->
add_type (TClassDecl c)
) ctx.m.module_using;
(* TODO: wildcard packages. How? *)
(* packages and toplevel types *)
let class_paths = ctx.com.class_path in
let class_paths = List.filter (fun s -> s <> "") class_paths in
let packages = ref [] in
let add_package pack =
try
begin match PMap.find pack ctx.com.package_rules with
| Forbidden ->
()
| _ ->
raise Not_found
end
with Not_found ->
if not (List.mem pack !packages) then packages := pack :: !packages
in
List.iter (fun dir ->
try
let entries = Sys.readdir dir in
Array.iter (fun file ->
match file with
| "." | ".." ->
()
| _ when Sys.is_directory (dir ^ file) ->
add_package file
| _ ->
let l = String.length file in
if l > 3 && String.sub file (l - 3) 3 = ".hx" then begin
try
let name = String.sub file 0 (l - 3) in
let md = Typeload.load_module ctx ([],name) Ast.null_pos in
List.iter (fun mt ->
if (t_infos mt).mt_path = md.m_path then add_type mt
) md.m_types
with _ ->
()
end
) entries;
with Sys_error _ ->
()
) class_paths;
List.iter (fun pack ->
DynArray.add acc (ITPackage pack)
) !packages;
List.iter (fun mt ->
DynArray.add acc (ITType mt)
) !module_types;
raise (DisplayToplevel (DynArray.to_list acc))
(* ---------------------------------------------------------------------- *)
(* PASS 3 : type expression & check structure *)
let rec unify_min_raise ctx (el:texpr list) : t =
let rec base_types t =
let tl = ref [] in
let rec loop t = (match t with
| TInst(cl, params) ->
(match cl.cl_kind with
| KTypeParameter tl -> List.iter loop tl
| _ -> ());
List.iter (fun (ic, ip) ->
let t = apply_params cl.cl_params params (TInst (ic,ip)) in
loop t
) cl.cl_implements;
(match cl.cl_super with None -> () | Some (csup, pl) ->
let t = apply_params cl.cl_params params (TInst (csup,pl)) in
loop t);
tl := t :: !tl;
| TEnum(en,(_ :: _ as tl2)) ->
tl := (TEnum(en,List.map (fun _ -> t_dynamic) tl2)) :: !tl;
tl := t :: !tl;
| TType (td,pl) ->
loop (apply_params td.t_params pl td.t_type);
(* prioritize the most generic definition *)
tl := t :: !tl;
| TLazy f -> loop (!f())
| TMono r -> (match !r with None -> () | Some t -> loop t)
| _ -> tl := t :: !tl)
in
loop t;
!tl
in
match el with
| [] -> mk_mono()
| [e] -> e.etype
| _ ->
let rec chk_null e = is_null e.etype ||
match e.eexpr with
| TConst TNull -> true
| TBlock el ->
(match List.rev el with
| [] -> false
| e :: _ -> chk_null e)
| TParenthesis e | TMeta(_,e) -> chk_null e
| _ -> false
in
(* First pass: Try normal unification and find out if null is involved. *)
let rec loop t = function
| [] ->
false, t
| e :: el ->
let t = if chk_null e then ctx.t.tnull t else t in
try
unify_raise ctx e.etype t e.epos;
loop t el
with Error (Unify _,_) -> try
unify_raise ctx t e.etype e.epos;
loop (if is_null t then ctx.t.tnull e.etype else e.etype) el
with Error (Unify _,_) ->
true, t
in
let has_error, t = loop (mk_mono()) el in
if not has_error then
t
else try
(* specific case for const anon : we don't want to hide fields but restrict their common type *)
let fcount = ref (-1) in
let field_count a =
PMap.fold (fun _ acc -> acc + 1) a.a_fields 0
in
let expr f = match f.cf_expr with None -> mk (TBlock []) f.cf_type f.cf_pos | Some e -> e in
let fields = List.fold_left (fun acc e ->
match follow e.etype with
| TAnon a when !(a.a_status) = Const ->
if !fcount = -1 then begin
fcount := field_count a;
PMap.map (fun f -> [expr f]) a.a_fields
end else begin
if !fcount <> field_count a then raise Not_found;
PMap.mapi (fun n el -> expr (PMap.find n a.a_fields) :: el) acc
end
| _ ->
raise Not_found
) PMap.empty el in
let fields = PMap.foldi (fun n el acc ->
let t = try unify_min_raise ctx el with Error (Unify _, _) -> raise Not_found in
PMap.add n (mk_field n t (List.hd el).epos) acc
) fields PMap.empty in
TAnon { a_fields = fields; a_status = ref Closed }
with Not_found ->
(* Second pass: Get all base types (interfaces, super classes and their interfaces) of most general type.
Then for each additional type filter all types that do not unify. *)
let common_types = base_types t in
let dyn_types = List.fold_left (fun acc t ->
let rec loop c =
Meta.has Meta.UnifyMinDynamic c.cl_meta || (match c.cl_super with None -> false | Some (c,_) -> loop c)
in
match t with
| TInst (c,params) when params <> [] && loop c ->
TInst (c,List.map (fun _ -> t_dynamic) params) :: acc
| _ -> acc
) [] common_types in
let common_types = ref (match List.rev dyn_types with [] -> common_types | l -> common_types @ l) in
let loop e =
let first_error = ref None in
let filter t = (try unify_raise ctx e.etype t e.epos; true
with Error (Unify l, p) as err -> if !first_error = None then first_error := Some(err); false)
in
common_types := List.filter filter !common_types;
match !common_types, !first_error with
| [], Some err -> raise err
| _ -> ()
in
match !common_types with
| [] ->
error "No common base type found" (punion (List.hd el).epos (List.hd (List.rev el)).epos)
| _ ->
List.iter loop (List.tl el);
List.hd !common_types
let unify_min ctx el =
try unify_min_raise ctx el
with Error (Unify l,p) ->
if not ctx.untyped then display_error ctx (error_msg (Unify l)) p;
(List.hd el).etype
let is_forced_inline c cf =
match c with
| Some { cl_extern = true } -> true
| Some { cl_kind = KAbstractImpl _ } -> true
| _ when Meta.has Meta.Extern cf.cf_meta -> true
| _ -> false
let rec unify_call_args' ctx el args r callp inline force_inline =
let call_error err p =
raise (Error (Call_error err,p))
in
let arg_error ul name opt p =
let err = Stack (Unify ul,Custom ("For " ^ (if opt then "optional " else "") ^ "function argument '" ^ name ^ "'")) in
call_error (Could_not_unify err) p
in
let mk_pos_infos t =
let infos = mk_infos ctx callp [] in
type_expr ctx infos (WithType t)
in
let rec default_value name t =
if is_pos_infos t then
mk_pos_infos t
else
null (ctx.t.tnull t) callp
in
let skipped = ref [] in
let skip name ul t =
if not ctx.com.config.pf_can_skip_non_nullable_argument && not (is_nullable t) then
call_error (Cannot_skip_non_nullable name) callp;
skipped := (name,ul) :: !skipped;
default_value name t
in
(* let force_inline, is_extern = match cf with Some(TInst(c,_),f) -> is_forced_inline (Some c) f, c.cl_extern | _ -> false, false in *)
let type_against t e =
let e = type_expr ctx e (WithTypeResume t) in
(try Codegen.AbstractCast.cast_or_unify_raise ctx t e e.epos with Error (Unify l,p) -> raise (WithTypeError (l,p)));
in
let rec loop el args = match el,args with
| [],[] ->
[]
| _,[name,false,t] when (match follow t with TAbstract({a_path = ["haxe";"extern"],"Rest"},_) -> true | _ -> false) ->
begin match follow t with
| TAbstract({a_path=(["haxe";"extern"],"Rest")},[t]) ->
(try List.map (fun e -> type_against t e,false) el with WithTypeError(ul,p) -> arg_error ul name false p)
| _ ->
assert false
end
| [],(_,false,_) :: _ ->
call_error (Not_enough_arguments args) callp
| [],(name,true,t) :: args ->
begin match loop [] args with
| [] when not (inline && (ctx.g.doinline || force_inline)) && not ctx.com.config.pf_pad_nulls ->
if is_pos_infos t then [mk_pos_infos t,true]
else []
| args ->
let e_def = default_value name t in
(e_def,true) :: args
end
| (_,p) :: _, [] ->
begin match List.rev !skipped with
| [] -> call_error Too_many_arguments p
| (s,ul) :: _ -> arg_error ul s true p
end
| e :: el,(name,opt,t) :: args ->
begin try
let e = type_against t e in
(e,opt) :: loop el args
with
WithTypeError (ul,p) ->
if opt then
let e_def = skip name ul t in
(e_def,true) :: loop (e :: el) args
else
arg_error ul name false p
end
in
let el = loop el args in
el,TFun(args,r)
let unify_call_args ctx el args r p inline force_inline =
let el,tf = unify_call_args' ctx el args r p inline force_inline in
List.map fst el,tf
let unify_field_call ctx fa el args ret p inline =
let map_cf cf0 map cf =
let t = map (monomorphs cf.cf_params cf.cf_type) in
begin match cf.cf_expr,cf.cf_kind with
| None,Method MethInline when not ctx.com.config.pf_overload ->
(* This is really awkward and shouldn't be here. We'll keep it for
3.2 in order to not break code that relied on the quirky behavior
in 3.1.3, but it should really be reviewed afterwards.
Related issue: https://github.com/HaxeFoundation/haxe/issues/3846
*)
cf.cf_expr <- cf0.cf_expr;
cf.cf_kind <- cf0.cf_kind;
| _ ->
()
end;
t,cf
in
let expand_overloads map cf =
(TFun(args,ret),cf) :: (List.map (map_cf cf map) cf.cf_overloads)
in
let candidates,co,cf,mk_fa = match fa with
| FStatic(c,cf) ->
expand_overloads (fun t -> t) cf,Some c,cf,(fun cf -> FStatic(c,cf))
| FAnon cf ->
expand_overloads (fun t -> t) cf,None,cf,(fun cf -> FAnon cf)
| FInstance(c,tl,cf) ->
let map = apply_params c.cl_params tl in
let cfl = if cf.cf_name = "new" || not (Meta.has Meta.Overload cf.cf_meta && ctx.com.config.pf_overload) then
List.map (map_cf cf map) cf.cf_overloads
else
List.map (fun (t,cf) -> map (monomorphs cf.cf_params t),cf) (Typeload.get_overloads c cf.cf_name)
in
(TFun(args,ret),cf) :: cfl,Some c,cf,(fun cf -> FInstance(c,tl,cf))
| FClosure(co,cf) ->
let c = match co with None -> None | Some (c,_) -> Some c in
expand_overloads (fun t -> t) cf,c,cf,(fun cf -> match co with None -> FAnon cf | Some (c,tl) -> FInstance(c,tl,cf))
| _ ->
error "Invalid field call" p
in
let is_forced_inline = is_forced_inline co cf in
let is_overload = Meta.has Meta.Overload cf.cf_meta in
let attempt_call t cf = match follow t with
| TFun(args,ret) ->
let el,tf = unify_call_args' ctx el args ret p inline is_forced_inline in
let mk_call ethis p_field =
let ef = mk (TField(ethis,mk_fa cf)) tf p_field in
make_call ctx ef (List.map fst el) ret p
in
el,tf,mk_call
| _ ->
assert false
in
let rec loop candidates = match candidates with
| [] -> [],[]
| (t,cf) :: candidates ->
begin try
let candidate = attempt_call t cf in
if ctx.com.config.pf_overload && is_overload then begin
let candidates,failures = loop candidates in
candidate :: candidates,failures
end else
[candidate],[]
with Error (Call_error _,_) as err ->
let candidates,failures = loop candidates in
candidates,err :: failures
end
in
match candidates with
| [t,cf] ->
let el,tf,mk_call = attempt_call t cf in
List.map fst el,tf,mk_call
| _ ->
let candidates,failures = loop candidates in
let fail () = match List.rev failures with
| err :: _ -> raise err
| _ -> assert false
in
if is_overload && ctx.com.config.pf_overload then begin match Codegen.Overloads.reduce_compatible candidates with
| [] -> fail()
| [el,tf,mk_call] -> List.map fst el,tf,mk_call
| _ -> error "Ambiguous overload" p
end else begin match List.rev candidates with
| [] -> fail()
| (el,tf,mk_call) :: _ -> List.map fst el,tf,mk_call
end
let fast_enum_field e ef p =
let et = mk (TTypeExpr (TEnumDecl e)) (TAnon { a_fields = PMap.empty; a_status = ref (EnumStatics e) }) p in
TField (et,FEnum (e,ef))
let rec type_module_type ctx t tparams p =
match t with
| TClassDecl c ->
let t_tmp = {
t_path = [],"Class<" ^ (s_type_path c.cl_path) ^ ">" ;
t_module = c.cl_module;
t_doc = None;
t_pos = c.cl_pos;
t_type = TAnon {
a_fields = c.cl_statics;
a_status = ref (Statics c);
};
t_private = true;
t_params = [];
t_meta = no_meta;
} in
mk (TTypeExpr (TClassDecl c)) (TType (t_tmp,[])) p
| TEnumDecl e ->
let types = (match tparams with None -> List.map (fun _ -> mk_mono()) e.e_params | Some l -> l) in
mk (TTypeExpr (TEnumDecl e)) (TType (e.e_type,types)) p
| TTypeDecl s ->
let t = apply_params s.t_params (List.map (fun _ -> mk_mono()) s.t_params) s.t_type in
if not (Common.defined ctx.com Define.NoDeprecationWarnings) then
Codegen.DeprecationCheck.check_typedef ctx.com s p;
(match follow t with
| TEnum (e,params) ->
type_module_type ctx (TEnumDecl e) (Some params) p
| TInst (c,params) ->
type_module_type ctx (TClassDecl c) (Some params) p
| TAbstract (a,params) ->
type_module_type ctx (TAbstractDecl a) (Some params) p
| _ ->
error (s_type_path s.t_path ^ " is not a value") p)
| TAbstractDecl { a_impl = Some c } ->
type_module_type ctx (TClassDecl c) tparams p
| TAbstractDecl a ->
if not (Meta.has Meta.RuntimeValue a.a_meta) then error (s_type_path a.a_path ^ " is not a value") p;
let t_tmp = {
t_path = [],"Abstract<" ^ (s_type_path a.a_path) ^ ">";
t_module = a.a_module;
t_doc = None;
t_pos = a.a_pos;
t_type = TAnon {
a_fields = PMap.empty;
a_status = ref (AbstractStatics a);
};
t_private = true;
t_params = [];
t_meta = no_meta;
} in
mk (TTypeExpr (TAbstractDecl a)) (TType (t_tmp,[])) p
let type_type ctx tpath p =
type_module_type ctx (Typeload.load_type_def ctx p { tpackage = fst tpath; tname = snd tpath; tparams = []; tsub = None }) None p
let get_constructor ctx c params p =
match c.cl_kind with
| KAbstractImpl a ->
let f = (try PMap.find "_new" c.cl_statics with Not_found -> error (s_type_path a.a_path ^ " does not have a constructor") p) in
let ct = field_type ctx c params f p in
apply_params a.a_params params ct, f
| _ ->
let ct, f = (try Type.get_constructor (fun f -> field_type ctx c params f p) c with Not_found -> error (s_type_path c.cl_path ^ " does not have a constructor") p) in
apply_params c.cl_params params ct, f
let make_call ctx e params t p =
try
let ethis,cl,f = match e.eexpr with
| TField (ethis,fa) ->
let co,cf = match fa with
| FInstance(c,_,cf) | FStatic(c,cf) -> Some c,cf
| FAnon cf -> None,cf
| _ -> raise Exit
in
ethis,co,cf
| _ ->
raise Exit
in
if f.cf_kind <> Method MethInline then raise Exit;
let config = match cl with
| Some ({cl_kind = KAbstractImpl _}) when Meta.has Meta.Impl f.cf_meta ->
let t = if f.cf_name = "_new" then
t
else if params = [] then
error "Invalid abstract implementation function" f.cf_pos
else
follow (List.hd params).etype
in
begin match t with
| TAbstract(a,pl) ->
let has_params = a.a_params <> [] || f.cf_params <> [] in
let monos = List.map (fun _ -> mk_mono()) f.cf_params in
let map_type = fun t -> apply_params a.a_params pl (apply_params f.cf_params monos t) in
Some (has_params,map_type)
| _ ->
None
end
| _ ->
None
in
ignore(follow f.cf_type); (* force evaluation *)
let params = List.map (ctx.g.do_optimize ctx) params in
let force_inline = is_forced_inline cl f in
(match f.cf_expr with
| Some { eexpr = TFunction fd } ->
(match Optimizer.type_inline ctx f fd ethis params t config p force_inline with
| None ->
if force_inline then error "Inline could not be done" p;
raise Exit;
| Some e -> e)
| _ ->
(*
we can't inline because there is most likely a loop in the typing.
this can be caused by mutually recursive vars/functions, some of them
being inlined or not. In that case simply ignore inlining.
*)
raise Exit)
with Exit ->
mk (TCall (e,params)) t p
let mk_array_get_call ctx (cf,tf,r,e1,e2o) c ebase p = match cf.cf_expr with
| None ->
if not (Meta.has Meta.NoExpr cf.cf_meta) && ctx.com.display = DMNone then display_error ctx "Recursive array get method" p;
mk (TArray(ebase,e1)) r p
| Some _ ->
let et = type_module_type ctx (TClassDecl c) None p in
let ef = mk (TField(et,(FStatic(c,cf)))) tf p in
make_call ctx ef [ebase;e1] r p
let mk_array_set_call ctx (cf,tf,r,e1,e2o) c ebase p =
let evalue = match e2o with None -> assert false | Some e -> e in
match cf.cf_expr with
| None ->
if not (Meta.has Meta.NoExpr cf.cf_meta) && ctx.com.display = DMNone then display_error ctx "Recursive array set method" p;
let ea = mk (TArray(ebase,e1)) r p in
mk (TBinop(OpAssign,ea,evalue)) r p
| Some _ ->
let et = type_module_type ctx (TClassDecl c) None p in
let ef = mk (TField(et,(FStatic(c,cf)))) tf p in
make_call ctx ef [ebase;e1;evalue] r p
let rec acc_get ctx g p =
match g with
| AKNo f -> error ("Field " ^ f ^ " cannot be accessed for reading") p
| AKExpr e -> e
| AKSet _ | AKAccess _ -> assert false
| AKUsing (et,c,cf,e) when ctx.in_display ->
(* Generate a TField node so we can easily match it for position/usage completion (issue #1968) *)
let ec = type_module_type ctx (TClassDecl c) None p in
let t = match follow et.etype with
| TFun (_ :: args,ret) -> TFun(args,ret)
| _ -> et.etype
in
mk (TField(ec,FStatic(c,cf))) t et.epos
| AKUsing (et,_,cf,e) ->
(* build a closure with first parameter applied *)
(match follow et.etype with
| TFun (_ :: args,ret) ->
let tcallb = TFun (args,ret) in
let twrap = TFun ([("_e",false,e.etype)],tcallb) in
(* arguments might not have names in case of variable fields of function types, so we generate one (issue #2495) *)
let args = List.map (fun (n,o,t) ->
let t = if o then ctx.t.tnull t else t in