Debian Codegraph @

src/com/google/javascript/jscomp/TightenTypes.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 package com.google.javascript.jscomp;
17
18 import static com.google.javascript.rhino.jstype.JSTypeNative.U2U_CONSTRUCTOR_TYPE;
19 import static com.google.javascript.rhino.jstype.JSTypeNative.UNKNOWN_TYPE;
20
21 import com.google.common.base.Preconditions;
22 import com.google.common.collect.Lists;
23 import com.google.common.collect.Maps;
24 import com.google.common.collect.Sets;
25 import com.google.javascript.jscomp.ConcreteType.ConcreteFunctionType;
26 import com.google.javascript.jscomp.ConcreteType.ConcreteInstanceType;
27 import com.google.javascript.jscomp.NodeTraversal.AbstractShallowCallback;
28 import com.google.javascript.rhino.JSDocInfo;
29 import com.google.javascript.rhino.Node;
30 import com.google.javascript.rhino.Token;
31 import com.google.javascript.rhino.jstype.FunctionType;
32 import com.google.javascript.rhino.jstype.JSType;
33 import com.google.javascript.rhino.jstype.JSTypeNative;
34 import com.google.javascript.rhino.jstype.JSTypeRegistry;
35 import com.google.javascript.rhino.jstype.ObjectType;
36 import com.google.javascript.rhino.jstype.StaticReference;
37 import com.google.javascript.rhino.jstype.StaticScope;
38 import com.google.javascript.rhino.jstype.StaticSlot;
39
40 import java.util.Collection;
41 import java.util.Iterator;
42 import java.util.List;
43 import java.util.Map;
44 import java.util.Set;
45
46 /**
47 * Computes the set of possible concrete types for every variable, property,
48 * function argument, and function return value in the program. Unlike a normal
49 * reference type annotation, a concrete type of A indicates that an instance of
50 * A -- not a subclass of A -- is a possible value.
51 *
52 * Also unlike normal type checking, this pass does not assume that all defined
53 * functions are actually called. Instead, it assumes only that the top-level
54 * code is executed plus any implicit calls detected, such as calls to functions
55 * exported via goog.exportSymbol or Element.addEventListener. Hence, this pass
56 * also performs a very strict form of dead code detection. Elimination of dead
57 * code will occur because the disambiguation pass can rename all uncalled
58 * functions to have distinct names, which will then appear to be uncalled to
59 * the normal unused property remover.
60 *
61 * Since concrete types are all reference types, we only care about the limited
62 * set of actions that apply to them: assignments to variables/properties,
63 * method calls, and return statements. To speed up and simplify the
64 * implementation, the first time a scope is processed, we make one pass through
65 * it {@link CreateScope} to translate it into a list of Actions. Each Action
66 * can translate itself into a list of assignments: method calls are just
67 * assignments to the parameter variables, while return statements are
68 * assignments to a special $return slot. Each time a scope is (re-)processed,
69 * we iterate over the assignments produced by the actions and update the types
70 * of the target slots. Once we complete a pass through all scopes with no
71 * changes, we are done.
72 *
73 */
74 class TightenTypes implements CompilerPass, ConcreteType.Factory {
75 public static final String NON_HALTING_ERROR_MSG =
76 "TightenTypes pass appears to be stuck in an infinite loop.";
77
78 /** The compiler that invoked this pass. */
79 private final AbstractCompiler compiler;
80
81 /**
82 * Map of function type information to their concrete wrappers. These must be
83 * reused so that each declaration has only a single concrete type, which will
84 * hold all the known types that flow to its arguments and return value.
85 */
86 private final Map<Node, ConcreteFunctionType> functionFromDeclaration =
87 Maps.newHashMap();
88
89 /**
90 * Secondary index of concrete functions by JSType. This is necessary for
91 * retrieving the concrete type of a superclass, where the actual declaration
92 * is not at hand. Note that we must use an identity hash map here because
93 * functions are compared using the signature only.
94 */
95 private final Map<FunctionType, ConcreteFunctionType> functionFromJSType =
96 Maps.newIdentityHashMap();
97
98 /**
99 * Map of instance type information to their concrete wrappers. These must be
100 * reused so that each property has only one variable, which will store all
101 * known types that flow to that variable.
102 */
103 private final Map<ObjectType, ConcreteInstanceType> instanceFromJSType =
104 Maps.newHashMap();
105
106 /**
107 * Memoized results of "createTypeIntersection" calls.
108 */
109 private final Map<ConcreteJSTypePair, ConcreteType> typeIntersectionMemos =
110 Maps.newHashMap();
111
112 /** Scope storing the top-level variables and functions. */
113 private ConcreteScope topScope;
114
115 TightenTypes(AbstractCompiler compiler) {
116 this.compiler = compiler;
117 }
118
119 /** Returns the top scope computed during the pass. */
120 ConcreteScope getTopScope() { return topScope; }
121
122 /** Convenience method to get the type registry of the compiler. */
123 @Override
124 public JSTypeRegistry getTypeRegistry() { return compiler.getTypeRegistry(); }
125
126 /** All concrete instance types encountered during flow analysis. */
127 private Set<ConcreteType> allInstantiatedTypes = Sets.newHashSet();
128
129 @Override
130 public void process(Node externRoot, Node jsRoot) {
131 // Create the scope of top-level variables and functions.
132 topScope = new ConcreteScope(null);
133 topScope.initForExternRoot(externRoot);
134 topScope.initForScopeRoot(jsRoot);
135
136 // Process the assignments in each scope in the working set until no more
137 // changes are detected. Each time a new scope is discovered (starting with
138 // the top-level scope), it is added to the working set to be processed.
139 // Since changes in almost any scope can affect another, we iterate over all
140 // discovered scopes until no further changes occur.
141
142 long maxIterations = 1000;
143 long iterations = 0;
144
145 Set<ConcreteScope> workSet = Sets.newHashSet(topScope);
146 List<ConcreteScope> workList = Lists.newArrayList(topScope);
147
148 boolean changed;
149 do {
150 changed = false;
151 for (int i = 0; i < workList.size(); ++i) {
152 ConcreteScope scope = workList.get(i);
153 for (Action action : scope.getActions()) {
154 for (Assignment assign : action.getAssignments(scope)) {
155 if (assign.slot.addConcreteType(assign.type)) {
156 changed = true;
157 ConcreteScope varScope = assign.slot.getScope();
158 if ((varScope != scope) && !workSet.contains(varScope)) {
159 workSet.add(varScope);
160 workList.add(varScope);
161 }
162 }
163 }
164 }
165 }
166 Preconditions.checkState(++iterations != maxIterations,
167 NON_HALTING_ERROR_MSG);
168 } while (changed);
169 }
170
171 /**
172 * Represents a scope in which a set of slots are declared. The scope also
173 * includes code, which is normalized to a set of actions (which may affect
174 * slots in other scopes as well).
175 */
176 class ConcreteScope implements StaticScope<ConcreteType> {
177 private final ConcreteScope parent;
178 private final Map<String, ConcreteSlot> slots;
179 private final List<Action> actions;
180
181 ConcreteScope(ConcreteScope parent) {
182 this.parent = parent;
183 this.slots = Maps.newHashMap();
184 this.actions = Lists.newArrayList();
185 }
186
187 @Override
188 public Node getRootNode() { return null; }
189
190 @Override
191 public StaticScope<ConcreteType> getParentScope() { return parent; }
192
193 @Override
194 public StaticSlot<ConcreteType> getOwnSlot(String name) {
195 return slots.get(name);
196 }
197
198 @Override
199 public StaticSlot<ConcreteType> getSlot(String name) {
200 StaticSlot<ConcreteType> var = getOwnSlot(name);
201 if (var != null) {
202 return var;
203 } else if (parent != null) {
204 return parent.getSlot(name);
205 } else {
206 return null;
207 }
208 }
209
210 /** Returns all the slots in this scope. */
211 Collection<ConcreteSlot> getSlots() { return slots.values(); }
212
213 @Override
214 public ConcreteType getTypeOfThis() {
215 // Since the slot doesn't have a reference to its ConcreteType, we can't
216 // reference the ConcreteFunctionType directly to get the typeOfThis.
217 ConcreteSlot thisVar = slots.get(ConcreteFunctionType.THIS_SLOT_NAME);
218 return (thisVar != null) ? thisVar.getType() : ConcreteType.NONE;
219 }
220
221 /** Add a declaration for the given variable. */
222 void declareSlot(String name, Node declaration) {
223 slots.put(name, new ConcreteSlot(this, name));
224 }
225
226 /** Add a declaration for the given variable with the given type. */
227 void declareSlot(String name, Node declaration, ConcreteType type) {
228 ConcreteSlot var = new ConcreteSlot(this, name);
229 var.addConcreteType(type);
230 slots.put(name, var);
231 }
232
233 /** Returns all the actions performed in the code of this scope. */
234 List<Action> getActions() { return actions; }
235
236 /** Finds assignments and variables from the function body. */
237 void initForScopeRoot(Node decl) {
238 Preconditions.checkNotNull(decl);
239 if (decl.isFunction()) {
240 decl = decl.getLastChild();
241 }
242 Preconditions.checkArgument(decl.isBlock());
243
244 NodeTraversal.traverse(compiler, decl, new CreateScope(this, false));
245 }
246
247 /** Finds assignments and variables from the given externs. */
248 void initForExternRoot(Node decl) {
249 Preconditions.checkNotNull(decl);
250 Preconditions.checkArgument(decl.isBlock());
251
252 NodeTraversal.traverse(compiler, decl, new CreateScope(this, true));
253 }
254
255 /** Adds the given action to the list for the code in this scope. */
256 void addAction(Action action) { actions.add(action); }
257
258 @Override public String toString() {
259 return getTypeOfThis().toString() + " " + getSlots();
260 }
261 }
262
263 /** Represents a variable or function declared in a scope. */
264 static class ConcreteSlot implements StaticSlot<ConcreteType> {
265 private final ConcreteScope scope;
266 private final String name;
267 private ConcreteType type;
268
269 ConcreteSlot(ConcreteScope scope, String name) {
270 this.scope = scope;
271 this.name = name;
272 this.type = ConcreteType.NONE;
273 }
274
275 /** Returns the scope in which this slot exists. */
276 ConcreteScope getScope() { return scope; }
277
278 /** Returns the name of this slot in its scope. */
279 @Override public String getName() { return name; }
280
281 @Override public ConcreteType getType() { return type; }
282
283 /** Whether this type was inferred rather than declared (always true). */
284 @Override public boolean isTypeInferred() { return true; }
285
286 @Override public StaticReference<ConcreteType> getDeclaration() {
287 return null;
288 }
289
290 @Override public JSDocInfo getJSDocInfo() {
291 return null;
292 }
293
294 /**
295 * Adds the given type to the possible concrete types for this slot.
296 * Returns whether the added type was not already known.
297 */
298 boolean addConcreteType(ConcreteType type) {
299 ConcreteType origType = this.type;
300 this.type = origType.unionWith(type);
301 return !this.type.equals(origType);
302 }
303
304 @Override public String toString() {
305 return getName() + ": " + getType();
306 }
307 }
308
309 /**
310 * Represents a type of action performed in the body of scope that may affect
311 * the concrete types of slot. Example actions are a function call, a
312 * variable assignment, and a property assignment. The function call will
313 * create assignments for each of the function parameters, for the "this"
314 * slot, and for the "call" slot. Property and variable assignment actions
315 * create assignments for the property or variable they represent.
316 */
317 private static interface Action {
318 /** Returns all assignments that may occur by this action. */
319 Collection<Assignment> getAssignments(ConcreteScope scope);
320 }
321
322 /** Represents an assignment to a variable of a set of possible types. */
323 private static class Assignment {
324 private final ConcreteSlot slot;
325 private final ConcreteType type;
326
327 Assignment(ConcreteSlot slot, ConcreteType type) {
328 this.slot = slot;
329 this.type = type;
330
331 Preconditions.checkNotNull(slot);
332 Preconditions.checkNotNull(type);
333 }
334 }
335
336 /** Records an assignment of an expression to a variable. */
337 private class VariableAssignAction implements Action {
338 private final ConcreteSlot slot;
339 private final Node expression;
340
341 VariableAssignAction(ConcreteSlot slot, Node expr) {
342 this.slot = slot;
343 this.expression = expr;
344
345 Preconditions.checkNotNull(slot);
346 Preconditions.checkNotNull(expr);
347 }
348
349 @Override
350 public Collection<Assignment> getAssignments(ConcreteScope scope) {
351 return Lists.newArrayList(
352 new Assignment(slot, inferConcreteType(scope, expression)));
353 }
354 }
355
356 /** Records an assignment of an expression to a property of an object. */
357 private class PropertyAssignAction implements Action {
358 private final Node receiver;
359 private final String propName;
360 private final Node expression;
361
362 PropertyAssignAction(Node receiver, Node expr) {
363 this.receiver = receiver;
364 this.propName = receiver.getNext().getString();
365 this.expression = expr;
366
367 Preconditions.checkNotNull(receiver);
368 Preconditions.checkNotNull(propName);
369 Preconditions.checkNotNull(expr);
370 }
371
372 /**
373 * Returns all assignments that could occur as a result of this property
374 * assign action. Each type in the receiver is checked for a property
375 * {@code propName}, and if that property exists, it is assigned the type
376 * of {@code expression}.
377 */
378 @Override
379 public Collection<Assignment> getAssignments(ConcreteScope scope) {
380 ConcreteType recvType = inferConcreteType(scope, receiver);
381 ConcreteType exprType = inferConcreteType(scope, expression);
382
383 List<Assignment> assigns = Lists.newArrayList();
384 for (StaticSlot<ConcreteType> prop
385 : recvType.getPropertySlots(propName)) {
386 assigns.add(new Assignment((ConcreteSlot) prop, exprType));
387 }
388 return assigns;
389 }
390 }
391
392 /** Helper class to build a FunctionCall object. */
393 private class FunctionCallBuilder {
394 private boolean isNewCall = false;
395 private boolean isCallFunction = false;
396 private final Node receiver;
397 private final Node firstArgument;
398 private String propName = null;
399
400 FunctionCallBuilder(Node receiver, Node firstArgument) {
401 this.receiver = receiver;
402 this.firstArgument = firstArgument;
403 }
404
405 FunctionCallBuilder setPropName(String propName) {
406 this.propName = propName;
407 return this;
408 }
409
410 /** Should be called iff this is a new call, e.g. new Object(); */
411 FunctionCallBuilder setIsNewCall(boolean isNew) {
412 Preconditions.checkState(!(isCallFunction && isNew),
413 "A function call cannot be of the form: new Object.call()");
414
415 isNewCall = isNew;
416 return this;
417 }
418
419 /**
420 * Should be called iff this is a {@code call()} function call,
421 * e.g. Array.prototype.slice.call(arguments, 0);
422 */
423 FunctionCallBuilder setIsCallFunction() {
424 Preconditions.checkState(!isNewCall,
425 "A function call cannot be of the form: new Object.call()");
426
427 isCallFunction = true;
428 return this;
429 }
430
431 Action build() {
432 if (isCallFunction) {
433 return new NativeCallFunctionCall(receiver, propName, firstArgument);
434 } else {
435 return new FunctionCall(isNewCall, receiver, propName, firstArgument);
436 }
437 }
438 }
439
440 /**
441 * Returns a list of assignments that will result from a function call with
442 * the given concrete types.
443 */
444 private List<Assignment> getFunctionCallAssignments(ConcreteType recvType,
445 ConcreteType thisType, List<ConcreteType> argTypes) {
446 List<Assignment> assigns = Lists.newArrayList();
447 for (ConcreteFunctionType fType : recvType.getFunctions()) {
448 assigns.add(new Assignment((ConcreteSlot) fType.getCallSlot(), fType));
449 assigns.add(new Assignment((ConcreteSlot) fType.getThisSlot(), thisType));
450 for (int i = 0; i < argTypes.size(); ++i) {
451 ConcreteSlot variable = (ConcreteSlot) fType.getParameterSlot(i);
452 // TODO(johnlenz): Support "arguments" references in function bodies.
453 // For now, ignore anonymous arguments.
454 if (variable != null) {
455 assigns.add(new Assignment(variable, argTypes.get(i)));
456 }
457 }
458 }
459 return assigns;
460 }
461
462 /**
463 * Records a call to a function with a given set of concrete types. This is
464 * used for function calls that originate outside the scope of the user code.
465 * E.g. callbacks from an extern function.
466 */
467 private class ExternFunctionCall implements Action {
468 private Node receiver;
469 private ConcreteType thisType;
470 private List<ConcreteType> argTypes;
471
472 ExternFunctionCall(Node receiver, ConcreteType thisType,
473 List<ConcreteType> argTypes) {
474 this.receiver = receiver;
475 this.thisType = thisType;
476 this.argTypes = argTypes;
477 }
478
479 @Override
480 public Collection<Assignment> getAssignments(ConcreteScope scope) {
481 return getFunctionCallAssignments(inferConcreteType(scope, receiver),
482 thisType, argTypes);
483 }
484 }
485
486 /** Records a call to a function with a given set of arguments. */
487 private class FunctionCall implements Action {
488 private final boolean isNewCall;
489 private final Node receiver;
490 private final String propName;
491 private final Node firstArgument;
492
493 /**
494 * The function called is {@code receiver} or, if {@code propName} is
495 * non-null, the {@propName} field of {@code receiver}.
496 */
497 FunctionCall(boolean isNewCall, Node receiver, String propName,
498 Node firstArgument) {
499 this.isNewCall = isNewCall;
500 this.receiver = receiver;
501 this.propName = propName;
502 this.firstArgument = firstArgument;
503
504 Preconditions.checkNotNull(receiver);
505 }
506
507 @Override
508 public Collection<Assignment> getAssignments(ConcreteScope scope) {
509 ConcreteType thisType = ConcreteType.NONE;
510 ConcreteType recvType = inferConcreteType(scope, receiver);
511
512 // If a property name was specified, then the receiver is actually the
513 // type of this and the actual receiver is the type of that property.
514 if (propName != null) {
515 thisType = recvType;
516 recvType = thisType.getPropertyType(propName);
517 }
518
519 if (recvType.isAll()) {
520 // TODO(user): ensure that this will trigger for code like
521 // functions[3]();
522 throw new AssertionError(
523 "Found call on all type, which makes tighten types useless.");
524 }
525
526 // If this is a call to new, then a new instance of the receiver is
527 // created and passed in as the value of this.
528 if (isNewCall) {
529 thisType = ConcreteType.NONE;
530 for (ConcreteInstanceType instType
531 : recvType.getFunctionInstanceTypes()) {
532 thisType = thisType.unionWith(instType);
533 }
534 boolean added = allInstantiatedTypes.add(thisType);
535 if (added) {
536 // A new type instance invalidates the cached type intersections.
537 typeIntersectionMemos.clear();
538 }
539 }
540
541 List<ConcreteType> argTypes = Lists.newArrayList();
542 for (Node arg = firstArgument; arg != null; arg = arg.getNext()) {
543 argTypes.add(inferConcreteType(scope, arg));
544 }
545
546 return getFunctionCallAssignments(recvType, thisType, argTypes);
547 }
548 }
549
550 /** Records a call to the native call() function. */
551 private class NativeCallFunctionCall implements Action {
552 private final Node receiver;
553 private final String propName;
554 private final Node firstArgument;
555
556 NativeCallFunctionCall(Node receiver, String propName, Node firstArgument) {
557 this.receiver = receiver;
558 this.propName = propName;
559 this.firstArgument = firstArgument;
560
561 Preconditions.checkNotNull(receiver);
562 }
563
564 @Override
565 public Collection<Assignment> getAssignments(ConcreteScope scope) {
566 ConcreteType thisType = (firstArgument != null)
567 ? inferConcreteType(scope, firstArgument)
568 : getTopScope().getTypeOfThis();
569 ConcreteType recvType = inferConcreteType(scope, receiver);
570
571 if (recvType instanceof ConcreteInstanceType &&
572 ((ConcreteInstanceType) recvType).isFunctionPrototype()) {
573 recvType = thisType.getPropertyType(propName);
574 }
575 List<ConcreteType> argTypes = Lists.newArrayList();
576 // Skip the first argument for call() as it is the 'this' object.
577 for (Node arg = firstArgument.getNext();
578 arg != null;
579 arg = arg.getNext()) {
580 argTypes.add(inferConcreteType(scope, arg));
581 }
582 return getFunctionCallAssignments(recvType, thisType, argTypes);
583 }
584 }
585
586 /** Adds all the variables and assignments to a given scope from the code. */
587 private class CreateScope extends AbstractShallowCallback {
588 private final ConcreteScope scope;
589 private final boolean inExterns;
590
591 CreateScope(ConcreteScope scope, boolean inExterns) {
592 this.scope = scope;
593 this.inExterns = inExterns;
594 }
595
596 // TODO(user): handle object literals like { a: new Foo };
597 @Override
598 public void visit(NodeTraversal t, Node n, Node parent) {
599 switch (n.getType()) {
600 case Token.VAR:
601 // Variable declaration, e.g. var a = b;
602 Node name;
603 for (name = n.getFirstChild(); name != null; name = name.getNext()) {
604 if (inExterns) {
605 // In externs, we have to trust the type information because there
606 // are not necessarily assignments to the variables, calls to the
607 // functions, etc.
608 scope.declareSlot(name.getString(), n, createType(name, scope));
609 } else {
610 scope.declareSlot(name.getString(), n);
611 if (name.getFirstChild() != null) {
612 addActions(createAssignmentActions(
613 name, name.getFirstChild(), n));
614 }
615 }
616 }
617 break;
618
619 case Token.GETPROP:
620 // Property access, e.g. a.b = c;
621 if (inExterns) {
622 ConcreteType type = inferConcreteType(getTopScope(), n);
623 // We only need to set a type if one hasn't been assigned by
624 // something else, e.g. an ASSIGN node.
625 if (type.isNone()) {
626 ConcreteScope scope =
627 (ConcreteScope) inferConcreteType(getTopScope(),
628 n.getFirstChild()).getScope();
629 if (scope != null) {
630 type = createType(n.getJSType());
631 if (type.isNone() || type.isAll()) {
632 break;
633 }
634 type = createUnionWithSubTypes(type);
635 Node nameNode = n.getLastChild();
636 scope.declareSlot(nameNode.getString(), n, type);
637 }
638 }
639 }
640 break;
641
642 case Token.FUNCTION:
643 // Function declaration, e.g. function Foo() {};
644 if (NodeUtil.isFunctionDeclaration(n)) {
645 if (!n.getJSType().isNoObjectType()) {
646 ConcreteFunctionType type = createConcreteFunction(n, scope);
647 scope.declareSlot(n.getFirstChild().getString(), n, type);
648
649 if (inExterns && type.getInstanceType() != null) {
650 // We must assume all extern types are instantiated since they
651 // can be created by the browser itself.
652 allInstantiatedTypes.add(type.getInstanceType());
653 }
654 }
655 }
656 break;
657
658 case Token.ASSIGN:
659 // Variable assignment, e.g. a = b;
660 Node lhs = n.getFirstChild();
661 if (inExterns) {
662 // Again, we have to trust the externs.
663 ConcreteScope scope;
664 if (lhs.isGetProp()) {
665 ConcreteType type = inferConcreteType(getTopScope(),
666 lhs.getFirstChild());
667 scope = (ConcreteScope) type.getScope();
668 } else {
669 scope = getTopScope();
670 }
671
672 if (scope == null) break;
673
674 ConcreteType type = inferConcreteType(getTopScope(), n);
675 if (type.isNone() || type.isAll()) {
676 break;
677 }
678
679 if (type.isFunction()) {
680 JSType lhsType = lhs.getJSType();
681 if (lhsType == null) {
682 break;
683 }
684 FunctionType funType =
685 lhsType.restrictByNotNullOrUndefined().toMaybeFunctionType();
686 if (funType == null) {
687 break;
688 }
689 ConcreteType retType = createType(funType.getReturnType());
690 retType = createUnionWithSubTypes(retType);
691 ConcreteType newret = type.toFunction().getReturnSlot()
692 .getType().unionWith(retType);
693 ((ConcreteScope) type.getScope()).declareSlot(
694 ConcreteFunctionType.RETURN_SLOT_NAME, n, newret);
695 }
696 scope.declareSlot(lhs.getLastChild().getString(), n, type);
697 } else {
698 addActions(createAssignmentActions(lhs, n.getLastChild(), n));
699 }
700 break;
701
702 case Token.NEW:
703 case Token.CALL:
704 Node receiver = n.getFirstChild();
705 if (receiver.isGetProp()) {
706 Node first = receiver.getFirstChild();
707 // Special case the call() function.
708 if ("call".equals(first.getNext().getString())) {
709 if (first.isGetProp()) {
710 // foo.bar.call()
711 addAction(new FunctionCallBuilder(first, receiver.getNext())
712 .setPropName(first.getFirstChild().getNext().getString())
713 .setIsCallFunction()
714 .build());
715 } else {
716 // bar.call()
717 addAction(new FunctionCallBuilder(
718 first, receiver.getNext()).setIsCallFunction()
719 .build());
720 }
721 } else {
722 // foo.bar()
723 addAction(new FunctionCallBuilder(first, receiver.getNext())
724 .setPropName(first.getNext().getString())
725 .build());
726 }
727 } else {
728 // foo() or new Foo()
729 addAction(new FunctionCallBuilder(receiver, receiver.getNext())
730 .setIsNewCall(n.isNew())
731 .build());
732 }
733 break;
734
735 case Token.NAME:
736 if (parent.isCatch() && parent.getFirstChild() == n) {
737 // The variable in a catch statement gets defined in the scope of
738 // the catch block. We approximate that, as does the normal type
739 // system, by declaring a variable for it in the scope in which the
740 // catch is declared.
741 scope.declareSlot(n.getString(), n,
742 createUnionWithSubTypes(
743 createType(getTypeRegistry().getType("Error")).toInstance()));
744 }
745 break;
746
747 case Token.RETURN:
748 if (n.getFirstChild() != null) {
749 addAction(new VariableAssignAction(
750 (ConcreteSlot) scope.getOwnSlot(
751 ConcreteFunctionType.RETURN_SLOT_NAME), n.getFirstChild()));
752 }
753 break;
754 }
755
756 Collection<Action> actions = getImplicitActions(n);
757 if (actions != null) {
758 for (Action action : actions) {
759 addAction(action);
760 }
761 }
762 }
763
764 /** Adds the given action to the scope (in non-externs only). */
765 private void addAction(Action action) {
766 Preconditions.checkState(!inExterns, "Unexpected action in externs.");
767 scope.addAction(action);
768 }
769
770 /** Adds the given action to the scope (in non-externs only). */
771 private void addActions(List<Action> actions) {
772 Preconditions.checkState(!inExterns, "Unexpected action in externs.");
773 for (Action action : actions) {
774 scope.addAction(action);
775 }
776 }
777
778 /**
779 * Returns an action for assigning the right-hand-side to the left or null
780 * if this assignment should be ignored.
781 */
782 private List<Action> createAssignmentActions(
783 Node lhs, Node rhs, Node parent) {
784 switch (lhs.getType()) {
785 case Token.NAME:
786 ConcreteSlot var = (ConcreteSlot) scope.getSlot(lhs.getString());
787 Preconditions.checkState(var != null,
788 "Type tightener could not find variable with name %s",
789 lhs.getString());
790 return Lists.<Action>newArrayList(
791 new VariableAssignAction(var, rhs));
792
793 case Token.GETPROP:
794 Node receiver = lhs.getFirstChild();
795 return Lists.<Action>newArrayList(
796 new PropertyAssignAction(receiver, rhs));
797
798 case Token.GETELEM:
799 return Lists.newArrayList();
800
801 default:
802 throw new AssertionError(
803 "Bad LHS for assignment: " + parent.toStringTree());
804 }
805 }
806
807 private ExternFunctionCall createExternFunctionCall(
808 Node receiver, JSType jsThisType, FunctionType fun) {
809 List<ConcreteType> argTypes = Lists.newArrayList();
810 ConcreteType thisType;
811 if (fun != null) {
812 thisType = createType(jsThisType);
813 for (Node arg : fun.getParameters()) {
814 argTypes.add(createType(arg, scope));
815 }
816 } else {
817 thisType = ConcreteType.NONE;
818 }
819 return new ExternFunctionCall(receiver, thisType, argTypes);
820 }
821
822 private JSType getJSType(Node n) {
823 if (n.getJSType() != null) {
824 return n.getJSType();
825 } else {
826 return getTypeRegistry().getNativeType(UNKNOWN_TYPE);
827 }
828 }
829
830 /**
831 * Returns any actions that are implicit in the given code. This can return
832 * null instead of an empty collection if none are found.
833 */
834 private Collection<Action> getImplicitActions(Node n) {
835 switch (n.getType()) {
836 case Token.CALL:
837 // Functions passed to externs functions are considered called.
838 // E.g. window.setTimeout(callback, 100);
839 // TODO(user): support global extern function calls if necessary
840 // TODO(user): handle addEventListener for the case of an object
841 // implementing the EventListener interface.
842 Node receiver = n.getFirstChild();
843 if (!inExterns && receiver.isGetProp()) {
844 return getImplicitActionsFromCall(n, receiver.getJSType());
845 }
846 break;
847
848 case Token.ASSIGN:
849 Node lhs = n.getFirstChild();
850 // Functions assigned to externs properties are considered called.
851 // E.g. element.onclick = function handle(evt) {};
852 if (!inExterns && lhs.isGetProp()) {
853 return getImplicitActionsFromProp(lhs.getFirstChild().getJSType(),
854 lhs.getLastChild().getString(), n.getLastChild());
855 }
856 break;
857 }
858 return null;
859 }
860
861 private Collection<Action> getImplicitActionsFromCall(
862 Node n, JSType recvType) {
863 Node receiver = n.getFirstChild();
864 if (recvType.isUnionType()) {
865 List<Action> actions = Lists.newArrayList();
866 for (JSType alt : recvType.toMaybeUnionType().getAlternates()) {
867 actions.addAll(getImplicitActionsFromCall(n, alt));
868 }
869 return actions;
870 } else if (!(recvType.isFunctionType())) {
871 return Lists.<Action>newArrayList();
872 }
873
874 ObjectType objType = ObjectType.cast(
875 getJSType(receiver.getFirstChild())
876 .restrictByNotNullOrUndefined());
877 String prop = receiver.getLastChild().getString();
878 if (objType != null &&
879 (objType.isPropertyInExterns(prop)) &&
880 (recvType.toMaybeFunctionType()).getParameters() != null) {
881 List<Action> actions = Lists.newArrayList();
882
883 // Look for a function type in the argument list.
884 Iterator<Node> paramIter =
885 (recvType.toMaybeFunctionType()).getParameters().iterator();
886 Iterator<Node> argumentIter = n.children().iterator();
887 argumentIter.next(); // Skip the function name.
888 while (paramIter.hasNext() && argumentIter.hasNext()) {
889 Node arg = argumentIter.next();
890 Node param = paramIter.next();
891 if (arg.getJSType() != null && arg.getJSType().isFunctionType()) {
892 actions.addAll(getImplicitActionsFromArgument(
893 arg,
894 arg.getJSType().toMaybeFunctionType().getTypeOfThis()
895 .toObjectType(),
896 param.getJSType()));
897 }
898 }
899 return actions;
900 }
901 return Lists.<Action>newArrayList();
902 }
903
904 private Collection<Action> getImplicitActionsFromArgument(
905 Node arg, ObjectType thisType, JSType paramType) {
906 if (paramType.isUnionType()) {
907 List<Action> actions = Lists.newArrayList();
908 for (JSType paramAlt : paramType.toMaybeUnionType().getAlternates()) {
909 actions.addAll(
910 getImplicitActionsFromArgument(arg, thisType, paramAlt));
911 }
912 return actions;
913 } else if (paramType.isFunctionType()) {
914 return Lists.<Action>newArrayList(createExternFunctionCall(
915 arg, thisType, paramType.toMaybeFunctionType()));
916 } else {
917 return Lists.<Action>newArrayList(createExternFunctionCall(
918 arg, thisType, null));
919 }
920 }
921
922 private Collection<Action> getImplicitActionsFromProp(
923 JSType jsType, String prop, Node fnNode) {
924 List<Action> actions = Lists.newArrayList();
925 if (jsType.isUnionType()) {
926 boolean found = false;
927 for (JSType alt : jsType.toMaybeUnionType().getAlternates()) {
928 ObjectType altObj = ObjectType.cast(alt);
929 if (altObj != null) {
930 actions.addAll(getImplicitActionsFromPropNonUnion(
931 altObj, prop, fnNode));
932 if (altObj.hasProperty(prop)) {
933 found = true;
934 }
935 }
936 }
937 if (found) {
938 return actions;
939 }
940 } else {
941 ObjectType objType = ObjectType.cast(jsType);
942 if (objType != null &&
943 !objType.isUnknownType() && objType.hasProperty(prop)) {
944 return getImplicitActionsFromPropNonUnion(objType, prop, fnNode);
945 }
946 }
947
948 // If we didn't find a type that has the property, then check if there
949 // exists a property with this name anywhere in the externs.
950 for (ObjectType type :
951 getTypeRegistry().getEachReferenceTypeWithProperty(prop)) {
952 actions.addAll(
953 getImplicitActionsFromPropNonUnion(
954 type, prop, fnNode));
955 }
956 return actions;
957 }
958
959 private Collection<Action> getImplicitActionsFromPropNonUnion(
960 ObjectType jsType, String prop, Node fnNode) {
961 JSType propType = jsType.getPropertyType(prop)
962 .restrictByNotNullOrUndefined();
963 if (jsType.isPropertyInExterns(prop) && propType.isFunctionType()) {
964 ObjectType thisType = jsType;
965 if (jsType.isFunctionPrototypeType()) {
966 thisType = thisType.getOwnerFunction().getInstanceType();
967 }
968 FunctionType callType = propType.toMaybeFunctionType();
969 Action action = createExternFunctionCall(
970 fnNode, thisType, callType);
971 return Lists.<Action>newArrayList(action);
972 }
973 return Lists.<Action>newArrayList();
974 }
975 }
976
977 /** Returns a concrete type from the JSType of the given variable. */
978 private ConcreteType createType(Node name, ConcreteScope scope) {
979 Preconditions.checkNotNull(name);
980 Preconditions.checkArgument(name.isName());
981
982 if (name.getJSType() == null) {
983 return ConcreteType.ALL;
984 }
985
986 if ((name.getFirstChild() != null)
987 && (name.getFirstChild().isFunction())) {
988 return createConcreteFunction(name.getFirstChild(), scope);
989 }
990
991 return createType(name.getJSType());
992 }
993
994 /** Returns a concrete type from the given JSType. */
995 private ConcreteType createType(JSType jsType) {
996 if (jsType.isUnknownType() || jsType.isEmptyType()) {
997 return ConcreteType.ALL;
998 }
999
1000 if (jsType.isUnionType()) {
1001 ConcreteType type = ConcreteType.NONE;
1002 for (JSType alt : jsType.toMaybeUnionType().getAlternates()) {
1003 type = type.unionWith(createType(alt));
1004 }
1005 return type;
1006 }
1007
1008 if (jsType.isFunctionType()) {
1009 if (getConcreteFunction(jsType.toMaybeFunctionType()) != null) {
1010 return getConcreteFunction(jsType.toMaybeFunctionType());
1011 }
1012 // Since we don't have a declaration, it's not concrete.
1013 return ConcreteType.ALL;
1014 }
1015
1016 if (jsType.isObject()) {
1017 return createConcreteInstance(jsType.toObjectType());
1018 }
1019
1020 return ConcreteType.NONE; // Not a reference type.
1021 }
1022
1023 /**
1024 * Returns a concrete type from the given JSType that includes the concrete
1025 * types for subtypes and implementing types for any interfaces.
1026 */
1027 private ConcreteType createTypeWithSubTypes(JSType jsType) {
1028 ConcreteType ret = ConcreteType.NONE;
1029 if (jsType.isUnionType()) {
1030 for (JSType alt : jsType.toMaybeUnionType().getAlternates()) {
1031 ret = ret.unionWith(createTypeWithSubTypes(alt));
1032 }
1033 } else {
1034 ObjectType instType = ObjectType.cast(jsType);
1035 if (instType != null &&
1036 instType.getConstructor() != null &&
1037 instType.getConstructor().isInterface()) {
1038 Collection<FunctionType> implementors =
1039 getTypeRegistry().getDirectImplementors(instType);
1040
1041 for (FunctionType implementor : implementors) {
1042 ret = ret.unionWith(createTypeWithSubTypes(
1043 implementor.getInstanceType()));
1044 }
1045 } else {
1046 ret = ret.unionWith(createUnionWithSubTypes(createType(jsType)));
1047 }
1048 }
1049 return ret;
1050 }
1051
1052 /** Computes the concrete types that can result from the given expression. */
1053 ConcreteType inferConcreteType(ConcreteScope scope, Node expr) {
1054 Preconditions.checkNotNull(scope);
1055 Preconditions.checkNotNull(expr);
1056 ConcreteType ret;
1057 switch (expr.getType()) {
1058 case Token.NAME:
1059 StaticSlot<ConcreteType> slot = scope.getSlot(expr.getString());
1060
1061 if (slot != null) {
1062 ret = slot.getType();
1063 } else {
1064 // This should occur only for extern variables, which we are assuming
1065 // do not ever get assigned instances of user types.
1066 ret = ConcreteType.ALL;
1067 }
1068 break;
1069
1070 case Token.THIS:
1071 ret = scope.getTypeOfThis();
1072 break;
1073
1074 case Token.ASSIGN:
1075 // Using the right-hand side is more specific since the left hand side
1076 // is a variable of some sort that can be assigned elsewhere.
1077 ret = inferConcreteType(scope, expr.getLastChild());
1078 break;
1079
1080 case Token.COMMA:
1081 ret = inferConcreteType(scope, expr.getLastChild());
1082 break;
1083
1084 case Token.AND:
1085 // Since a reference type is always true, only the right hand side could
1086 // actually be returned.
1087 ret = inferConcreteType(scope, expr.getLastChild());
1088 break;
1089
1090 case Token.OR:
1091 ret = inferConcreteType(scope, expr.getFirstChild()).unionWith(
1092 inferConcreteType(scope, expr.getLastChild()));
1093 break;
1094
1095 case Token.HOOK:
1096 ret = inferConcreteType(scope,
1097 expr.getFirstChild().getNext()).unionWith(
1098 inferConcreteType(scope, expr.getLastChild()));
1099 break;
1100
1101 case Token.GETPROP:
1102 ConcreteType recvType = inferConcreteType(scope, expr.getFirstChild());
1103 if (recvType.isAll()) {
1104 ret = recvType;
1105 break;
1106 }
1107 Node prop = expr.getLastChild();
1108 String propName = prop.getString();
1109 ConcreteType type = recvType.getPropertyType(propName);
1110 if ("prototype".equals(propName)) {
1111 for (ConcreteFunctionType funType : recvType.getFunctions()) {
1112 type = type.unionWith(funType.getPrototypeType());
1113 }
1114 } else if (compiler.getCodingConvention()
1115 .isSuperClassReference(propName)) {
1116 for (ConcreteFunctionType superType : recvType.getSuperclassTypes()) {
1117 type = type.unionWith(superType.getPrototypeType());
1118 }
1119 } else if ("call".equals(propName)) {
1120 type = recvType;
1121 }
1122 ret = type;
1123 break;
1124
1125 case Token.GETELEM:
1126 ret = ConcreteType.ALL;
1127 break;
1128
1129 case Token.CALL:
1130 // TODO(user): Support apply on functions.
1131 // TODO(user): Create goog.bind that curries some arguments.
1132 ConcreteType targetType =
1133 inferConcreteType(scope, expr.getFirstChild());
1134 if (targetType.isAll()) {
1135 ret = targetType;
1136 break;
1137 }
1138 ret = ConcreteType.NONE;
1139 for (ConcreteFunctionType funType : targetType.getFunctions()) {
1140 ret = ret.unionWith(funType.getReturnSlot().getType());
1141 }
1142 break;
1143
1144 case Token.NEW:
1145 ConcreteType constructorType =
1146 inferConcreteType(scope, expr.getFirstChild());
1147 if (constructorType.isAll()) {
1148 throw new AssertionError("Attempted new call on all type!");
1149 }
1150 ret = ConcreteType.NONE;
1151 for (ConcreteInstanceType instType
1152 : constructorType.getFunctionInstanceTypes()) {
1153 ret = ret.unionWith(instType);
1154 }
1155 allInstantiatedTypes.add(ret);
1156 break;
1157
1158 case Token.FUNCTION:
1159 ret = createConcreteFunction(expr, scope);
1160 break;
1161
1162 case Token.OBJECTLIT:
1163 if ((expr.getJSType() != null) && !expr.getJSType().isUnknownType()) {
1164 JSType exprType = expr.getJSType().restrictByNotNullOrUndefined();
1165 ConcreteType inst = createConcreteInstance(exprType.toObjectType());
1166 allInstantiatedTypes.add(inst);
1167 ret = inst;
1168 } else {
1169 ret = ConcreteType.ALL;
1170 }
1171 break;
1172
1173 case Token.ARRAYLIT:
1174 ObjectType arrayType = (ObjectType) getTypeRegistry()
1175 .getNativeType(JSTypeNative.ARRAY_TYPE);
1176 ConcreteInstanceType inst = createConcreteInstance(arrayType);
1177 allInstantiatedTypes.add(inst);
1178 ret = inst;
1179 break;
1180
1181 default:
1182 ret = ConcreteType.NONE;
1183 }
1184 return createTypeIntersection(ret, expr.getJSType());
1185 }
1186
1187 private ConcreteType createTypeIntersection(
1188 ConcreteType concreteType, JSType jsType) {
1189 // TODO(johnlenz): Even with memoizing all the time of this pass is still
1190 // spent in this function (due to invalidation caused by changes to
1191 // allInstantiatedTypes), specifically calls to ConcreteUnionType.unionWith
1192 ConcreteJSTypePair key = new ConcreteJSTypePair(concreteType, jsType);
1193 ConcreteType ret = typeIntersectionMemos.get(key);
1194 if (ret != null) {
1195 return ret;
1196 }
1197
1198 if (jsType == null || jsType.isUnknownType() || concreteType.isNone()) {
1199 ret = concreteType;
1200 } else if (concreteType.isUnion() || concreteType.isSingleton()) {
1201 ret = concreteType.intersectWith(createTypeWithSubTypes(jsType));
1202 } else {
1203 Preconditions.checkState(concreteType.isAll());
1204 ret = createTypeWithSubTypes(jsType);
1205 }
1206 ret = ret.intersectWith(ConcreteType.createForTypes(allInstantiatedTypes));
1207
1208 // Keep all function types, as restricting to instantiated types will only
1209 // keep instance types.
1210 // TODO(user): only keep functions that match the JS type.
1211 for (ConcreteFunctionType functionType : concreteType.getFunctions()) {
1212 ret = ret.unionWith(functionType);
1213 }
1214
1215 // The prototype type is special as it should only appear from a direct
1216 // reference to Foo.prototype, and not via a type cast, thus, do not filter
1217 // them out. We do not include them in the list of instantiated types.
1218 for (ConcreteInstanceType prototype : concreteType.getPrototypeTypes()) {
1219 ret = ret.unionWith(prototype);
1220 }
1221
1222 // Anonymous object types and enums will get removed in the createForTypes
1223 // call, so add them back in as well.
1224 for (ConcreteInstanceType instance : concreteType.getInstances()) {
1225 if (!instance.instanceType.isInstanceType()
1226 && !instance.isFunctionPrototype()) {
1227 ret = ret.unionWith(instance);
1228 }
1229 }
1230
1231 typeIntersectionMemos.put(key, ret);
1232 return ret;
1233 }
1234
1235 @Override
1236 public ConcreteFunctionType createConcreteFunction(
1237 Node decl, StaticScope<ConcreteType> parent) {
1238 ConcreteFunctionType funType = functionFromDeclaration.get(decl);
1239 if (funType == null) {
1240 functionFromDeclaration.put(decl,
1241 funType = new ConcreteFunctionType(this, decl, parent));
1242 if (decl.getJSType() != null) {
1243 functionFromJSType.put(decl.getJSType().toMaybeFunctionType(), funType);
1244 }
1245 }
1246 return funType;
1247 }
1248
1249 @Override
1250 public ConcreteInstanceType createConcreteInstance(ObjectType instanceType) {
1251 // This should be an instance or function prototype object, not a function.
1252 Preconditions.checkArgument(
1253 !instanceType.isFunctionType() ||
1254 instanceType == getTypeRegistry().getNativeType(U2U_CONSTRUCTOR_TYPE));
1255 ConcreteInstanceType instType = instanceFromJSType.get(instanceType);
1256 if (instType == null) {
1257 instanceFromJSType.put(instanceType,
1258 instType = new ConcreteInstanceType(this, instanceType));
1259 }
1260 return instType;
1261 }
1262
1263 /** Returns the (already created) function with the given declaration. */
1264 ConcreteFunctionType getConcreteFunction(Node decl) {
1265 return functionFromDeclaration.get(decl);
1266 }
1267
1268 /** Returns the function (if any) for the given node. */
1269 @Override
1270 public ConcreteFunctionType getConcreteFunction(FunctionType functionType) {
1271 return functionFromJSType.get(functionType);
1272 }
1273
1274 /** Returns the function (if any) for the given node. */
1275 @Override
1276 public ConcreteInstanceType getConcreteInstance(ObjectType instanceType) {
1277 return instanceFromJSType.get(instanceType);
1278 }
1279
1280 @Override
1281 public StaticScope<ConcreteType> createFunctionScope(
1282 Node decl, StaticScope<ConcreteType> parent) {
1283 ConcreteScope scope = new ConcreteScope((ConcreteScope) parent);
1284 scope.declareSlot(ConcreteFunctionType.CALL_SLOT_NAME, decl);
1285 scope.declareSlot(ConcreteFunctionType.THIS_SLOT_NAME, decl);
1286 scope.declareSlot(ConcreteFunctionType.RETURN_SLOT_NAME, decl);
1287 for (Node n = decl.getFirstChild().getNext().getFirstChild();
1288 n != null;
1289 n = n.getNext()) {
1290 scope.declareSlot(n.getString(), n);
1291 }
1292 // TODO(user): Create an 'arguments' variable that returns the union
1293 // of the concrete types of all parameters.
1294 scope.initForScopeRoot(decl.getLastChild());
1295 return scope;
1296 }
1297
1298 @Override
1299 public StaticScope<ConcreteType> createInstanceScope(
1300 ObjectType instanceType) {
1301 ConcreteScope parentScope = null;
1302 ObjectType implicitProto = instanceType.getImplicitPrototype();
1303 if (implicitProto != null && !implicitProto.isUnknownType()) {
1304 ConcreteInstanceType prototype = createConcreteInstance(implicitProto);
1305 parentScope = (ConcreteScope) prototype.getScope();
1306 }
1307 ConcreteScope scope = new ConcreteScope(parentScope);
1308 for (String propName : instanceType.getOwnPropertyNames()) {
1309 scope.declareSlot(propName, null);
1310 }
1311 return scope;
1312 }
1313
1314 /**
1315 * Returns a ConcreteType that is the union of the given type and all of its
1316 * subtypes. This assumes that the passed in type is an instance type,
1317 * otherwise an empty set is returned. The returned set will be instance
1318 * types.
1319 */
1320 ConcreteType createUnionWithSubTypes(ConcreteType type) {
1321 Set<ConcreteType> set = null;
1322 if (type.isInstance()) {
1323 set = getSubTypes(type.toInstance());
1324 }
1325
1326 return ConcreteType.createForTypes(set).unionWith(type);
1327 }
1328
1329 /** Returns the set of subtypes of the given type. */
1330 private Set<ConcreteType> getSubTypes(ConcreteInstanceType type) {
1331 if (type.getConstructorType() == null) {
1332 return null;
1333 }
1334
1335 Set<ConcreteType> set = Sets.newHashSet();
1336 getSubTypes(type.getConstructorType().getJSType(), set);
1337 return set;
1338 }
1339
1340 /**
1341 * Adds all subtypes of the given type to the provided set.
1342 * @return false if the all type was encountered, else true.
1343 */
1344 private boolean getSubTypes(FunctionType type, Set<ConcreteType> set) {
1345 if (type.getSubTypes() != null) {
1346 for (FunctionType sub : type.getSubTypes()) {
1347 ConcreteType concrete = createType(sub);
1348 if (concrete.isFunction()
1349 && concrete.toFunction().getInstanceType() != null) {
1350 concrete = concrete.toFunction().getInstanceType();
1351 if (!set.contains(concrete)) {
1352 set.add(concrete);
1353 if (!getSubTypes(sub, set)) {
1354 return false;
1355 }
1356 }
1357 } else {
1358 // The only time we should find a subtype that doesn't have an
1359 // instance type is for the odd case of ActiveXObject, which is
1360 // of the NoObject type and will be returned as a subtype of Object.
1361 set.clear();
1362 set.add(ConcreteType.ALL);
1363 return false;
1364 }
1365 }
1366 }
1367 return true;
1368 }
1369
1370 /**
1371 * A simple class used to pair a concrete type and a JS type. Used to
1372 * memoize the results of a "createTypeIntersection" call.
1373 */
1374 static class ConcreteJSTypePair {
1375 final ConcreteType concrete;
1376 final JSType jstype;
1377 final int hashcode;
1378
1379 ConcreteJSTypePair(ConcreteType concrete, JSType jstype) {
1380 this.concrete = concrete;
1381 this.jstype = jstype;
1382 this.hashcode = concrete.hashCode() + getJSTypeHashCode();
1383 }
1384
1385 private int getJSTypeHashCode() {
1386 return jstype != null ? jstype.hashCode() : 0;
1387 }
1388
1389 private boolean equalsJSType(JSType jsType) {
1390 if (jsType == null || jstype == null) {
1391 return jstype == jsType;
1392 } else {
1393 return jsType.equals(this.jstype);
1394 }
1395 }
1396
1397 @Override
1398 public boolean equals(Object o) {
1399 if (o instanceof ConcreteJSTypePair) {
1400 ConcreteJSTypePair pair = (ConcreteJSTypePair) o;
1401 if ((pair.concrete.equals(this.concrete)
1402 && equalsJSType(pair.jstype))) {
1403 return true;
1404 }
1405 }
1406 return false;
1407 }
1408
1409 @Override
1410 public int hashCode() {
1411 return hashcode;
1412 }
1413 }
1414 }