-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
GlobalTypeInfoCollector.java
2945 lines (2749 loc) · 120 KB
/
GlobalTypeInfoCollector.java
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 2013 The Closure Compiler Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.javascript.jscomp;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import com.google.common.base.Preconditions;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.LinkedHashMultimap;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.Multimap;
import com.google.common.collect.MultimapBuilder;
import com.google.javascript.jscomp.AbstractCompiler.MostRecentTypechecker;
import com.google.javascript.jscomp.CodingConvention.Bind;
import com.google.javascript.jscomp.CodingConvention.DelegateRelationship;
import com.google.javascript.jscomp.CodingConvention.SubclassRelationship;
import com.google.javascript.jscomp.NewTypeInference.WarningReporter;
import com.google.javascript.jscomp.NodeTraversal.AbstractShallowCallback;
import com.google.javascript.jscomp.newtypes.Declaration;
import com.google.javascript.jscomp.newtypes.DeclaredFunctionType;
import com.google.javascript.jscomp.newtypes.EnumType;
import com.google.javascript.jscomp.newtypes.FunctionNamespace;
import com.google.javascript.jscomp.newtypes.FunctionType;
import com.google.javascript.jscomp.newtypes.FunctionTypeBuilder;
import com.google.javascript.jscomp.newtypes.JSType;
import com.google.javascript.jscomp.newtypes.JSTypeCreatorFromJSDoc;
import com.google.javascript.jscomp.newtypes.JSTypeCreatorFromJSDoc.FunctionAndSlotType;
import com.google.javascript.jscomp.newtypes.JSTypes;
import com.google.javascript.jscomp.newtypes.Namespace;
import com.google.javascript.jscomp.newtypes.NamespaceLit;
import com.google.javascript.jscomp.newtypes.NominalType;
import com.google.javascript.jscomp.newtypes.NominalTypeBuilderNti;
import com.google.javascript.jscomp.newtypes.ObjectKind;
import com.google.javascript.jscomp.newtypes.QualifiedName;
import com.google.javascript.jscomp.newtypes.RawNominalType;
import com.google.javascript.jscomp.newtypes.Typedef;
import com.google.javascript.jscomp.newtypes.UniqueNameGenerator;
import com.google.javascript.rhino.IR;
import com.google.javascript.rhino.JSDocInfo;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.NominalTypeBuilder;
import com.google.javascript.rhino.SimpleSourceFile;
import com.google.javascript.rhino.Token;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Nullable;
/**
* Populates GlobalTypeInfo.
*
* <p>Used by the new type inference. See go/jscompiler-new-type-checker for the
* latest updates.
*
* @author blickly@google.com (Ben Lickly)
* @author dimvar@google.com (Dimitris Vardoulakis)
*/
public class GlobalTypeInfoCollector implements CompilerPass {
static final DiagnosticType DUPLICATE_JSDOC = DiagnosticType.warning(
"JSC_NTI_DUPLICATE_JSDOC",
"Found two JsDoc comments for variable: {0}.\n");
static final DiagnosticType REDECLARED_PROPERTY = DiagnosticType.warning(
"JSC_NTI_REDECLARED_PROPERTY",
"Found two declarations for property {0} on {1}.\n");
static final DiagnosticType INVALID_PROP_OVERRIDE = DiagnosticType.warning(
"JSC_NTI_INVALID_PROP_OVERRIDE",
"Invalid redeclaration of property {0}.\n"
+ "inherited type : {1}\n"
+ "overriding type : {2}\n");
static final DiagnosticType CTOR_IN_DIFFERENT_SCOPE = DiagnosticType.warning(
"JSC_NTI_CTOR_IN_DIFFERENT_SCOPE",
"Modifying the prototype is only allowed if the constructor is "
+ "in the same scope\n");
static final DiagnosticType UNRECOGNIZED_TYPE_NAME = DiagnosticType.warning(
"JSC_NTI_UNRECOGNIZED_TYPE_NAME",
"Type annotation references non-existent type {0}.");
static final DiagnosticType STRUCT_WITHOUT_CTOR_OR_INTERF = DiagnosticType.warning(
"JSC_NTI_STRUCT_WITHOUT_CTOR_OR_INTERF",
"@struct used without @constructor, @interface, or @record.");
static final DiagnosticType DICT_WITHOUT_CTOR = DiagnosticType.warning(
"JSC_NTI_DICT_WITHOUT_CTOR",
"@dict used without @constructor.");
static final DiagnosticType EXPECTED_CONSTRUCTOR = DiagnosticType.warning(
"JSC_NTI_EXPECTED_CONSTRUCTOR",
"Expected constructor name but found {0}.");
static final DiagnosticType EXPECTED_INTERFACE = DiagnosticType.warning(
"JSC_NTI_EXPECTED_INTERFACE",
"Expected interface name but found {0}.");
static final DiagnosticType INEXISTENT_PARAM = DiagnosticType.warning(
"JSC_NTI_INEXISTENT_PARAM",
"parameter {0} does not appear in {1}''s parameter list");
static final DiagnosticType CONST_WITHOUT_INITIALIZER =
DiagnosticType.warning(
"JSC_NTI_CONST_WITHOUT_INITIALIZER",
"Constants must be initialized when they are defined.");
static final DiagnosticType COULD_NOT_INFER_CONST_TYPE =
DiagnosticType.warning(
"JSC_NTI_COULD_NOT_INFER_CONST_TYPE",
"All constants must be typed. The compiler could not infer the type "
+ "of constant {0}. Please use an explicit type annotation. "
+ "For more information, see:\n"
+ "https://github.com/google/closure-compiler/wiki/Using-NTI-(new-type-inference)#warnings-about-uninferred-constants");
static final DiagnosticType MISPLACED_CONST_ANNOTATION =
DiagnosticType.warning(
"JSC_NTI_MISPLACED_CONST_ANNOTATION",
"This property cannot be @const. "
+ "The @const annotation is only allowed for "
+ "properties of namespaces, prototype properties, "
+ "static properties of constructors, and "
+ "properties of the form this.prop declared inside constructors "
+ "and prototype methods.");
static final DiagnosticType CANNOT_OVERRIDE_FINAL_METHOD =
DiagnosticType.warning(
"JSC_NTI_CANNOT_OVERRIDE_FINAL_METHOD",
"Final method {0} cannot be overriden.");
static final DiagnosticType CANNOT_INIT_TYPEDEF =
DiagnosticType.warning(
"JSC_NTI_CANNOT_INIT_TYPEDEF",
"A typedef variable represents a type name; it cannot be assigned a value.");
static final DiagnosticType ANONYMOUS_NOMINAL_TYPE =
DiagnosticType.warning(
"JSC_NTI_ANONYMOUS_NOMINAL_TYPE",
"Must specify a name when defining a class or interface.");
static final DiagnosticType MALFORMED_ENUM =
DiagnosticType.warning(
"JSC_NTI_MALFORMED_ENUM",
"An enum must be initialized to a non-empty object literal.");
static final DiagnosticType DUPLICATE_PROP_IN_ENUM =
DiagnosticType.warning(
"JSC_NTI_DUPLICATE_PROP_IN_ENUM",
"Property {0} appears twice in the enum declaration.");
static final DiagnosticType LENDS_ON_BAD_TYPE =
DiagnosticType.warning(
"JSC_NTI_LENDS_ON_BAD_TYPE",
"May only lend properties to namespaces, constructors and their"
+ " prototypes. Found {0}.");
static final DiagnosticType INVALID_INTERFACE_PROP_INITIALIZER =
DiagnosticType.warning(
"JSC_NTI_INVALID_INTERFACE_PROP_INITIALIZER",
"Invalid initialization of interface property.");
static final DiagnosticType SETTER_WITH_RETURN =
DiagnosticType.warning(
"JSC_NTI_SETTER_WITH_RETURN",
"Cannot declare a return type on a setter.");
static final DiagnosticType WRONG_PARAMETER_COUNT =
DiagnosticType.warning(
"JSC_NTI_WRONG_PARAMETER_COUNT",
"Function definition does not have the declared number of parameters.\n"
+ "Expected: {0}\n"
+ "Found: {1}");
static final DiagnosticType CANNOT_ADD_PROPERTIES_TO_TYPEDEF =
DiagnosticType.warning(
"JSC_NTI_CANNOT_ADD_PROPERTIES_TO_TYPEDEF",
"A typedef should only be used in type annotations, not as a value."
+ " Adding properties to typedefs is not allowed.");
static final DiagnosticType SUPER_INTERFACES_HAVE_INCOMPATIBLE_PROPERTIES =
DiagnosticType.warning(
"JSC_NTI_SUPER_INTERFACES_HAVE_INCOMPATIBLE_PROPERTIES",
"Interface {0} has a property {1} with incompatible types in "
+ "its super interfaces: {2}");
static final DiagnosticType ONE_TYPE_FOR_MANY_VARS = DiagnosticType.warning(
"JSC_NTI_ONE_TYPE_FOR_MANY_VARS",
"Having one type annotation for multiple variables is not allowed.");
static final DiagnosticType UNKNOWN_OVERRIDE =
DiagnosticType.warning(
"JSC_NTI_UNKNOWN_OVERRIDE",
"property {0} not defined on any supertype of {1}");
static final DiagnosticType INTERFACE_METHOD_NOT_IMPLEMENTED =
DiagnosticType.warning(
"JSC_NTI_INTERFACE_METHOD_NOT_IMPLEMENTED",
"property {0} on interface {1} is not implemented by type {2}");
static final DiagnosticType INTERFACE_METHOD_NOT_EMPTY =
DiagnosticType.warning(
"JSC_NTI_INTERFACE_METHOD_NOT_EMPTY",
"interface member functions must have an empty body");
static final DiagnosticType ABSTRACT_METHOD_IN_CONCRETE_CLASS =
DiagnosticType.warning(
"JSC_NTI_ABSTRACT_METHOD_IN_CONCRETE_CLASS",
"Abstract methods can only appear in abstract classes. "
+ "Please declare class {0} as @abstract");
static final DiagnosticType ABSTRACT_METHOD_IN_INTERFACE =
DiagnosticType.warning(
"JSC_NTI_ABSTRACT_METHOD_IN_INTERFACE",
"Abstract methods cannot appear in interfaces");
static final DiagnosticType ABSTRACT_METHOD_NOT_IMPLEMENTED_IN_CONCRETE_CLASS =
DiagnosticType.warning(
"JSC_NTI_ABSTRACT_METHOD_NOT_IMPLEMENTED_IN_CONCRETE_CLASS",
"Abstract method {0} from superclass {1} not implemented");
static final DiagnosticGroup COMPATIBLE_DIAGNOSTICS = new DiagnosticGroup(
ABSTRACT_METHOD_IN_CONCRETE_CLASS,
CANNOT_OVERRIDE_FINAL_METHOD,
DICT_WITHOUT_CTOR,
DUPLICATE_PROP_IN_ENUM,
EXPECTED_CONSTRUCTOR,
EXPECTED_INTERFACE,
INEXISTENT_PARAM,
INTERFACE_METHOD_NOT_IMPLEMENTED,
INTERFACE_METHOD_NOT_EMPTY,
INVALID_INTERFACE_PROP_INITIALIZER,
INVALID_PROP_OVERRIDE,
LENDS_ON_BAD_TYPE,
ONE_TYPE_FOR_MANY_VARS,
REDECLARED_PROPERTY,
STRUCT_WITHOUT_CTOR_OR_INTERF,
SUPER_INTERFACES_HAVE_INCOMPATIBLE_PROPERTIES,
UNKNOWN_OVERRIDE,
UNRECOGNIZED_TYPE_NAME,
WRONG_PARAMETER_COUNT);
static final DiagnosticGroup NEW_DIAGNOSTICS = new DiagnosticGroup(
ABSTRACT_METHOD_IN_INTERFACE,
ABSTRACT_METHOD_NOT_IMPLEMENTED_IN_CONCRETE_CLASS,
ANONYMOUS_NOMINAL_TYPE,
CANNOT_ADD_PROPERTIES_TO_TYPEDEF,
CANNOT_INIT_TYPEDEF,
CONST_WITHOUT_INITIALIZER,
COULD_NOT_INFER_CONST_TYPE,
CTOR_IN_DIFFERENT_SCOPE,
DUPLICATE_JSDOC,
MALFORMED_ENUM,
MISPLACED_CONST_ANNOTATION,
SETTER_WITH_RETURN);
private WarningReporter warnings;
private final transient AbstractCompiler compiler;
private final CodingConvention convention;
// Uses %, which is not allowed in identifiers, to avoid naming clashes
// with existing functions.
private static final String ANON_FUN_PREFIX = "%anon_fun";
private static final String WINDOW_INSTANCE = "window";
private static final String WINDOW_CLASS = "Window";
private DefaultNameGenerator funNameGen;
// Only for original definitions, not for aliased constructors
private Map<Node, RawNominalType> nominaltypesByNode = new LinkedHashMap<>();
// propertyDefs collects places in the AST where properties are defined.
// For properties that are methods, PropertyDef includes some extra information.
// We use propertyDefs to handle inheritance issues, e.g., invalid property overrides.
// Keyed on RawNominalTypes and property names.
private HashBasedTable<RawNominalType, String, PropertyDef> propertyDefs =
HashBasedTable.create();
private final Set<RawNominalType> inProgressFreezes = new LinkedHashSet<>();
private final GlobalTypeInfo globalTypeInfo;
private final SimpleInference simpleInference;
private final OrderedExterns orderedExterns;
private RawNominalType window;
// This list is populated during CollectNamedTypes and is complete during ProcessScope.
private final List<NTIScope> scopes;
public GlobalTypeInfoCollector(AbstractCompiler compiler) {
this.warnings = new WarningReporter(compiler);
this.compiler = compiler;
this.funNameGen = new DefaultNameGenerator(ImmutableSet.<String>of(), "", null);
this.globalTypeInfo = compiler.getGlobalTypeInfo();
this.simpleInference = new SimpleInference(this.globalTypeInfo);
this.convention = compiler.getCodingConvention();
this.orderedExterns = new OrderedExterns();
this.scopes = new ArrayList<>();
}
@Override
public void process(Node externs, Node root) {
checkNotNull(warnings, "Cannot rerun GlobalTypeInfoCollector.process");
checkArgument(externs == null || externs.isRoot());
checkArgument(root.isRoot(), "Root must be ROOT, but is %s", root.getToken());
this.compiler.setMostRecentTypechecker(MostRecentTypechecker.NTI);
NTIScope globalScope = new NTIScope(root, null, ImmutableList.<String>of(), getCommonTypes());
globalScope.addUnknownTypeNames(this.globalTypeInfo.getUnknownTypeNames());
this.globalTypeInfo.setGlobalScope(globalScope);
this.scopes.add(globalScope);
// Processing of a scope is split into many separate phases, and it's not
// straightforward to remember which phase does what.
// (1) Find names of classes, interfaces, typedefs, enums, and namespaces
// defined in the global scope.
CollectNamedTypes rootCnt = new CollectNamedTypes(globalScope);
NodeTraversal.traverseEs6(this.compiler, externs, this.orderedExterns);
rootCnt.collectNamedTypesInExterns();
defineObjectAndFunctionIfMissing();
NodeTraversal.traverseEs6(compiler, root, rootCnt);
// (2) Determine the type represented by each typedef and each enum
globalScope.resolveTypedefs(getTypeParser());
globalScope.resolveEnums(getTypeParser());
// (3) Repeat steps 1-2 for all the other scopes (outer-to-inner)
for (int i = 1; i < this.scopes.size(); i++) {
NTIScope s = this.scopes.get(i);
CollectNamedTypes cnt = new CollectNamedTypes(s);
NodeTraversal.traverseEs6(compiler, s.getBody(), cnt);
s.resolveTypedefs(getTypeParser());
s.resolveEnums(getTypeParser());
if (NewTypeInference.measureMem) {
NewTypeInference.updatePeakMem();
}
}
// (4) The bulk of the global-scope processing happens here:
// - Create scopes for functions
// - Declare properties on types
ProcessScope rootPs = new ProcessScope(globalScope);
if (externs != null) {
NodeTraversal.traverseEs6(compiler, externs, rootPs);
}
NodeTraversal.traverseEs6(compiler, root, rootPs);
// (5) Things that must happen after the traversal of the scope
rootPs.finishProcessingScope();
// (6) Repeat steps 4-5 for all the other scopes (outer-to-inner)
for (int i = 1; i < this.scopes.size(); i++) {
NTIScope s = this.scopes.get(i);
ProcessScope ps = new ProcessScope(s);
NodeTraversal.traverseEs6(compiler, s.getBody(), ps);
ps.finishProcessingScope();
if (NewTypeInference.measureMem) {
NewTypeInference.updatePeakMem();
}
}
// (7) Adjust types of properties based on inheritance information.
// Report errors in the inheritance chain. Do Window last.
Collection<RawNominalType> windows = new ArrayList<>();
for (Map.Entry<Node, RawNominalType> entry : nominaltypesByNode.entrySet()) {
RawNominalType rawType = entry.getValue();
if (this.window != null && rawType.hasAncestorClass(this.window)) {
windows.add(rawType);
continue;
}
checkAndFreezeNominalType(rawType);
}
JSType globalThisType = null;
if (this.window != null) {
// Copy properties from window to Window.prototype, because sometimes
// people pass window around rather than using it directly.
Namespace winNs = globalScope.getNamespace(WINDOW_INSTANCE);
if (winNs != null) {
winNs.copyWindowProperties(getCommonTypes(), this.window);
}
for (RawNominalType rawType : windows) {
checkAndFreezeNominalType(rawType);
}
if (winNs != null) {
((NamespaceLit) winNs).setWindowType(this.window.getAsNominalType());
// Type the global THIS as window
globalThisType = winNs.toJSType();
}
}
if (globalThisType == null) {
// Type the global THIS as a loose object
globalThisType = getCommonTypes().getTopObject().withLoose();
}
getCommonTypes().setGlobalThis(globalThisType);
globalScope.setDeclaredType(
(new FunctionTypeBuilder(getCommonTypes())).
addReceiverType(globalThisType).buildDeclaration());
this.globalTypeInfo.setRawNominalTypes(nominaltypesByNode.values());
nominaltypesByNode = null;
propertyDefs = null;
for (NTIScope s : this.scopes) {
s.freezeScope();
}
this.simpleInference.setScopesAreFrozen();
// Traverse the externs and annotate them with types.
// Only works for the top level, not inside function bodies.
NodeTraversal.traverseEs6(
this.compiler, externs, new NodeTraversal.AbstractShallowCallback() {
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
if (n.isQualifiedName()) {
Declaration d = getGlobalScope().getDeclaration(QualifiedName.fromNode(n), false);
JSType type = simpleInferDeclaration(d);
if (type == null) {
type = simpleInferExpr(n, getGlobalScope());
}
// Type-based passes expect the externs to be annotated, so use ? when type is null.
n.setTypeI(type != null ? type : getCommonTypes().UNKNOWN);
}
}
});
Map<Node, String> unknownTypes = getTypeParser().getUnknownTypesMap();
for (Map.Entry<Node, String> unknownTypeEntry : unknownTypes.entrySet()) {
this.warnings.add(JSError.make(unknownTypeEntry.getKey(),
UNRECOGNIZED_TYPE_NAME, unknownTypeEntry.getValue()));
}
// The jsdoc parser doesn't have access to the error functions in the jscomp
// package, so we collect its warnings here.
for (JSError warning : getTypeParser().getWarnings()) {
this.warnings.add(warning);
}
this.warnings = null;
this.funNameGen = null;
reorderScopesForNTI();
this.compiler.setExternProperties(ImmutableSet.copyOf(getExternPropertyNames()));
}
/**
* After ProcessScope, scopes are stored in a list; shallower scopes appear before deeper
* scopes (i.e., the top level is first). This method rearranges them in the order in which
* we will process them in NewTypeInference. The order in which scopes are processed in NTI is
* crucial for good type checking, because each function is only checked once; there is no
* global-fixpoint phase.
*
* Unannotated callbacks are processed at the end. This means that by the time we typecheck a
* callback, we have checked the surrounding scope, and we have inferred a good signature.
*
* For the rest of the scopes, we process deeper scopes before shallower scopes
* (the top level is processed last). Then, if a declared function f is called in the same
* scope S in which it is defined, we typecheck S after f, and we have a function summary for f.
*
* TODO(dimvar): We also want to use summaries when type checking method calls to unannotated
* methods. To do that, we will need to process all methods in the beginning, and then the
* remaining scopes.
*/
private void reorderScopesForNTI() {
List<NTIScope> scopes = this.scopes;
ArrayList<NTIScope> result = new ArrayList<>(scopes.size());
ArrayList<NTIScope> callbacks = new ArrayList<>();
for (int i = scopes.size() - 1; i >= 0; i--) {
NTIScope s = scopes.get(i);
if (NodeUtil.isUnannotatedCallback(s.getRoot())) {
callbacks.add(s);
} else {
result.add(s);
}
}
// Outer unannotated callbacks are processed before inner unannotated callbacks, so that if
// a callback contains another callback, the outer one is analyzed first.
Collections.reverse(callbacks);
result.addAll(callbacks);
this.globalTypeInfo.setScopes(result);
}
private void setWindow(RawNominalType rawType) {
this.window = rawType;
}
private static boolean isWindowRawType(RawNominalType rawType) {
return rawType.getName().equals(WINDOW_CLASS) && rawType.getDefSite().isFromExterns();
}
private RawNominalType dummyRawTypeForMissingExterns(String name) {
Node defSite = NodeUtil.emptyFunction();
defSite.setStaticSourceFile(new SimpleSourceFile("", true));
return RawNominalType.makeClass(
getCommonTypes(), defSite, name, ImmutableList.of(), ObjectKind.UNRESTRICTED, false);
}
private void defineObjectAndFunctionIfMissing() {
JSTypes commonTypes = getCommonTypes();
if (commonTypes.getObjectType() == null) {
commonTypes.setObjectType(dummyRawTypeForMissingExterns("Object"));
}
if (commonTypes.getLiteralObjNominalType() == null) {
RawNominalType objLitRawType = dummyRawTypeForMissingExterns(JSTypes.OBJLIT_CLASS_NAME);
objLitRawType.addSuperClass(commonTypes.getObjectType());
commonTypes.setLiteralObjNominalType(objLitRawType);
}
if (commonTypes.getFunctionType() == null) {
commonTypes.setFunctionType(dummyRawTypeForMissingExterns("Function"));
}
}
private ImmutableCollection<PropertyDef> getPropDefsFromInterface(
NominalType nominalType, String pname) {
checkArgument(nominalType.isFrozen());
checkArgument(nominalType.isInterface() || nominalType.isBuiltinObject());
if (nominalType.getPropDeclaredType(pname) == null) {
return ImmutableSet.of();
} else if (propertyDefs.get(nominalType.getId(), pname) != null) {
PropertyDef propDef = propertyDefs.get(nominalType.getId(), pname);
return ImmutableSet.of(
nominalType.isGeneric() ? propDef.substituteNominalGenerics(nominalType) : propDef);
}
ImmutableSet.Builder<PropertyDef> result = ImmutableSet.builder();
for (NominalType interf : nominalType.getInstantiatedInterfaces()) {
result.addAll(getPropDefsFromInterface(interf, pname));
}
return result.build();
}
private PropertyDef getPropDefFromClass(NominalType nominalType, String pname) {
while (nominalType.getPropDeclaredType(pname) != null) {
checkArgument(nominalType.isFrozen());
checkArgument(nominalType.isClass());
if (propertyDefs.get(nominalType.getId(), pname) != null) {
PropertyDef propDef = propertyDefs.get(nominalType.getId(), pname);
return nominalType.isGeneric() ? propDef.substituteNominalGenerics(nominalType) : propDef;
}
nominalType = nominalType.getInstantiatedSuperclass();
}
return null;
}
private void checkAndFreezeNominalType(RawNominalType rawType) {
if (rawType.isFrozen()) {
return;
}
checkState(inProgressFreezes.add(rawType),
"Cycle in freeze order: %s (%s)", rawType, inProgressFreezes);
NominalType superClass = rawType.getSuperClass();
Set<String> nonInheritedPropNames = rawType.getAllNonInheritedProps();
if (superClass != null && !superClass.isFrozen()) {
checkAndFreezeNominalType(superClass.getRawNominalType());
}
for (NominalType superInterf : rawType.getInterfaces()) {
if (!superInterf.isFrozen()) {
checkAndFreezeNominalType(superInterf.getRawNominalType());
}
}
Multimap<String, DeclaredFunctionType> propMethodTypesToProcess = LinkedHashMultimap.create();
Multimap<String, JSType> propTypesToProcess = LinkedHashMultimap.create();
// Collect inherited types for extended classes
if (superClass != null) {
checkState(superClass.isFrozen());
// TODO(blickly): Can we optimize this to skip unnecessary iterations?
for (String pname : superClass.getPropertyNames()) {
if (superClass.isAbstractClass()
&& superClass.hasAbstractMethod(pname)
&& !rawType.isAbstractClass()
&& !rawType.mayHaveOwnNonStrayProp(pname)) {
warnings.add(JSError.make(
rawType.getDefSite(), ABSTRACT_METHOD_NOT_IMPLEMENTED_IN_CONCRETE_CLASS,
pname, superClass.getName()));
}
nonInheritedPropNames.remove(pname);
checkSuperProperty(
rawType, superClass, pname, propMethodTypesToProcess, propTypesToProcess);
}
}
// Collect inherited types for extended/implemented interfaces
for (NominalType superInterf : rawType.getInterfaces()) {
checkState(superInterf.isFrozen());
for (String pname : superInterf.getPropertyNames()) {
nonInheritedPropNames.remove(pname);
checkSuperProperty(
rawType, superInterf, pname, propMethodTypesToProcess, propTypesToProcess);
}
}
// Munge inherited types of methods
for (String pname : propMethodTypesToProcess.keySet()) {
Collection<DeclaredFunctionType> methodTypes = propMethodTypesToProcess.get(pname);
checkState(!methodTypes.isEmpty());
PropertyDef localPropDef = propertyDefs.get(rawType, pname);
// To find the declared type of a method, we must meet declared types
// from all inherited methods.
DeclaredFunctionType superMethodType = DeclaredFunctionType.meet(methodTypes);
DeclaredFunctionType localMethodType = localPropDef.methodType;
boolean getsTypeFromParent = getsTypeInfoFromParentMethod(localPropDef);
if (superMethodType == null) {
// If the inherited types are not compatible, pick one.
superMethodType = methodTypes.iterator().next();
warnings.add(JSError.make(localPropDef.defSite,
SUPER_INTERFACES_HAVE_INCOMPATIBLE_PROPERTIES,
rawType.getName(), pname, methodTypes.toString()));
} else if (getsTypeFromParent
&& localMethodType.getMaxArity() > superMethodType.getMaxArity()) {
// When getsTypeFromParent is true, we will miss the invalid override
// earlier, so we check here.
warnings.add(JSError.make(
localPropDef.defSite, INVALID_PROP_OVERRIDE, pname,
superMethodType.toFunctionType().toString(),
localMethodType.toFunctionType().toString()));
}
DeclaredFunctionType updatedMethodType =
localMethodType.withTypeInfoFromSuper(superMethodType, getsTypeFromParent);
localPropDef.updateMethodType(updatedMethodType);
propTypesToProcess.put(pname,
getCommonTypes().fromFunctionType(updatedMethodType.toFunctionType()));
}
// Check inherited types of all props
add_interface_props:
for (String pname : propTypesToProcess.keySet()) {
Collection<JSType> defs = propTypesToProcess.get(pname);
checkState(!defs.isEmpty());
JSType resultType = getCommonTypes().TOP;
for (JSType inheritedType : defs) {
resultType = JSType.meet(resultType, inheritedType);
if (!resultType.isBottom()) {
resultType = inheritedType;
} else {
warnings.add(
JSError.make(
rawType.getDefSite(),
SUPER_INTERFACES_HAVE_INCOMPATIBLE_PROPERTIES,
rawType.getName(),
pname,
defs.toString()));
continue add_interface_props;
}
}
// TODO(dimvar): check if we can have @const props here
rawType.addProtoProperty(pname, null, resultType, false);
}
// Warn when inheriting from incompatible IObject types
if (rawType.inheritsFromIObject()) {
JSType wrapped = rawType.getInstanceAsJSType();
if (wrapped.getIndexType() == null) {
warnings.add(
JSError.make(
rawType.getDefSite(),
SUPER_INTERFACES_HAVE_INCOMPATIBLE_PROPERTIES,
rawType.getName(),
"IObject<K,V>#index",
"the keys K have types that can't be joined."));
} else if (wrapped.getIndexedType() == null) {
warnings.add(
JSError.make(
rawType.getDefSite(),
SUPER_INTERFACES_HAVE_INCOMPATIBLE_PROPERTIES,
rawType.getName(),
"IObject<K,V>#index",
"the values V should have a common subtype."));
}
}
// Warn for a prop declared with @override that isn't overriding anything.
for (String pname : nonInheritedPropNames) {
PropertyDef propDef = propertyDefs.get(rawType, pname);
if (propDef != null) {
Node propDefsite = propDef.defSite;
JSDocInfo jsdoc = NodeUtil.getBestJSDocInfo(propDefsite);
if (jsdoc != null && jsdoc.isOverride()) {
warnings.add(JSError.make(propDefsite, UNKNOWN_OVERRIDE, pname, rawType.getName()));
}
}
}
// Freeze nominal type once all properties are added.
rawType.freeze();
if (rawType.isBuiltinObject()) {
NominalType literalObj = getCommonTypes().getLiteralObjNominalType();
if (!literalObj.isFrozen()) {
literalObj.getRawNominalType().freeze();
}
}
inProgressFreezes.remove(rawType);
}
// TODO(dimvar): the finalization method and this one should be cleaned up;
// they are very hard to understand.
private void checkSuperProperty(
RawNominalType current, NominalType superType, String pname,
Multimap<String, DeclaredFunctionType> propMethodTypesToProcess,
Multimap<String, JSType> propTypesToProcess) {
JSType inheritedPropType = superType.getPropDeclaredType(pname);
if (inheritedPropType == null) {
// No need to go further for undeclared props.
return;
}
Collection<PropertyDef> inheritedPropDefs;
if (superType.isInterface()) {
inheritedPropDefs = getPropDefsFromInterface(superType, pname);
// If a class is defined by mixin application, add missing property defs from the
// super interface, o/w checkSuperProperty will break for its subclasses.
if (isCtorDefinedByCall(current)) {
for (PropertyDef inheritedDef : inheritedPropDefs) {
if (!current.mayHaveProp(pname)) {
propertyDefs.put(current, pname, inheritedDef);
}
}
}
} else {
PropertyDef propdef = getPropDefFromClass(superType, pname);
// This can happen if superType is a class created by a mixin application. The class may
// have prototype properties but we can't see where these properties are defined.
if (propdef == null) {
return;
}
inheritedPropDefs = ImmutableSet.of(propdef);
}
if (superType.isInterface()
&& current.isClass()
&& !isCtorDefinedByCall(current)
&& !current.mayHaveNonStrayProp(pname)) {
warnings.add(JSError.make(
inheritedPropDefs.iterator().next().defSite,
INTERFACE_METHOD_NOT_IMPLEMENTED,
pname, superType.toString(), current.toString()));
return;
}
PropertyDef localPropDef = propertyDefs.get(current, pname);
// If the property is inherited, we want to drop the result of getInstancePropDeclaredType.
JSType localPropType =
localPropDef == null ? null : current.getInstancePropDeclaredType(pname);
if (localPropDef != null && superType.isClass()
&& localPropType != null
&& localPropType.getFunType() != null
&& superType.hasConstantProp(pname)) {
// TODO(dimvar): This doesn't work for multiple levels in the hierarchy.
// Clean up how we process inherited properties and then fix this.
warnings.add(JSError.make(
localPropDef.defSite, CANNOT_OVERRIDE_FINAL_METHOD, pname));
return;
}
if (localPropType == null && superType.isInterface()) {
// Add property from interface to class
propTypesToProcess.put(pname, inheritedPropType);
} else if (localPropType != null
&& !getsTypeInfoFromParentMethod(localPropDef)
&& !isValidOverride(localPropType, inheritedPropType)) {
warnings.add(JSError.make(
localPropDef.defSite, INVALID_PROP_OVERRIDE, pname,
inheritedPropType.toString(), localPropType.toString()));
} else if (localPropType != null && localPropDef.methodType != null) {
// If we are looking at a method definition, munging may be needed
for (PropertyDef inheritedPropDef : inheritedPropDefs) {
if (inheritedPropDef.methodType != null) {
propMethodTypesToProcess.put(pname, inheritedPropDef.methodType);
}
}
}
}
private boolean isValidOverride(JSType localPropType, JSType inheritedPropType) {
FunctionType localFunType = localPropType.getFunType();
FunctionType inheritedFunType = inheritedPropType.getFunType();
if (localFunType == null) {
return localPropType.isSubtypeOf(inheritedPropType);
} else if (inheritedFunType == null) {
return false;
} else {
return localFunType.isValidOverride(inheritedFunType);
}
}
private static boolean getsTypeInfoFromParentMethod(PropertyDef pd) {
if (pd == null || pd.methodType == null) {
return false;
}
JSDocInfo jsdoc = NodeUtil.getBestJSDocInfo(pd.defSite);
if (jsdoc == null) {
return true;
}
return (jsdoc.isOverride() || jsdoc.isExport()) && !jsdoc.containsFunctionDeclaration();
}
private boolean isAliasedTypedef(Node lhsQnameNode, NTIScope s) {
return getAliasedTypedef(lhsQnameNode, s) != null;
}
/**
* If lhs represents the lhs of a typedef-aliasing statement, return that typedef.
*/
@Nullable
private Typedef getAliasedTypedef(Node lhs, NTIScope s) {
if (!NodeUtil.isAliasedConstDefinition(lhs)) {
return null;
}
Node rhs = NodeUtil.getRValueOfLValue(lhs);
checkState(rhs != null && rhs.isQualifiedName());
return s.getTypedef(QualifiedName.fromNode(rhs));
}
/**
* Each node in the iterable is either a function expression or a statement.
* The statement can be of: a function, a var, an expr_result containing an assignment,
* or an expr_result containing a getprop.
* The statement represents an externs definition of a qualified name.
* We iterate over qnames from shorter (ie, variables) to longer.
* For qnames with the same length, we visit them in the order in which they are defined
* in the source.
*/
private static class OrderedExterns extends AbstractShallowCallback implements Iterable<Node> {
/**
* treeKeys ensures that the iteration will be in increasing order of qname length:
* variables first, simple getprops second, and so on.
* arrayListValues ensures that for qnames of the same length, the order of iteration
* follows the order of the definitions in the source.
*/
final ListMultimap<Integer, Node> orderedExternDefs =
MultimapBuilder.treeKeys().arrayListValues().build();
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
switch (n.getToken()) {
case VAR:
case FUNCTION:
addDefinition(n);
break;
case EXPR_RESULT: {
Node expr = n.getFirstChild();
if (expr.isAssign() || expr.isGetProp()) {
addDefinition(n);
}
break;
}
default:
break;
}
}
Node getDefinedQname(Node definition) {
switch (definition.getToken()) {
case VAR:
return definition.getFirstChild();
case FUNCTION: {
Node name = NodeUtil.getNameNode(definition);
// Return a non-null node for anonymous functions
return name == null ? definition.getFirstChild() : name;
}
case EXPR_RESULT: {
Node expr = definition.getFirstChild();
if (expr.isGetProp()) {
return expr;
}
checkState(expr.isAssign(), "Expected assignment, found %s", expr);
return expr.getFirstChild();
}
default:
throw new RuntimeException("Unexpected definition " + definition);
}
}
void addDefinition(Node definition) {
Node qname = getDefinedQname(definition);
int len = NodeUtil.getLengthOfQname(qname);
this.orderedExternDefs.put(len, definition);
}
@Override
public Iterator<Node> iterator() {
return orderedExternDefs.values().iterator();
}
}
/**
* Collects names of classes, interfaces, namespaces, typedefs and enums.
* This way, if a type name appears before its declaration, we know what it refers to.
*/
private class CollectNamedTypes extends AbstractShallowCallback {
private final NTIScope currentScope;
private Node nameNodeDefiningWindow = null;
CollectNamedTypes(NTIScope s) {
this.currentScope = s;
}
void collectNamedTypesInExterns() {
for (Node definition : orderedExterns) {
visitNode(definition);
}
// Visit the definition of window last, to ensure that the Window type has been defined.
if (this.nameNodeDefiningWindow != null) {
visitWindowVar(nameNodeDefiningWindow);
}
}
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
visitNode(n);
}
public void visitNode(Node n) {
switch (n.getToken()) {
case FUNCTION:
visitFunctionEarly(n);
break;
case VAR:
visitVar(n);
break;
case NAME:
visitName(n);
break;
case EXPR_RESULT:
visitExprResult(n);
break;
default:
break;
}
}
private void visitExprResult(Node n) {
checkArgument(n.isExprResult());
Node expr = n.getFirstChild();
switch (expr.getToken()) {
case ASSIGN:
Node lhs = expr.getFirstChild();
if (isCtorDefinedByCall(lhs)) {
visitNewCtorDefinedByCall(lhs);
return;
}
if (!lhs.isGetProp()) {
return;
}
expr = lhs;
// fall through
case GETPROP:
if (isCtorWithoutFunctionLiteral(expr)) {
visitNewCtorWithoutFunctionLiteral(expr);
return;
}
if (isPrototypeProperty(expr)
|| NodeUtil.referencesThis(expr)
|| !expr.isQualifiedName()) {
// Class & prototype properties are handled in ProcessScope
return;
}
processQualifiedDefinition(expr);
break;
default:
break;
}
}
private void visitName(Node n) {
checkArgument(n.isName());
if (this.currentScope.isFunction()) {
NTIScope.mayRecordEscapedVar(this.currentScope, n.getString());
}
}
private void visitVar(Node n) {
checkArgument(n.isVar());
Node nameNode = n.getFirstChild();
String varName = nameNode.getString();
if (NodeUtil.isNamespaceDecl(nameNode)) {
visitObjlitNamespace(new QualifiedName(varName), nameNode);
} else if (NodeUtil.isTypedefDecl(nameNode)) {
visitTypedef(nameNode);
} else if (NodeUtil.isEnumDecl(nameNode)) {
visitEnum(nameNode);
} else if (isAliasedTypedef(nameNode, this.currentScope)) {
visitAliasedTypedef(nameNode);
} else if (isAliasedNamespaceDefinition(nameNode)) {
visitAliasedNamespace(new QualifiedName(varName), nameNode);
} else if (varName.equals(WINDOW_INSTANCE) && nameNode.isFromExterns()) {
this.nameNodeDefiningWindow = nameNode;
// We call visitWindowVar at the end, to ensure the Window type has been defined.
// Add a dummy extern here to define the variable as an extern.
// We don't have a unit test for this, but it is needed to avoid spuriously registering