Debian Codegraph @

src/com/google/javascript/jscomp/TypeCheck.java

raw symbols SCIP
1 /*
2 * Copyright 2006 The Closure Compiler Authors.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package com.google.javascript.jscomp;
18
19 import static com.google.javascript.rhino.jstype.JSTypeNative.ARRAY_TYPE;
20 import static com.google.javascript.rhino.jstype.JSTypeNative.BOOLEAN_TYPE;
21 import static com.google.javascript.rhino.jstype.JSTypeNative.NULL_TYPE;
22 import static com.google.javascript.rhino.jstype.JSTypeNative.NUMBER_TYPE;
23 import static com.google.javascript.rhino.jstype.JSTypeNative.OBJECT_FUNCTION_TYPE;
24 import static com.google.javascript.rhino.jstype.JSTypeNative.OBJECT_TYPE;
25 import static com.google.javascript.rhino.jstype.JSTypeNative.REGEXP_TYPE;
26 import static com.google.javascript.rhino.jstype.JSTypeNative.STRING_TYPE;
27 import static com.google.javascript.rhino.jstype.JSTypeNative.UNKNOWN_TYPE;
28 import static com.google.javascript.rhino.jstype.JSTypeNative.VOID_TYPE;
29
30 import com.google.common.base.Preconditions;
31 import com.google.common.collect.ImmutableSet;
32 import com.google.javascript.jscomp.Scope.Var;
33 import com.google.javascript.jscomp.type.ReverseAbstractInterpreter;
34 import com.google.javascript.rhino.JSDocInfo;
35 import com.google.javascript.rhino.Node;
36 import com.google.javascript.rhino.Token;
37 import com.google.javascript.rhino.jstype.EnumType;
38 import com.google.javascript.rhino.jstype.FunctionType;
39 import com.google.javascript.rhino.jstype.JSType;
40 import com.google.javascript.rhino.jstype.JSTypeNative;
41 import com.google.javascript.rhino.jstype.JSTypeRegistry;
42 import com.google.javascript.rhino.jstype.ObjectType;
43 import com.google.javascript.rhino.jstype.TernaryValue;
44
45 import java.util.HashMap;
46 import java.util.Iterator;
47 import java.util.Set;
48
49 /**
50 * <p>Checks the types of JS expressions against any declared type
51 * information.</p>
52 *
53 */
54 public class TypeCheck implements NodeTraversal.Callback, CompilerPass {
55
56 //
57 // Internal errors
58 //
59 static final DiagnosticType UNEXPECTED_TOKEN = DiagnosticType.error(
60 "JSC_INTERNAL_ERROR_UNEXPECTED_TOKEN",
61 "Internal Error: Don't know how to handle {0}");
62
63
64 //
65 // User warnings
66 //
67
68 protected static final String OVERRIDING_PROTOTYPE_WITH_NON_OBJECT =
69 "overriding prototype with non-object";
70
71 // TODO(user): make all the non private messages private once the
72 // TypedScopeCreator has been merged with the type checker.
73 static final DiagnosticType DETERMINISTIC_TEST =
74 DiagnosticType.warning(
75 "JSC_DETERMINISTIC_TEST",
76 "condition always evaluates to {2}\n" +
77 "left : {0}\n" +
78 "right: {1}");
79
80 static final DiagnosticType DETERMINISTIC_TEST_NO_RESULT =
81 DiagnosticType.warning(
82 "JSC_DETERMINISTIC_TEST_NO_RESULT",
83 "condition always evaluates to the same value\n" +
84 "left : {0}\n" +
85 "right: {1}");
86
87 static final DiagnosticType INEXISTENT_ENUM_ELEMENT =
88 DiagnosticType.warning(
89 "JSC_INEXISTENT_ENUM_ELEMENT",
90 "element {0} does not exist on this enum");
91
92 // disabled by default. This one only makes sense if you're using
93 // well-typed externs.
94 static final DiagnosticType INEXISTENT_PROPERTY =
95 DiagnosticType.disabled(
96 "JSC_INEXISTENT_PROPERTY",
97 "Property {0} never defined on {1}");
98
99 protected static final DiagnosticType NOT_A_CONSTRUCTOR =
100 DiagnosticType.warning(
101 "JSC_NOT_A_CONSTRUCTOR",
102 "cannot instantiate non-constructor");
103
104 static final DiagnosticType BIT_OPERATION =
105 DiagnosticType.warning(
106 "JSC_BAD_TYPE_FOR_BIT_OPERATION",
107 "operator {0} cannot be applied to {1}");
108
109 static final DiagnosticType NOT_CALLABLE =
110 DiagnosticType.warning(
111 "JSC_NOT_FUNCTION_TYPE",
112 "{0} expressions are not callable");
113
114 static final DiagnosticType CONSTRUCTOR_NOT_CALLABLE =
115 DiagnosticType.warning(
116 "JSC_CONSTRUCTOR_NOT_CALLABLE",
117 "Constructor {0} should be called with the \"new\" keyword");
118
119 static final DiagnosticType FUNCTION_MASKS_VARIABLE =
120 DiagnosticType.warning(
121 "JSC_FUNCTION_MASKS_VARIABLE",
122 "function {0} masks variable (IE bug)");
123
124 static final DiagnosticType MULTIPLE_VAR_DEF = DiagnosticType.warning(
125 "JSC_MULTIPLE_VAR_DEF",
126 "declaration of multiple variables with shared type information");
127
128 static final DiagnosticType ENUM_DUP = DiagnosticType.error("JSC_ENUM_DUP",
129 "enum element {0} already defined");
130
131 static final DiagnosticType ENUM_NOT_CONSTANT =
132 DiagnosticType.warning("JSC_ENUM_NOT_CONSTANT",
133 "enum key {0} must be a syntactic constant");
134
135 static final DiagnosticType INVALID_INTERFACE_MEMBER_DECLARATION =
136 DiagnosticType.warning(
137 "JSC_INVALID_INTERFACE_MEMBER_DECLARATION",
138 "interface members can only be empty property declarations,"
139 + " empty functions{0}");
140
141 static final DiagnosticType INTERFACE_FUNCTION_NOT_EMPTY =
142 DiagnosticType.warning(
143 "JSC_INTERFACE_FUNCTION_NOT_EMPTY",
144 "interface member functions must have an empty body");
145
146 static final DiagnosticType CONFLICTING_SHAPE_TYPE =
147 DiagnosticType.warning(
148 "JSC_CONFLICTING_SHAPE_TYPE",
149 "{1} cannot extend this type; {0}s can only extend {0}s");
150
151 static final DiagnosticType CONFLICTING_EXTENDED_TYPE =
152 DiagnosticType.warning(
153 "JSC_CONFLICTING_EXTENDED_TYPE",
154 "{1} cannot extend this type; {0}s can only extend {0}s");
155
156 static final DiagnosticType CONFLICTING_IMPLEMENTED_TYPE =
157 DiagnosticType.warning(
158 "JSC_CONFLICTING_IMPLEMENTED_TYPE",
159 "{0} cannot implement this type; " +
160 "an interface can only extend, but not implement interfaces");
161
162 static final DiagnosticType BAD_IMPLEMENTED_TYPE =
163 DiagnosticType.warning(
164 "JSC_IMPLEMENTS_NON_INTERFACE",
165 "can only implement interfaces");
166
167 static final DiagnosticType HIDDEN_SUPERCLASS_PROPERTY =
168 DiagnosticType.warning(
169 "JSC_HIDDEN_SUPERCLASS_PROPERTY",
170 "property {0} already defined on superclass {1}; " +
171 "use @override to override it");
172
173 static final DiagnosticType HIDDEN_INTERFACE_PROPERTY =
174 DiagnosticType.warning(
175 "JSC_HIDDEN_INTERFACE_PROPERTY",
176 "property {0} already defined on interface {1}; " +
177 "use @override to override it");
178
179 static final DiagnosticType HIDDEN_SUPERCLASS_PROPERTY_MISMATCH =
180 DiagnosticType.warning("JSC_HIDDEN_SUPERCLASS_PROPERTY_MISMATCH",
181 "mismatch of the {0} property type and the type " +
182 "of the property it overrides from superclass {1}\n" +
183 "original: {2}\n" +
184 "override: {3}");
185
186 static final DiagnosticType UNKNOWN_OVERRIDE =
187 DiagnosticType.warning(
188 "JSC_UNKNOWN_OVERRIDE",
189 "property {0} not defined on any superclass of {1}");
190
191 static final DiagnosticType INTERFACE_METHOD_OVERRIDE =
192 DiagnosticType.warning(
193 "JSC_INTERFACE_METHOD_OVERRIDE",
194 "property {0} is already defined by the {1} extended interface");
195
196 static final DiagnosticType UNKNOWN_EXPR_TYPE =
197 DiagnosticType.warning("JSC_UNKNOWN_EXPR_TYPE",
198 "could not determine the type of this expression");
199
200 static final DiagnosticType UNRESOLVED_TYPE =
201 DiagnosticType.warning("JSC_UNRESOLVED_TYPE",
202 "could not resolve the name {0} to a type");
203
204 static final DiagnosticType WRONG_ARGUMENT_COUNT =
205 DiagnosticType.warning(
206 "JSC_WRONG_ARGUMENT_COUNT",
207 "Function {0}: called with {1} argument(s). " +
208 "Function requires at least {2} argument(s){3}.");
209
210 static final DiagnosticType ILLEGAL_IMPLICIT_CAST =
211 DiagnosticType.warning(
212 "JSC_ILLEGAL_IMPLICIT_CAST",
213 "Illegal annotation on {0}. @implicitCast may only be used in " +
214 "externs.");
215
216 static final DiagnosticType INCOMPATIBLE_EXTENDED_PROPERTY_TYPE =
217 DiagnosticType.warning(
218 "JSC_INCOMPATIBLE_EXTENDED_PROPERTY_TYPE",
219 "Interface {0} has a property {1} with incompatible types in " +
220 "its super interfaces {2} and {3}");
221
222 static final DiagnosticType EXPECTED_THIS_TYPE =
223 DiagnosticType.warning(
224 "JSC_EXPECTED_THIS_TYPE",
225 "\"{0}\" must be called with a \"this\" type");
226
227 static final DiagnosticType IN_USED_WITH_STRUCT =
228 DiagnosticType.warning("JSC_IN_USED_WITH_STRUCT",
229 "Cannot use the IN operator with structs");
230
231 static final DiagnosticType ILLEGAL_PROPERTY_CREATION =
232 DiagnosticType.warning("JSC_ILLEGAL_PROPERTY_CREATION",
233 "Cannot add a property to a struct instance " +
234 "after it is constructed.");
235
236 static final DiagnosticType ILLEGAL_OBJLIT_KEY =
237 DiagnosticType.warning(
238 "ILLEGAL_OBJLIT_KEY",
239 "Illegal key, the object literal is a {0}");
240
241 static final DiagnosticGroup ALL_DIAGNOSTICS = new DiagnosticGroup(
242 DETERMINISTIC_TEST,
243 DETERMINISTIC_TEST_NO_RESULT,
244 INEXISTENT_ENUM_ELEMENT,
245 INEXISTENT_PROPERTY,
246 NOT_A_CONSTRUCTOR,
247 BIT_OPERATION,
248 NOT_CALLABLE,
249 CONSTRUCTOR_NOT_CALLABLE,
250 FUNCTION_MASKS_VARIABLE,
251 MULTIPLE_VAR_DEF,
252 ENUM_DUP,
253 ENUM_NOT_CONSTANT,
254 INVALID_INTERFACE_MEMBER_DECLARATION,
255 INTERFACE_FUNCTION_NOT_EMPTY,
256 CONFLICTING_SHAPE_TYPE,
257 CONFLICTING_EXTENDED_TYPE,
258 CONFLICTING_IMPLEMENTED_TYPE,
259 BAD_IMPLEMENTED_TYPE,
260 HIDDEN_SUPERCLASS_PROPERTY,
261 HIDDEN_INTERFACE_PROPERTY,
262 HIDDEN_SUPERCLASS_PROPERTY_MISMATCH,
263 UNKNOWN_OVERRIDE,
264 INTERFACE_METHOD_OVERRIDE,
265 UNKNOWN_EXPR_TYPE,
266 UNRESOLVED_TYPE,
267 WRONG_ARGUMENT_COUNT,
268 ILLEGAL_IMPLICIT_CAST,
269 INCOMPATIBLE_EXTENDED_PROPERTY_TYPE,
270 EXPECTED_THIS_TYPE,
271 IN_USED_WITH_STRUCT,
272 ILLEGAL_PROPERTY_CREATION,
273 ILLEGAL_OBJLIT_KEY,
274 RhinoErrorReporter.TYPE_PARSE_ERROR,
275 TypedScopeCreator.UNKNOWN_LENDS,
276 TypedScopeCreator.LENDS_ON_NON_OBJECT,
277 TypedScopeCreator.CTOR_INITIALIZER,
278 TypedScopeCreator.IFACE_INITIALIZER,
279 FunctionTypeBuilder.THIS_TYPE_NON_OBJECT);
280
281 private final AbstractCompiler compiler;
282 private final TypeValidator validator;
283
284 private final ReverseAbstractInterpreter reverseInterpreter;
285
286 private final JSTypeRegistry typeRegistry;
287 private Scope topScope;
288
289 private MemoizedScopeCreator scopeCreator;
290
291 private final CheckLevel reportMissingOverride;
292 private final CheckLevel reportUnknownTypes;
293
294 // This may be expensive, so don't emit these warnings if they're
295 // explicitly turned off.
296 private boolean reportMissingProperties = true;
297
298 private InferJSDocInfo inferJSDocInfo = null;
299
300 // These fields are used to calculate the percentage of expressions typed.
301 private int typedCount = 0;
302 private int nullCount = 0;
303 private int unknownCount = 0;
304 private boolean inExterns;
305
306 // A state boolean to see we are currently in @notypecheck section of the
307 // code.
308 private int noTypeCheckSection = 0;
309
310 public TypeCheck(AbstractCompiler compiler,
311 ReverseAbstractInterpreter reverseInterpreter,
312 JSTypeRegistry typeRegistry,
313 Scope topScope,
314 MemoizedScopeCreator scopeCreator,
315 CheckLevel reportMissingOverride,
316 CheckLevel reportUnknownTypes) {
317 this.compiler = compiler;
318 this.validator = compiler.getTypeValidator();
319 this.reverseInterpreter = reverseInterpreter;
320 this.typeRegistry = typeRegistry;
321 this.topScope = topScope;
322 this.scopeCreator = scopeCreator;
323 this.reportMissingOverride = reportMissingOverride;
324 this.reportUnknownTypes = reportUnknownTypes;
325 this.inferJSDocInfo = new InferJSDocInfo(compiler);
326 }
327
328 public TypeCheck(AbstractCompiler compiler,
329 ReverseAbstractInterpreter reverseInterpreter,
330 JSTypeRegistry typeRegistry,
331 CheckLevel reportMissingOverride,
332 CheckLevel reportUnknownTypes) {
333 this(compiler, reverseInterpreter, typeRegistry, null, null,
334 reportMissingOverride, reportUnknownTypes);
335 }
336
337 TypeCheck(AbstractCompiler compiler,
338 ReverseAbstractInterpreter reverseInterpreter,
339 JSTypeRegistry typeRegistry) {
340 this(compiler, reverseInterpreter, typeRegistry, null, null,
341 CheckLevel.WARNING, CheckLevel.OFF);
342 }
343
344 /** Turn on the missing property check. Returns this for easy chaining. */
345 TypeCheck reportMissingProperties(boolean report) {
346 reportMissingProperties = report;
347 return this;
348 }
349
350 /**
351 * Main entry point for this phase of processing. This follows the pattern for
352 * JSCompiler phases.
353 *
354 * @param externsRoot The root of the externs parse tree.
355 * @param jsRoot The root of the input parse tree to be checked.
356 */
357 @Override
358 public void process(Node externsRoot, Node jsRoot) {
359 Preconditions.checkNotNull(scopeCreator);
360 Preconditions.checkNotNull(topScope);
361
362 Node externsAndJs = jsRoot.getParent();
363 Preconditions.checkState(externsAndJs != null);
364 Preconditions.checkState(
365 externsRoot == null || externsAndJs.hasChild(externsRoot));
366
367 if (externsRoot != null) {
368 check(externsRoot, true);
369 }
370 check(jsRoot, false);
371 }
372
373 /** Main entry point of this phase for testing code. */
374 public Scope processForTesting(Node externsRoot, Node jsRoot) {
375 Preconditions.checkState(scopeCreator == null);
376 Preconditions.checkState(topScope == null);
377
378 Preconditions.checkState(jsRoot.getParent() != null);
379 Node externsAndJsRoot = jsRoot.getParent();
380
381 scopeCreator = new MemoizedScopeCreator(new TypedScopeCreator(compiler));
382 topScope = scopeCreator.createScope(externsAndJsRoot, null);
383
384 TypeInferencePass inference = new TypeInferencePass(compiler,
385 reverseInterpreter, topScope, scopeCreator);
386
387 inference.process(externsRoot, jsRoot);
388 process(externsRoot, jsRoot);
389
390 return topScope;
391 }
392
393
394 public void check(Node node, boolean externs) {
395 Preconditions.checkNotNull(node);
396
397 NodeTraversal t = new NodeTraversal(compiler, this, scopeCreator);
398 inExterns = externs;
399 t.traverseWithScope(node, topScope);
400 if (externs) {
401 inferJSDocInfo.process(node, null);
402 } else {
403 inferJSDocInfo.process(null, node);
404 }
405 }
406
407
408 private void checkNoTypeCheckSection(Node n, boolean enterSection) {
409 switch (n.getType()) {
410 case Token.SCRIPT:
411 case Token.BLOCK:
412 case Token.VAR:
413 case Token.FUNCTION:
414 case Token.ASSIGN:
415 JSDocInfo info = n.getJSDocInfo();
416 if (info != null && info.isNoTypeCheck()) {
417 if (enterSection) {
418 noTypeCheckSection++;
419 } else {
420 noTypeCheckSection--;
421 }
422 }
423 validator.setShouldReport(noTypeCheckSection == 0);
424 break;
425 }
426 }
427
428 private void report(NodeTraversal t, Node n, DiagnosticType diagnosticType,
429 String... arguments) {
430 if (noTypeCheckSection == 0) {
431 t.report(n, diagnosticType, arguments);
432 }
433 }
434
435 @Override
436 public boolean shouldTraverse(
437 NodeTraversal t, Node n, Node parent) {
438 checkNoTypeCheckSection(n, true);
439 switch (n.getType()) {
440 case Token.FUNCTION:
441 // normal type checking
442 final Scope outerScope = t.getScope();
443 final String functionPrivateName = n.getFirstChild().getString();
444 if (functionPrivateName != null && functionPrivateName.length() > 0 &&
445 outerScope.isDeclared(functionPrivateName, false) &&
446 // Ideally, we would want to check whether the type in the scope
447 // differs from the type being defined, but then the extern
448 // redeclarations of built-in types generates spurious warnings.
449 !(outerScope.getVar(
450 functionPrivateName).getType() instanceof FunctionType)) {
451 report(t, n, FUNCTION_MASKS_VARIABLE, functionPrivateName);
452 }
453
454 // TODO(user): Only traverse the function's body. The function's
455 // name and arguments are traversed by the scope creator, and ideally
456 // should not be traversed by the type checker.
457 break;
458 }
459 return true;
460 }
461
462 /**
463 * This is the meat of the type checking. It is basically one big switch,
464 * with each case representing one type of parse tree node. The individual
465 * cases are usually pretty straightforward.
466 *
467 * @param t The node traversal object that supplies context, such as the
468 * scope chain to use in name lookups as well as error reporting.
469 * @param n The node being visited.
470 * @param parent The parent of the node n.
471 */
472 @Override
473 public void visit(NodeTraversal t, Node n, Node parent) {
474 JSType childType;
475 JSType leftType, rightType;
476 Node left, right;
477 // To be explicitly set to false if the node is not typeable.
478 boolean typeable = true;
479
480 switch (n.getType()) {
481 case Token.CAST:
482 Node expr = n.getFirstChild();
483 ensureTyped(t, n, getJSType(expr));
484
485 // If the cast, tightens the type apply it, so it is available post
486 // normalization.
487 JSType castType = getJSType(n);
488 JSType exprType = getJSType(expr);
489 if (castType.isSubtype(exprType)) {
490 expr.setJSType(castType);
491 }
492 break;
493
494 case Token.NAME:
495 typeable = visitName(t, n, parent);
496 break;
497
498 case Token.PARAM_LIST:
499 typeable = false;
500 break;
501
502 case Token.COMMA:
503 ensureTyped(t, n, getJSType(n.getLastChild()));
504 break;
505
506 case Token.TRUE:
507 case Token.FALSE:
508 ensureTyped(t, n, BOOLEAN_TYPE);
509 break;
510
511 case Token.THIS:
512 ensureTyped(t, n, t.getScope().getTypeOfThis());
513 break;
514
515 case Token.NULL:
516 ensureTyped(t, n, NULL_TYPE);
517 break;
518
519 case Token.NUMBER:
520 ensureTyped(t, n, NUMBER_TYPE);
521 break;
522
523 case Token.STRING:
524 ensureTyped(t, n, STRING_TYPE);
525 break;
526
527 case Token.STRING_KEY:
528 typeable = false;
529 break;
530
531 case Token.GETTER_DEF:
532 case Token.SETTER_DEF:
533 // Object literal keys are handled with OBJECTLIT
534 break;
535
536 case Token.ARRAYLIT:
537 ensureTyped(t, n, ARRAY_TYPE);
538 break;
539
540 case Token.REGEXP:
541 ensureTyped(t, n, REGEXP_TYPE);
542 break;
543
544 case Token.GETPROP:
545 visitGetProp(t, n, parent);
546 typeable = !(parent.isAssign() &&
547 parent.getFirstChild() == n);
548 break;
549
550 case Token.GETELEM:
551 visitGetElem(t, n);
552 // The type of GETELEM is always unknown, so no point counting that.
553 // If that unknown leaks elsewhere (say by an assignment to another
554 // variable), then it will be counted.
555 typeable = false;
556 break;
557
558 case Token.VAR:
559 visitVar(t, n);
560 typeable = false;
561 break;
562
563 case Token.NEW:
564 visitNew(t, n);
565 break;
566
567 case Token.CALL:
568 visitCall(t, n);
569 typeable = !parent.isExprResult();
570 break;
571
572 case Token.RETURN:
573 visitReturn(t, n);
574 typeable = false;
575 break;
576
577 case Token.DEC:
578 case Token.INC:
579 left = n.getFirstChild();
580 checkPropCreation(t, left);
581 validator.expectNumber(t, left, getJSType(left), "increment/decrement");
582 ensureTyped(t, n, NUMBER_TYPE);
583 break;
584
585 case Token.NOT:
586 ensureTyped(t, n, BOOLEAN_TYPE);
587 break;
588
589 case Token.VOID:
590 ensureTyped(t, n, VOID_TYPE);
591 break;
592
593 case Token.TYPEOF:
594 ensureTyped(t, n, STRING_TYPE);
595 break;
596
597 case Token.BITNOT:
598 childType = getJSType(n.getFirstChild());
599 if (!childType.matchesInt32Context()) {
600 report(t, n, BIT_OPERATION, NodeUtil.opToStr(n.getType()),
601 childType.toString());
602 }
603 ensureTyped(t, n, NUMBER_TYPE);
604 break;
605
606 case Token.POS:
607 case Token.NEG:
608 left = n.getFirstChild();
609 validator.expectNumber(t, left, getJSType(left), "sign operator");
610 ensureTyped(t, n, NUMBER_TYPE);
611 break;
612
613 case Token.EQ:
614 case Token.NE:
615 case Token.SHEQ:
616 case Token.SHNE: {
617 left = n.getFirstChild();
618 right = n.getLastChild();
619
620 if (left.isTypeOf()) {
621 if (right.isString()) {
622 checkTypeofString(t, right, right.getString());
623 }
624 } else if (right.isTypeOf() && left.isString()) {
625 checkTypeofString(t, left, left.getString());
626 }
627
628 leftType = getJSType(left);
629 rightType = getJSType(right);
630
631 // We do not want to warn about explicit comparisons to VOID. People
632 // often do this if they think their type annotations screwed up.
633 //
634 // We do want to warn about cases where people compare things like
635 // (Array|null) == (Function|null)
636 // because it probably means they screwed up.
637 //
638 // This heuristic here is not perfect, but should catch cases we
639 // care about without too many false negatives.
640 JSType leftTypeRestricted = leftType.restrictByNotNullOrUndefined();
641 JSType rightTypeRestricted = rightType.restrictByNotNullOrUndefined();
642
643 TernaryValue result = TernaryValue.UNKNOWN;
644 if (n.getType() == Token.EQ || n.getType() == Token.NE) {
645 result = leftTypeRestricted.testForEquality(rightTypeRestricted);
646 if (n.isNE()) {
647 result = result.not();
648 }
649 } else {
650 // SHEQ or SHNE
651 if (!leftTypeRestricted.canTestForShallowEqualityWith(
652 rightTypeRestricted)) {
653 result = n.getType() == Token.SHEQ ?
654 TernaryValue.FALSE : TernaryValue.TRUE;
655 }
656 }
657
658 if (result != TernaryValue.UNKNOWN) {
659 report(t, n, DETERMINISTIC_TEST, leftType.toString(),
660 rightType.toString(), result.toString());
661 }
662 ensureTyped(t, n, BOOLEAN_TYPE);
663 break;
664 }
665
666 case Token.LT:
667 case Token.LE:
668 case Token.GT:
669 case Token.GE:
670 leftType = getJSType(n.getFirstChild());
671 rightType = getJSType(n.getLastChild());
672 if (rightType.isNumber()) {
673 validator.expectNumber(
674 t, n, leftType, "left side of numeric comparison");
675 } else if (leftType.isNumber()) {
676 validator.expectNumber(
677 t, n, rightType, "right side of numeric comparison");
678 } else if (leftType.matchesNumberContext() &&
679 rightType.matchesNumberContext()) {
680 // OK.
681 } else {
682 // Whether the comparison is numeric will be determined at runtime
683 // each time the expression is evaluated. Regardless, both operands
684 // should match a string context.
685 String message = "left side of comparison";
686 validator.expectString(t, n, leftType, message);
687 validator.expectNotNullOrUndefined(
688 t, n, leftType, message, getNativeType(STRING_TYPE));
689 message = "right side of comparison";
690 validator.expectString(t, n, rightType, message);
691 validator.expectNotNullOrUndefined(
692 t, n, rightType, message, getNativeType(STRING_TYPE));
693 }
694 ensureTyped(t, n, BOOLEAN_TYPE);
695 break;
696
697 case Token.IN:
698 left = n.getFirstChild();
699 right = n.getLastChild();
700 rightType = getJSType(right);
701 validator.expectString(t, left, getJSType(left), "left side of 'in'");
702 validator.expectObject(t, n, rightType, "'in' requires an object");
703 if (rightType.isStruct()) {
704 report(t, right, IN_USED_WITH_STRUCT);
705 }
706 ensureTyped(t, n, BOOLEAN_TYPE);
707 break;
708
709 case Token.INSTANCEOF:
710 left = n.getFirstChild();
711 right = n.getLastChild();
712 rightType = getJSType(right).restrictByNotNullOrUndefined();
713 validator.expectAnyObject(
714 t, left, getJSType(left), "deterministic instanceof yields false");
715 validator.expectActualObject(
716 t, right, rightType, "instanceof requires an object");
717 ensureTyped(t, n, BOOLEAN_TYPE);
718 break;
719
720 case Token.ASSIGN:
721 visitAssign(t, n);
722 typeable = false;
723 break;
724
725 case Token.ASSIGN_LSH:
726 case Token.ASSIGN_RSH:
727 case Token.ASSIGN_URSH:
728 case Token.ASSIGN_DIV:
729 case Token.ASSIGN_MOD:
730 case Token.ASSIGN_BITOR:
731 case Token.ASSIGN_BITXOR:
732 case Token.ASSIGN_BITAND:
733 case Token.ASSIGN_SUB:
734 case Token.ASSIGN_ADD:
735 case Token.ASSIGN_MUL:
736 checkPropCreation(t, n.getFirstChild());
737 // fall through
738
739 case Token.LSH:
740 case Token.RSH:
741 case Token.URSH:
742 case Token.DIV:
743 case Token.MOD:
744 case Token.BITOR:
745 case Token.BITXOR:
746 case Token.BITAND:
747 case Token.SUB:
748 case Token.ADD:
749 case Token.MUL:
750 visitBinaryOperator(n.getType(), t, n);
751 break;
752
753 case Token.DELPROP:
754 ensureTyped(t, n, BOOLEAN_TYPE);
755 break;
756
757 case Token.CASE:
758 JSType switchType = getJSType(parent.getFirstChild());
759 JSType caseType = getJSType(n.getFirstChild());
760 validator.expectSwitchMatchesCase(t, n, switchType, caseType);
761 typeable = false;
762 break;
763
764 case Token.WITH: {
765 Node child = n.getFirstChild();
766 childType = getJSType(child);
767 validator.expectObject(t, child, childType, "with requires an object");
768 typeable = false;
769 break;
770 }
771
772 case Token.FUNCTION:
773 visitFunction(t, n);
774 break;
775
776 // These nodes have no interesting type behavior.
777 case Token.LABEL:
778 case Token.LABEL_NAME:
779 case Token.SWITCH:
780 case Token.BREAK:
781 case Token.CATCH:
782 case Token.TRY:
783 case Token.SCRIPT:
784 case Token.EXPR_RESULT:
785 case Token.BLOCK:
786 case Token.EMPTY:
787 case Token.DEFAULT_CASE:
788 case Token.CONTINUE:
789 case Token.DEBUGGER:
790 case Token.THROW:
791 typeable = false;
792 break;
793
794 // These nodes require data flow analysis.
795 case Token.DO:
796 case Token.IF:
797 case Token.WHILE:
798 typeable = false;
799 break;
800
801 case Token.FOR:
802 if (NodeUtil.isForIn(n)) {
803 Node obj = n.getChildAtIndex(1);
804 if (getJSType(obj).isStruct()) {
805 report(t, obj, IN_USED_WITH_STRUCT);
806 }
807 }
808 typeable = false;
809 break;
810
811 // These nodes are typed during the type inference.
812 case Token.AND:
813 case Token.HOOK:
814 case Token.OBJECTLIT:
815 case Token.OR:
816 if (n.getJSType() != null) { // If we didn't run type inference.
817 ensureTyped(t, n);
818 } else {
819 // If this is an enum, then give that type to the objectlit as well.
820 if ((n.isObjectLit())
821 && (parent.getJSType() instanceof EnumType)) {
822 ensureTyped(t, n, parent.getJSType());
823 } else {
824 ensureTyped(t, n);
825 }
826 }
827 if (n.isObjectLit()) {
828 JSType typ = getJSType(n);
829 for (Node key : n.children()) {
830 visitObjLitKey(t, key, n, typ);
831 }
832 }
833 break;
834
835 default:
836 report(t, n, UNEXPECTED_TOKEN, Token.name(n.getType()));
837 ensureTyped(t, n);
838 break;
839 }
840
841 // Don't count externs since the user's code may not even use that part.
842 typeable = typeable && !inExterns;
843
844 if (typeable) {
845 doPercentTypedAccounting(t, n);
846 }
847
848 checkNoTypeCheckSection(n, false);
849 }
850
851 private void checkTypeofString(NodeTraversal t, Node n, String s) {
852 if (!(s.equals("number") || s.equals("string") || s.equals("boolean") ||
853 s.equals("undefined") || s.equals("function") ||
854 s.equals("object") || s.equals("unknown"))) {
855 validator.expectValidTypeofName(t, n, s);
856 }
857 }
858
859 /**
860 * Counts the given node in the typed statistics.
861 * @param n a node that should be typed
862 */
863 private void doPercentTypedAccounting(NodeTraversal t, Node n) {
864 JSType type = n.getJSType();
865 if (type == null) {
866 nullCount++;
867 } else if (type.isUnknownType()) {
868 if (reportUnknownTypes.isOn()) {
869 compiler.report(
870 t.makeError(n, reportUnknownTypes, UNKNOWN_EXPR_TYPE));
871 }
872 unknownCount++;
873 } else {
874 typedCount++;
875 }
876 }
877
878 /**
879 * Visits an assignment <code>lvalue = rvalue</code>. If the
880 * <code>lvalue</code> is a prototype modification, we change the schema
881 * of the object type it is referring to.
882 * @param t the traversal
883 * @param assign the assign node
884 * (<code>assign.isAssign()</code> is an implicit invariant)
885 */
886 private void visitAssign(NodeTraversal t, Node assign) {
887 JSDocInfo info = assign.getJSDocInfo();
888 Node lvalue = assign.getFirstChild();
889 Node rvalue = assign.getLastChild();
890
891 // Check property sets to 'object.property' when 'object' is known.
892 if (lvalue.isGetProp()) {
893 Node object = lvalue.getFirstChild();
894 JSType objectJsType = getJSType(object);
895 Node property = lvalue.getLastChild();
896 String pname = property.getString();
897
898 // the first name in this getprop refers to an interface
899 // we perform checks in addition to the ones below
900 if (object.isGetProp()) {
901 JSType jsType = getJSType(object.getFirstChild());
902 if (jsType.isInterface() &&
903 object.getLastChild().getString().equals("prototype")) {
904 visitInterfaceGetprop(t, assign, object, pname, lvalue, rvalue);
905 }
906 }
907
908 checkEnumAlias(t, info, rvalue);
909 checkPropCreation(t, lvalue);
910
911 // Prototype assignments are special, because they actually affect
912 // the definition of a class. These are mostly validated
913 // during TypedScopeCreator, and we only look for the "dumb" cases here.
914 // object.prototype = ...;
915 if (pname.equals("prototype")) {
916 if (objectJsType != null && objectJsType.isFunctionType()) {
917 FunctionType functionType = objectJsType.toMaybeFunctionType();
918 if (functionType.isConstructor()) {
919 JSType rvalueType = rvalue.getJSType();
920 validator.expectObject(t, rvalue, rvalueType,
921 OVERRIDING_PROTOTYPE_WITH_NON_OBJECT);
922 // Only assign structs to the prototype of a @struct constructor
923 if (functionType.makesStructs() && !rvalueType.isStruct()) {
924 String funName = functionType.getTypeOfThis().toString();
925 compiler.report(t.makeError(assign, CONFLICTING_SHAPE_TYPE,
926 "struct", funName));
927 }
928 return;
929 }
930 }
931 }
932
933 // The generic checks for 'object.property' when 'object' is known,
934 // and 'property' is declared on it.
935 // object.property = ...;
936 ObjectType type = ObjectType.cast(
937 objectJsType.restrictByNotNullOrUndefined());
938 if (type != null) {
939 if (type.hasProperty(pname) &&
940 !type.isPropertyTypeInferred(pname) &&
941 !propertyIsImplicitCast(type, pname)) {
942 JSType expectedType = type.getPropertyType(pname);
943 if (!expectedType.isUnknownType()) {
944 validator.expectCanAssignToPropertyOf(
945 t, assign, getJSType(rvalue),
946 expectedType, object, pname);
947 checkPropertyInheritanceOnGetpropAssign(
948 t, assign, object, pname, info, expectedType);
949 return;
950 }
951 }
952 }
953
954 // If we couldn't get the property type with normal object property
955 // lookups, then check inheritance anyway with the unknown type.
956 checkPropertyInheritanceOnGetpropAssign(
957 t, assign, object, pname, info, getNativeType(UNKNOWN_TYPE));
958 }
959
960 // Check qualified name sets to 'object' and 'object.property'.
961 // This can sometimes handle cases when the type of 'object' is not known.
962 // e.g.,
963 // var obj = createUnknownType();
964 // /** @type {number} */ obj.foo = true;
965 JSType leftType = getJSType(lvalue);
966 if (lvalue.isQualifiedName()) {
967 // variable with inferred type case
968 Var var = t.getScope().getVar(lvalue.getQualifiedName());
969 if (var != null) {
970 if (var.isTypeInferred()) {
971 return;
972 }
973
974 if (NodeUtil.getRootOfQualifiedName(lvalue).isThis() &&
975 t.getScope() != var.getScope()) {
976 // Don't look at "this.foo" variables from other scopes.
977 return;
978 }
979
980 if (var.getType() != null) {
981 leftType = var.getType();
982 }
983 }
984 }
985
986 // Fall through case for arbitrary LHS and arbitrary RHS.
987 Node rightChild = assign.getLastChild();
988 JSType rightType = getJSType(rightChild);
989 if (validator.expectCanAssignTo(
990 t, assign, rightType, leftType, "assignment")) {
991 ensureTyped(t, assign, rightType);
992 } else {
993 ensureTyped(t, assign);
994 }
995 }
996
997 /**
998 * After a struct object is created, we can't add new properties to it, with
999 * one exception. We allow creation of "static" properties like
1000 * Foo.prototype.bar = baz;
1001 * where Foo.prototype is a struct, if the assignment happens at the top level
1002 * and the constructor Foo is defined in the same file.
1003 */
1004 private void checkPropCreation(NodeTraversal t, Node lvalue) {
1005 if (lvalue.isGetProp()) {
1006 Node obj = lvalue.getFirstChild();
1007 Node prop = lvalue.getLastChild();
1008 JSType objType = getJSType(obj);
1009 String pname = prop.getString();
1010
1011 if (!objType.isStruct() || objType.hasProperty(pname)) {
1012 return;
1013 }
1014 Scope s = t.getScope();
1015 if (obj.isThis() && getJSType(s.getRootNode()).isConstructor()) {
1016 return;
1017 }
1018 // Prop created outside ctor, check that it's a static prop
1019 Node assgnStm = lvalue.getParent().getParent();
1020 if (objType instanceof ObjectType &&
1021 s.isGlobal() &&
1022 NodeUtil.isPrototypePropertyDeclaration(assgnStm)) {
1023 ObjectType instance =
1024 objType.toObjectType().getOwnerFunction().getInstanceType();
1025 String file = lvalue.getSourceFileName();
1026 Node ctor = instance.getConstructor().getSource();
1027 if (ctor != null && ctor.getSourceFileName().equals(file)) {
1028 return;
1029 }
1030 }
1031 report(t, prop, ILLEGAL_PROPERTY_CREATION);
1032 }
1033 }
1034
1035 private void checkPropertyInheritanceOnGetpropAssign(
1036 NodeTraversal t, Node assign, Node object, String property,
1037 JSDocInfo info, JSType propertyType) {
1038 // Inheritance checks for prototype properties.
1039 //
1040 // TODO(nicksantos): This isn't the right place to do this check. We
1041 // really want to do this when we're looking at the constructor.
1042 // We'd find all its properties and make sure they followed inheritance
1043 // rules, like we currently do for @implements to make sure
1044 // all the methods are implemented.
1045 //
1046 // As-is, this misses many other ways to override a property.
1047 //
1048 // object.prototype.property = ...;
1049 if (object.isGetProp()) {
1050 Node object2 = object.getFirstChild();
1051 String property2 = NodeUtil.getStringValue(object.getLastChild());
1052
1053 if ("prototype".equals(property2)) {
1054 JSType jsType = getJSType(object2);
1055 if (jsType.isFunctionType()) {
1056 FunctionType functionType = jsType.toMaybeFunctionType();
1057 if (functionType.isConstructor() || functionType.isInterface()) {
1058 checkDeclaredPropertyInheritance(
1059 t, assign, functionType, property, info, propertyType);
1060 }
1061 }
1062 }
1063 }
1064 }
1065
1066 /**
1067 * Visits an object literal field definition <code>key : value</code>.
1068 *
1069 * If the <code>lvalue</code> is a prototype modification, we change the
1070 * schema of the object type it is referring to.
1071 *
1072 * @param t the traversal
1073 * @param key the assign node
1074 */
1075 private void visitObjLitKey(
1076 NodeTraversal t, Node key, Node objlit, JSType litType) {
1077 // Do not validate object lit value types in externs. We don't really care,
1078 // and it makes it easier to generate externs.
1079 if (objlit.isFromExterns()) {
1080 ensureTyped(t, key);
1081 return;
1082 }
1083
1084 // Structs must have unquoted keys and dicts must have quoted keys
1085 if (litType.isStruct() && key.isQuotedString()) {
1086 report(t, key, ILLEGAL_OBJLIT_KEY, "struct");
1087 } else if (litType.isDict() && !key.isQuotedString()) {
1088 report(t, key, ILLEGAL_OBJLIT_KEY, "dict");
1089 }
1090
1091 // TODO(johnlenz): Validate get and set function declarations are valid
1092 // as is the functions can have "extraneous" bits.
1093
1094 // For getter and setter property definitions the
1095 // r-value type != the property type.
1096 Node rvalue = key.getFirstChild();
1097 JSType rightType = NodeUtil.getObjectLitKeyTypeFromValueType(
1098 key, getJSType(rvalue));
1099 if (rightType == null) {
1100 rightType = getNativeType(UNKNOWN_TYPE);
1101 }
1102
1103 Node owner = objlit;
1104
1105 // Validate value is assignable to the key type.
1106
1107 JSType keyType = getJSType(key);
1108
1109 JSType allowedValueType = keyType;
1110 if (allowedValueType.isEnumElementType()) {
1111 allowedValueType =
1112 allowedValueType.toMaybeEnumElementType().getPrimitiveType();
1113 }
1114
1115 boolean valid = validator.expectCanAssignToPropertyOf(t, key,
1116 rightType, allowedValueType,
1117 owner, NodeUtil.getObjectLitKeyName(key));
1118 if (valid) {
1119 ensureTyped(t, key, rightType);
1120 } else {
1121 ensureTyped(t, key);
1122 }
1123
1124 // Validate that the key type is assignable to the object property type.
1125 // This is necessary as the objlit may have been cast to a non-literal
1126 // object type.
1127 // TODO(johnlenz): consider introducing a CAST node to the AST (or
1128 // perhaps a parentheses node).
1129
1130 JSType objlitType = getJSType(objlit);
1131 ObjectType type = ObjectType.cast(
1132 objlitType.restrictByNotNullOrUndefined());
1133 if (type != null) {
1134 String property = NodeUtil.getObjectLitKeyName(key);
1135 if (type.hasProperty(property) &&
1136 !type.isPropertyTypeInferred(property) &&
1137 !propertyIsImplicitCast(type, property)) {
1138 validator.expectCanAssignToPropertyOf(
1139 t, key, keyType,
1140 type.getPropertyType(property), owner, property);
1141 }
1142 return;
1143 }
1144 }
1145
1146 /**
1147 * Returns true if any type in the chain has an implicitCast annotation for
1148 * the given property.
1149 */
1150 private boolean propertyIsImplicitCast(ObjectType type, String prop) {
1151 for (; type != null; type = type.getImplicitPrototype()) {
1152 JSDocInfo docInfo = type.getOwnPropertyJSDocInfo(prop);
1153 if (docInfo != null && docInfo.isImplicitCast()) {
1154 return true;
1155 }
1156 }
1157 return false;
1158 }
1159
1160 /**
1161 * Given a constructor type and a property name, check that the property has
1162 * the JSDoc annotation @override iff the property is declared on a
1163 * superclass. Several checks regarding inheritance correctness are also
1164 * performed.
1165 */
1166 private void checkDeclaredPropertyInheritance(
1167 NodeTraversal t, Node n, FunctionType ctorType, String propertyName,
1168 JSDocInfo info, JSType propertyType) {
1169 // If the supertype doesn't resolve correctly, we've warned about this
1170 // already.
1171 if (hasUnknownOrEmptySupertype(ctorType)) {
1172 return;
1173 }
1174
1175 FunctionType superClass = ctorType.getSuperClassConstructor();
1176 boolean superClassHasProperty = superClass != null &&
1177 superClass.getInstanceType().hasProperty(propertyName);
1178 boolean superClassHasDeclaredProperty = superClass != null &&
1179 superClass.getInstanceType().isPropertyTypeDeclared(propertyName);
1180
1181 // For interface
1182 boolean superInterfaceHasProperty = false;
1183 boolean superInterfaceHasDeclaredProperty = false;
1184 if (ctorType.isInterface()) {
1185 for (ObjectType interfaceType : ctorType.getExtendedInterfaces()) {
1186 superInterfaceHasProperty =
1187 superInterfaceHasProperty ||
1188 interfaceType.hasProperty(propertyName);
1189 superInterfaceHasDeclaredProperty =
1190 superInterfaceHasDeclaredProperty ||
1191 interfaceType.isPropertyTypeDeclared(propertyName);
1192 }
1193 }
1194 boolean declaredOverride = info != null && info.isOverride();
1195
1196 boolean foundInterfaceProperty = false;
1197 if (ctorType.isConstructor()) {
1198 for (JSType implementedInterface :
1199 ctorType.getAllImplementedInterfaces()) {
1200 if (implementedInterface.isUnknownType() ||
1201 implementedInterface.isEmptyType()) {
1202 continue;
1203 }
1204 FunctionType interfaceType =
1205 implementedInterface.toObjectType().getConstructor();
1206 Preconditions.checkNotNull(interfaceType);
1207
1208 boolean interfaceHasProperty =
1209 interfaceType.getPrototype().hasProperty(propertyName);
1210 foundInterfaceProperty = foundInterfaceProperty ||
1211 interfaceHasProperty;
1212 if (reportMissingOverride.isOn()
1213 && !declaredOverride
1214 && interfaceHasProperty) {
1215 // @override not present, but the property does override an interface
1216 // property
1217 compiler.report(t.makeError(n, reportMissingOverride,
1218 HIDDEN_INTERFACE_PROPERTY, propertyName,
1219 interfaceType.getTopMostDefiningType(propertyName).toString()));
1220 }
1221 }
1222 }
1223
1224 if (!declaredOverride
1225 && !superClassHasProperty
1226 && !superInterfaceHasProperty) {
1227 // nothing to do here, it's just a plain new property
1228 return;
1229 }
1230
1231 ObjectType topInstanceType = superClassHasDeclaredProperty ?
1232 superClass.getTopMostDefiningType(propertyName) : null;
1233 boolean declaredLocally =
1234 ctorType.isConstructor() &&
1235 (ctorType.getPrototype().hasOwnProperty(propertyName) ||
1236 ctorType.getInstanceType().hasOwnProperty(propertyName));
1237 if (reportMissingOverride.isOn()
1238 && !declaredOverride
1239 && superClassHasDeclaredProperty
1240 && declaredLocally) {
1241 // @override not present, but the property does override a superclass
1242 // property
1243 compiler.report(t.makeError(n, reportMissingOverride,
1244 HIDDEN_SUPERCLASS_PROPERTY, propertyName,
1245 topInstanceType.toString()));
1246 }
1247
1248 // @override is present and we have to check that it is ok
1249 if (superClassHasDeclaredProperty) {
1250 // there is a superclass implementation
1251 JSType superClassPropType =
1252 superClass.getInstanceType().getPropertyType(propertyName);
1253 if (!propertyType.isSubtype(superClassPropType)) {
1254 compiler.report(
1255 t.makeError(n, HIDDEN_SUPERCLASS_PROPERTY_MISMATCH,
1256 propertyName, topInstanceType.toString(),
1257 superClassPropType.toString(), propertyType.toString()));
1258 }
1259 } else if (superInterfaceHasDeclaredProperty) {
1260 // there is an super interface property
1261 for (ObjectType interfaceType : ctorType.getExtendedInterfaces()) {
1262 if (interfaceType.hasProperty(propertyName)) {
1263 JSType superPropertyType =
1264 interfaceType.getPropertyType(propertyName);
1265 if (!propertyType.isSubtype(superPropertyType)) {
1266 topInstanceType = interfaceType.getConstructor().
1267 getTopMostDefiningType(propertyName);
1268 compiler.report(
1269 t.makeError(n, HIDDEN_SUPERCLASS_PROPERTY_MISMATCH,
1270 propertyName, topInstanceType.toString(),
1271 superPropertyType.toString(),
1272 propertyType.toString()));
1273 }
1274 }
1275 }
1276 } else if (!foundInterfaceProperty
1277 && !superClassHasProperty
1278 && !superInterfaceHasProperty) {
1279 // there is no superclass nor interface implementation
1280 compiler.report(
1281 t.makeError(n, UNKNOWN_OVERRIDE,
1282 propertyName, ctorType.getInstanceType().toString()));
1283 }
1284 }
1285
1286 /**
1287 * Given a constructor or an interface type, find out whether the unknown
1288 * type is a supertype of the current type.
1289 */
1290 private static boolean hasUnknownOrEmptySupertype(FunctionType ctor) {
1291 Preconditions.checkArgument(ctor.isConstructor() || ctor.isInterface());
1292 Preconditions.checkArgument(!ctor.isUnknownType());
1293
1294 // The type system should notice inheritance cycles on its own
1295 // and break the cycle.
1296 while (true) {
1297 ObjectType maybeSuperInstanceType =
1298 ctor.getPrototype().getImplicitPrototype();
1299 if (maybeSuperInstanceType == null) {
1300 return false;
1301 }
1302 if (maybeSuperInstanceType.isUnknownType() ||
1303 maybeSuperInstanceType.isEmptyType()) {
1304 return true;
1305 }
1306 ctor = maybeSuperInstanceType.getConstructor();
1307 if (ctor == null) {
1308 return false;
1309 }
1310 Preconditions.checkState(ctor.isConstructor() || ctor.isInterface());
1311 }
1312 }
1313
1314 /**
1315 * Visits an ASSIGN node for cases such as
1316 * <pre>
1317 * interface.property2.property = ...;
1318 * </pre>
1319 */
1320 private void visitInterfaceGetprop(NodeTraversal t, Node assign, Node object,
1321 String property, Node lvalue, Node rvalue) {
1322
1323 JSType rvalueType = getJSType(rvalue);
1324
1325 // Only 2 values are allowed for methods:
1326 // goog.abstractMethod
1327 // function () {};
1328 // or for properties, no assignment such as:
1329 // InterfaceFoo.prototype.foobar;
1330
1331 String abstractMethodName =
1332 compiler.getCodingConvention().getAbstractMethodName();
1333 if (!rvalueType.isFunctionType()) {
1334 // This is bad i18n style but we don't localize our compiler errors.
1335 String abstractMethodMessage = (abstractMethodName != null)
1336 ? ", or " + abstractMethodName
1337 : "";
1338 compiler.report(
1339 t.makeError(object, INVALID_INTERFACE_MEMBER_DECLARATION,
1340 abstractMethodMessage));
1341 }
1342
1343 if (assign.getLastChild().isFunction()
1344 && !NodeUtil.isEmptyBlock(assign.getLastChild().getLastChild())) {
1345 compiler.report(
1346 t.makeError(object, INTERFACE_FUNCTION_NOT_EMPTY,
1347 abstractMethodName));
1348 }
1349 }
1350
1351 /**
1352 * Visits a NAME node.
1353 *
1354 * @param t The node traversal object that supplies context, such as the
1355 * scope chain to use in name lookups as well as error reporting.
1356 * @param n The node being visited.
1357 * @param parent The parent of the node n.
1358 * @return whether the node is typeable or not
1359 */
1360 boolean visitName(NodeTraversal t, Node n, Node parent) {
1361 // At this stage, we need to determine whether this is a leaf
1362 // node in an expression (which therefore needs to have a type
1363 // assigned for it) versus some other decorative node that we
1364 // can safely ignore. Function names, arguments (children of LP nodes) and
1365 // variable declarations are ignored.
1366 // TODO(user): remove this short-circuiting in favor of a
1367 // pre order traversal of the FUNCTION, CATCH, LP and VAR nodes.
1368 int parentNodeType = parent.getType();
1369 if (parentNodeType == Token.FUNCTION ||
1370 parentNodeType == Token.CATCH ||
1371 parentNodeType == Token.PARAM_LIST ||
1372 parentNodeType == Token.VAR) {
1373 return false;
1374 }
1375
1376 JSType type = n.getJSType();
1377 if (type == null) {
1378 type = getNativeType(UNKNOWN_TYPE);
1379 Var var = t.getScope().getVar(n.getString());
1380 if (var != null) {
1381 JSType varType = var.getType();
1382 if (varType != null) {
1383 type = varType;
1384 }
1385 }
1386 }
1387 ensureTyped(t, n, type);
1388 return true;
1389 }
1390
1391 /**
1392 * Visits a GETPROP node.
1393 *
1394 * @param t The node traversal object that supplies context, such as the
1395 * scope chain to use in name lookups as well as error reporting.
1396 * @param n The node being visited.
1397 * @param parent The parent of <code>n</code>
1398 */
1399 private void visitGetProp(NodeTraversal t, Node n, Node parent) {
1400 // obj.prop or obj.method()
1401 // Lots of types can appear on the left, a call to a void function can
1402 // never be on the left. getPropertyType will decide what is acceptable
1403 // and what isn't.
1404 Node property = n.getLastChild();
1405 Node objNode = n.getFirstChild();
1406 JSType childType = getJSType(objNode);
1407
1408 if (childType.isDict()) {
1409 report(t, property, TypeValidator.ILLEGAL_PROPERTY_ACCESS, "'.'", "dict");
1410 } else if (validator.expectNotNullOrUndefined(t, n, childType,
1411 "No properties on this expression", getNativeType(OBJECT_TYPE))) {
1412 checkPropertyAccess(childType, property.getString(), t, n);
1413 }
1414 ensureTyped(t, n);
1415 }
1416
1417 /**
1418 * Emit a warning if we can prove that a property cannot possibly be
1419 * defined on an object. Note the difference between JS and a strictly
1420 * statically typed language: we're checking if the property
1421 * *cannot be defined*, whereas a java compiler would check if the
1422 * property *can be undefined*.
1423 */
1424 private void checkPropertyAccess(JSType childType, String propName,
1425 NodeTraversal t, Node n) {
1426 // If the property type is unknown, check the object type to see if it
1427 // can ever be defined. We explicitly exclude CHECKED_UNKNOWN (for
1428 // properties where we've checked that it exists, or for properties on
1429 // objects that aren't in this binary).
1430 JSType propType = getJSType(n);
1431 if (propType.isEquivalentTo(typeRegistry.getNativeType(UNKNOWN_TYPE))) {
1432 childType = childType.autobox();
1433 ObjectType objectType = ObjectType.cast(childType);
1434 if (objectType != null) {
1435 // We special-case object types so that checks on enums can be
1436 // much stricter, and so that we can use hasProperty (which is much
1437 // faster in most cases).
1438 if (!objectType.hasProperty(propName) ||
1439 objectType.isEquivalentTo(
1440 typeRegistry.getNativeType(UNKNOWN_TYPE))) {
1441 if (objectType instanceof EnumType) {
1442 report(t, n, INEXISTENT_ENUM_ELEMENT, propName);
1443 } else {
1444 checkPropertyAccessHelper(objectType, propName, t, n);
1445 }
1446 }
1447
1448 } else {
1449 checkPropertyAccessHelper(childType, propName, t, n);
1450 }
1451 }
1452 }
1453
1454 private void checkPropertyAccessHelper(JSType objectType, String propName,
1455 NodeTraversal t, Node n) {
1456 if (!objectType.isEmptyType() &&
1457 reportMissingProperties && !isPropertyTest(n)) {
1458 if (!typeRegistry.canPropertyBeDefined(objectType, propName)) {
1459 report(t, n, INEXISTENT_PROPERTY, propName,
1460 validator.getReadableJSTypeName(n.getFirstChild(), true));
1461 }
1462 }
1463 }
1464
1465 /**
1466 * Determines whether this node is testing for the existence of a property.
1467 * If true, we will not emit warnings about a missing property.
1468 *
1469 * @param getProp The GETPROP being tested.
1470 */
1471 private boolean isPropertyTest(Node getProp) {
1472 Node parent = getProp.getParent();
1473 switch (parent.getType()) {
1474 case Token.CALL:
1475 return parent.getFirstChild() != getProp &&
1476 compiler.getCodingConvention().isPropertyTestFunction(parent);
1477
1478 case Token.IF:
1479 case Token.WHILE:
1480 case Token.DO:
1481 case Token.FOR:
1482 return NodeUtil.getConditionExpression(parent) == getProp;
1483
1484 case Token.INSTANCEOF:
1485 case Token.TYPEOF:
1486 return true;
1487
1488 case Token.AND:
1489 case Token.HOOK:
1490 return parent.getFirstChild() == getProp;
1491
1492 case Token.NOT:
1493 return parent.getParent().isOr() &&
1494 parent.getParent().getFirstChild() == parent;
1495
1496 case Token.CAST:
1497 return isPropertyTest(parent);
1498 }
1499 return false;
1500 }
1501
1502 /**
1503 * Visits a GETELEM node.
1504 *
1505 * @param t The node traversal object that supplies context, such as the
1506 * scope chain to use in name lookups as well as error reporting.
1507 * @param n The node being visited.
1508 */
1509 private void visitGetElem(NodeTraversal t, Node n) {
1510 validator.expectIndexMatch(
1511 t, n, getJSType(n.getFirstChild()), getJSType(n.getLastChild()));
1512 ensureTyped(t, n);
1513 }
1514
1515 /**
1516 * Visits a VAR node.
1517 *
1518 * @param t The node traversal object that supplies context, such as the
1519 * scope chain to use in name lookups as well as error reporting.
1520 * @param n The node being visited.
1521 */
1522 private void visitVar(NodeTraversal t, Node n) {
1523 // TODO(nicksantos): Fix this so that the doc info always shows up
1524 // on the NAME node. We probably want to wait for the parser
1525 // merge to fix this.
1526 JSDocInfo varInfo = n.hasOneChild() ? n.getJSDocInfo() : null;
1527 for (Node name : n.children()) {
1528 Node value = name.getFirstChild();
1529 // A null var would indicate a bug in the scope creation logic.
1530 Var var = t.getScope().getVar(name.getString());
1531
1532 if (value != null) {
1533 JSType valueType = getJSType(value);
1534 JSType nameType = var.getType();
1535 nameType = (nameType == null) ? getNativeType(UNKNOWN_TYPE) : nameType;
1536
1537 JSDocInfo info = name.getJSDocInfo();
1538 if (info == null) {
1539 info = varInfo;
1540 }
1541
1542 checkEnumAlias(t, info, value);
1543 if (var.isTypeInferred()) {
1544 ensureTyped(t, name, valueType);
1545 } else {
1546 validator.expectCanAssignTo(
1547 t, value, valueType, nameType, "initializing variable");
1548 }
1549 }
1550 }
1551 }
1552
1553 /**
1554 * Visits a NEW node.
1555 */
1556 private void visitNew(NodeTraversal t, Node n) {
1557 Node constructor = n.getFirstChild();
1558 JSType type = getJSType(constructor).restrictByNotNullOrUndefined();
1559 if (type.isConstructor() || type.isEmptyType() || type.isUnknownType()) {
1560 FunctionType fnType = type.toMaybeFunctionType();
1561 if (fnType != null) {
1562 visitParameterList(t, n, fnType);
1563 ensureTyped(t, n, fnType.getInstanceType());
1564 } else {
1565 ensureTyped(t, n);
1566 }
1567 } else {
1568 report(t, n, NOT_A_CONSTRUCTOR);
1569 ensureTyped(t, n);
1570 }
1571 }
1572
1573 /**
1574 * Check whether there's any property conflict for for a particular super
1575 * interface
1576 * @param t The node traversal object that supplies context
1577 * @param n The node being visited
1578 * @param functionName The function name being checked
1579 * @param properties The property names in the super interfaces that have
1580 * been visited
1581 * @param currentProperties The property names in the super interface
1582 * that have been visited
1583 * @param interfaceType The super interface that is being visited
1584 */
1585 private void checkInterfaceConflictProperties(NodeTraversal t, Node n,
1586 String functionName, HashMap<String, ObjectType> properties,
1587 HashMap<String, ObjectType> currentProperties,
1588 ObjectType interfaceType) {
1589 ObjectType implicitProto = interfaceType.getImplicitPrototype();
1590 Set<String> currentPropertyNames;
1591 if (implicitProto == null) {
1592 // This can be the case if interfaceType is proxy to a non-existent
1593 // object (which is a bad type annotation, but shouldn't crash).
1594 currentPropertyNames = ImmutableSet.of();
1595 } else {
1596 currentPropertyNames = implicitProto.getOwnPropertyNames();
1597 }
1598 for (String name : currentPropertyNames) {
1599 ObjectType oType = properties.get(name);
1600 if (oType != null) {
1601 if (!interfaceType.getPropertyType(name).isEquivalentTo(
1602 oType.getPropertyType(name))) {
1603 compiler.report(
1604 t.makeError(n, INCOMPATIBLE_EXTENDED_PROPERTY_TYPE,
1605 functionName, name, oType.toString(),
1606 interfaceType.toString()));
1607 }
1608 }
1609 currentProperties.put(name, interfaceType);
1610 }
1611 for (ObjectType iType : interfaceType.getCtorExtendedInterfaces()) {
1612 checkInterfaceConflictProperties(t, n, functionName, properties,
1613 currentProperties, iType);
1614 }
1615 }
1616
1617 /**
1618 * Visits a {@link Token#FUNCTION} node.
1619 *
1620 * @param t The node traversal object that supplies context, such as the
1621 * scope chain to use in name lookups as well as error reporting.
1622 * @param n The node being visited.
1623 */
1624 private void visitFunction(NodeTraversal t, Node n) {
1625 FunctionType functionType = JSType.toMaybeFunctionType(n.getJSType());
1626 String functionPrivateName = n.getFirstChild().getString();
1627 if (functionType.isConstructor()) {
1628 FunctionType baseConstructor = functionType.getSuperClassConstructor();
1629 if (baseConstructor != getNativeType(OBJECT_FUNCTION_TYPE) &&
1630 baseConstructor != null &&
1631 baseConstructor.isInterface()) {
1632 compiler.report(
1633 t.makeError(n, CONFLICTING_EXTENDED_TYPE,
1634 "constructor", functionPrivateName));
1635 } else {
1636 if (baseConstructor != getNativeType(OBJECT_FUNCTION_TYPE)) {
1637 ObjectType proto = functionType.getPrototype();
1638 if (functionType.makesStructs() && !proto.isStruct()) {
1639 compiler.report(t.makeError(n, CONFLICTING_SHAPE_TYPE,
1640 "struct", functionPrivateName));
1641 } else if (functionType.makesDicts() && !proto.isDict()) {
1642 compiler.report(t.makeError(n, CONFLICTING_SHAPE_TYPE,
1643 "dict", functionPrivateName));
1644 }
1645 }
1646 // All interfaces are properly implemented by a class
1647 for (JSType baseInterface : functionType.getImplementedInterfaces()) {
1648 boolean badImplementedType = false;
1649 ObjectType baseInterfaceObj = ObjectType.cast(baseInterface);
1650 if (baseInterfaceObj != null) {
1651 FunctionType interfaceConstructor =
1652 baseInterfaceObj.getConstructor();
1653 if (interfaceConstructor != null &&
1654 !interfaceConstructor.isInterface()) {
1655 badImplementedType = true;
1656 }
1657 } else {
1658 badImplementedType = true;
1659 }
1660 if (badImplementedType) {
1661 report(t, n, BAD_IMPLEMENTED_TYPE, functionPrivateName);
1662 }
1663 }
1664 // check properties
1665 validator.expectAllInterfaceProperties(t, n, functionType);
1666 }
1667 } else if (functionType.isInterface()) {
1668 // Interface must extend only interfaces
1669 for (ObjectType extInterface : functionType.getExtendedInterfaces()) {
1670 if (extInterface.getConstructor() != null
1671 && !extInterface.getConstructor().isInterface()) {
1672 compiler.report(
1673 t.makeError(n, CONFLICTING_EXTENDED_TYPE,
1674 "interface", functionPrivateName));
1675 }
1676 }
1677
1678 // Check whether the extended interfaces have any conflicts
1679 if (functionType.getExtendedInterfacesCount() > 1) {
1680 // Only check when extending more than one interfaces
1681 HashMap<String, ObjectType> properties
1682 = new HashMap<String, ObjectType>();
1683 HashMap<String, ObjectType> currentProperties
1684 = new HashMap<String, ObjectType>();
1685 for (ObjectType interfaceType : functionType.getExtendedInterfaces()) {
1686 currentProperties.clear();
1687 checkInterfaceConflictProperties(t, n, functionPrivateName,
1688 properties, currentProperties, interfaceType);
1689 properties.putAll(currentProperties);
1690 }
1691 }
1692 }
1693 }
1694
1695 /**
1696 * Visits a CALL node.
1697 *
1698 * @param t The node traversal object that supplies context, such as the
1699 * scope chain to use in name lookups as well as error reporting.
1700 * @param n The node being visited.
1701 */
1702 private void visitCall(NodeTraversal t, Node n) {
1703 Node child = n.getFirstChild();
1704 JSType childType = getJSType(child).restrictByNotNullOrUndefined();
1705
1706 if (!childType.canBeCalled()) {
1707 report(t, n, NOT_CALLABLE, childType.toString());
1708 ensureTyped(t, n);
1709 return;
1710 }
1711
1712 // A couple of types can be called as if they were functions.
1713 // If it is a function type, then validate parameters.
1714 if (childType.isFunctionType()) {
1715 FunctionType functionType = childType.toMaybeFunctionType();
1716
1717 boolean isExtern = false;
1718 JSDocInfo functionJSDocInfo = functionType.getJSDocInfo();
1719 if (functionJSDocInfo != null &&
1720 functionJSDocInfo.getAssociatedNode() != null) {
1721 isExtern = functionJSDocInfo.getAssociatedNode().isFromExterns();
1722 }
1723
1724 // Non-native constructors should not be called directly
1725 // unless they specify a return type and are defined
1726 // in an extern.
1727 if (functionType.isConstructor() &&
1728 !functionType.isNativeObjectType() &&
1729 (functionType.getReturnType().isUnknownType() ||
1730 functionType.getReturnType().isVoidType() ||
1731 !isExtern)) {
1732 report(t, n, CONSTRUCTOR_NOT_CALLABLE, childType.toString());
1733 }
1734
1735 // Functions with explicit 'this' types must be called in a GETPROP
1736 // or GETELEM.
1737 if (functionType.isOrdinaryFunction() &&
1738 !functionType.getTypeOfThis().isUnknownType() &&
1739 !(functionType.getTypeOfThis().toObjectType() != null &&
1740 functionType.getTypeOfThis().toObjectType().isNativeObjectType()) &&
1741 !(child.isGetElem() ||
1742 child.isGetProp())) {
1743 report(t, n, EXPECTED_THIS_TYPE, functionType.toString());
1744 }
1745
1746 visitParameterList(t, n, functionType);
1747 ensureTyped(t, n, functionType.getReturnType());
1748 } else {
1749 ensureTyped(t, n);
1750 }
1751
1752 // TODO: Add something to check for calls of RegExp objects, which is not
1753 // supported by IE. Either say something about the return type or warn
1754 // about the non-portability of the call or both.
1755 }
1756
1757 /**
1758 * Visits the parameters of a CALL or a NEW node.
1759 */
1760 private void visitParameterList(NodeTraversal t, Node call,
1761 FunctionType functionType) {
1762 Iterator<Node> arguments = call.children().iterator();
1763 arguments.next(); // skip the function name
1764
1765 Iterator<Node> parameters = functionType.getParameters().iterator();
1766 int ordinal = 0;
1767 Node parameter = null;
1768 Node argument = null;
1769 while (arguments.hasNext() &&
1770 (parameters.hasNext() ||
1771 parameter != null && parameter.isVarArgs())) {
1772 // If there are no parameters left in the list, then the while loop
1773 // above implies that this must be a var_args function.
1774 if (parameters.hasNext()) {
1775 parameter = parameters.next();
1776 }
1777 argument = arguments.next();
1778 ordinal++;
1779
1780 validator.expectArgumentMatchesParameter(t, argument,
1781 getJSType(argument), getJSType(parameter), call, ordinal);
1782 }
1783
1784 int numArgs = call.getChildCount() - 1;
1785 int minArgs = functionType.getMinArguments();
1786 int maxArgs = functionType.getMaxArguments();
1787 if (minArgs > numArgs || maxArgs < numArgs) {
1788 report(t, call, WRONG_ARGUMENT_COUNT,
1789 validator.getReadableJSTypeName(call.getFirstChild(), false),
1790 String.valueOf(numArgs), String.valueOf(minArgs),
1791 maxArgs != Integer.MAX_VALUE ?
1792 " and no more than " + maxArgs + " argument(s)" : "");
1793 }
1794 }
1795
1796 /**
1797 * Visits a RETURN node.
1798 *
1799 * @param t The node traversal object that supplies context, such as the
1800 * scope chain to use in name lookups as well as error reporting.
1801 * @param n The node being visited.
1802 */
1803 private void visitReturn(NodeTraversal t, Node n) {
1804 JSType jsType = getJSType(t.getEnclosingFunction());
1805
1806 if (jsType.isFunctionType()) {
1807 FunctionType functionType = jsType.toMaybeFunctionType();
1808
1809 JSType returnType = functionType.getReturnType();
1810
1811 // if no return type is specified, undefined must be returned
1812 // (it's a void function)
1813 if (returnType == null) {
1814 returnType = getNativeType(VOID_TYPE);
1815 }
1816
1817 // fetching the returned value's type
1818 Node valueNode = n.getFirstChild();
1819 JSType actualReturnType;
1820 if (valueNode == null) {
1821 actualReturnType = getNativeType(VOID_TYPE);
1822 valueNode = n;
1823 } else {
1824 actualReturnType = getJSType(valueNode);
1825 }
1826
1827 // verifying
1828 validator.expectCanAssignTo(t, valueNode, actualReturnType, returnType,
1829 "inconsistent return type");
1830 }
1831 }
1832
1833 /**
1834 * This function unifies the type checking involved in the core binary
1835 * operators and the corresponding assignment operators. The representation
1836 * used internally is such that common code can handle both kinds of
1837 * operators easily.
1838 *
1839 * @param op The operator.
1840 * @param t The traversal object, needed to report errors.
1841 * @param n The node being checked.
1842 */
1843 private void visitBinaryOperator(int op, NodeTraversal t, Node n) {
1844 Node left = n.getFirstChild();
1845 JSType leftType = getJSType(left);
1846 Node right = n.getLastChild();
1847 JSType rightType = getJSType(right);
1848 switch (op) {
1849 case Token.ASSIGN_LSH:
1850 case Token.ASSIGN_RSH:
1851 case Token.LSH:
1852 case Token.RSH:
1853 case Token.ASSIGN_URSH:
1854 case Token.URSH:
1855 if (!leftType.matchesInt32Context()) {
1856 report(t, left, BIT_OPERATION,
1857 NodeUtil.opToStr(n.getType()), leftType.toString());
1858 }
1859 if (!rightType.matchesUint32Context()) {
1860 report(t, right, BIT_OPERATION,
1861 NodeUtil.opToStr(n.getType()), rightType.toString());
1862 }
1863 break;
1864
1865 case Token.ASSIGN_DIV:
1866 case Token.ASSIGN_MOD:
1867 case Token.ASSIGN_MUL:
1868 case Token.ASSIGN_SUB:
1869 case Token.DIV:
1870 case Token.MOD:
1871 case Token.MUL:
1872 case Token.SUB:
1873 validator.expectNumber(t, left, leftType, "left operand");
1874 validator.expectNumber(t, right, rightType, "right operand");
1875 break;
1876
1877 case Token.ASSIGN_BITAND:
1878 case Token.ASSIGN_BITXOR:
1879 case Token.ASSIGN_BITOR:
1880 case Token.BITAND:
1881 case Token.BITXOR:
1882 case Token.BITOR:
1883 validator.expectBitwiseable(t, left, leftType,
1884 "bad left operand to bitwise operator");
1885 validator.expectBitwiseable(t, right, rightType,
1886 "bad right operand to bitwise operator");
1887 break;
1888
1889 case Token.ASSIGN_ADD:
1890 case Token.ADD:
1891 break;
1892
1893 default:
1894 report(t, n, UNEXPECTED_TOKEN, Token.name(op));
1895 }
1896 ensureTyped(t, n);
1897 }
1898
1899
1900 /**
1901 * <p>Checks enum aliases.
1902 *
1903 * <p>We verify that the enum element type of the enum used
1904 * for initialization is a subtype of the enum element type of
1905 * the enum the value is being copied in.</p>
1906 *
1907 * <p>Example:</p>
1908 * <pre>var myEnum = myOtherEnum;</pre>
1909 *
1910 * <p>Enum aliases are irregular, so we need special code for this :(</p>
1911 *
1912 * @param value the value used for initialization of the enum
1913 */
1914 private void checkEnumAlias(
1915 NodeTraversal t, JSDocInfo declInfo, Node value) {
1916 if (declInfo == null || !declInfo.hasEnumParameterType()) {
1917 return;
1918 }
1919
1920 JSType valueType = getJSType(value);
1921 if (!valueType.isEnumType()) {
1922 return;
1923 }
1924
1925 EnumType valueEnumType = valueType.toMaybeEnumType();
1926 JSType valueEnumPrimitiveType =
1927 valueEnumType.getElementsType().getPrimitiveType();
1928 validator.expectCanAssignTo(t, value, valueEnumPrimitiveType,
1929 declInfo.getEnumParameterType().evaluate(t.getScope(), typeRegistry),
1930 "incompatible enum element types");
1931 }
1932
1933 /**
1934 * This method gets the JSType from the Node argument and verifies that it is
1935 * present.
1936 */
1937 private JSType getJSType(Node n) {
1938 JSType jsType = n.getJSType();
1939 if (jsType == null) {
1940 // TODO(nicksantos): This branch indicates a compiler bug, not worthy of
1941 // halting the compilation but we should log this and analyze to track
1942 // down why it happens. This is not critical and will be resolved over
1943 // time as the type checker is extended.
1944 return getNativeType(UNKNOWN_TYPE);
1945 } else {
1946 return jsType;
1947 }
1948 }
1949
1950 // TODO(nicksantos): TypeCheck should never be attaching types to nodes.
1951 // All types should be attached by TypeInference. This is not true today
1952 // for legacy reasons. There are a number of places where TypeInference
1953 // doesn't attach a type, as a signal to TypeCheck that it needs to check
1954 // that node's type.
1955
1956 /**
1957 * Ensure that the given node has a type. If it does not have one,
1958 * attach the UNKNOWN_TYPE.
1959 */
1960 private void ensureTyped(NodeTraversal t, Node n) {
1961 ensureTyped(t, n, getNativeType(UNKNOWN_TYPE));
1962 }
1963
1964 private void ensureTyped(NodeTraversal t, Node n, JSTypeNative type) {
1965 ensureTyped(t, n, getNativeType(type));
1966 }
1967
1968 /**
1969 * Enforces type casts, and ensures the node is typed.
1970 *
1971 * A cast in the way that we use it in JSDoc annotations never
1972 * alters the generated code and therefore never can induce any runtime
1973 * operation. What this means is that a 'cast' is really just a compile
1974 * time constraint on the underlying value. In the future, we may add
1975 * support for run-time casts for compiled tests.
1976 *
1977 * To ensure some shred of sanity, we enforce the notion that the
1978 * type you are casting to may only meaningfully be a narrower type
1979 * than the underlying declared type. We also invalidate optimizations
1980 * on bad type casts.
1981 *
1982 * @param t The traversal object needed to report errors.
1983 * @param n The node getting a type assigned to it.
1984 * @param type The type to be assigned.
1985 */
1986 private void ensureTyped(NodeTraversal t, Node n, JSType type) {
1987 // Make sure FUNCTION nodes always get function type.
1988 Preconditions.checkState(!n.isFunction() ||
1989 type.isFunctionType() ||
1990 type.isUnknownType());
1991 JSDocInfo info = n.getJSDocInfo();
1992 if (info != null) {
1993 if (info.hasType()) {
1994 // TODO(johnlenz): Change this so that we only look for casts on CAST
1995 // nodes one the misplaced type annotation warning is on by default and
1996 // people have been given a chance to fix them. As is, this is here
1997 // simply for legacy casts.
1998 JSType infoType = info.getType().evaluate(t.getScope(), typeRegistry);
1999 validator.expectCanCast(t, n, infoType, type);
2000 type = infoType;
2001 }
2002
2003 if (info.isImplicitCast() && !inExterns) {
2004 String propName = n.isGetProp() ?
2005 n.getLastChild().getString() : "(missing)";
2006 compiler.report(
2007 t.makeError(n, ILLEGAL_IMPLICIT_CAST, propName));
2008 }
2009 }
2010
2011 if (n.getJSType() == null) {
2012 n.setJSType(type);
2013 }
2014 }
2015
2016 /**
2017 * Returns the percentage of nodes typed by the type checker.
2018 * @return a number between 0.0 and 100.0
2019 */
2020 double getTypedPercent() {
2021 int total = nullCount + unknownCount + typedCount;
2022 return (total == 0) ? 0.0 : (100.0 * typedCount) / total;
2023 }
2024
2025 private JSType getNativeType(JSTypeNative typeId) {
2026 return typeRegistry.getNativeType(typeId);
2027 }
2028 }