-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
GlobalTypeInfoCollector.java
2825 lines (2645 loc) · 113 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.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.LinkedHashMultimap;
import com.google.common.collect.Multimap;
import com.google.javascript.jscomp.AbstractCompiler.MostRecentTypechecker;
import com.google.javascript.jscomp.CodingConvention.Bind;
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.NominalType;
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.Token;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* 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 FUNCTION_CONSTRUCTOR_NOT_DEFINED =
DiagnosticType.error(
"JSC_NTI_FUNCTION_CONSTRUCTOR_NOT_DEFINED",
"You must provide externs that define the built-in Function constructor.");
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,
FUNCTION_CONSTRUCTOR_NOT_DEFINED,
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";
// A property of this name is used as a marker during const inference,
// to avoid misuse of constructor types.
private static final QualifiedName CONST_INFERENCE_MARKER =
new QualifiedName("jscomp$infer$const$property");
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<>();
// Keyed on RawNominalTypes and property names
private HashBasedTable<RawNominalType, String, PropertyDef> propertyDefs =
HashBasedTable.create();
private final GlobalTypeInfo globalTypeInfo;
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.convention = compiler.getCodingConvention();
}
@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);
this.globalTypeInfo.initGlobalTypeInfo(root);
// 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(getGlobalScope());
if (externs != null) {
NodeTraversal.traverseEs6(compiler, externs, rootCnt);
}
NodeTraversal.traverseEs6(compiler, root, rootCnt);
// (2) Determine the type represented by each typedef and each enum
getGlobalScope().resolveTypedefs(getTypeParser());
getGlobalScope().resolveEnums(getTypeParser());
// (3) Repeat steps 1-2 for all the other scopes (outer-to-inner)
for (int i = 1; i < getScopes().size(); i++) {
NTIScope s = getScopes().get(i);
CollectNamedTypes cnt = new CollectNamedTypes(s);
NodeTraversal.traverseEs6(compiler, s.getBody(), cnt);
s.resolveTypedefs(getTypeParser());
s.resolveEnums(getTypeParser());
if (NewTypeInference.measureMem) {
NewTypeInference.updatePeakMem();
}
}
// If the Function constructor isn't defined, we cannot create function
// types. Exit early.
if (getCommonTypes().getFunctionType() == null) {
warnings.add(JSError.make(root, FUNCTION_CONSTRUCTOR_NOT_DEFINED));
return;
}
// (4) The bulk of the global-scope processing happens here:
// - Create scopes for functions
// - Declare properties on types
ProcessScope rootPs = new ProcessScope(getGlobalScope());
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 < getScopes().size(); i++) {
NTIScope s = getScopes().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.
RawNominalType win = null;
for (Map.Entry<Node, RawNominalType> entry : nominaltypesByNode.entrySet()) {
RawNominalType rawType = entry.getValue();
if (rawType.getName().equals(WINDOW_CLASS) && entry.getKey().isFromExterns()) {
win = rawType;
continue;
}
checkAndFreezeNominalType(rawType);
}
JSType globalThisType;
if (win != null) {
// Copy properties from window to Window.prototype, because sometimes
// people pass window around rather than using it directly.
// Copying the properties is correct only when there is a single object
// of type Window in the program. But in very rare cases, people subclass Window.
// Then, win is frozen here and we don't copy the properties.
// Window has been subclassed iff it is already frozen here.
Namespace winNs = getGlobalScope().getNamespace(WINDOW_INSTANCE);
if (winNs != null && !win.isFrozen()) {
winNs.copyWindowProperties(getCommonTypes(), win);
}
checkAndFreezeNominalType(win);
// Type the global THIS as window
globalThisType = win.getInstanceAsJSType();
} else {
// Type the global THIS as a loose object
globalThisType = getCommonTypes().getTopObject().withLoose();
}
getCommonTypes().setGlobalThis(globalThisType);
getGlobalScope().setDeclaredType(
(new FunctionTypeBuilder(getCommonTypes())).
addReceiverType(globalThisType).buildDeclaration());
this.globalTypeInfo.setRawNominalTypes(nominaltypesByNode.values());
nominaltypesByNode = null;
propertyDefs = null;
for (NTIScope s : getScopes()) {
s.freezeScope();
}
// 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);
n.setTypeI(type);
}
}
});
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;
// If a scope s1 contains a scope s2, then s2 must be before s1 in scopes.
// The type inference relies on this fact to process deeper scopes
// before shallower scopes.
Collections.reverse(getScopes());
this.compiler.setExternProperties(ImmutableSet.copyOf(getExternPropertyNames()));
}
private JSType simpleInferDeclaration(Declaration decl) {
if (decl == null) {
return null;
}
// Namespaces (literals, enums, constructors) get populated during ProcessScope,
// so it's generally NOT safe to convert them to jstypes until after ProcessScope is done.
// However, we've seen examples where it is useful to use the constructor type
// during inference, e.g., to get the type of the instance from it.
// We allow this use case but add a marker property to make sure that the constructor type
// itself doesn't leak into the result.
if (decl.getNominal() != null) {
FunctionType ctorFn = decl.getNominal().getConstructorFunction();
if (ctorFn == null) {
return null;
}
return getCommonTypes().fromFunctionType(ctorFn)
.withProperty(CONST_INFERENCE_MARKER, getCommonTypes().UNKNOWN);
}
if (decl.getTypeOfSimpleDecl() != null) {
return decl.getTypeOfSimpleDecl();
}
NTIScope funScope = (NTIScope) decl.getFunctionScope();
if (funScope != null) {
DeclaredFunctionType dft = funScope.getDeclaredFunctionType();
if (dft == null) {
return null;
}
return getCommonTypes().fromFunctionType(dft.toFunctionType());
}
return null;
}
private Collection<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;
}
NominalType superClass = rawType.getSuperClass();
Set<String> nonInheritedPropNames = rawType.getAllOwnProps();
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.getAllPropsOfClass()) {
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.getAllPropsOfInterface()) {
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);
checkState(propDef != null || rawType.getName().equals(WINDOW_CLASS));
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();
}
}
}
// 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);
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();
}
/**
* 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;
CollectNamedTypes(NTIScope s) {
this.currentScope = s;
}
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
switch (n.getToken()) {
case FUNCTION: {
visitFunctionEarly(n);
break;
}
case VAR: {
Node nameNode = n.getFirstChild();
String varName = nameNode.getString();
if (NodeUtil.isNamespaceDecl(nameNode)) {
visitObjlitNamespace(nameNode);
} else if (NodeUtil.isTypedefDecl(nameNode)) {
visitTypedef(nameNode);
} else if (NodeUtil.isEnumDecl(nameNode)) {
visitEnum(nameNode);
} else if (isAliasedNamespaceDefinition(nameNode)) {
visitAliasedNamespace(nameNode);
} else if (varName.equals(WINDOW_INSTANCE) && nameNode.isFromExterns()) {
visitWindowVar(nameNode);
} else if (isCtorDefinedByCall(nameNode)) {
visitNewCtorDefinedByCall(nameNode);
} else if (isCtorWithoutFunctionLiteral(nameNode)) {
visitNewCtorWithoutFunctionLiteral(nameNode);
}
if (!n.isFromExterns()
&& !this.currentScope.isDefinedLocally(varName, false)) {
// Add a dummy local to avoid shadowing errors, and to calculate
// escaped variables.
this.currentScope.addLocal(varName, getCommonTypes().UNKNOWN, false, false);
}
break;
}
case NAME: {
if (this.currentScope.isFunction()) {
NTIScope.mayRecordEscapedVar(this.currentScope, n.getString());
}
break;
}
case EXPR_RESULT: {
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;
}
break;
}
default:
break;
}
}
private void visitWindowVar(Node nameNode) {
JSType typeInJsdoc = getVarTypeFromAnnotation(nameNode, this.currentScope);
if (!this.currentScope.isDefinedLocally(WINDOW_INSTANCE, false)) {
this.currentScope.addLocal(WINDOW_INSTANCE, typeInJsdoc, false, true);
return;
}
// The externs may contain multiple definitions of window, or they may add
// properties to the window instance before "var window" is defined.
// In those cases, we want to pick the definition that has the Window
// nominal type.
NominalType maybeWin = typeInJsdoc == null
? null : typeInJsdoc.getNominalTypeIfSingletonObj();
if (maybeWin != null && maybeWin.getName().equals(WINDOW_CLASS)) {
this.currentScope.addLocal(WINDOW_INSTANCE, typeInJsdoc, false, true);
}
}
private void processQualifiedDefinition(Node qnameNode) {
checkArgument(qnameNode.isGetProp());
checkArgument(qnameNode.isQualifiedName());
Node recv = qnameNode.getFirstChild();
if (!this.currentScope.isNamespace(recv)
&& !mayCreateFunctionNamespace(recv)
&& !mayCreateWindowNamespace(recv)) {
return;
}
if (NodeUtil.isNamespaceDecl(qnameNode)) {
visitObjlitNamespace(qnameNode);
} else if (NodeUtil.isTypedefDecl(qnameNode)) {
visitTypedef(qnameNode);
} else if (NodeUtil.isEnumDecl(qnameNode)) {
visitEnum(qnameNode);
} else if (isAliasedNamespaceDefinition(qnameNode)) {
visitAliasedNamespace(qnameNode);
} else if (isAliasingGlobalThis(qnameNode)) {
visitGlobalThisAlias(qnameNode);
} else if (isQualifiedFunctionDefinition(qnameNode)) {
maybeAddFunctionToNamespace(qnameNode);
}
}
private boolean isAliasingGlobalThis(Node qnameNode) {
return convention.isAliasingGlobalThis(qnameNode.getParent())
&& this.currentScope.isTopLevel();
}
private void visitGlobalThisAlias(Node qnameNode) {
Namespace ns = getGlobalScope().getNamespace(WINDOW_INSTANCE);
if (ns != null) {
qnameNode.getParent().putBooleanProp(Node.ANALYZED_DURING_GTI, true);
this.currentScope.addNamespace(qnameNode, ns);
}
}
private boolean isAliasedNamespaceDefinition(Node qnameNode) {
Node rhs = NodeUtil.getRValueOfLValue(qnameNode);
if (rhs == null || !rhs.isQualifiedName()) {
return false;
}
Node parent = qnameNode.getParent();
JSDocInfo jsdoc = NodeUtil.getBestJSDocInfo(qnameNode);
if (jsdoc != null) {
return jsdoc.isConstructorOrInterface() || jsdoc.hasConstAnnotation();
}
// You can only alias variable namespaces at declaration, not at a random assignment later.
if (qnameNode.isName() && !parent.isVar()) {
return false;
}
if (!this.currentScope.isNamespace(rhs)) {
return false;
}
return qnameNode.isFromExterns()
// An ES6-module default export is transpiled to an assignment without @const,
// but we still consider it an alias.
|| (qnameNode.isGetProp()
&& qnameNode.getLastChild().getString().equals("default"))
// Aliased object-literal property; can happen after goog.module rewriting.
|| (qnameNode.isStringKey()
&& this.currentScope.isNamespace(NodeUtil.getBestLValue(parent)));
}
private boolean isQualifiedFunctionDefinition(Node qnameNode) {
checkArgument(qnameNode.isGetProp());
checkArgument(qnameNode.isQualifiedName());
Node parent = qnameNode.getParent();
JSDocInfo jsdoc = NodeUtil.getBestJSDocInfo(qnameNode);
return parent.isAssign()
&& parent.getParent().isExprResult()
&& parent.getLastChild().isFunction()
&& (jsdoc == null || jsdoc.containsFunctionDeclaration());
}
// Returns true iff it creates a new function namespace
private boolean mayCreateFunctionNamespace(Node qnameNode) {
if (!qnameNode.isQualifiedName()) {
return false;
}
QualifiedName qname = QualifiedName.fromNode(qnameNode);
checkState(!currentScope.isNamespace(qname));
if (!currentScope.isKnownFunction(qname)) {
return false;
}
if (qnameNode.isGetProp()) {
markAssignNodeAsAnalyzed(qnameNode.getGrandparent());
}
NTIScope s;
if (qnameNode.isName()) {
// s is the scope that contains the function
s = currentScope.getScope(qnameNode.getString()).getParent();
} else {
s = currentScope;
}
s.addFunNamespace(qnameNode);
return true;
}
private boolean mayCreateWindowNamespace(Node qnameNode) {
if (qnameNode.isName() && qnameNode.getString().equals(WINDOW_INSTANCE)
&& this.currentScope.isGlobalVar(WINDOW_INSTANCE)) {
getGlobalScope().addNamespaceLit(qnameNode);
return true;
}
return false;
}
private void visitObjlitNamespace(Node qnameNode) {
if (qnameNode.isGetProp()) {
markAssignNodeAsAnalyzed(qnameNode.getParent());
}
if (currentScope.isDefined(qnameNode)) {
if (qnameNode.isGetProp() && !NodeUtil.getRValueOfLValue(qnameNode).isOr()) {
warnings.add(JSError.make(qnameNode, REDECLARED_PROPERTY,
qnameNode.getLastChild().getString(),
qnameNode.getFirstChild().getQualifiedName()));
}
return;
}
currentScope.addNamespaceLit(qnameNode);
// If the object literal that defines the namespace has properties,
// some of them may define aliased namespaces. This is rare in hand-written
// code, but it happens often in code generated by the rewrite of
// goog.module exports.
Node maybeObjlit = NodeUtil.getRValueOfLValue(qnameNode);
if (maybeObjlit.isOr()) {
maybeObjlit = maybeObjlit.getLastChild();
}
Preconditions.checkState(maybeObjlit.isObjectLit(),
"Expected object literal, found %s", maybeObjlit);
for (Node propNode : maybeObjlit.children()) {
if (isAliasedNamespaceDefinition(propNode)) {
// Pretend that the alias was defined as an assignment to a qname
Node fakeGetprop = IR.getprop(qnameNode.cloneTree(), IR.string(propNode.getString()));
IR.assign(fakeGetprop, propNode.getFirstChild().cloneTree());
visitAliasedNamespace(fakeGetprop);
}
}
}