-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
TypeCheck.java
3231 lines (2899 loc) · 118 KB
/
TypeCheck.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 2006 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 static com.google.javascript.rhino.jstype.JSTypeNative.ARRAY_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.BOOLEAN_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.ITERABLE_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.NULL_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.NULL_VOID;
import static com.google.javascript.rhino.jstype.JSTypeNative.NUMBER_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.OBJECT_FUNCTION_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.OBJECT_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.REGEXP_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.STRING_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.SYMBOL_OBJECT_FUNCTION_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.UNKNOWN_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.VOID_TYPE;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Streams;
import com.google.javascript.jscomp.CodingConvention.SubclassRelationship;
import com.google.javascript.jscomp.CodingConvention.SubclassType;
import com.google.javascript.jscomp.type.ReverseAbstractInterpreter;
import com.google.javascript.rhino.JSDocInfo;
import com.google.javascript.rhino.JSTypeExpression;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.QualifiedName;
import com.google.javascript.rhino.Token;
import com.google.javascript.rhino.jstype.EnumType;
import com.google.javascript.rhino.jstype.FunctionType;
import com.google.javascript.rhino.jstype.JSType;
import com.google.javascript.rhino.jstype.JSType.SubtypingMode;
import com.google.javascript.rhino.jstype.JSTypeNative;
import com.google.javascript.rhino.jstype.JSTypeRegistry;
import com.google.javascript.rhino.jstype.JSTypeRegistry.PropDefinitionKind;
import com.google.javascript.rhino.jstype.NamedType;
import com.google.javascript.rhino.jstype.ObjectType;
import com.google.javascript.rhino.jstype.Property;
import com.google.javascript.rhino.jstype.TemplateTypeMap;
import com.google.javascript.rhino.jstype.TemplateTypeMapReplacer;
import com.google.javascript.rhino.jstype.TemplatizedType;
import com.google.javascript.rhino.jstype.TernaryValue;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import javax.annotation.Nullable;
/**
* <p>Checks the types of JS expressions against any declared type
* information.</p>
*
* @author nicksantos@google.com (Nick Santos)
*/
public final class TypeCheck implements NodeTraversal.Callback, CompilerPass {
//
// Internal errors
//
static final DiagnosticType UNEXPECTED_TOKEN = DiagnosticType.error(
"JSC_INTERNAL_ERROR_UNEXPECTED_TOKEN",
"Internal Error: TypeCheck doesn''t know how to handle {0}");
//
// User warnings
//
static final DiagnosticType DETERMINISTIC_TEST =
DiagnosticType.warning(
"JSC_DETERMINISTIC_TEST",
"condition always evaluates to {2}\n"
+ "left : {0}\n"
+ "right: {1}");
static final DiagnosticType INEXISTENT_ENUM_ELEMENT =
DiagnosticType.warning(
"JSC_INEXISTENT_ENUM_ELEMENT",
"element {0} does not exist on this enum");
public static final DiagnosticType INEXISTENT_PROPERTY =
DiagnosticType.warning(
"JSC_INEXISTENT_PROPERTY",
"Property {0} never defined on {1}");
// disabled by default. This one only makes sense if you're using
// well-typed externs.
static final DiagnosticType POSSIBLE_INEXISTENT_PROPERTY =
DiagnosticType.disabled(
"JSC_POSSIBLE_INEXISTENT_PROPERTY",
"Property {0} never defined on {1}");
static final DiagnosticType INEXISTENT_PROPERTY_WITH_SUGGESTION =
DiagnosticType.warning(
"JSC_INEXISTENT_PROPERTY_WITH_SUGGESTION",
"Property {0} never defined on {1}. Did you mean {2}?");
public static final DiagnosticType STRICT_INEXISTENT_PROPERTY =
DiagnosticType.disabled(
"JSC_STRICT_INEXISTENT_PROPERTY",
"Property {0} never defined on {1}");
public static final DiagnosticType STRICT_INEXISTENT_UNION_PROPERTY =
DiagnosticType.disabled(
"JSC_STRICT_INEXISTENT_UNION_PROPERTY",
"Property {0} not defined on all member types of {1}");
static final DiagnosticType STRICT_INEXISTENT_PROPERTY_WITH_SUGGESTION =
DiagnosticType.disabled(
"JSC_STRICT_INEXISTENT_PROPERTY_WITH_SUGGESTION",
"Property {0} never defined on {1}. Did you mean {2}?");
protected static final DiagnosticType NOT_A_CONSTRUCTOR =
DiagnosticType.warning(
"JSC_NOT_A_CONSTRUCTOR",
"cannot instantiate non-constructor");
static final DiagnosticType INSTANTIATE_ABSTRACT_CLASS =
DiagnosticType.warning(
"JSC_INSTANTIATE_ABSTRACT_CLASS",
"cannot instantiate abstract class");
static final DiagnosticType BIT_OPERATION =
DiagnosticType.warning(
"JSC_BAD_TYPE_FOR_BIT_OPERATION",
"operator {0} cannot be applied to {1}");
static final DiagnosticType NOT_CALLABLE =
DiagnosticType.warning(
"JSC_NOT_FUNCTION_TYPE",
"{0} expressions are not callable");
static final DiagnosticType CONSTRUCTOR_NOT_CALLABLE =
DiagnosticType.warning(
"JSC_CONSTRUCTOR_NOT_CALLABLE",
"Constructor {0} should be called with the \"new\" keyword");
static final DiagnosticType ABSTRACT_SUPER_METHOD_NOT_USABLE =
DiagnosticType.warning(
"JSC_ABSTRACT_SUPER_METHOD_NOT_USABLE",
"Abstract super method {0} cannot be dereferenced");
static final DiagnosticType FUNCTION_MASKS_VARIABLE =
DiagnosticType.warning("JSC_FUNCTION_MASKS_VARIABLE", "function {0} masks variable (IE bug)");
static final DiagnosticType MULTIPLE_VAR_DEF = DiagnosticType.warning(
"JSC_MULTIPLE_VAR_DEF",
"declaration of multiple variables with shared type information");
static final DiagnosticType ENUM_DUP = DiagnosticType.error("JSC_ENUM_DUP",
"enum element {0} already defined");
static final DiagnosticType INVALID_INTERFACE_MEMBER_DECLARATION =
DiagnosticType.warning(
"JSC_INVALID_INTERFACE_MEMBER_DECLARATION",
"interface members can only be empty property declarations,"
+ " empty functions{0}");
static final DiagnosticType INTERFACE_METHOD_NOT_EMPTY =
DiagnosticType.warning(
"JSC_INTERFACE_METHOD_NOT_EMPTY",
"interface member functions must have an empty body");
static final DiagnosticType CONFLICTING_EXTENDED_TYPE =
DiagnosticType.warning(
"JSC_CONFLICTING_EXTENDED_TYPE",
"{1} cannot extend this type; {0}s can only extend {0}s");
static final DiagnosticType ES5_CLASS_EXTENDING_ES6_CLASS =
DiagnosticType.warning(
"JSC_ES5_CLASS_EXTENDING_ES6_CLASS", "ES5 class {0} cannot extend ES6 class {1}");
static final DiagnosticType INTERFACE_EXTENDS_LOOP =
DiagnosticType.warning("JSC_INTERFACE_EXTENDS_LOOP", "extends loop involving {0}, loop: {1}");
static final DiagnosticType CONFLICTING_IMPLEMENTED_TYPE =
DiagnosticType.warning(
"JSC_CONFLICTING_IMPLEMENTED_TYPE",
"{0} cannot implement this type; "
+ "an interface can only extend, but not implement interfaces");
static final DiagnosticType BAD_IMPLEMENTED_TYPE =
DiagnosticType.warning(
"JSC_IMPLEMENTS_NON_INTERFACE",
"can only implement interfaces");
// disabled by default.
static final DiagnosticType HIDDEN_SUPERCLASS_PROPERTY =
DiagnosticType.disabled(
"JSC_HIDDEN_SUPERCLASS_PROPERTY",
"property {0} already defined on superclass {1}; use @override to override it");
static final DiagnosticType HIDDEN_PROTOTYPAL_SUPERTYPE_PROPERTY =
DiagnosticType.disabled(
"JSC_PROTOTYPAL_HIDDEN_SUPERCLASS_PROPERTY",
"property {0} already defined on supertype {1}; use @override to override it");
// disabled by default.
static final DiagnosticType HIDDEN_INTERFACE_PROPERTY =
DiagnosticType.disabled(
"JSC_HIDDEN_INTERFACE_PROPERTY",
"property {0} already defined on interface {1}; use @override to override it");
static final DiagnosticType HIDDEN_SUPERCLASS_PROPERTY_MISMATCH =
DiagnosticType.warning(
"JSC_HIDDEN_SUPERCLASS_PROPERTY_MISMATCH",
"mismatch of the {0} property type and the type "
+ "of the property it overrides from superclass {1}\n"
+ "original: {2}\n"
+ "override: {3}");
static final DiagnosticType HIDDEN_PROTOTYPAL_SUPERTYPE_PROPERTY_MISMATCH =
DiagnosticType.warning(
"JSC_HIDDEN_PROTOTYPAL_SUPERTYPE_PROPERTY_MISMATCH",
"mismatch of the {0} property type and the type "
+ "of the property it overrides from supertype {1}\n"
+ "original: {2}\n"
+ "override: {3}");
static final DiagnosticType UNKNOWN_OVERRIDE =
DiagnosticType.warning(
"JSC_UNKNOWN_OVERRIDE",
"property {0} not defined on any superclass of {1}");
static final DiagnosticType UNKNOWN_PROTOTYPAL_OVERRIDE =
DiagnosticType.warning(
"JSC_UNKNOWN_PROTOTYPAL_OVERRIDE", //
"property {0} not defined on any supertype of {1}");
static final DiagnosticType INTERFACE_METHOD_OVERRIDE =
DiagnosticType.warning(
"JSC_INTERFACE_METHOD_OVERRIDE",
"property {0} is already defined by the {1} extended interface");
static final DiagnosticType UNKNOWN_EXPR_TYPE =
DiagnosticType.warning(
"JSC_UNKNOWN_EXPR_TYPE", "could not determine the type of this expression");
static final DiagnosticType UNRESOLVED_TYPE =
DiagnosticType.warning("JSC_UNRESOLVED_TYPE",
"could not resolve the name {0} to a type");
static final DiagnosticType WRONG_ARGUMENT_COUNT =
DiagnosticType.warning(
"JSC_WRONG_ARGUMENT_COUNT",
"Function {0}: called with {1} argument(s). "
+ "Function requires at least {2} argument(s){3}.");
static final DiagnosticType ILLEGAL_IMPLICIT_CAST =
DiagnosticType.warning(
"JSC_ILLEGAL_IMPLICIT_CAST",
"Illegal annotation on {0}. @implicitCast may only be used in externs.");
static final DiagnosticType INCOMPATIBLE_EXTENDED_PROPERTY_TYPE =
DiagnosticType.warning(
"JSC_INCOMPATIBLE_EXTENDED_PROPERTY_TYPE",
"Interface {0} has a property {1} with incompatible types in "
+ "its super interfaces {2} and {3}");
static final DiagnosticType EXPECTED_THIS_TYPE =
DiagnosticType.warning(
"JSC_EXPECTED_THIS_TYPE",
"\"{0}\" must be called with a \"this\" type");
static final DiagnosticType IN_USED_WITH_STRUCT =
DiagnosticType.warning("JSC_IN_USED_WITH_STRUCT",
"Cannot use the IN operator with structs");
static final DiagnosticType ILLEGAL_PROPERTY_CREATION =
DiagnosticType.warning("JSC_ILLEGAL_PROPERTY_CREATION",
"Cannot add a property to a struct instance after it is constructed."
+ " (If you already declared the property, make sure to give it a type.)");
static final DiagnosticType ILLEGAL_OBJLIT_KEY =
DiagnosticType.warning("JSC_ILLEGAL_OBJLIT_KEY", "Illegal key, the object literal is a {0}");
static final DiagnosticType ILLEGAL_CLASS_KEY =
DiagnosticType.warning("JSC_ILLEGAL_CLASS_KEY", "Illegal key, the class is a {0}");
static final DiagnosticType NON_STRINGIFIABLE_OBJECT_KEY =
DiagnosticType.warning(
"JSC_NON_STRINGIFIABLE_OBJECT_KEY",
"Object type \"{0}\" contains non-stringifiable key and it may lead to an "
+ "error. Please use ES6 Map instead or implement your own Map structure.");
static final DiagnosticType ABSTRACT_METHOD_IN_CONCRETE_CLASS =
DiagnosticType.warning(
"JSC_ABSTRACT_METHOD_IN_CONCRETE_CLASS",
"Abstract methods can only appear in abstract classes. Please declare the class as "
+ "@abstract");
// If a diagnostic is disabled by default, do not add it in this list
// TODO(dimvar): Either INEXISTENT_PROPERTY shouldn't be here, or we should
// change DiagnosticGroups.setWarningLevel to not accidentally enable it.
static final DiagnosticGroup ALL_DIAGNOSTICS =
new DiagnosticGroup(
DETERMINISTIC_TEST,
INEXISTENT_ENUM_ELEMENT,
INEXISTENT_PROPERTY,
POSSIBLE_INEXISTENT_PROPERTY,
INEXISTENT_PROPERTY_WITH_SUGGESTION,
NOT_A_CONSTRUCTOR,
INSTANTIATE_ABSTRACT_CLASS,
BIT_OPERATION,
NOT_CALLABLE,
CONSTRUCTOR_NOT_CALLABLE,
FUNCTION_MASKS_VARIABLE,
MULTIPLE_VAR_DEF,
ENUM_DUP,
INVALID_INTERFACE_MEMBER_DECLARATION,
INTERFACE_METHOD_NOT_EMPTY,
CONFLICTING_EXTENDED_TYPE,
CONFLICTING_IMPLEMENTED_TYPE,
BAD_IMPLEMENTED_TYPE,
HIDDEN_SUPERCLASS_PROPERTY_MISMATCH,
HIDDEN_PROTOTYPAL_SUPERTYPE_PROPERTY_MISMATCH,
UNKNOWN_OVERRIDE,
UNKNOWN_PROTOTYPAL_OVERRIDE,
INTERFACE_METHOD_OVERRIDE,
UNRESOLVED_TYPE,
WRONG_ARGUMENT_COUNT,
ILLEGAL_IMPLICIT_CAST,
INCOMPATIBLE_EXTENDED_PROPERTY_TYPE,
EXPECTED_THIS_TYPE,
IN_USED_WITH_STRUCT,
ILLEGAL_CLASS_KEY,
ILLEGAL_PROPERTY_CREATION,
ILLEGAL_OBJLIT_KEY,
NON_STRINGIFIABLE_OBJECT_KEY,
ABSTRACT_METHOD_IN_CONCRETE_CLASS,
ABSTRACT_SUPER_METHOD_NOT_USABLE,
ES5_CLASS_EXTENDING_ES6_CLASS,
RhinoErrorReporter.TYPE_PARSE_ERROR,
RhinoErrorReporter.UNRECOGNIZED_TYPE_ERROR,
TypedScopeCreator.UNKNOWN_LENDS,
TypedScopeCreator.LENDS_ON_NON_OBJECT,
TypedScopeCreator.CTOR_INITIALIZER,
TypedScopeCreator.IFACE_INITIALIZER,
FunctionTypeBuilder.THIS_TYPE_NON_OBJECT);
private final AbstractCompiler compiler;
private final TypeValidator validator;
private final ReverseAbstractInterpreter reverseInterpreter;
private final JSTypeRegistry typeRegistry;
private TypedScope topScope;
private TypedScopeCreator scopeCreator;
private boolean reportUnknownTypes = false;
private SubtypingMode subtypingMode = SubtypingMode.NORMAL;
// This may be expensive, so don't emit these warnings if they're
// explicitly turned off.
private boolean reportMissingProperties = true;
private InferJSDocInfo inferJSDocInfo = null;
// These fields are used to calculate the percentage of expressions typed.
private int typedCount = 0;
private int nullCount = 0;
private int unknownCount = 0;
private boolean inExterns;
private static final class SuggestionPair {
private final String suggestion;
final int distance;
private SuggestionPair(String suggestion, int distance) {
this.suggestion = suggestion;
this.distance = distance;
}
}
public TypeCheck(
AbstractCompiler compiler,
ReverseAbstractInterpreter reverseInterpreter,
JSTypeRegistry typeRegistry,
TypedScope topScope,
TypedScopeCreator scopeCreator) {
this.compiler = compiler;
this.validator = compiler.getTypeValidator();
this.reverseInterpreter = reverseInterpreter;
this.typeRegistry = typeRegistry;
this.topScope = topScope;
this.scopeCreator = scopeCreator;
this.inferJSDocInfo = new InferJSDocInfo(compiler);
}
public TypeCheck(AbstractCompiler compiler,
ReverseAbstractInterpreter reverseInterpreter,
JSTypeRegistry typeRegistry) {
this(compiler, reverseInterpreter, typeRegistry, null, null);
}
/** Turn on the missing property check. Returns this for easy chaining. */
TypeCheck reportMissingProperties(boolean report) {
reportMissingProperties = report;
return this;
}
/** Turn on the unknown types check. Returns this for easy chaining. */
TypeCheck reportUnknownTypes(boolean report) {
reportUnknownTypes = report;
return this;
}
/**
* Main entry point for this phase of processing. This follows the pattern for
* JSCompiler phases.
*
* @param externsRoot The root of the externs parse tree.
* @param jsRoot The root of the input parse tree to be checked.
*/
@Override
public void process(Node externsRoot, Node jsRoot) {
checkNotNull(scopeCreator);
checkNotNull(topScope);
Node externsAndJs = jsRoot.getParent();
checkState(externsAndJs != null);
checkState(externsRoot == null || externsAndJs.hasChild(externsRoot));
if (externsRoot != null) {
check(externsRoot, true);
}
check(jsRoot, false);
}
/**
* Main entry point of this phase for testing code.
*
* @param externsRoot may be null or a ROOT node. If null the externs are not typechecked. Note:
* the externs node must always exist in the AST, even if not typechecked.
* @param jsRoot must be a ROOT node and the second child of the global ROOT.
*/
public TypedScope processForTesting(Node externsRoot, Node jsRoot) {
checkState(scopeCreator == null);
checkState(topScope == null);
checkArgument(externsRoot == null || externsRoot.isRoot(), externsRoot);
checkArgument(jsRoot.isRoot(), jsRoot);
checkState(jsRoot.getParent() != null && jsRoot.getParent().isRoot(), jsRoot.getParent());
Node externsAndJsRoot = jsRoot.getParent();
checkState(
externsRoot == null || externsRoot.getNext() == jsRoot,
"externs root must be the preceding sibling of the js root");
scopeCreator = new TypedScopeCreator(compiler);
topScope = scopeCreator.createScope(externsAndJsRoot, null);
TypeInferencePass inference =
new TypeInferencePass(compiler, reverseInterpreter, topScope, scopeCreator);
inference.process(externsRoot, jsRoot);
process(externsRoot, jsRoot);
return topScope;
}
void check(Node node, boolean externs) {
checkNotNull(node);
NodeTraversal t = new NodeTraversal(compiler, this, scopeCreator);
inExterns = externs;
t.traverseWithScope(node, topScope);
if (externs) {
inferJSDocInfo.process(node, null);
} else {
inferJSDocInfo.process(null, node);
}
}
private void report(Node n, DiagnosticType diagnosticType, String... arguments) {
compiler.report(JSError.make(n, diagnosticType, arguments));
}
@Override
public boolean shouldTraverse(NodeTraversal t, Node n, Node parent) {
if (n.isScript()) {
String filename = n.getSourceFileName();
if (filename != null && filename.endsWith(".java.js")) {
this.subtypingMode = SubtypingMode.IGNORE_NULL_UNDEFINED;
} else {
this.subtypingMode = SubtypingMode.NORMAL;
}
this.validator.setSubtypingMode(this.subtypingMode);
}
switch (n.getToken()) {
case FUNCTION:
// normal type checking
final TypedScope outerScope = t.getTypedScope();
// Check for a bug in IE9 (quirks mode) and earlier where bleeding function names would
// refer to the wrong variable (i.e. "var x; var y = function x() { use(x); }" would pass
// the 'x' from the outer scope, rather than the local alias bled into the function).
final TypedVar var = outerScope.getVar(n.getFirstChild().getString());
if (var != null
&& var.getScope().hasSameContainerScope(outerScope)
// Ideally, we would want to check whether the type in the scope
// differs from the type being defined, but then the extern
// redeclarations of built-in types generates spurious warnings.
&& !(var.getType() instanceof FunctionType)
&& !TypeValidator.hasDuplicateDeclarationSuppression(compiler, var.getNameNode())) {
report(n, FUNCTION_MASKS_VARIABLE, var.getName());
}
// TODO(user): Only traverse the function's body. The function's
// name and arguments are traversed by the scope creator, and ideally
// should not be traversed by the type checker.
break;
default:
break;
}
return true;
}
/**
* This is the meat of the type checking. It is basically one big switch,
* with each case representing one type of parse tree node. The individual
* cases are usually pretty straightforward.
*
* @param t The node traversal object that supplies context, such as the
* scope chain to use in name lookups as well as error reporting.
* @param n The node being visited.
* @param parent The parent of the node n.
*/
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
JSType childType;
JSType leftType;
JSType rightType;
Node left;
Node right;
// To be explicitly set to false if the node is not typeable.
boolean typeable = true;
switch (n.getToken()) {
case CAST:
Node expr = n.getFirstChild();
JSType exprType = getJSType(expr);
JSType castType = getJSType(n);
// TODO(johnlenz): determine if we can limit object literals in some
// way.
if (!expr.isObjectLit()) {
validator.expectCanCast(n, castType, exprType);
}
ensureTyped(n, castType);
expr.setJSTypeBeforeCast(exprType);
if (castType.restrictByNotNullOrUndefined().isSubtypeOf(exprType)
|| expr.isObjectLit()) {
expr.setJSType(castType);
}
break;
case NAME:
typeable = visitName(t, n, parent);
break;
case COMMA:
ensureTyped(n, getJSType(n.getLastChild()));
break;
case THIS:
ensureTyped(n, t.getTypedScope().getTypeOfThis());
break;
case NULL:
ensureTyped(n, NULL_TYPE);
break;
case NUMBER:
ensureTyped(n, NUMBER_TYPE);
break;
case GETTER_DEF:
case SETTER_DEF:
// Object literal keys are handled with OBJECTLIT
break;
case ARRAYLIT:
ensureTyped(n, ARRAY_TYPE);
break;
case REGEXP:
ensureTyped(n, REGEXP_TYPE);
break;
case GETPROP:
visitGetProp(t, n);
typeable = !(parent.isAssign() && parent.getFirstChild() == n);
break;
case GETELEM:
visitGetElem(n);
// The type of GETELEM is always unknown, so no point counting that.
// If that unknown leaks elsewhere (say by an assignment to another
// variable), then it will be counted.
typeable = false;
break;
case VAR:
case LET:
case CONST:
visitVar(t, n);
typeable = false;
break;
case NEW:
visitNew(n);
break;
case CALL:
visitCall(t, n);
typeable = !parent.isExprResult();
break;
case RETURN:
visitReturn(t, n);
typeable = false;
break;
case YIELD:
visitYield(t, n);
break;
case SUPER:
case NEW_TARGET:
case AWAIT:
ensureTyped(n);
break;
case DEC:
case INC:
left = n.getFirstChild();
checkPropCreation(left);
validator.expectNumber(left, getJSType(left), "increment/decrement");
ensureTyped(n, NUMBER_TYPE);
break;
case VOID:
ensureTyped(n, VOID_TYPE);
break;
case STRING:
case TYPEOF:
case TEMPLATELIT:
case TEMPLATELIT_STRING:
ensureTyped(n, STRING_TYPE);
break;
case TAGGED_TEMPLATELIT:
visitTaggedTemplateLit(n);
ensureTyped(n);
break;
case BITNOT:
childType = getJSType(n.getFirstChild());
if (!childType.matchesNumberContext()) {
report(n, BIT_OPERATION, NodeUtil.opToStr(n.getToken()), childType.toString());
} else {
this.validator.expectNumberStrict(n, childType, "bitwise NOT");
}
ensureTyped(n, NUMBER_TYPE);
break;
case POS:
case NEG:
left = n.getFirstChild();
if (n.getToken() == Token.NEG) {
// We are more permissive with +, because it is used to coerce to number
validator.expectNumber(left, getJSType(left), "sign operator");
}
ensureTyped(n, NUMBER_TYPE);
break;
case EQ:
case NE:
case SHEQ:
case SHNE:
{
left = n.getFirstChild();
right = n.getLastChild();
if (left.isTypeOf()) {
if (right.isString()) {
checkTypeofString(right, right.getString());
}
} else if (right.isTypeOf() && left.isString()) {
checkTypeofString(left, left.getString());
}
leftType = getJSType(left);
rightType = getJSType(right);
// We do not want to warn about explicit comparisons to VOID. People
// often do this if they think their type annotations screwed up.
//
// We do want to warn about cases where people compare things like
// (Array|null) == (Function|null)
// because it probably means they screwed up.
//
// This heuristic here is not perfect, but should catch cases we
// care about without too many false negatives.
JSType leftTypeRestricted = leftType.restrictByNotNullOrUndefined();
JSType rightTypeRestricted = rightType.restrictByNotNullOrUndefined();
TernaryValue result = TernaryValue.UNKNOWN;
if (n.getToken() == Token.EQ || n.isNE()) {
result = leftTypeRestricted.testForEquality(rightTypeRestricted);
if (n.isNE()) {
result = result.not();
}
} else {
// SHEQ or SHNE
if (!leftTypeRestricted.canTestForShallowEqualityWith(rightTypeRestricted)) {
result = n.getToken() == Token.SHEQ ? TernaryValue.FALSE : TernaryValue.TRUE;
}
}
if (result != TernaryValue.UNKNOWN) {
report(
n,
DETERMINISTIC_TEST,
leftType.toString(),
rightType.toString(),
result.toString());
}
ensureTyped(n, BOOLEAN_TYPE);
break;
}
case LT:
case LE:
case GT:
case GE:
Node leftSide = n.getFirstChild();
Node rightSide = n.getLastChild();
leftType = getJSType(leftSide);
rightType = getJSType(rightSide);
if (rightType.isUnknownType()) {
// validate comparable left
validator.expectStringOrNumber(leftSide, leftType, "left side of comparison");
} else if (leftType.isUnknownType()) {
// validate comparable right
validator.expectStringOrNumber(rightSide, rightType, "right side of comparison");
} else if (rightType.isNumber()) {
validator.expectNumber(leftSide, leftType, "left side of numeric comparison");
} else if (leftType.isNumber()) {
validator.expectNumber(rightSide, rightType, "right side of numeric comparison");
} else {
String errorMsg = "expected matching types in comparison";
this.validator.expectMatchingTypesStrict(n, leftType, rightType, errorMsg);
if (!leftType.matchesNumberContext() || !rightType.matchesNumberContext()) {
// Whether the comparison is numeric will be determined at runtime
// each time the expression is evaluated. Regardless, both operands
// should match a string context.
String message = "left side of comparison";
validator.expectString(leftSide, leftType, message);
validator.expectNotNullOrUndefined(
t, leftSide, leftType, message, getNativeType(STRING_TYPE));
message = "right side of comparison";
validator.expectString(rightSide, rightType, message);
validator.expectNotNullOrUndefined(
t, rightSide, rightType, message, getNativeType(STRING_TYPE));
}
}
ensureTyped(n, BOOLEAN_TYPE);
break;
case IN:
left = n.getFirstChild();
right = n.getLastChild();
rightType = getJSType(right);
validator.expectStringOrSymbol(left, getJSType(left), "left side of 'in'");
validator.expectObject(n, rightType, "'in' requires an object");
if (rightType.isStruct()) {
report(right, IN_USED_WITH_STRUCT);
}
ensureTyped(n, BOOLEAN_TYPE);
break;
case INSTANCEOF:
left = n.getFirstChild();
right = n.getLastChild();
rightType = getJSType(right).restrictByNotNullOrUndefined();
validator.expectAnyObject(left, getJSType(left), "deterministic instanceof yields false");
validator.expectActualObject(right, rightType, "instanceof requires an object");
ensureTyped(n, BOOLEAN_TYPE);
break;
case ASSIGN:
visitAssign(t, n);
typeable = false;
break;
case ASSIGN_LSH:
case ASSIGN_RSH:
case ASSIGN_URSH:
case ASSIGN_DIV:
case ASSIGN_MOD:
case ASSIGN_BITOR:
case ASSIGN_BITXOR:
case ASSIGN_BITAND:
case ASSIGN_SUB:
case ASSIGN_ADD:
case ASSIGN_MUL:
case ASSIGN_EXPONENT:
checkPropCreation(n.getFirstChild());
// fall through
case LSH:
case RSH:
case URSH:
case DIV:
case MOD:
case BITOR:
case BITXOR:
case BITAND:
case SUB:
case ADD:
case MUL:
case EXPONENT:
visitBinaryOperator(n.getToken(), n);
break;
case TRUE:
case FALSE:
case NOT:
case DELPROP:
ensureTyped(n, BOOLEAN_TYPE);
break;
case CASE:
JSType switchType = getJSType(parent.getFirstChild());
JSType caseType = getJSType(n.getFirstChild());
validator.expectSwitchMatchesCase(n, switchType, caseType);
typeable = false;
break;
case WITH: {
Node child = n.getFirstChild();
childType = getJSType(child);
validator.expectObject(child, childType, "with requires an object");
typeable = false;
break;
}
case FUNCTION:
visitFunction(n);
break;
case CLASS:
visitClass(n);
break;
// These nodes have no interesting type behavior.
// These nodes require data flow analysis.
case PARAM_LIST:
case STRING_KEY:
case MEMBER_FUNCTION_DEF:
case COMPUTED_PROP:
case LABEL:
case LABEL_NAME:
case SWITCH:
case BREAK:
case CATCH:
case TRY:
case SCRIPT:
case MODULE_BODY:
case EXPR_RESULT:
case BLOCK:
case ROOT:
case EMPTY:
case DEFAULT_CASE:
case CONTINUE:
case DEBUGGER:
case THROW:
case DO:
case IF:
case WHILE:
case FOR:
case TEMPLATELIT_SUB:
case REST:
case DESTRUCTURING_LHS:
typeable = false;
break;
case ARRAY_PATTERN:
ensureTyped(n);
validator.expectAutoboxesToIterable(
n, getJSType(n), "array pattern destructuring requires an Iterable");
break;
case OBJECT_PATTERN:
visitObjectPattern(n);
break;
case DEFAULT_VALUE:
checkCanAssignToWithScope(
t,
n,
n.getFirstChild(),
getJSType(n.getSecondChild()),
/* info= */ null,
"default value has wrong type");
// Every other usage of a destructuring pattern is checked while visiting the pattern,
// but default values are different because they are a conditional assignment and the
// pattern is not given the default value's type
Node lhs = n.getFirstChild();
Node rhs = n.getSecondChild();
if (lhs.isArrayPattern()) {
validator.expectAutoboxesToIterable(
rhs, getJSType(rhs), "array pattern destructuring requires an Iterable");
} else if (lhs.isObjectPattern()) {
// Verify that the value is not null/undefined, since those can't be destructured.
validator.expectObject(
rhs, getJSType(rhs), "cannot destructure a 'null' or 'undefined' default value");
}
typeable = false;
break;
case CLASS_MEMBERS: {
JSType typ = parent.getJSType().toMaybeFunctionType().getInstanceType();
for (Node child = n.getFirstChild(); child != null; child = child.getNext()) {
visitObjectOrClassLiteralKey(child, n.getParent(), typ);
}
typeable = false;
break;
}
case FOR_IN:
Node obj = n.getSecondChild();
if (getJSType(obj).isStruct()) {
report(obj, IN_USED_WITH_STRUCT);
}
typeable = false;
break;
case FOR_OF:
case FOR_AWAIT_OF:
ensureTyped(n.getSecondChild());
typeable = false;
break;
// These nodes are typed during the type inference.
case AND:
case HOOK:
case OBJECTLIT:
case OR:
if (n.getJSType() != null) { // If we didn't run type inference.
ensureTyped(n);
} else {
// If this is an enum, then give that type to the objectlit as well.
if (n.isObjectLit() && (parent.getJSType() instanceof EnumType)) {
ensureTyped(n, parent.getJSType());
} else {
ensureTyped(n);
}
}
if (n.isObjectLit()) {
JSType typ = getJSType(n);
for (Node key : n.children()) {
visitObjectOrClassLiteralKey(key, n, typ);
}
}
break;
case SPREAD:
checkSpread(n);
typeable = false;
break;
default: