-
Notifications
You must be signed in to change notification settings - Fork 3k
/
naming.ml
2067 lines (1896 loc) · 72 KB
/
naming.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) 2014, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the "hack" directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*)
(** Module "naming" a program.
*
* The naming phase consists in several things
* 1- get all the global names
* 2- transform all the local names into a unique identifier
*)
open Utils
open Ast
module N = Nast
module ShapeMap = N.ShapeMap
module SN = Naming_special_names
(*****************************************************************************)
(* The types *)
(*****************************************************************************)
type fun_set = Utils.SSet.t
type class_set = Utils.SSet.t
type typedef_set = Utils.SSet.t
type const_set = Utils.SSet.t
type decl_set = fun_set * class_set * typedef_set * const_set
type class_cache = Nast.class_ option Utils.SMap.t ref
(* We want to keep the positions of names that have been
* replaced by identifiers.
*)
type positioned_ident = (Pos.t * Ident.t)
type map = positioned_ident SMap.t
type canon_names_map = string SMap.t
let canon_key = String.lowercase
(* <T as A>, A is a type constraint *)
type type_constraint = hint option
type genv = {
(* strict? decl? partial? *)
in_mode: Ast.mode;
(* are we in the body of a try statement? *)
in_try: bool;
(* are we in the body of a non-static member function? *)
in_member_fun: bool;
(* In function foo<T1, ..., Tn> or class<T1, ..., Tn>, the field
* type_params knows T1 .. Tn. It is able to find out about the
* constraint on these parameters. *)
type_params: type_constraint SMap.t;
(* The parameters is their original order
* Necessary to type "this".
*)
type_paraml: Ast.id list;
(* Set of class names defined, and their positions *)
classes: (map * canon_names_map) ref;
(* Set of function names defined, and their positions *)
funs: map ref;
(* Set of typedef names defined, and their position *)
typedefs: map ref;
(* Set of constant names defined, and their position *)
gconsts: map ref;
(* The current class, None if we are in a function *)
cclass: Ast.class_ option;
(* Normally we don't need to add dependencies at this stage, but there
* are edge cases when we do. *)
droot: Typing_deps.Dep.variant option;
(* Namespace environment, e.g., what namespace we're in and what use
* declarations are in play. *)
namespace: Namespace_env.env;
}
(* How to behave when we see an unbound name. Either we raise an
error, or we call a function first and continue if it can resolve
the name. This is used to nest environments when processing
closures. *)
type unbound_mode =
| UBMErr
| UBMFunc of ((Pos.t * string) -> positioned_ident)
(* The local environment *)
type lenv = {
(* The set of locals *)
locals: map ref;
(* The set of constants *)
consts: map ref;
(* A map of variable names to a list of previous references.
Only used in find refs mode *)
references: (Pos.t list) SMap.t ref;
(* Variable name of the target we're finding references for,
if we've found it *)
find_refs_target_name: string option ref;
(* We keep all the locals, even if we are in a different scope
* to provide better error messages.
* if you write:
* if(...) {
* $x = ...;
* }
* Technically, passed this point, $x is unbound.
* But it is much better to keep it somewhere, so that you can
* say it is bound, but in a different scope.
*)
all_locals: Pos.t SMap.t ref;
(* Some statements can define new variables afterwards, e.g.,
* if (...) {
* $x = ...;
* } else {
* $x = ...;
* }
* We need to give $x the same name in both branches, but we don't want
* $x to actually be a local until after the if block. So we stash it here,
* to indicate a name has been pre-allocated, but that the variable isn't
* actually defined yet.
*)
pending_locals: map ref;
(* Tag controlling what we do when we encounter an unbound name.
* This is used when processing a lambda expression body that has
* an automatic use list.
*
* See expr_lambda for details.
*)
unbound_mode: unbound_mode;
(* The presence of "yield" in the function body changes the type of the
* function into a generator, with no other syntactic indications
* elsewhere. For the sanity of the typechecker, we flatten this out into
* fun_kind, but need to track if we've seen a "yield" in order to do so.
*)
has_yield: bool ref;
}
(* The environment VISIBLE to the outside world. *)
type env = {
iclasses: map * canon_names_map;
ifuns: map;
itypedefs: map;
iconsts: map;
}
(**
* Returns the list of classes which have been seen.
* Useful for things like dumping json formatted information about the www
* world.
*)
let get_classes env =
SMap.fold (fun key _ acc -> key :: acc) (fst env.iclasses) []
(*****************************************************************************)
(* Predefined names *)
(*****************************************************************************)
let predef_funs = ref SMap.empty
let predef_fun x =
let var = Pos.none, Ident.make x in
predef_funs := SMap.add x var !predef_funs;
x
let anon = predef_fun "?anon"
let is_int = predef_fun SN.StdlibFunctions.is_int
let is_bool = predef_fun SN.StdlibFunctions.is_bool
let is_array = predef_fun SN.StdlibFunctions.is_array
let is_float = predef_fun SN.StdlibFunctions.is_float
let is_string = predef_fun SN.StdlibFunctions.is_string
let is_null = predef_fun SN.StdlibFunctions.is_null
let is_resource = predef_fun SN.StdlibFunctions.is_resource
let predef_tests_list =
[is_int; is_bool; is_float; is_string; is_null; is_array; is_resource]
let predef_tests = List.fold_right SSet.add predef_tests_list SSet.empty
(*****************************************************************************)
(* Empty (initial) environments *)
(*****************************************************************************)
let empty = {
iclasses = SMap.empty, SMap.empty;
ifuns = !predef_funs;
itypedefs = SMap.empty;
iconsts = SMap.empty;
}
(* The primitives to manipulate the naming environment *)
module Env = struct
let empty_local() = {
locals = ref SMap.empty;
consts = ref SMap.empty;
all_locals = ref SMap.empty;
references = ref SMap.empty;
pending_locals = ref SMap.empty;
find_refs_target_name = ref None;
unbound_mode = UBMErr;
has_yield = ref false;
}
let empty_global env = {
in_mode = Ast.Mstrict;
in_try = false;
in_member_fun = false;
type_params = SMap.empty;
type_paraml = [];
classes = ref env.iclasses;
funs = ref env.ifuns;
typedefs = ref env.itypedefs;
gconsts = ref env.iconsts;
cclass = None;
droot = None;
namespace = Namespace_env.empty;
}
let make_class_genv genv params c = {
in_mode =
(if !Autocomplete.auto_complete then Ast.Mpartial else c.c_mode);
in_try = false;
in_member_fun = false;
type_params = params;
type_paraml = List.map (fun (_, x, _) -> x) c.c_tparams;
classes = ref genv.iclasses;
funs = ref genv.ifuns;
typedefs = ref genv.itypedefs;
gconsts = ref genv.iconsts;
cclass = Some c;
droot = Some (Typing_deps.Dep.Class (snd c.c_name));
namespace = c.c_namespace;
}
let make_class_env genv params c =
let genv = make_class_genv genv params c in
let lenv = empty_local () in
let env = genv, lenv in
env
let make_typedef_genv genv cstrs tdef = {
in_mode = (if !Ide.is_ide_mode then Ast.Mpartial else Ast.Mstrict);
in_try = false;
in_member_fun = false;
type_params = cstrs;
type_paraml = List.map (fun (_, x, _) -> x) tdef.t_tparams;
classes = ref genv.iclasses;
funs = ref genv.ifuns;
typedefs = ref genv.itypedefs;
gconsts = ref genv.iconsts;
cclass = None;
droot = None;
namespace = tdef.t_namespace;
}
let make_typedef_env genv cstrs tdef =
let genv = make_typedef_genv genv cstrs tdef in
let lenv = empty_local () in
let env = genv, lenv in
env
let make_fun_genv genv params f = {
in_mode = f.f_mode;
in_try = false;
in_member_fun = false;
type_params = params;
type_paraml = [];
classes = ref genv.iclasses;
funs = ref genv.ifuns;
typedefs = ref genv.itypedefs;
gconsts = ref genv.iconsts;
cclass = None;
droot = Some (Typing_deps.Dep.Fun (snd f.f_name));
namespace = f.f_namespace;
}
let make_const_genv genv cst = {
in_mode = cst.cst_mode;
in_try = false;
in_member_fun = false;
type_params = SMap.empty;
type_paraml = [];
classes = ref genv.iclasses;
funs = ref genv.ifuns;
typedefs = ref genv.itypedefs;
gconsts = ref genv.iconsts;
cclass = None;
droot = Some (Typing_deps.Dep.GConst (snd cst.cst_name));
namespace = cst.cst_namespace;
}
let make_const_env genv cst =
let genv = make_const_genv genv cst in
let lenv = empty_local () in
let env = genv, lenv in
env
let new_var env (p, x) =
if SMap.mem x !env
then begin
let p', _ = SMap.find_unsafe x !env in
Errors.error_name_already_bound x x p p'
end;
let y = p, Ident.make x in
env := SMap.add x y !env;
y
let lookup genv env (p, x) =
let v = SMap.get x !env in
match v with
| None ->
(match genv.in_mode with
| Ast.Mstrict -> Errors.unbound_name p x
| Ast.Mdecl | Ast.Mpartial -> ()
);
p, Ident.make x
| Some v -> p, snd v
(* Check and see if the user might have been trying to use one of the
* generics in scope as a runtime value *)
let check_no_runtime_generic genv (p, name) =
let tparaml = SMap.keys genv.type_params in
if List.mem name tparaml then Errors.generic_at_runtime p;
()
let canonicalize genv env_and_names (p, name) =
let env, canon_names = !env_and_names in
if SMap.mem name env then (p, name)
else (
let name_key = canon_key name in
match SMap.get name_key canon_names with
| Some canonical ->
let p_canon, _ = SMap.find_unsafe canonical env in
Errors.did_you_mean_naming p name p_canon canonical;
(* Recovering from the capitalization error means
* returning the name in its canonical form *)
p, canonical
| None ->
(match genv.in_mode with
| Ast.Mstrict -> Errors.unbound_name p name
| Ast.Mdecl | Ast.Mpartial -> ());
p, name
)
(* Is called bad_style, but it is still an error ... Whatever *)
let bad_style env (p, x) =
let p' = SMap.get x !(env.all_locals) in
match p' with None -> assert false | Some p' ->
Errors.different_scope p x p'
let is_superglobal =
let l = [
"$GLOBALS"; "$_SERVER"; "$_GET"; "$_POST"; "$_FILES";
"$_COOKIE"; "$_SESSION"; "$_REQUEST"; "$_ENV"
] in
let h = Hashtbl.create 23 in
List.iter (fun x -> Hashtbl.add h x true) l;
fun x -> Hashtbl.mem h x
(* Adds a local variable, without any check *)
let add_lvar (_, lenv) (_, name) (p, x) =
lenv.locals := SMap.add name (p, x) !(lenv.locals)
(* Saves the position of local variables if we're in find refs mode*)
let save_ref x p lenv =
Find_refs.process_var_ref p x;
(* If we've already located the target and name of this var is
the same, add it to the result list *)
(match !(lenv.find_refs_target_name) with
| Some target ->
if target = x then
Find_refs.find_refs_result := p :: !Find_refs.find_refs_result;
| None -> ()
);
(* If we haven't found the target yet: *)
match !Find_refs.find_refs_target with
| None -> ()
| Some (line, char_pos) ->
(* store the location of this reference for later *)
lenv.references := (match SMap.get x !(lenv.references) with
| None -> SMap.add x (p :: []) !(lenv.references)
| Some lst -> SMap.add x (p :: lst) !(lenv.references));
let l, start, end_ = Pos.info_pos p in
if l = line && start <= char_pos && char_pos <= end_
then begin
(* This is the target, so stop looking for it,
save the target name, and copy the current references
to this target to the result list *)
Find_refs.find_refs_target := None;
lenv.find_refs_target_name := Some x;
Find_refs.find_refs_result :=
(match SMap.get x !(lenv.references) with
| None -> []
| Some lst -> lst
);
end;
()
(* Defines a new local variable *)
let new_lvar (_, lenv) (p, x) =
let lcl = SMap.get x !(lenv.locals) in
match lcl with
| Some lcl -> p, snd lcl
| None ->
save_ref x p lenv;
let ident = match SMap.get x !(lenv.pending_locals) with
| Some (_, ident) -> ident
| None -> Ident.make x in
let y = p, ident in
lenv.all_locals := SMap.add x p !(lenv.all_locals);
lenv.locals := SMap.add x y !(lenv.locals);
y
let new_pending_lvar (_, lenv) (p, x) =
match SMap.get x !(lenv.locals), SMap.get x !(lenv.pending_locals) with
| None, None ->
let y = p, Ident.make x in
lenv.pending_locals := SMap.add x y !(lenv.pending_locals)
| _ -> ()
let promote_pending (_, lenv as env) =
SMap.iter begin fun x (p, ident) ->
add_lvar env (p, x) (p, ident)
end !(lenv.pending_locals);
lenv.pending_locals := SMap.empty
let handle_undefined_variable (genv, env) (p, x) =
match env.unbound_mode with
| UBMErr -> Errors.undefined p x; p, Ident.make x
| UBMFunc f -> f (p, x)
(* Function used to name a local variable *)
let lvar (genv, env) (p, x) =
if is_superglobal x && genv.in_mode = Ast.Mpartial
then p, Ident.tmp()
else
let lcl = SMap.get x !(env.locals) in
match lcl with
| Some lcl -> (if fst lcl != p then save_ref x p env); p, snd lcl
| None when not !Autocomplete.auto_complete ->
if SMap.mem x !(env.all_locals)
then bad_style env (p, x);
handle_undefined_variable (genv, env) (p, x)
| None -> p, Ident.tmp()
let get_name genv namespace x =
ignore (lookup genv namespace x); x
(* For dealing with namespace fallback on functions and constants. *)
let elaborate_and_get_name_with_fallback mk_dep genv genv_sect x =
let fq_x = Namespaces.elaborate_id genv.namespace x in
let need_fallback =
genv.namespace.Namespace_env.ns_name <> None &&
not (String.contains (snd x) '\\') in
if need_fallback then begin
let global_x = (fst x, "\\" ^ (snd x)) in
(* Explicitly add dependencies on both of the functions we could be
* referring to here. Normally naming doesn't have to deal with deps at
* all -- they are added during typechecking just by the nature of
* looking up a class or function name. However, we're flattening
* namespaces here, and the fallback behavior of functions means that we
* might suddenly be referring to a different function without any
* change to the callsite at all. Adding both dependencies explicitly
* captures this action-at-a-distance. *)
Typing_deps.add_idep genv.droot (mk_dep (snd fq_x));
Typing_deps.add_idep genv.droot (mk_dep (snd global_x));
let mem (_, s) = SMap.mem s !(genv_sect) in
match mem fq_x, mem global_x with
(* Found in the current namespace *)
| true, _ -> get_name genv genv_sect fq_x
(* Found in the global namespace *)
| _, true -> get_name genv genv_sect global_x
(* Not found. Pick the more specific one to error on. *)
| false, false -> get_name genv genv_sect fq_x
end else
get_name genv genv_sect fq_x
let const (genv, env) x = get_name genv env.consts x
let global_const (genv, env) x =
elaborate_and_get_name_with_fallback
(* Same idea as Dep.FunName, see below. *)
(fun x -> Typing_deps.Dep.GConstName x)
genv
genv.gconsts
x
let class_name (genv, _) x =
(* Generic names are not allowed to shadow class names *)
check_no_runtime_generic genv x;
let x = Namespaces.elaborate_id genv.namespace x in
let pos, name = canonicalize genv genv.classes x in
(* Don't let people use strictly internal classes
* (except when they are being declared in .hhi files) *)
if name = SN.Classes.cHH_BuiltinEnum &&
not (str_ends_with (Relative_path.to_absolute (Pos.filename pos)) ".hhi")
then Errors.using_internal_class pos (strip_ns name);
pos, name
let fun_id (genv, _) x =
elaborate_and_get_name_with_fallback
(* Not just Dep.Fun, but Dep.FunName. This forces an incremental full
* redeclaration of this class if the name changes, not just a
* retypecheck -- the name that is referred to here actually changes as
* a result of what else is defined, which is stronger than just the need
* to retypecheck. *)
(fun x -> Typing_deps.Dep.FunName x)
genv
genv.funs
x
let new_const (genv, env) x =
try ignore (new_var env.consts x); x with exn ->
match genv.in_mode with
| Ast.Mstrict -> raise exn
| Ast.Mpartial | Ast.Mdecl -> x
let resilient_new_canon_var env_and_names (p, name) =
let env, canon_names = !env_and_names in
let name_key = canon_key name in
match SMap.get name_key canon_names with
| Some canonical ->
let p', id = SMap.find_unsafe canonical env in
if Pos.compare p p' = 0 then (p, id)
else begin
Errors.error_name_already_bound name canonical p p';
p', id
end
| None ->
let pos_and_id = p, Ident.make name in
env_and_names :=
SMap.add name pos_and_id env, SMap.add name_key name canon_names;
pos_and_id
let resilient_new_var env (p, x) =
if SMap.mem x !env
then begin
let p', y = SMap.find_unsafe x !env in
if Pos.compare p p' = 0 then (p, y)
else begin
Errors.error_name_already_bound x x p p';
p', y
end
end
else
let y = p, Ident.make x in
env := SMap.add x y !env;
y
let new_fun_id genv x =
if SMap.mem (snd x) !predef_funs then () else
ignore (resilient_new_var genv.funs x)
let new_class_id genv x =
ignore (resilient_new_canon_var genv.classes x)
let new_typedef_id genv x =
let v = resilient_new_canon_var genv.classes x in
genv.typedefs := SMap.add (snd x) v !(genv.typedefs);
()
let new_global_const_id genv x =
let v = resilient_new_var genv.gconsts x in
genv.gconsts := SMap.add (snd x) v !(genv.gconsts);
()
(* Scope, keep the locals, go and name the body, and leave the
* local environment intact
*)
let scope env f =
let genv, lenv = env in
let lenv_copy = !(lenv.locals) in
let lenv_pending_copy = !(lenv.pending_locals) in
let res = f env in
lenv.locals := lenv_copy;
lenv.pending_locals := lenv_pending_copy;
res
end
(*****************************************************************************)
(* Updating the environment *)
(*****************************************************************************)
let remove_decls env (funs, classes, typedefs, consts) =
let funs = SSet.diff funs predef_tests in
let ifuns = SSet.fold SMap.remove funs env.ifuns in
let canonicalize_set = (fun elt acc -> SSet.add (canon_key elt) acc) in
let class_namekeys = SSet.fold canonicalize_set classes SSet.empty in
let typedef_namekeys = SSet.fold canonicalize_set typedefs SSet.empty in
let iclassmap, iclassnames = env.iclasses in
let iclassmap, iclassnames =
SSet.fold SMap.remove classes iclassmap,
SSet.fold SMap.remove class_namekeys iclassnames
in
let iclassmap, iclassnames =
SSet.fold SMap.remove typedefs iclassmap,
SSet.fold SMap.remove typedef_namekeys iclassnames
in
let itypedefs = SSet.fold SMap.remove typedefs env.itypedefs in
let iconsts = SSet.fold SMap.remove consts env.iconsts in
{
ifuns = ifuns;
iclasses = iclassmap, iclassnames;
itypedefs = itypedefs;
iconsts = iconsts;
}
(*****************************************************************************)
(* Helpers *)
(*****************************************************************************)
(* Alok is constantly complaining that in partial mode,
* he forgets to bind a type parameter, for example T,
* and because partial assumes T is just a class that lives
* in PHP land there is no error message.
* So to help him, I am adding a rule that if
* the class name starts with a T and is only 2 characters
* it is considered a type variable. You will not be able to
* define a class T in php land in this scheme ... But it is a bad
* name for a class anyway.
*)
let is_alok_type_name (_, x) = String.length x <= 2 && x.[0] = 'T'
let check_constraint (_, (pos, name), _) =
(* TODO refactor this in a seperate module for errors *)
if String.lowercase name = "this"
then Errors.this_reserved pos
else if name.[0] <> 'T' then Errors.start_with_T pos
let check_repetition s param =
let x = snd param.param_id in
if SSet.mem x s
then Errors.already_bound (fst param.param_id) x;
SSet.add x s
(* Check that a name is not a typedef *)
let no_typedef (genv, _) cid =
let (pos, name) = Namespaces.elaborate_id genv.namespace cid in
if SMap.mem name !(genv.typedefs)
then
let def_pos, _ = SMap.find_unsafe name !(genv.typedefs) in
Errors.unexpected_typedef pos def_pos
let hint_no_typedef env = function
| _, Happly (x, _) -> no_typedef env x
| _ -> ()
let convert_shape_name env = function
| SFlit (pos, s) -> (pos, N.SFlit (pos, s))
| SFclass_const (x, (pos, y)) ->
let class_name = Env.class_name env x in
(pos, N.SFclass_const (class_name, (pos, y)))
let splat_unexpected = function
| [] -> ()
| (pos, _) :: _ -> Errors.naming_too_few_arguments pos; ()
(*****************************************************************************)
(* The entry point to build the naming environment *)
(*****************************************************************************)
let make_env old_env ~funs ~classes ~typedefs ~consts =
let genv = Env.empty_global old_env in
List.iter (Env.new_fun_id genv) funs;
List.iter (Env.new_class_id genv) classes;
List.iter (Env.new_typedef_id genv) typedefs;
List.iter (Env.new_global_const_id genv) consts;
let new_env = {
iclasses = !(genv.classes);
ifuns = !(genv.funs);
itypedefs = !(genv.typedefs);
iconsts = !(genv.gconsts);
} in
new_env
(*****************************************************************************)
(* Naming of type hints *)
(*****************************************************************************)
let rec hint ?(is_static_var=false) ?(allow_this=false) env (p, h) =
p, hint_ ~allow_this is_static_var p env h
and hint_ ~allow_this is_static_var p env x =
let hint = hint ~is_static_var ~allow_this in
match x with
| Htuple hl -> N.Htuple (List.map (hint env) hl)
| Hoption h -> N.Hoption (hint env h)
| Hfun (hl, opt, h) -> N.Hfun (List.map (hint env) hl, opt, hint env h)
| Happly ((_, x) as id, hl) -> hint_id ~allow_this env is_static_var id hl
| Hshape fdl -> N.Hshape
begin
List.fold_left begin fun fdm (pname, h) ->
let pos, name = convert_shape_name env pname in
if ShapeMap.mem name fdm
then Errors.fd_name_already_bound pos;
ShapeMap.add name (hint env h) fdm
end ShapeMap.empty fdl
end
and hint_id ~allow_this env is_static_var (p, x as id) hl =
Naming_hooks.dispatch_hint_hook id;
let hint = hint ~allow_this in
let params = (fst env).type_params in
if is_alok_type_name id && not (SMap.mem x params)
then Errors.typeparam_alok id;
if is_static_var && SMap.mem x params
then Errors.generic_class_var (fst id);
(* some common Xhp screw ups *)
if (x = "Xhp") || (x = ":Xhp") || (x = "XHP")
then Errors.disallowed_xhp_type p x;
match try_castable_hint ~allow_this env p x hl with
| Some h -> h
| None -> begin
match x with
| x when x.[0] = '\\' &&
( x = ("\\"^SN.Typehints.void)
|| x = ("\\"^SN.Typehints.int)
|| x = ("\\"^SN.Typehints.bool)
|| x = ("\\"^SN.Typehints.float)
|| x = ("\\"^SN.Typehints.num)
|| x = ("\\"^SN.Typehints.string)
|| x = ("\\"^SN.Typehints.resource)
|| x = ("\\"^SN.Typehints.mixed)
|| x = ("\\"^SN.Typehints.array)
|| x = ("\\"^SN.Typehints.arraykey)
|| x = ("\\"^SN.Typehints.integer)
|| x = ("\\"^SN.Typehints.boolean)
|| x = ("\\"^SN.Typehints.double)
|| x = ("\\"^SN.Typehints.real)
) ->
Errors.primitive_toplevel p;
N.Hany
| x when x = SN.Typehints.void -> N.Hprim N.Tvoid
| x when x = SN.Typehints.num -> N.Hprim N.Tnum
| x when x = SN.Typehints.resource -> N.Hprim N.Tresource
| x when x = SN.Typehints.arraykey -> N.Hprim N.Tarraykey
| x when x = SN.Typehints.mixed -> N.Hmixed
| x when x = SN.Typehints.shape ->
Errors.shape_typehint p;
N.Hany
| x when x = SN.Typehints.this && allow_this ->
if hl != []
then Errors.this_no_argument p;
(match (fst env).cclass with
| None ->
Errors.this_hint_outside_class p;
N.Hany
| Some c ->
let tparaml = (fst env).type_paraml in
let tparaml = List.map begin fun (param_pos, param_name) ->
let _, cstr = get_constraint env param_name in
let cstr = opt_map (hint env) cstr in
param_pos, N.Habstr (param_name, cstr)
end tparaml in
N.Habstr (SN.Typehints.this, Some (fst c.c_name, N.Happly (c.c_name, tparaml))))
| x when x = SN.Typehints.this ->
(match (fst env).cclass with
| None ->
Errors.this_hint_outside_class p
| Some _ ->
Errors.this_must_be_return p
);
N.Hany
| _ when String.lowercase x = SN.Typehints.this ->
Errors.lowercase_this p x;
N.Hany
| _ when SMap.mem x params ->
if hl <> [] then
Errors.tparam_with_tparam p x;
let env, gen_constraint = get_constraint env x in
N.Habstr (x, opt_map (hint env) gen_constraint)
| _ ->
(* In the future, when we have proper covariant support, we can
* allow SN.Typehints.this to instantiate any covariant type variable. For
* example, let us pretend that we have this defined:
*
* interface IFoo<read Tread, write Twrite>
*
* IFoo<this, int> and IFoo<IFoo<this, int>, int> are ok
* IFoo<int, this> and IFoo<int, IFoo<this>> are not ok
*
* For now, we're hardcoding the fact that all type variables for
* Awaitable and WaitHandle are covariant (well, there's only one
* type variable, but yeah...). We turn on allow_this in
* Awaitable and WaitHandle cases to support members that look
* like:
*
* private ?WaitHandle<this> wh = ...; // e.g. generic preparables
*)
let (_, cname) as name = Env.class_name env id in
let gen_read_api_covariance =
(cname = SN.FB.cGenReadApi || cname = SN.FB.cGenReadIdxApi) in
let privacy_policy_base_covariance =
(cname = SN.FB.cPrivacyPolicyBase) in
let data_type_covariance =
(cname = SN.FB.cDataType || cname = SN.FB.cDataTypeImplProvider) in
let awaitable_covariance =
(cname = SN.Classes.cAwaitable || cname = SN.Classes.cWaitHandle) in
let allow_this = allow_this &&
(awaitable_covariance || gen_read_api_covariance ||
privacy_policy_base_covariance || data_type_covariance) in
N.Happly (name, hintl ~allow_this env hl)
end
(* Hints that are valid both as casts and type annotations. Neither casts nor
* annotations are a strict subset of the other: For instance, 'object' is not
* a valid annotation. Thus callers will have to handle the remaining cases. *)
and try_castable_hint ?(allow_this=false) env p x hl =
let hint = hint ~allow_this in
match x with
| x when x = SN.Typehints.int -> Some (N.Hprim N.Tint)
| x when x = SN.Typehints.bool -> Some (N.Hprim N.Tbool)
| x when x = SN.Typehints.float -> Some (N.Hprim N.Tfloat)
| x when x = SN.Typehints.string -> Some (N.Hprim N.Tstring)
| x when x = SN.Typehints.array ->
Some (match hl with
| [] -> N.Harray (None, None)
| [x] -> N.Harray (Some (hint env x), None)
| [x; y] -> N.Harray (Some (hint env x), Some (hint env y))
| _ -> Errors.naming_too_many_arguments p; N.Hany
)
| x when x = SN.Typehints.integer ->
Errors.integer_instead_of_int p;
Some (N.Hprim N.Tint)
| x when x = SN.Typehints.boolean ->
Errors.boolean_instead_of_bool p;
Some (N.Hprim N.Tbool)
| x when x = SN.Typehints.double ->
Errors.double_instead_of_float p;
Some (N.Hprim N.Tfloat)
| x when x = SN.Typehints.real ->
Errors.real_instead_of_float p;
Some (N.Hprim N.Tfloat)
| _ -> None
and get_constraint env tparam =
let params = (fst env).type_params in
let gen_constraint = SMap.find_unsafe tparam params in
let genv, lenv = env in
let genv = { genv with type_params = SMap.add tparam None params } in
let env = genv, lenv in
env, gen_constraint
and hintl ~allow_this env l = List.map (hint ~allow_this env) l
(*****************************************************************************)
(* All the methods and static methods of an interface are "implicitely"
* declared as abstract
*)
(*****************************************************************************)
let add_abstract m = {m with N.m_abstract = true}
let add_abstractl methods = List.map add_abstract methods
let interface c constructor methods smethods =
if c.c_kind <> Cinterface then constructor, methods, smethods else
let constructor = opt_map add_abstract constructor in
let methods = add_abstractl methods in
let smethods = add_abstractl smethods in
constructor, methods, smethods
(*****************************************************************************)
(* Checking for collision on method names *)
(*****************************************************************************)
let check_method acc { N.m_name = (p, x); _ } =
if SSet.mem x acc
then Errors.method_name_already_bound p x;
SSet.add x acc
let check_name_collision methods =
ignore (List.fold_left check_method SSet.empty methods)
(*****************************************************************************)
(* Checking for shadowing of method type parameters *)
(*****************************************************************************)
let check_method_tparams class_tparam_names { N.m_tparams = tparams; _ } =
List.iter
(fun (_, (p,x),_) -> List.iter
(fun (pc,xc) -> if (x = xc) then Errors.shadowed_type_param p pc x)
class_tparam_names)
tparams
let check_tparams_shadow class_tparam_names methods =
List.iter (check_method_tparams class_tparam_names) methods
(*****************************************************************************)
(* Check if the body of a method/function is UNSAFE *)
(*****************************************************************************)
let rec is_unsafe_body = function
| [] -> false
| Block x :: rl -> is_unsafe_body x || is_unsafe_body rl
| Unsafe :: _ -> true
| _ :: rl -> is_unsafe_body rl
(*****************************************************************************)
(* The entry point to CHECK the program, and transform the program *)
(*****************************************************************************)
let rec class_constraints genv tparams =
let cstrs = make_constraints tparams in
(* Checking there is no cycle in the type constraints *)
List.iter (Naming_ast_helpers.HintCycle.check_constraint cstrs) tparams;
cstrs
(* Naming of a class *)
and class_ genv c =
let cstrs = class_constraints genv c.c_tparams in
let env = Env.make_class_env genv cstrs c in
(* Checking for a code smell *)
List.iter check_constraint c.c_tparams;
List.iter (hint_no_typedef env) c.c_extends;
List.iter (hint_no_typedef env) c.c_implements;
let name = Env.class_name env c.c_name in
let smethods = List.fold_right (class_static_method env) c.c_body [] in
let svars = List.fold_right (class_var_static env) c.c_body [] in
let vars = List.fold_right (class_var env) c.c_body [] in
let v_names = List.map (fun x -> snd x.N.cv_id) vars in
let v_names = List.fold_right SSet.add v_names SSet.empty in
let sm_names = List.map (fun x -> snd x.N.m_name) smethods in
let sm_names = List.fold_right SSet.add sm_names SSet.empty in
let parents = List.map (hint ~allow_this:true env) c.c_extends in
let fmethod = class_method env sm_names v_names in
let methods = List.fold_right fmethod c.c_body [] in
let uses = List.fold_right (class_use env) c.c_body [] in
let req_implements, req_extends = List.fold_right
(class_require env c.c_kind) c.c_body ([], []) in
let tparam_l = type_paraml env c.c_tparams in
let consts = List.fold_right (class_const env) c.c_body [] in
let implements = List.map (hint ~allow_this:true env) c.c_implements in
let constructor = List.fold_left (constructor env) None c.c_body in
let constructor, methods, smethods =
interface c constructor methods smethods in
let class_tparam_names = List.map (fun (_, x,_) -> x) c.c_tparams in
let enum = opt_map (enum_ env) c.c_enum in
check_name_collision methods;
check_tparams_shadow class_tparam_names methods;
check_name_collision smethods;
check_tparams_shadow class_tparam_names smethods;
{ N.c_mode = c.c_mode;
N.c_final = c.c_final;
N.c_is_xhp = c.c_is_xhp;
N.c_kind = c.c_kind;
N.c_name = name;
N.c_tparams = tparam_l;
N.c_extends = parents;
N.c_uses = uses;
N.c_req_extends = req_extends;
N.c_req_implements = req_implements;
N.c_implements = implements;
N.c_consts = consts;
N.c_static_vars = svars;
N.c_vars = vars;
N.c_constructor = constructor;
N.c_static_methods = smethods;
N.c_methods = methods;
N.c_user_attributes = c.c_user_attributes;
N.c_enum = enum
}
and enum_ env e =
{ N.e_base = hint env e.e_base;
N.e_constraint = opt_map (hint env) e.e_constraint;
}
and type_paraml env tparams =
let _, ret = List.fold_left
(fun (seen, tparaml) ((_, (p, name), _) as tparam) ->
match SMap.get name seen with
| None -> (SMap.add name p seen, (type_param env tparam)::tparaml)
| Some pos ->
Errors.shadowed_type_param p pos name;
seen, tparaml
)
(SMap.empty, [])
tparams in
List.rev ret