Debian Codegraph @

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

raw symbols SCIP
1 /*
2 * Copyright 2008 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_OBJECT_TYPE;
21 import static com.google.javascript.rhino.jstype.JSTypeNative.BOOLEAN_TYPE;
22 import static com.google.javascript.rhino.jstype.JSTypeNative.CHECKED_UNKNOWN_TYPE;
23 import static com.google.javascript.rhino.jstype.JSTypeNative.NULL_TYPE;
24 import static com.google.javascript.rhino.jstype.JSTypeNative.NUMBER_TYPE;
25 import static com.google.javascript.rhino.jstype.JSTypeNative.NUMBER_VALUE_OR_OBJECT_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 import com.google.common.base.Preconditions;
30 import com.google.common.collect.Lists;
31 import com.google.common.collect.Maps;
32 import com.google.javascript.jscomp.CodingConvention.AssertionFunctionSpec;
33 import com.google.javascript.jscomp.ControlFlowGraph.Branch;
34 import com.google.javascript.jscomp.Scope.Var;
35 import com.google.javascript.jscomp.graph.DiGraph.DiGraphEdge;
36 import com.google.javascript.jscomp.type.FlowScope;
37 import com.google.javascript.jscomp.type.ReverseAbstractInterpreter;
38 import com.google.javascript.rhino.JSDocInfo;
39 import com.google.javascript.rhino.Node;
40 import com.google.javascript.rhino.Token;
41 import com.google.javascript.rhino.jstype.BooleanLiteralSet;
42 import com.google.javascript.rhino.jstype.FunctionType;
43 import com.google.javascript.rhino.jstype.JSType;
44 import com.google.javascript.rhino.jstype.JSTypeNative;
45 import com.google.javascript.rhino.jstype.JSTypeRegistry;
46 import com.google.javascript.rhino.jstype.ModificationVisitor;
47 import com.google.javascript.rhino.jstype.ObjectType;
48 import com.google.javascript.rhino.jstype.TemplateTypeMap;
49 import com.google.javascript.rhino.jstype.StaticSlot;
50 import com.google.javascript.rhino.jstype.TemplateType;
51 import com.google.javascript.rhino.jstype.UnionType;
52
53 import java.util.Collections;
54 import java.util.Iterator;
55 import java.util.List;
56 import java.util.Map;
57
58 /**
59 * Type inference within a script node or a function body, using the data-flow
60 * analysis framework.
61 *
62 */
63 class TypeInference
64 extends DataFlowAnalysis.BranchedForwardDataFlowAnalysis<Node, FlowScope> {
65
66 // TODO(johnlenz): We no longer make this check, but we should.
67 static final DiagnosticType FUNCTION_LITERAL_UNDEFINED_THIS =
68 DiagnosticType.warning(
69 "JSC_FUNCTION_LITERAL_UNDEFINED_THIS",
70 "Function literal argument refers to undefined this argument");
71
72 private final AbstractCompiler compiler;
73 private final JSTypeRegistry registry;
74 private final ReverseAbstractInterpreter reverseInterpreter;
75 private final Scope syntacticScope;
76 private final FlowScope functionScope;
77 private final FlowScope bottomScope;
78 private final Map<String, AssertionFunctionSpec> assertionFunctionsMap;
79
80 // For convenience
81 private final ObjectType unknownType;
82
83 TypeInference(AbstractCompiler compiler, ControlFlowGraph<Node> cfg,
84 ReverseAbstractInterpreter reverseInterpreter,
85 Scope functionScope,
86 Map<String, AssertionFunctionSpec> assertionFunctionsMap) {
87 super(cfg, new LinkedFlowScope.FlowScopeJoinOp());
88 this.compiler = compiler;
89 this.registry = compiler.getTypeRegistry();
90 this.reverseInterpreter = reverseInterpreter;
91 this.unknownType = registry.getNativeObjectType(UNKNOWN_TYPE);
92
93 this.syntacticScope = functionScope;
94 inferArguments(functionScope);
95
96 this.functionScope = LinkedFlowScope.createEntryLattice(functionScope);
97 this.assertionFunctionsMap = assertionFunctionsMap;
98
99 // For each local variable declared with the VAR keyword, the entry
100 // type is VOID.
101 Iterator<Var> varIt =
102 functionScope.getDeclarativelyUnboundVarsWithoutTypes();
103 while (varIt.hasNext()) {
104 Var var = varIt.next();
105 if (isUnflowable(var)) {
106 continue;
107 }
108
109 this.functionScope.inferSlotType(
110 var.getName(), getNativeType(VOID_TYPE));
111 }
112
113 this.bottomScope = LinkedFlowScope.createEntryLattice(
114 Scope.createLatticeBottom(functionScope.getRootNode()));
115 }
116
117 /**
118 * Infers all of a function's arguments if their types aren't declared.
119 */
120 private void inferArguments(Scope functionScope) {
121 Node functionNode = functionScope.getRootNode();
122 Node astParameters = functionNode.getFirstChild().getNext();
123 Node iifeArgumentNode = null;
124
125 if (NodeUtil.isCallOrNewTarget(functionNode)) {
126 iifeArgumentNode = functionNode.getNext();
127 }
128
129 FunctionType functionType =
130 JSType.toMaybeFunctionType(functionNode.getJSType());
131 if (functionType != null) {
132 Node parameterTypes = functionType.getParametersNode();
133 if (parameterTypes != null) {
134 Node parameterTypeNode = parameterTypes.getFirstChild();
135 for (Node astParameter : astParameters.children()) {
136 Var var = functionScope.getVar(astParameter.getString());
137 Preconditions.checkNotNull(var);
138 if (var.isTypeInferred() &&
139 var.getType() == unknownType) {
140 JSType newType = null;
141
142 if (iifeArgumentNode != null) {
143 newType = iifeArgumentNode.getJSType();
144 } else if (parameterTypeNode != null) {
145 newType = parameterTypeNode.getJSType();
146 }
147
148 if (newType != null) {
149 var.setType(newType);
150 astParameter.setJSType(newType);
151 }
152 }
153
154 if (parameterTypeNode != null) {
155 parameterTypeNode = parameterTypeNode.getNext();
156 }
157 if (iifeArgumentNode != null) {
158 iifeArgumentNode = iifeArgumentNode.getNext();
159 }
160 }
161 }
162 }
163 }
164
165 @Override
166 FlowScope createInitialEstimateLattice() {
167 return bottomScope;
168 }
169
170 @Override
171 FlowScope createEntryLattice() {
172 return functionScope;
173 }
174
175 @Override
176 FlowScope flowThrough(Node n, FlowScope input) {
177 // If we have not walked a path from <entry> to <n>, then we don't
178 // want to infer anything about this scope.
179 if (input == bottomScope) {
180 return input;
181 }
182
183 FlowScope output = input.createChildFlowScope();
184 output = traverse(n, output);
185 return output;
186 }
187
188 @Override
189 @SuppressWarnings({"fallthrough", "incomplete-switch"})
190 List<FlowScope> branchedFlowThrough(Node source, FlowScope input) {
191 // NOTE(nicksantos): Right now, we just treat ON_EX edges like UNCOND
192 // edges. If we wanted to be perfect, we'd actually JOIN all the out
193 // lattices of this flow with the in lattice, and then make that the out
194 // lattice for the ON_EX edge. But it's probably too expensive to be
195 // worthwhile.
196 FlowScope output = flowThrough(source, input);
197 Node condition = null;
198 FlowScope conditionFlowScope = null;
199 BooleanOutcomePair conditionOutcomes = null;
200
201 List<DiGraphEdge<Node, Branch>> branchEdges = getCfg().getOutEdges(source);
202 List<FlowScope> result = Lists.newArrayListWithCapacity(branchEdges.size());
203 for (DiGraphEdge<Node, Branch> branchEdge : branchEdges) {
204 Branch branch = branchEdge.getValue();
205 FlowScope newScope = output;
206
207 switch (branch) {
208 case ON_TRUE:
209 if (NodeUtil.isForIn(source)) {
210 // item is assigned a property name, so its type should be string.
211 Node item = source.getFirstChild();
212 Node obj = item.getNext();
213
214 FlowScope informed = traverse(obj, output.createChildFlowScope());
215
216 if (item.isVar()) {
217 item = item.getFirstChild();
218 }
219 if (item.isName()) {
220 JSType iterKeyType = getNativeType(STRING_TYPE);
221 ObjectType objType = getJSType(obj).dereference();
222 JSType objIndexType = objType == null ?
223 null : objType.getTemplateTypeMap().getTemplateType(
224 registry.getObjectIndexKey());
225 if (objIndexType != null && !objIndexType.isUnknownType()) {
226 JSType narrowedKeyType =
227 iterKeyType.getGreatestSubtype(objIndexType);
228 if (!narrowedKeyType.isEmptyType()) {
229 iterKeyType = narrowedKeyType;
230 }
231 }
232 redeclareSimpleVar(informed, item, iterKeyType);
233 }
234 newScope = informed;
235 break;
236 }
237
238 // FALL THROUGH
239
240 case ON_FALSE:
241 if (condition == null) {
242 condition = NodeUtil.getConditionExpression(source);
243 if (condition == null && source.isCase()) {
244 condition = source;
245
246 // conditionFlowScope is cached from previous iterations
247 // of the loop.
248 if (conditionFlowScope == null) {
249 conditionFlowScope = traverse(
250 condition.getFirstChild(), output.createChildFlowScope());
251 }
252 }
253 }
254
255 if (condition != null) {
256 if (condition.isAnd() ||
257 condition.isOr()) {
258 // When handling the short-circuiting binary operators,
259 // the outcome scope on true can be different than the outcome
260 // scope on false.
261 //
262 // TODO(nicksantos): The "right" way to do this is to
263 // carry the known outcome all the way through the
264 // recursive traversal, so that we can construct a
265 // different flow scope based on the outcome. However,
266 // this would require a bunch of code and a bunch of
267 // extra computation for an edge case. This seems to be
268 // a "good enough" approximation.
269
270 // conditionOutcomes is cached from previous iterations
271 // of the loop.
272 if (conditionOutcomes == null) {
273 conditionOutcomes = condition.isAnd() ?
274 traverseAnd(condition, output.createChildFlowScope()) :
275 traverseOr(condition, output.createChildFlowScope());
276 }
277 newScope =
278 reverseInterpreter.getPreciserScopeKnowingConditionOutcome(
279 condition,
280 conditionOutcomes.getOutcomeFlowScope(
281 condition.getType(), branch == Branch.ON_TRUE),
282 branch == Branch.ON_TRUE);
283 } else {
284 // conditionFlowScope is cached from previous iterations
285 // of the loop.
286 if (conditionFlowScope == null) {
287 conditionFlowScope =
288 traverse(condition, output.createChildFlowScope());
289 }
290 newScope =
291 reverseInterpreter.getPreciserScopeKnowingConditionOutcome(
292 condition, conditionFlowScope, branch == Branch.ON_TRUE);
293 }
294 }
295 break;
296 }
297
298 result.add(newScope.optimize());
299 }
300 return result;
301 }
302
303 private FlowScope traverse(Node n, FlowScope scope) {
304 switch (n.getType()) {
305 case Token.ASSIGN:
306 scope = traverseAssign(n, scope);
307 break;
308
309 case Token.NAME:
310 scope = traverseName(n, scope);
311 break;
312
313 case Token.GETPROP:
314 scope = traverseGetProp(n, scope);
315 break;
316
317 case Token.AND:
318 scope = traverseAnd(n, scope).getJoinedFlowScope()
319 .createChildFlowScope();
320 break;
321
322 case Token.OR:
323 scope = traverseOr(n, scope).getJoinedFlowScope()
324 .createChildFlowScope();
325 break;
326
327 case Token.HOOK:
328 scope = traverseHook(n, scope);
329 break;
330
331 case Token.OBJECTLIT:
332 scope = traverseObjectLiteral(n, scope);
333 break;
334
335 case Token.CALL:
336 scope = traverseCall(n, scope);
337 break;
338
339 case Token.NEW:
340 scope = traverseNew(n, scope);
341 break;
342
343 case Token.ASSIGN_ADD:
344 case Token.ADD:
345 scope = traverseAdd(n, scope);
346 break;
347
348 case Token.POS:
349 case Token.NEG:
350 scope = traverse(n.getFirstChild(), scope); // Find types.
351 n.setJSType(getNativeType(NUMBER_TYPE));
352 break;
353
354 case Token.ARRAYLIT:
355 scope = traverseArrayLiteral(n, scope);
356 break;
357
358 case Token.THIS:
359 n.setJSType(scope.getTypeOfThis());
360 break;
361
362 case Token.ASSIGN_LSH:
363 case Token.ASSIGN_RSH:
364 case Token.LSH:
365 case Token.RSH:
366 case Token.ASSIGN_URSH:
367 case Token.URSH:
368 case Token.ASSIGN_DIV:
369 case Token.ASSIGN_MOD:
370 case Token.ASSIGN_BITAND:
371 case Token.ASSIGN_BITXOR:
372 case Token.ASSIGN_BITOR:
373 case Token.ASSIGN_MUL:
374 case Token.ASSIGN_SUB:
375 case Token.DIV:
376 case Token.MOD:
377 case Token.BITAND:
378 case Token.BITXOR:
379 case Token.BITOR:
380 case Token.MUL:
381 case Token.SUB:
382 case Token.DEC:
383 case Token.INC:
384 case Token.BITNOT:
385 scope = traverseChildren(n, scope);
386 n.setJSType(getNativeType(NUMBER_TYPE));
387 break;
388
389 case Token.PARAM_LIST:
390 scope = traverse(n.getFirstChild(), scope);
391 n.setJSType(getJSType(n.getFirstChild()));
392 break;
393
394 case Token.COMMA:
395 scope = traverseChildren(n, scope);
396 n.setJSType(getJSType(n.getLastChild()));
397 break;
398
399 case Token.TYPEOF:
400 scope = traverseChildren(n, scope);
401 n.setJSType(getNativeType(STRING_TYPE));
402 break;
403
404 case Token.DELPROP:
405 case Token.LT:
406 case Token.LE:
407 case Token.GT:
408 case Token.GE:
409 case Token.NOT:
410 case Token.EQ:
411 case Token.NE:
412 case Token.SHEQ:
413 case Token.SHNE:
414 case Token.INSTANCEOF:
415 case Token.IN:
416 scope = traverseChildren(n, scope);
417 n.setJSType(getNativeType(BOOLEAN_TYPE));
418 break;
419
420 case Token.GETELEM:
421 scope = traverseGetElem(n, scope);
422 break;
423
424 case Token.EXPR_RESULT:
425 scope = traverseChildren(n, scope);
426 if (n.getFirstChild().isGetProp()) {
427 ensurePropertyDeclared(n.getFirstChild());
428 }
429 break;
430
431 case Token.SWITCH:
432 scope = traverse(n.getFirstChild(), scope);
433 break;
434
435 case Token.RETURN:
436 scope = traverseReturn(n, scope);
437 break;
438
439 case Token.VAR:
440 case Token.THROW:
441 scope = traverseChildren(n, scope);
442 break;
443
444 case Token.CATCH:
445 scope = traverseCatch(n, scope);
446 break;
447
448 case Token.CAST:
449 scope = traverseChildren(n, scope);
450 break;
451 }
452
453 // TODO(johnlenz): remove this after the CAST node change has shaken out.
454 if (!n.isFunction()) {
455 JSDocInfo info = n.getJSDocInfo();
456 if (info != null && info.hasType()) {
457 JSType castType = info.getType().evaluate(syntacticScope, registry);
458
459 // A stubbed type declaration on a qualified name should take
460 // effect for all subsequent accesses of that name,
461 // so treat it the same as an assign to that name.
462 if (n.isQualifiedName() &&
463 n.getParent().isExprResult()) {
464 updateScopeForTypeChange(scope, n, n.getJSType(), castType);
465 }
466
467 n.setJSType(castType);
468 }
469 }
470
471 return scope;
472 }
473
474 /**
475 * Traverse a return value.
476 */
477 private FlowScope traverseReturn(Node n, FlowScope scope) {
478 scope = traverseChildren(n, scope);
479
480 Node retValue = n.getFirstChild();
481 if (retValue != null) {
482 JSType type = functionScope.getRootNode().getJSType();
483 if (type != null) {
484 FunctionType fnType = type.toMaybeFunctionType();
485 if (fnType != null) {
486 inferPropertyTypesToMatchConstraint(
487 retValue.getJSType(), fnType.getReturnType());
488 }
489 }
490 }
491 return scope;
492 }
493
494 /**
495 * Any value can be thrown, so it's really impossible to determine the type
496 * of a CATCH param. Treat it as the UNKNOWN type.
497 */
498 private FlowScope traverseCatch(Node catchNode, FlowScope scope) {
499 Node name = catchNode.getFirstChild();
500 JSType type;
501 // If the catch expression name was declared in the catch use that type,
502 // otherwise use "unknown".
503 JSDocInfo info = name.getJSDocInfo();
504 if (info != null && info.hasType()) {
505 type = info.getType().evaluate(syntacticScope, registry);
506 } else {
507 type = getNativeType(JSTypeNative.UNKNOWN_TYPE);
508 }
509 redeclareSimpleVar(scope, name, type);
510 name.setJSType(type);
511 return scope;
512 }
513
514 private FlowScope traverseAssign(Node n, FlowScope scope) {
515 Node left = n.getFirstChild();
516 Node right = n.getLastChild();
517 scope = traverseChildren(n, scope);
518
519 JSType leftType = left.getJSType();
520 JSType rightType = getJSType(right);
521 n.setJSType(rightType);
522
523 updateScopeForTypeChange(scope, left, leftType, rightType);
524 return scope;
525 }
526
527 /**
528 * Updates the scope according to the result of a type change, like
529 * an assignment or a type cast.
530 */
531 private void updateScopeForTypeChange(
532 FlowScope scope, Node left, JSType leftType, JSType resultType) {
533 Preconditions.checkNotNull(resultType);
534 switch (left.getType()) {
535 case Token.NAME:
536 String varName = left.getString();
537 Var var = syntacticScope.getVar(varName);
538
539 // When looking at VAR initializers for declared VARs, we trust
540 // the declared type over the type it's being initialized to.
541 // This has two purposes:
542 // 1) We avoid re-declaring declared variables so that built-in
543 // types defined in externs are not redeclared.
544 // 2) When there's a lexical closure like
545 // /** @type {?string} */ var x = null;
546 // function f() { x = 'xyz'; }
547 // the inference will ignore the lexical closure,
548 // which is just wrong. This bug needs to be fixed eventually.
549 boolean isVarDeclaration = left.hasChildren();
550 if (!isVarDeclaration || var == null || var.isTypeInferred()) {
551 redeclareSimpleVar(scope, left, resultType);
552 }
553 left.setJSType(isVarDeclaration || leftType == null ?
554 resultType : null);
555
556 if (var != null && var.isTypeInferred()) {
557 JSType oldType = var.getType();
558 var.setType(oldType == null ?
559 resultType : oldType.getLeastSupertype(resultType));
560 }
561 break;
562 case Token.GETPROP:
563 String qualifiedName = left.getQualifiedName();
564 if (qualifiedName != null) {
565 scope.inferQualifiedSlot(left, qualifiedName,
566 leftType == null ? unknownType : leftType,
567 resultType);
568 }
569
570 left.setJSType(resultType);
571 ensurePropertyDefined(left, resultType);
572 break;
573 }
574 }
575
576 /**
577 * Defines a property if the property has not been defined yet.
578 */
579 private void ensurePropertyDefined(Node getprop, JSType rightType) {
580 String propName = getprop.getLastChild().getString();
581 Node obj = getprop.getFirstChild();
582 JSType nodeType = getJSType(obj);
583 ObjectType objectType = ObjectType.cast(
584 nodeType.restrictByNotNullOrUndefined());
585 if (objectType == null) {
586 registry.registerPropertyOnType(propName, nodeType);
587 } else {
588 // Don't add the property to @struct objects outside a constructor
589 if (nodeType.isStruct() && !objectType.hasProperty(propName)) {
590 if (!(obj.isThis() &&
591 getJSType(syntacticScope.getRootNode()).isConstructor())) {
592 return;
593 }
594 }
595
596 if (ensurePropertyDeclaredHelper(getprop, objectType)) {
597 return;
598 }
599
600 if (!objectType.isPropertyTypeDeclared(propName)) {
601 // We do not want a "stray" assign to define an inferred property
602 // for every object of this type in the program. So we use a heuristic
603 // approach to determine whether to infer the property.
604 //
605 // 1) If the property is already defined, join it with the previously
606 // inferred type.
607 // 2) If this isn't an instance object, define it.
608 // 3) If the property of an object is being assigned in the constructor,
609 // define it.
610 // 4) If this is a stub, define it.
611 // 5) Otherwise, do not define the type, but declare it in the registry
612 // so that we can use it for missing property checks.
613 if (objectType.hasProperty(propName) || !objectType.isInstanceType()) {
614 if ("prototype".equals(propName)) {
615 objectType.defineDeclaredProperty(propName, rightType, getprop);
616 } else {
617 objectType.defineInferredProperty(propName, rightType, getprop);
618 }
619 } else if (obj.isThis() &&
620 getJSType(syntacticScope.getRootNode()).isConstructor()) {
621 objectType.defineInferredProperty(propName, rightType, getprop);
622 } else {
623 registry.registerPropertyOnType(propName, objectType);
624 }
625 }
626 }
627 }
628
629 /**
630 * Defines a declared property if it has not been defined yet.
631 *
632 * This handles the case where a property is declared on an object where
633 * the object type is inferred, and so the object type will not
634 * be known in {@code TypedScopeCreator}.
635 */
636 private void ensurePropertyDeclared(Node getprop) {
637 ObjectType ownerType = ObjectType.cast(
638 getJSType(getprop.getFirstChild()).restrictByNotNullOrUndefined());
639 if (ownerType != null) {
640 ensurePropertyDeclaredHelper(getprop, ownerType);
641 }
642 }
643
644 /**
645 * Declares a property on its owner, if necessary.
646 * @return True if a property was declared.
647 */
648 private boolean ensurePropertyDeclaredHelper(
649 Node getprop, ObjectType objectType) {
650 String propName = getprop.getLastChild().getString();
651 String qName = getprop.getQualifiedName();
652 if (qName != null) {
653 Var var = syntacticScope.getVar(qName);
654 if (var != null && !var.isTypeInferred()) {
655 // Handle normal declarations that could not be addressed earlier.
656 if (propName.equals("prototype") ||
657 // Handle prototype declarations that could not be addressed earlier.
658 (!objectType.hasOwnProperty(propName) &&
659 (!objectType.isInstanceType() ||
660 (var.isExtern() && !objectType.isNativeObjectType())))) {
661 return objectType.defineDeclaredProperty(
662 propName, var.getType(), getprop);
663 }
664 }
665 }
666 return false;
667 }
668
669 private FlowScope traverseName(Node n, FlowScope scope) {
670 String varName = n.getString();
671 Node value = n.getFirstChild();
672 JSType type = n.getJSType();
673 if (value != null) {
674 scope = traverse(value, scope);
675 updateScopeForTypeChange(scope, n, n.getJSType() /* could be null */,
676 getJSType(value));
677 return scope;
678 } else {
679 StaticSlot<JSType> var = scope.getSlot(varName);
680 if (var != null) {
681 // There are two situations where we don't want to use type information
682 // from the scope, even if we have it.
683
684 // 1) The var is escaped and assigned in an inner scope, e.g.,
685 // function f() { var x = 3; function g() { x = null } (x); }
686 boolean isInferred = var.isTypeInferred();
687 boolean unflowable = isInferred &&
688 isUnflowable(syntacticScope.getVar(varName));
689
690 // 2) We're reading type information from another scope for an
691 // inferred variable. That variable is assigned more than once,
692 // and we can't know which type we're getting.
693 //
694 // var t = null; function f() { (t); } doStuff(); t = {};
695 //
696 // Notice that this heuristic isn't perfect. For example, you might
697 // have:
698 //
699 // function f() { (t); } f(); var t = 3;
700 //
701 // In this case, we would infer the first reference to t as
702 // type {number}, even though it's undefined.
703 boolean nonLocalInferredSlot = false;
704 if (isInferred && syntacticScope.isLocal()) {
705 Var maybeOuterVar = syntacticScope.getParent().getVar(varName);
706 if (var == maybeOuterVar &&
707 !maybeOuterVar.isMarkedAssignedExactlyOnce()) {
708 nonLocalInferredSlot = true;
709 }
710 }
711
712 if (!unflowable && !nonLocalInferredSlot) {
713 type = var.getType();
714 if (type == null) {
715 type = unknownType;
716 }
717 }
718 }
719 }
720 n.setJSType(type);
721 return scope;
722 }
723
724 /** Traverse each element of the array. */
725 private FlowScope traverseArrayLiteral(Node n, FlowScope scope) {
726 scope = traverseChildren(n, scope);
727 n.setJSType(getNativeType(ARRAY_TYPE));
728 return scope;
729 }
730
731 private FlowScope traverseObjectLiteral(Node n, FlowScope scope) {
732 JSType type = n.getJSType();
733 Preconditions.checkNotNull(type);
734
735 for (Node name = n.getFirstChild(); name != null; name = name.getNext()) {
736 scope = traverse(name.getFirstChild(), scope);
737 }
738
739 // Object literals can be reflected on other types, or changed with
740 // type casts.
741 // See CodingConvention#getObjectLiteralCase and goog.object.reflect.
742 // Ignore these types of literals.
743 // TODO(nicksantos): There should be an "anonymous object" type that
744 // we can check for here.
745 ObjectType objectType = ObjectType.cast(type);
746 if (objectType == null) {
747 return scope;
748 }
749
750 boolean hasLendsName = n.getJSDocInfo() != null &&
751 n.getJSDocInfo().getLendsName() != null;
752 if (objectType.hasReferenceName() && !hasLendsName) {
753 return scope;
754 }
755
756 String qObjName = NodeUtil.getBestLValueName(
757 NodeUtil.getBestLValue(n));
758 for (Node name = n.getFirstChild(); name != null;
759 name = name.getNext()) {
760 String memberName = NodeUtil.getObjectLitKeyName(name);
761 if (memberName != null) {
762 JSType rawValueType = name.getFirstChild().getJSType();
763 JSType valueType = NodeUtil.getObjectLitKeyTypeFromValueType(
764 name, rawValueType);
765 if (valueType == null) {
766 valueType = unknownType;
767 }
768 objectType.defineInferredProperty(memberName, valueType, name);
769
770 // Do normal flow inference if this is a direct property assignment.
771 if (qObjName != null && name.isStringKey()) {
772 String qKeyName = qObjName + "." + memberName;
773 Var var = syntacticScope.getVar(qKeyName);
774 JSType oldType = var == null ? null : var.getType();
775 if (var != null && var.isTypeInferred()) {
776 var.setType(oldType == null ?
777 valueType : oldType.getLeastSupertype(oldType));
778 }
779
780 scope.inferQualifiedSlot(name, qKeyName,
781 oldType == null ? unknownType : oldType,
782 valueType);
783 }
784 } else {
785 n.setJSType(unknownType);
786 }
787 }
788 return scope;
789 }
790
791 private FlowScope traverseAdd(Node n, FlowScope scope) {
792 Node left = n.getFirstChild();
793 Node right = left.getNext();
794 scope = traverseChildren(n, scope);
795
796 JSType leftType = left.getJSType();
797 JSType rightType = right.getJSType();
798
799 JSType type = unknownType;
800 if (leftType != null && rightType != null) {
801 boolean leftIsUnknown = leftType.isUnknownType();
802 boolean rightIsUnknown = rightType.isUnknownType();
803 if (leftIsUnknown && rightIsUnknown) {
804 type = unknownType;
805 } else if ((!leftIsUnknown && leftType.isString()) ||
806 (!rightIsUnknown && rightType.isString())) {
807 type = getNativeType(STRING_TYPE);
808 } else if (leftIsUnknown || rightIsUnknown) {
809 type = unknownType;
810 } else if (isAddedAsNumber(leftType) && isAddedAsNumber(rightType)) {
811 type = getNativeType(NUMBER_TYPE);
812 } else {
813 type = registry.createUnionType(STRING_TYPE, NUMBER_TYPE);
814 }
815 }
816 n.setJSType(type);
817
818 if (n.isAssignAdd()) {
819 updateScopeForTypeChange(scope, left, leftType, type);
820 }
821
822 return scope;
823 }
824
825 private boolean isAddedAsNumber(JSType type) {
826 return type.isSubtype(registry.createUnionType(VOID_TYPE, NULL_TYPE,
827 NUMBER_VALUE_OR_OBJECT_TYPE, BOOLEAN_TYPE, BOOLEAN_OBJECT_TYPE));
828 }
829
830 private FlowScope traverseHook(Node n, FlowScope scope) {
831 Node condition = n.getFirstChild();
832 Node trueNode = condition.getNext();
833 Node falseNode = n.getLastChild();
834
835 // verify the condition
836 scope = traverse(condition, scope);
837
838 // reverse abstract interpret the condition to produce two new scopes
839 FlowScope trueScope = reverseInterpreter.
840 getPreciserScopeKnowingConditionOutcome(
841 condition, scope, true);
842 FlowScope falseScope = reverseInterpreter.
843 getPreciserScopeKnowingConditionOutcome(
844 condition, scope, false);
845
846 // traverse the true node with the trueScope
847 traverse(trueNode, trueScope.createChildFlowScope());
848
849 // traverse the false node with the falseScope
850 traverse(falseNode, falseScope.createChildFlowScope());
851
852 // meet true and false nodes' types and assign
853 JSType trueType = trueNode.getJSType();
854 JSType falseType = falseNode.getJSType();
855 if (trueType != null && falseType != null) {
856 n.setJSType(trueType.getLeastSupertype(falseType));
857 } else {
858 n.setJSType(null);
859 }
860
861 return scope.createChildFlowScope();
862 }
863
864 private FlowScope traverseCall(Node n, FlowScope scope) {
865 scope = traverseChildren(n, scope);
866
867 Node left = n.getFirstChild();
868 JSType functionType = getJSType(left).restrictByNotNullOrUndefined();
869 if (functionType.isFunctionType()) {
870 FunctionType fnType = functionType.toMaybeFunctionType();
871 n.setJSType(fnType.getReturnType());
872 backwardsInferenceFromCallSite(n, fnType);
873 } else if (functionType.isEquivalentTo(
874 getNativeType(CHECKED_UNKNOWN_TYPE))) {
875 n.setJSType(getNativeType(CHECKED_UNKNOWN_TYPE));
876 }
877
878 scope = tightenTypesAfterAssertions(scope, n);
879 return scope;
880 }
881
882 private FlowScope tightenTypesAfterAssertions(FlowScope scope,
883 Node callNode) {
884 Node left = callNode.getFirstChild();
885 Node firstParam = left.getNext();
886 AssertionFunctionSpec assertionFunctionSpec =
887 assertionFunctionsMap.get(left.getQualifiedName());
888 if (assertionFunctionSpec == null || firstParam == null) {
889 return scope;
890 }
891 Node assertedNode = assertionFunctionSpec.getAssertedParam(firstParam);
892 if (assertedNode == null) {
893 return scope;
894 }
895 JSType assertedType = assertionFunctionSpec.getAssertedType(
896 callNode, registry);
897 String assertedNodeName = assertedNode.getQualifiedName();
898
899 JSType narrowed;
900 // Handle assertions that enforce expressions evaluate to true.
901 if (assertedType == null) {
902 // Handle arbitrary expressions within the assert.
903 scope = reverseInterpreter.getPreciserScopeKnowingConditionOutcome(
904 assertedNode, scope, true);
905 // Build the result of the assertExpression
906 narrowed = getJSType(assertedNode).restrictByNotNullOrUndefined();
907 } else {
908 // Handle assertions that enforce expressions are of a certain type.
909 JSType type = getJSType(assertedNode);
910 narrowed = type.getGreatestSubtype(assertedType);
911 if (assertedNodeName != null && type.differsFrom(narrowed)) {
912 scope = narrowScope(scope, assertedNode, narrowed);
913 }
914 }
915
916 callNode.setJSType(narrowed);
917 return scope;
918 }
919
920 private FlowScope narrowScope(FlowScope scope, Node node, JSType narrowed) {
921 if (node.isThis()) {
922 // "this" references don't need to be modeled in the control flow graph.
923 return scope;
924 }
925
926 scope = scope.createChildFlowScope();
927 if (node.isGetProp()) {
928 scope.inferQualifiedSlot(
929 node, node.getQualifiedName(), getJSType(node), narrowed);
930 } else {
931 redeclareSimpleVar(scope, node, narrowed);
932 }
933 return scope;
934 }
935
936 /**
937 * We only do forward type inference. We do not do full backwards
938 * type inference.
939 *
940 * In other words, if we have,
941 * <code>
942 * var x = f();
943 * g(x);
944 * </code>
945 * a forward type-inference engine would try to figure out the type
946 * of "x" from the return type of "f". A backwards type-inference engine
947 * would try to figure out the type of "x" from the parameter type of "g".
948 *
949 * However, there are a few special syntactic forms where we do some
950 * some half-assed backwards type-inference, because programmers
951 * expect it in this day and age. To take an example from Java,
952 * <code>
953 * List<String> x = Lists.newArrayList();
954 * </code>
955 * The Java compiler will be able to infer the generic type of the List
956 * returned by newArrayList().
957 *
958 * In much the same way, we do some special-case backwards inference for
959 * JS. Those cases are enumerated here.
960 */
961 private void backwardsInferenceFromCallSite(Node n, FunctionType fnType) {
962 boolean updatedFnType = inferTemplatedTypesForCall(n, fnType);
963 if (updatedFnType) {
964 fnType = n.getFirstChild().getJSType().toMaybeFunctionType();
965 }
966 updateTypeOfParameters(n, fnType);
967 updateBind(n);
968 }
969
970 /**
971 * When "bind" is called on a function, we infer the type of the returned
972 * "bound" function by looking at the number of parameters in the call site.
973 */
974 private void updateBind(Node n) {
975 CodingConvention.Bind bind =
976 compiler.getCodingConvention().describeFunctionBind(n, true);
977 if (bind == null) {
978 return;
979 }
980
981 FunctionType callTargetFn = getJSType(bind.target)
982 .restrictByNotNullOrUndefined().toMaybeFunctionType();
983 if (callTargetFn == null) {
984 return;
985 }
986
987 n.setJSType(
988 callTargetFn.getBindReturnType(
989 // getBindReturnType expects the 'this' argument to be included.
990 bind.getBoundParameterCount() + 1));
991 }
992
993 /**
994 * For functions with function parameters, type inference will set the type of
995 * a function literal argument from the function parameter type.
996 */
997 private void updateTypeOfParameters(Node n, FunctionType fnType) {
998 int i = 0;
999 int childCount = n.getChildCount();
1000 for (Node iParameter : fnType.getParameters()) {
1001 if (i + 1 >= childCount) {
1002 // TypeCheck#visitParametersList will warn so we bail.
1003 return;
1004 }
1005
1006 JSType iParameterType = getJSType(iParameter);
1007 Node iArgument = n.getChildAtIndex(i + 1);
1008 JSType iArgumentType = getJSType(iArgument);
1009 inferPropertyTypesToMatchConstraint(iArgumentType, iParameterType);
1010
1011 // TODO(johnlenz): Filter out non-function types
1012 // (such as null and undefined) as
1013 // we only care about FUNCTION subtypes here.
1014 JSType restrictedParameter = iParameterType
1015 .restrictByNotNullOrUndefined()
1016 .toMaybeFunctionType();
1017 if (restrictedParameter != null) {
1018 if (iArgument.isFunction() &&
1019 iArgumentType.isFunctionType() &&
1020 iArgument.getJSDocInfo() == null) {
1021 iArgument.setJSType(restrictedParameter);
1022 }
1023 }
1024 i++;
1025 }
1026 }
1027
1028 private Map<TemplateType, JSType> inferTemplateTypesFromParameters(
1029 FunctionType fnType, Node call) {
1030 if (fnType.getTemplateTypeMap().getTemplateKeys().isEmpty()) {
1031 return Collections.emptyMap();
1032 }
1033
1034 Map<TemplateType, JSType> resolvedTypes = Maps.newIdentityHashMap();
1035
1036 Node callTarget = call.getFirstChild();
1037 if (NodeUtil.isGet(callTarget)) {
1038 Node obj = callTarget.getFirstChild();
1039 maybeResolveTemplatedType(
1040 fnType.getTypeOfThis(),
1041 getJSType(obj),
1042 resolvedTypes);
1043 }
1044
1045 if (call.hasMoreThanOneChild()) {
1046 maybeResolveTemplateTypeFromNodes(
1047 fnType.getParameters(),
1048 call.getChildAtIndex(1).siblings(),
1049 resolvedTypes);
1050 }
1051 return resolvedTypes;
1052 }
1053
1054 private void maybeResolveTemplatedType(
1055 JSType paramType,
1056 JSType argType,
1057 Map<TemplateType, JSType> resolvedTypes) {
1058 if (paramType.isTemplateType()) {
1059 // @param {T}
1060 resolvedTemplateType(
1061 resolvedTypes, paramType.toMaybeTemplateType(), argType);
1062 } else if (paramType.isUnionType()) {
1063 // @param {Array.<T>|NodeList|Arguments|{length:number}}
1064 UnionType unionType = paramType.toMaybeUnionType();
1065 for (JSType alernative : unionType.getAlternates()) {
1066 maybeResolveTemplatedType(alernative, argType, resolvedTypes);
1067 }
1068 } else if (paramType.isFunctionType()) {
1069 FunctionType paramFunctionType = paramType.toMaybeFunctionType();
1070 FunctionType argFunctionType = argType
1071 .restrictByNotNullOrUndefined()
1072 .collapseUnion()
1073 .toMaybeFunctionType();
1074 if (argFunctionType != null && argFunctionType.isSubtype(paramType)) {
1075 // infer from return type of the function type
1076 maybeResolveTemplatedType(
1077 paramFunctionType.getTypeOfThis(),
1078 argFunctionType.getTypeOfThis(), resolvedTypes);
1079 // infer from return type of the function type
1080 maybeResolveTemplatedType(
1081 paramFunctionType.getReturnType(),
1082 argFunctionType.getReturnType(), resolvedTypes);
1083 // infer from parameter types of the function type
1084 maybeResolveTemplateTypeFromNodes(
1085 paramFunctionType.getParameters(),
1086 argFunctionType.getParameters(), resolvedTypes);
1087 }
1088 } else if (paramType.isTemplatizedType()) {
1089 // @param {Array.<T>}
1090 ObjectType referencedParamType = paramType
1091 .toMaybeTemplatizedType()
1092 .getReferencedType();
1093 JSType argObjectType = argType
1094 .restrictByNotNullOrUndefined()
1095 .collapseUnion();
1096
1097 if (argObjectType.isSubtype(referencedParamType)) {
1098 // If the argument type is a subtype of the parameter type, resolve any
1099 // template types amongst their templatized types.
1100 TemplateTypeMap paramTypeMap = paramType.getTemplateTypeMap();
1101 TemplateTypeMap argTypeMap = argObjectType.getTemplateTypeMap();
1102 for (TemplateType key : paramTypeMap.getTemplateKeys()) {
1103 maybeResolveTemplatedType(
1104 paramTypeMap.getTemplateType(key),
1105 argTypeMap.getTemplateType(key),
1106 resolvedTypes);
1107 }
1108 }
1109 }
1110 }
1111
1112 private void maybeResolveTemplateTypeFromNodes(
1113 Iterable<Node> declParams,
1114 Iterable<Node> callParams,
1115 Map<TemplateType, JSType> resolvedTypes) {
1116 maybeResolveTemplateTypeFromNodes(
1117 declParams.iterator(), callParams.iterator(), resolvedTypes);
1118 }
1119
1120 private void maybeResolveTemplateTypeFromNodes(
1121 Iterator<Node> declParams,
1122 Iterator<Node> callParams,
1123 Map<TemplateType, JSType> resolvedTypes) {
1124 while (declParams.hasNext() && callParams.hasNext()) {
1125 Node declParam = declParams.next();
1126 maybeResolveTemplatedType(
1127 getJSType(declParam),
1128 getJSType(callParams.next()),
1129 resolvedTypes);
1130 if (declParam.isVarArgs()) {
1131 while (callParams.hasNext()) {
1132 maybeResolveTemplatedType(
1133 getJSType(declParam),
1134 getJSType(callParams.next()),
1135 resolvedTypes);
1136 }
1137 }
1138 }
1139 }
1140
1141 private void resolvedTemplateType(
1142 Map<TemplateType, JSType> map, TemplateType template, JSType resolved) {
1143 JSType previous = map.get(template);
1144 if (!resolved.isUnknownType()) {
1145 if (previous == null) {
1146 map.put(template, resolved);
1147 } else {
1148 JSType join = previous.getLeastSupertype(resolved);
1149 map.put(template, join);
1150 }
1151 }
1152 }
1153
1154 private static class TemplateTypeReplacer extends ModificationVisitor {
1155 private final Map<TemplateType, JSType> replacements;
1156 private final JSTypeRegistry registry;
1157 boolean madeChanges = false;
1158
1159 TemplateTypeReplacer(
1160 JSTypeRegistry registry, Map<TemplateType, JSType> replacements) {
1161 super(registry);
1162 this.registry = registry;
1163 this.replacements = replacements;
1164 }
1165
1166 @Override
1167 public JSType caseTemplateType(TemplateType type) {
1168 madeChanges = true;
1169 JSType replacement = replacements.get(type);
1170 return replacement != null ?
1171 replacement : registry.getNativeType(UNKNOWN_TYPE);
1172 }
1173 }
1174
1175 /**
1176 * For functions with function(this: T, ...) and T as parameters, type
1177 * inference will set the type of this on a function literal argument to the
1178 * the actual type of T.
1179 */
1180 private boolean inferTemplatedTypesForCall(
1181 Node n, FunctionType fnType) {
1182 if (fnType.getTemplateTypeMap().getTemplateKeys().isEmpty()) {
1183 return false;
1184 }
1185
1186 // Try to infer the template types
1187 Map<TemplateType, JSType> inferred = inferTemplateTypesFromParameters(
1188 fnType, n);
1189
1190 // Replace all template types. If we couldn't find a replacement, we
1191 // replace it with UNKNOWN.
1192 TemplateTypeReplacer replacer = new TemplateTypeReplacer(
1193 registry, inferred);
1194 Node callTarget = n.getFirstChild();
1195
1196 FunctionType replacementFnType = fnType.visit(replacer)
1197 .toMaybeFunctionType();
1198 Preconditions.checkNotNull(replacementFnType);
1199
1200 callTarget.setJSType(replacementFnType);
1201 n.setJSType(replacementFnType.getReturnType());
1202
1203 return replacer.madeChanges;
1204 }
1205
1206 private FlowScope traverseNew(Node n, FlowScope scope) {
1207 scope = traverseChildren(n, scope);
1208
1209 Node constructor = n.getFirstChild();
1210 JSType constructorType = constructor.getJSType();
1211 JSType type = null;
1212 if (constructorType != null) {
1213 constructorType = constructorType.restrictByNotNullOrUndefined();
1214 if (constructorType.isUnknownType()) {
1215 type = unknownType;
1216 } else {
1217 FunctionType ct = constructorType.toMaybeFunctionType();
1218 if (ct == null && constructorType instanceof FunctionType) {
1219 // If constructorType is a NoObjectType, then toMaybeFunctionType will
1220 // return null. But NoObjectType implements the FunctionType
1221 // interface, precisely because it can validly construct objects.
1222 ct = (FunctionType) constructorType;
1223 }
1224 if (ct != null && ct.isConstructor()) {
1225 type = ct.getInstanceType();
1226 backwardsInferenceFromCallSite(n, ct);
1227 }
1228 }
1229 }
1230 n.setJSType(type);
1231 return scope;
1232 }
1233
1234 private BooleanOutcomePair traverseAnd(Node n, FlowScope scope) {
1235 return traverseShortCircuitingBinOp(n, scope, true);
1236 }
1237
1238 private FlowScope traverseChildren(Node n, FlowScope scope) {
1239 for (Node el = n.getFirstChild(); el != null; el = el.getNext()) {
1240 scope = traverse(el, scope);
1241 }
1242 return scope;
1243 }
1244
1245 private FlowScope traverseGetElem(Node n, FlowScope scope) {
1246 scope = traverseChildren(n, scope);
1247 JSType type = getJSType(n.getFirstChild()).restrictByNotNullOrUndefined();
1248 TemplateTypeMap typeMap = type.getTemplateTypeMap();
1249 if (typeMap.hasTemplateType(registry.getObjectElementKey())) {
1250 n.setJSType(typeMap.getTemplateType(registry.getObjectElementKey()));
1251 }
1252 return dereferencePointer(n.getFirstChild(), scope);
1253 }
1254
1255 private FlowScope traverseGetProp(Node n, FlowScope scope) {
1256 Node objNode = n.getFirstChild();
1257 Node property = n.getLastChild();
1258 scope = traverseChildren(n, scope);
1259
1260 n.setJSType(
1261 getPropertyType(
1262 objNode.getJSType(), property.getString(), n, scope));
1263 return dereferencePointer(n.getFirstChild(), scope);
1264 }
1265
1266 /**
1267 * Suppose X is an object with inferred properties.
1268 * Suppose also that X is used in a way where it would only type-check
1269 * correctly if some of those properties are widened.
1270 * Then we should be polite and automatically widen X's properties for him.
1271 *
1272 * For a concrete example, consider:
1273 * param x {{prop: (number|undefined)}}
1274 * function f(x) {}
1275 * f({});
1276 *
1277 * If we give the anonymous object an inferred property of (number|undefined),
1278 * then this code will type-check appropriately.
1279 */
1280 private void inferPropertyTypesToMatchConstraint(
1281 JSType type, JSType constraint) {
1282 if (type == null || constraint == null) {
1283 return;
1284 }
1285
1286 type.matchConstraint(constraint);
1287 }
1288
1289 /**
1290 * If we access a property of a symbol, then that symbol is not
1291 * null or undefined.
1292 */
1293 private FlowScope dereferencePointer(Node n, FlowScope scope) {
1294 if (n.isQualifiedName()) {
1295 JSType type = getJSType(n);
1296 JSType narrowed = type.restrictByNotNullOrUndefined();
1297 if (type != narrowed) {
1298 scope = narrowScope(scope, n, narrowed);
1299 }
1300 }
1301 return scope;
1302 }
1303
1304 private JSType getPropertyType(JSType objType, String propName,
1305 Node n, FlowScope scope) {
1306 // We often have a couple of different types to choose from for the
1307 // property. Ordered by accuracy, we have
1308 // 1) A locally inferred qualified name (which is in the FlowScope)
1309 // 2) A globally declared qualified name (which is in the FlowScope)
1310 // 3) A property on the owner type (which is on objType)
1311 // 4) A name in the type registry (as a last resort)
1312 JSType propertyType = null;
1313 boolean isLocallyInferred = false;
1314
1315 // Scopes sometimes contain inferred type info about qualified names.
1316 String qualifiedName = n.getQualifiedName();
1317 StaticSlot<JSType> var = scope.getSlot(qualifiedName);
1318 if (var != null) {
1319 JSType varType = var.getType();
1320 if (varType != null) {
1321 boolean isDeclared = !var.isTypeInferred();
1322 isLocallyInferred = (var != syntacticScope.getSlot(qualifiedName));
1323 if (isDeclared || isLocallyInferred) {
1324 propertyType = varType;
1325 }
1326 }
1327 }
1328
1329 if (propertyType == null && objType != null) {
1330 JSType foundType = objType.findPropertyType(propName);
1331 if (foundType != null) {
1332 propertyType = foundType;
1333 }
1334 }
1335
1336 if ((propertyType == null || propertyType.isUnknownType())
1337 && qualifiedName != null) {
1338 // If we find this node in the registry, then we can infer its type.
1339 ObjectType regType = ObjectType.cast(registry.getType(qualifiedName));
1340 if (regType != null) {
1341 propertyType = regType.getConstructor();
1342 }
1343 }
1344
1345 if (propertyType == null) {
1346 return unknownType;
1347 } else if (propertyType.isEquivalentTo(unknownType) && isLocallyInferred) {
1348 // If the type has been checked in this scope,
1349 // then use CHECKED_UNKNOWN_TYPE instead to indicate that.
1350 return getNativeType(CHECKED_UNKNOWN_TYPE);
1351 } else {
1352 return propertyType;
1353 }
1354 }
1355
1356 private BooleanOutcomePair traverseOr(Node n, FlowScope scope) {
1357 return traverseShortCircuitingBinOp(n, scope, false);
1358 }
1359
1360 private BooleanOutcomePair traverseShortCircuitingBinOp(
1361 Node n, FlowScope scope, boolean condition) {
1362 Node left = n.getFirstChild();
1363 Node right = n.getLastChild();
1364
1365 // type the left node
1366 BooleanOutcomePair leftLiterals =
1367 traverseWithinShortCircuitingBinOp(left,
1368 scope.createChildFlowScope());
1369 JSType leftType = left.getJSType();
1370
1371 // reverse abstract interpret the left node to produce the correct
1372 // scope in which to verify the right node
1373 FlowScope rightScope = reverseInterpreter.
1374 getPreciserScopeKnowingConditionOutcome(
1375 left, leftLiterals.getOutcomeFlowScope(left.getType(), condition),
1376 condition);
1377
1378 // type the right node
1379 BooleanOutcomePair rightLiterals =
1380 traverseWithinShortCircuitingBinOp(
1381 right, rightScope.createChildFlowScope());
1382 JSType rightType = right.getJSType();
1383
1384 JSType type;
1385 BooleanOutcomePair literals;
1386 if (leftType != null && rightType != null) {
1387 leftType = leftType.getRestrictedTypeGivenToBooleanOutcome(!condition);
1388 if (leftLiterals.toBooleanOutcomes ==
1389 BooleanLiteralSet.get(!condition)) {
1390 // Use the restricted left type, since the right side never gets
1391 // evaluated.
1392 type = leftType;
1393 literals = leftLiterals;
1394 } else {
1395 // Use the join of the restricted left type knowing the outcome of the
1396 // ToBoolean predicate and of the right type.
1397 type = leftType.getLeastSupertype(rightType);
1398 literals =
1399 getBooleanOutcomePair(leftLiterals, rightLiterals, condition);
1400 }
1401
1402 // Exclude the boolean type if the literal set is empty because a boolean
1403 // can never actually be returned.
1404 if (literals.booleanValues == BooleanLiteralSet.EMPTY &&
1405 getNativeType(BOOLEAN_TYPE).isSubtype(type)) {
1406 // Exclusion only make sense for a union type.
1407 if (type.isUnionType()) {
1408 type = type.toMaybeUnionType().getRestrictedUnion(
1409 getNativeType(BOOLEAN_TYPE));
1410 }
1411 }
1412 } else {
1413 type = null;
1414 literals = new BooleanOutcomePair(
1415 BooleanLiteralSet.BOTH, BooleanLiteralSet.BOTH,
1416 leftLiterals.getJoinedFlowScope(),
1417 rightLiterals.getJoinedFlowScope());
1418 }
1419 n.setJSType(type);
1420
1421 return literals;
1422 }
1423
1424 private BooleanOutcomePair traverseWithinShortCircuitingBinOp(Node n,
1425 FlowScope scope) {
1426 switch (n.getType()) {
1427 case Token.AND:
1428 return traverseAnd(n, scope);
1429
1430 case Token.OR:
1431 return traverseOr(n, scope);
1432
1433 default:
1434 scope = traverse(n, scope);
1435 return newBooleanOutcomePair(n.getJSType(), scope);
1436 }
1437 }
1438
1439 /**
1440 * Infers the boolean outcome pair that can be taken by a
1441 * short-circuiting binary operation ({@code &&} or {@code ||}).
1442 * @see #getBooleanOutcomes(BooleanLiteralSet, BooleanLiteralSet, boolean)
1443 */
1444 BooleanOutcomePair getBooleanOutcomePair(BooleanOutcomePair left,
1445 BooleanOutcomePair right, boolean condition) {
1446 return new BooleanOutcomePair(
1447 getBooleanOutcomes(left.toBooleanOutcomes, right.toBooleanOutcomes,
1448 condition),
1449 getBooleanOutcomes(left.booleanValues, right.booleanValues, condition),
1450 left.getJoinedFlowScope(), right.getJoinedFlowScope());
1451 }
1452
1453 /**
1454 * Infers the boolean literal set that can be taken by a
1455 * short-circuiting binary operation ({@code &&} or {@code ||}).
1456 * @param left the set of possible {@code ToBoolean} predicate results for
1457 * the expression on the left side of the operator
1458 * @param right the set of possible {@code ToBoolean} predicate results for
1459 * the expression on the right side of the operator
1460 * @param condition the left side {@code ToBoolean} predicate result that
1461 * causes the right side to get evaluated (i.e. not short-circuited)
1462 * @return a set of possible {@code ToBoolean} predicate results for the
1463 * entire expression
1464 */
1465 static BooleanLiteralSet getBooleanOutcomes(BooleanLiteralSet left,
1466 BooleanLiteralSet right, boolean condition) {
1467 return right.union(left.intersection(BooleanLiteralSet.get(!condition)));
1468 }
1469
1470 /**
1471 * When traversing short-circuiting binary operations, we need to keep track
1472 * of two sets of boolean literals:
1473 * 1. {@code toBooleanOutcomes}: boolean literals as converted from any types,
1474 * 2. {@code booleanValues}: boolean literals from just boolean types.
1475 */
1476 private final class BooleanOutcomePair {
1477 final BooleanLiteralSet toBooleanOutcomes;
1478 final BooleanLiteralSet booleanValues;
1479
1480 // The scope if only half of the expression executed, when applicable.
1481 final FlowScope leftScope;
1482
1483 // The scope when the whole expression executed.
1484 final FlowScope rightScope;
1485
1486 // The scope when we don't know how much of the expression is executed.
1487 FlowScope joinedScope = null;
1488
1489 BooleanOutcomePair(
1490 BooleanLiteralSet toBooleanOutcomes, BooleanLiteralSet booleanValues,
1491 FlowScope leftScope, FlowScope rightScope) {
1492 this.toBooleanOutcomes = toBooleanOutcomes;
1493 this.booleanValues = booleanValues;
1494 this.leftScope = leftScope;
1495 this.rightScope = rightScope;
1496 }
1497
1498 /**
1499 * Gets the safe estimated scope without knowing if all of the
1500 * subexpressions will be evaluated.
1501 */
1502 FlowScope getJoinedFlowScope() {
1503 if (joinedScope == null) {
1504 if (leftScope == rightScope) {
1505 joinedScope = rightScope;
1506 } else {
1507 joinedScope = join(leftScope, rightScope);
1508 }
1509 }
1510 return joinedScope;
1511 }
1512
1513 /**
1514 * Gets the outcome scope if we do know the outcome of the entire
1515 * expression.
1516 */
1517 FlowScope getOutcomeFlowScope(int nodeType, boolean outcome) {
1518 if (nodeType == Token.AND && outcome ||
1519 nodeType == Token.OR && !outcome) {
1520 // We know that the whole expression must have executed.
1521 return rightScope;
1522 } else {
1523 return getJoinedFlowScope();
1524 }
1525 }
1526 }
1527
1528 private BooleanOutcomePair newBooleanOutcomePair(
1529 JSType jsType, FlowScope flowScope) {
1530 if (jsType == null) {
1531 return new BooleanOutcomePair(
1532 BooleanLiteralSet.BOTH, BooleanLiteralSet.BOTH, flowScope, flowScope);
1533 }
1534 return new BooleanOutcomePair(jsType.getPossibleToBooleanOutcomes(),
1535 registry.getNativeType(BOOLEAN_TYPE).isSubtype(jsType) ?
1536 BooleanLiteralSet.BOTH : BooleanLiteralSet.EMPTY,
1537 flowScope, flowScope);
1538 }
1539
1540 private void redeclareSimpleVar(
1541 FlowScope scope, Node nameNode, JSType varType) {
1542 Preconditions.checkState(nameNode.isName());
1543 String varName = nameNode.getString();
1544 if (varType == null) {
1545 varType = getNativeType(JSTypeNative.UNKNOWN_TYPE);
1546 }
1547 if (isUnflowable(syntacticScope.getVar(varName))) {
1548 return;
1549 }
1550 scope.inferSlotType(varName, varType);
1551 }
1552
1553 private boolean isUnflowable(Var v) {
1554 return v != null && v.isLocal() && v.isMarkedEscaped() &&
1555 // It's OK to flow a variable in the scope where it's escaped.
1556 v.getScope() == syntacticScope;
1557 }
1558
1559 /**
1560 * This method gets the JSType from the Node argument and verifies that it is
1561 * present.
1562 */
1563 private JSType getJSType(Node n) {
1564 JSType jsType = n.getJSType();
1565 if (jsType == null) {
1566 // TODO(nicksantos): This branch indicates a compiler bug, not worthy of
1567 // halting the compilation but we should log this and analyze to track
1568 // down why it happens. This is not critical and will be resolved over
1569 // time as the type checker is extended.
1570 return unknownType;
1571 } else {
1572 return jsType;
1573 }
1574 }
1575
1576 private JSType getNativeType(JSTypeNative typeId) {
1577 return registry.getNativeType(typeId);
1578 }
1579 }