Debian Codegraph @

src/com/google/javascript/jscomp/DisambiguateProperties.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.common.base.Preconditions.checkState;
19
20 import com.google.common.base.Joiner;
21 import com.google.common.base.Preconditions;
22 import com.google.common.collect.HashMultimap;
23 import com.google.common.collect.ImmutableSet;
24 import com.google.common.collect.LinkedHashMultimap;
25 import com.google.common.collect.Lists;
26 import com.google.common.collect.Maps;
27 import com.google.common.collect.Multimap;
28 import com.google.common.collect.Sets;
29 import com.google.javascript.jscomp.AbstractCompiler.LifeCycleStage;
30 import com.google.javascript.jscomp.ConcreteType.ConcreteFunctionType;
31 import com.google.javascript.jscomp.ConcreteType.ConcreteInstanceType;
32 import com.google.javascript.jscomp.ConcreteType.ConcreteUnionType;
33 import com.google.javascript.jscomp.ConcreteType.ConcreteUniqueType;
34 import com.google.javascript.jscomp.NodeTraversal.ScopedCallback;
35 import com.google.javascript.jscomp.TypeValidator.TypeMismatch;
36 import com.google.javascript.jscomp.graph.StandardUnionFind;
37 import com.google.javascript.jscomp.graph.UnionFind;
38 import com.google.javascript.rhino.Node;
39 import com.google.javascript.rhino.jstype.FunctionType;
40 import com.google.javascript.rhino.jstype.JSType;
41 import com.google.javascript.rhino.jstype.JSTypeNative;
42 import com.google.javascript.rhino.jstype.JSTypeRegistry;
43 import com.google.javascript.rhino.jstype.ObjectType;
44 import com.google.javascript.rhino.jstype.StaticScope;
45
46 import java.util.Collection;
47 import java.util.List;
48 import java.util.Map;
49 import java.util.Set;
50 import java.util.Stack;
51 import java.util.logging.Logger;
52
53 /**
54 * DisambiguateProperties renames properties to disambiguate between unrelated
55 * fields with the same name. Two properties are considered related if they
56 * share a definition on their prototype chains, or if they are potentially
57 * referenced together via union types.
58 *
59 * <p> Renamimg only occurs if there are two or more distinct properties with
60 * the same name.
61 *
62 * <p> This pass allows other passes, such as inlining and code removal to take
63 * advantage of type information implicitly.
64 *
65 * <pre>
66 * Foo.a;
67 * Bar.a;
68 * </pre>
69 *
70 * <p> will become
71 *
72 * <pre>
73 * Foo.a$Foo;
74 * Bar.a$Bar;
75 * </pre>
76 *
77 */
78 class DisambiguateProperties<T> implements CompilerPass {
79 // To prevent the logs from filling up, we cap the number of warnings
80 // that we tell the user to fix per-property.
81 private static final int MAX_INVALDIATION_WARNINGS_PER_PROPERTY = 10;
82
83 private static final Logger logger = Logger.getLogger(
84 DisambiguateProperties.class.getName());
85
86 static class Warnings {
87 // TODO(user): {1} and {2} are not exactly useful for most people.
88 static final DiagnosticType INVALIDATION = DiagnosticType.disabled(
89 "JSC_INVALIDATION",
90 "Property disambiguator skipping all instances of property {0} "
91 + "because of type {1} node {2}. {3}");
92
93 static final DiagnosticType INVALIDATION_ON_TYPE = DiagnosticType.disabled(
94 "JSC_INVALIDATION_TYPE",
95 "Property disambiguator skipping instances of property {0} "
96 + "on type {1}. {2}");
97 }
98
99 private final AbstractCompiler compiler;
100 private final TypeSystem<T> typeSystem;
101
102 /**
103 * Map of a type to all the related errors that invalidated the type
104 * for disambiguation. It has be Object because of the generic nature of
105 * this pass.
106 */
107 private Multimap<Object, JSError> invalidationMap;
108
109 /**
110 * In practice any large code base will have thousands and thousands of
111 * type invalidations, which makes reporting all of the errors useless.
112 * However, certain properties are worth specifically guarding because of the
113 * large amount of code that can be removed as dead code. This list contains
114 * the properties (eg: "toString") that we care about; if any of these
115 * properties is invalidated it causes an error.
116 */
117 private final Map<String, CheckLevel> propertiesToErrorFor;
118
119 private class Property {
120 /** The name of the property. */
121 final String name;
122
123 /** All types on which the field exists, grouped together if related. */
124 private UnionFind<T> types;
125
126 /**
127 * A set of types for which renaming this field should be skipped. This
128 * list is first filled by fields defined in the externs file.
129 */
130 Set<T> typesToSkip = Sets.newHashSet();
131
132 /**
133 * If true, do not rename any instance of this field, as it has been
134 * referenced from an unknown type.
135 */
136 boolean skipRenaming;
137
138 /** Set of nodes for this field that need renaming. */
139 Set<Node> renameNodes = Sets.newHashSet();
140
141 /**
142 * Map from node to the highest type in the prototype chain containing the
143 * field for that node. In the case of a union, the type is the highest type
144 * of one of the types in the union.
145 */
146 final Map<Node, T> rootTypes = Maps.newHashMap();
147
148 Property(String name) {
149 this.name = name;
150 }
151
152 /** Returns the types on which this field is referenced. */
153 UnionFind<T> getTypes() {
154 if (types == null) {
155 types = new StandardUnionFind<T>();
156 }
157 return types;
158 }
159
160 /**
161 * Record that this property is referenced from this type.
162 * @return true if the type was recorded for this property, else false,
163 * which would happen if the type was invalidating.
164 */
165 boolean addType(T type, T top, T relatedType) {
166 checkState(!skipRenaming, "Attempt to record skipped property: %s", name);
167 if (typeSystem.isInvalidatingType(top)) {
168 invalidate();
169 return false;
170 } else {
171 if (typeSystem.isTypeToSkip(top)) {
172 addTypeToSkip(top);
173 }
174
175 if (relatedType == null) {
176 getTypes().add(top);
177 } else {
178 getTypes().union(top, relatedType);
179 }
180 typeSystem.recordInterfaces(type, top, this);
181 return true;
182 }
183 }
184
185 /** Records the given type as one to skip for this property. */
186 void addTypeToSkip(T type) {
187 for (T skipType : typeSystem.getTypesToSkipForType(type)) {
188 typesToSkip.add(skipType);
189 getTypes().union(skipType, type);
190 }
191 }
192
193 /** Invalidates any types related to invalid types. */
194 void expandTypesToSkip() {
195 // If we are not going to rename any properties, then we do not need to
196 // update the list of invalid types, as they are all invalid.
197 if (shouldRename()) {
198 int count = 0;
199 while (true) {
200 // It should usually only take one time through this do-while.
201 checkState(++count < 10, "Stuck in loop expanding types to skip.");
202
203 // Make sure that the representative type for each type to skip is
204 // marked as being skipped.
205 Set<T> rootTypesToSkip = Sets.newHashSet();
206 for (T subType : typesToSkip) {
207 rootTypesToSkip.add(types.find(subType));
208 }
209 typesToSkip.addAll(rootTypesToSkip);
210
211 Set<T> newTypesToSkip = Sets.newHashSet();
212 Set<T> allTypes = types.elements();
213 int originalTypesSize = allTypes.size();
214 for (T subType : allTypes) {
215 if (!typesToSkip.contains(subType)
216 && typesToSkip.contains(types.find(subType))) {
217 newTypesToSkip.add(subType);
218 }
219 }
220
221 for (T newType : newTypesToSkip) {
222 addTypeToSkip(newType);
223 }
224
225 // If there were not any new types added, we are done here.
226 if (types.elements().size() == originalTypesSize) {
227 break;
228 }
229 }
230 }
231 }
232
233 /** Returns true if any instance of this property should be renamed. */
234 boolean shouldRename() {
235 return !skipRenaming && types != null
236 && types.allEquivalenceClasses().size() > 1;
237 }
238
239 /**
240 * Returns true if this property should be renamed on this type.
241 * expandTypesToSkip() should be called before this, if anything has been
242 * added to the typesToSkip list.
243 */
244 boolean shouldRename(T type) {
245 return !skipRenaming && !typesToSkip.contains(type);
246 }
247
248 /**
249 * Invalidates a field from renaming. Used for field references on an
250 * object with unknown type.
251 */
252 boolean invalidate() {
253 boolean changed = !skipRenaming;
254 skipRenaming = true;
255 types = null;
256 return changed;
257 }
258
259 /**
260 * Schedule the node to potentially be renamed.
261 * @param node the node to rename
262 * @param type the highest type in the prototype chain for which the
263 * property is defined
264 * @return True if type was accepted without invalidation or if the property
265 * was already invalidated. False if this property was invalidated this
266 * time.
267 */
268 boolean scheduleRenaming(Node node, T type) {
269 if (!skipRenaming) {
270 if (typeSystem.isInvalidatingType(type)) {
271 invalidate();
272 return false;
273 }
274 renameNodes.add(node);
275 rootTypes.put(node, type);
276 }
277 return true;
278 }
279 }
280
281 private Map<String, Property> properties = Maps.newHashMap();
282
283 static DisambiguateProperties<JSType> forJSTypeSystem(
284 AbstractCompiler compiler,
285 Map<String, CheckLevel> propertiesToErrorFor) {
286 return new DisambiguateProperties<JSType>(
287 compiler, new JSTypeSystem(compiler), propertiesToErrorFor);
288 }
289
290 static DisambiguateProperties<ConcreteType> forConcreteTypeSystem(
291 AbstractCompiler compiler, TightenTypes tt,
292 Map<String, CheckLevel> propertiesToErrorFor) {
293 return new DisambiguateProperties<ConcreteType>(
294 compiler, new ConcreteTypeSystem(tt, compiler.getCodingConvention()),
295 propertiesToErrorFor);
296 }
297
298 /**
299 * This constructor should only be called by one of the helper functions
300 * above for either the JSType system, or the concrete type system.
301 */
302 private DisambiguateProperties(AbstractCompiler compiler,
303 TypeSystem<T> typeSystem, Map<String, CheckLevel> propertiesToErrorFor) {
304 this.compiler = compiler;
305 this.typeSystem = typeSystem;
306 this.propertiesToErrorFor = propertiesToErrorFor;
307 if (!this.propertiesToErrorFor.isEmpty()) {
308 this.invalidationMap = LinkedHashMultimap.create();
309 } else {
310 this.invalidationMap = null;
311 }
312 }
313
314 @Override
315 public void process(Node externs, Node root) {
316 Preconditions.checkState(
317 compiler.getLifeCycleStage() == LifeCycleStage.NORMALIZED);
318 for (TypeMismatch mis : compiler.getTypeValidator().getMismatches()) {
319 addInvalidatingType(mis.typeA, mis.src);
320 addInvalidatingType(mis.typeB, mis.src);
321 }
322
323 NodeTraversal.traverse(compiler, externs, new FindExternProperties());
324 NodeTraversal.traverse(compiler, root, new FindRenameableProperties());
325 renameProperties();
326 }
327
328 private void recordInvalidationError(JSType t, JSError error) {
329 if (!t.isObject()) {
330 return;
331 }
332 if (invalidationMap != null) {
333 invalidationMap.put(t, error);
334 }
335 }
336
337 /**
338 * Invalidates the given type, so that no properties on it will be renamed.
339 */
340 private void addInvalidatingType(JSType type, JSError error) {
341 type = type.restrictByNotNullOrUndefined();
342 if (type.isUnionType()) {
343 for (JSType alt : type.toMaybeUnionType().getAlternates()) {
344 addInvalidatingType(alt, error);
345 }
346 } else if (type.isEnumElementType()) {
347 addInvalidatingType(
348 type.toMaybeEnumElementType().getPrimitiveType(), error);
349 } else {
350 typeSystem.addInvalidatingType(type);
351 recordInvalidationError(type, error);
352 ObjectType objType = ObjectType.cast(type);
353 if (objType != null && objType.getImplicitPrototype() != null) {
354 typeSystem.addInvalidatingType(objType.getImplicitPrototype());
355 recordInvalidationError(objType.getImplicitPrototype(), error);
356 }
357 }
358 }
359
360
361 /** Returns the property for the given name, creating it if necessary. */
362 protected Property getProperty(String name) {
363 if (!properties.containsKey(name)) {
364 properties.put(name, new Property(name));
365 }
366 return properties.get(name);
367 }
368
369 /** Public for testing. */
370 T getTypeWithProperty(String field, T type) {
371 return typeSystem.getTypeWithProperty(field, type);
372 }
373
374 /** Tracks the current type system scope while traversing. */
375 private abstract class AbstractScopingCallback implements ScopedCallback {
376 protected final Stack<StaticScope<T>> scopes =
377 new Stack<StaticScope<T>>();
378
379 @Override
380 public boolean shouldTraverse(NodeTraversal t, Node n, Node parent) {
381 return true;
382 }
383
384 @Override
385 public void enterScope(NodeTraversal t) {
386 if (t.inGlobalScope()) {
387 scopes.push(typeSystem.getRootScope());
388 } else {
389 scopes.push(typeSystem.getFunctionScope(t.getScopeRoot()));
390 }
391 }
392
393 @Override
394 public void exitScope(NodeTraversal t) {
395 scopes.pop();
396 }
397
398 /** Returns the current scope at this point in the file. */
399 protected StaticScope<T> getScope() {
400 return scopes.peek();
401 }
402 }
403
404 /**
405 * Finds all properties defined in the externs file and sets them as
406 * ineligible for renaming from the type on which they are defined.
407 */
408 private class FindExternProperties extends AbstractScopingCallback {
409 @Override public void visit(NodeTraversal t, Node n, Node parent) {
410 // TODO(johnlenz): Support object-literal property definitions.
411 if (n.isGetProp()) {
412 String field = n.getLastChild().getString();
413 T type = typeSystem.getType(getScope(), n.getFirstChild(), field);
414 Property prop = getProperty(field);
415 if (typeSystem.isInvalidatingType(type)) {
416 prop.invalidate();
417 } else {
418 prop.addTypeToSkip(type);
419
420 // If this is a prototype property, then we want to skip assignments
421 // to the instance type as well. These assignments are not usually
422 // seen in the extern code itself, so we must handle them here.
423 if ((type = typeSystem.getInstanceFromPrototype(type)) != null) {
424 prop.getTypes().add(type);
425 prop.typesToSkip.add(type);
426 }
427 }
428 }
429 }
430 }
431
432 /**
433 * Traverses the tree, building a map from field names to Nodes for all
434 * fields that can be renamed.
435 */
436 private class FindRenameableProperties extends AbstractScopingCallback {
437 @Override
438 public void visit(NodeTraversal t, Node n, Node parent) {
439 if (n.isGetProp()) {
440 handleGetProp(t, n);
441 } else if (n.isObjectLit()) {
442 handleObjectLit(t, n);
443 }
444 }
445
446 /**
447 * Processes a GETPROP node.
448 */
449 private void handleGetProp(NodeTraversal t, Node n) {
450 String name = n.getLastChild().getString();
451 T type = typeSystem.getType(getScope(), n.getFirstChild(), name);
452
453 Property prop = getProperty(name);
454 if (!prop.scheduleRenaming(n.getLastChild(),
455 processProperty(t, prop, type, null))) {
456 if (propertiesToErrorFor.containsKey(name)) {
457 String suggestion = "";
458 if (type instanceof JSType) {
459 JSType jsType = (JSType) type;
460 if (jsType.isAllType() || jsType.isUnknownType()) {
461 if (n.getFirstChild().isThis()) {
462 suggestion = "The \"this\" object is unknown in the function,"+
463 "consider using @this";
464 } else {
465 String qName = n.getFirstChild().getQualifiedName();
466 suggestion = "Consider casting " + qName +
467 " if you know it's type.";
468 }
469 } else {
470 List<String> errors = Lists.newArrayList();
471 printErrorLocations(errors, jsType);
472 if (!errors.isEmpty()) {
473 suggestion = "Consider fixing errors for the following types:\n";
474 suggestion += Joiner.on("\n").join(errors);
475 }
476 }
477 }
478 compiler.report(JSError.make(
479 t.getSourceName(), n, propertiesToErrorFor.get(name),
480 Warnings.INVALIDATION, name,
481 (type == null ? "null" : type.toString()),
482 n.toString(), suggestion));
483 }
484 }
485 }
486
487 /**
488 * Processes a OBJECTLIT node.
489 */
490 private void handleObjectLit(NodeTraversal t, Node n) {
491 Node child = n.getFirstChild();
492 while (child != null) {
493 // Maybe STRING, GET, SET
494
495 // We should never see a mix of numbers and strings.
496 String name = child.getString();
497 T type = typeSystem.getType(getScope(), n, name);
498
499 Property prop = getProperty(name);
500 if (!prop.scheduleRenaming(child,
501 processProperty(t, prop, type, null))) {
502 // TODO(user): It doesn't look like the user can do much in this
503 // case right now.
504 if (propertiesToErrorFor.containsKey(name)) {
505 compiler.report(JSError.make(
506 t.getSourceName(), child, propertiesToErrorFor.get(name),
507 Warnings.INVALIDATION, name,
508 (type == null ? "null" : type.toString()), n.toString(), ""));
509 }
510 }
511 child = child.getNext();
512 }
513 }
514
515 private void printErrorLocations(List<String> errors, JSType t) {
516 if (!t.isObject() || t.isAllType()) {
517 return;
518 }
519
520 if (t.isUnionType()) {
521 for (JSType alt : t.toMaybeUnionType().getAlternates()) {
522 printErrorLocations(errors, alt);
523 }
524 return;
525 }
526
527 for (JSError error : invalidationMap.get(t)) {
528 if (errors.size() > MAX_INVALDIATION_WARNINGS_PER_PROPERTY) {
529 return;
530 }
531
532 errors.add(
533 t.toString() + " at " + error.sourceName + ":" + error.lineNumber);
534 }
535 }
536
537 /**
538 * Processes a property, adding it to the list of properties to rename.
539 * @return a representative type for the property reference, which will be
540 * the highest type on the prototype chain of the provided type. In the
541 * case of a union type, it will be the highest type on the prototype
542 * chain of one of the members of the union.
543 */
544 private T processProperty(
545 NodeTraversal t, Property prop, T type, T relatedType) {
546 type = typeSystem.restrictByNotNullOrUndefined(type);
547 if (prop.skipRenaming || typeSystem.isInvalidatingType(type)) {
548 return null;
549 }
550
551 Iterable<T> alternatives = typeSystem.getTypeAlternatives(type);
552 if (alternatives != null) {
553 T firstType = relatedType;
554 for (T subType : alternatives) {
555 T lastType = processProperty(t, prop, subType, firstType);
556 if (lastType != null) {
557 firstType = firstType == null ? lastType : firstType;
558 }
559 }
560 return firstType;
561 } else {
562 T topType = typeSystem.getTypeWithProperty(prop.name, type);
563 if (typeSystem.isInvalidatingType(topType)) {
564 return null;
565 }
566 prop.addType(type, topType, relatedType);
567 return topType;
568 }
569 }
570 }
571
572 /** Renames all properties with references on more than one type. */
573 void renameProperties() {
574 int propsRenamed = 0, propsSkipped = 0, instancesRenamed = 0,
575 instancesSkipped = 0, singleTypeProps = 0;
576
577 Set<String> reported = Sets.newHashSet();
578 for (Property prop : properties.values()) {
579 if (prop.shouldRename()) {
580 Map<T, String> propNames = buildPropNames(prop.getTypes(), prop.name);
581
582 ++propsRenamed;
583 prop.expandTypesToSkip();
584 for (Node node : prop.renameNodes) {
585 T rootType = prop.rootTypes.get(node);
586 if (prop.shouldRename(rootType)) {
587 String newName = propNames.get(rootType);
588 node.setString(newName);
589 compiler.reportCodeChange();
590 ++instancesRenamed;
591 } else {
592 ++instancesSkipped;
593
594 CheckLevel checkLevelForProp = propertiesToErrorFor.get(prop.name);
595 if (checkLevelForProp != null &&
596 checkLevelForProp != CheckLevel.OFF &&
597 !reported.contains(prop.name)) {
598 reported.add(prop.name);
599 compiler.report(JSError.make(
600 NodeUtil.getSourceName(node), node,
601 checkLevelForProp,
602 Warnings.INVALIDATION_ON_TYPE, prop.name,
603 rootType.toString(), ""));
604 }
605 }
606 }
607 } else {
608 if (prop.skipRenaming) {
609 ++propsSkipped;
610 } else {
611 ++singleTypeProps;
612 }
613 }
614 }
615 logger.fine("Renamed " + instancesRenamed + " instances of "
616 + propsRenamed + " properties.");
617 logger.fine("Skipped renaming " + instancesSkipped + " invalidated "
618 + "properties, " + propsSkipped + " instances of properties "
619 + "that were skipped for specific types and " + singleTypeProps
620 + " properties that were referenced from only one type.");
621 }
622
623 /**
624 * Chooses a name to use for renaming in each equivalence class and maps
625 * each type in that class to it.
626 */
627 private Map<T, String> buildPropNames(UnionFind<T> types, String name) {
628 Map<T, String> names = Maps.newHashMap();
629 for (Set<T> set : types.allEquivalenceClasses()) {
630 checkState(!set.isEmpty());
631
632 String typeName = null;
633 for (T type : set) {
634 if (typeName == null || type.toString().compareTo(typeName) < 0) {
635 typeName = type.toString();
636 }
637 }
638
639 String newName;
640 if ("{...}".equals(typeName)) {
641 newName = name;
642 } else {
643 newName = typeName.replaceAll("[^\\w$]", "_") + "$" + name;
644 }
645
646 for (T type : set) {
647 names.put(type, newName);
648 }
649 }
650 return names;
651 }
652
653 /** Returns a map from field name to types for which it will be renamed. */
654 Multimap<String, Collection<T>> getRenamedTypesForTesting() {
655 Multimap<String, Collection<T>> ret = HashMultimap.create();
656 for (Map.Entry<String, Property> entry: properties.entrySet()) {
657 Property prop = entry.getValue();
658 if (!prop.skipRenaming) {
659 for (Collection<T> c : prop.getTypes().allEquivalenceClasses()) {
660 if (!c.isEmpty() && !prop.typesToSkip.contains(c.iterator().next())) {
661 ret.put(entry.getKey(), c);
662 }
663 }
664 }
665 }
666 return ret;
667 }
668
669 /** Interface for providing the type information needed by this pass. */
670 private interface TypeSystem<T> {
671 // TODO(user): add a getUniqueName(T type) method that is guaranteed
672 // to be unique, performant and human-readable.
673
674 /** Returns the top-most scope used by the type system (if any). */
675 StaticScope<T> getRootScope();
676
677 /** Returns the new scope started at the given function node. */
678 StaticScope<T> getFunctionScope(Node node);
679
680 /**
681 * Returns the type of the given node.
682 * @param prop Only types with this property need to be returned. In general
683 * with type tightening, this will require no special processing, but in
684 * the case of an unknown JSType, we might need to add in the native
685 * types since we don't track them, but only if they have the given
686 * property.
687 */
688 T getType(StaticScope<T> scope, Node node, String prop);
689
690 /**
691 * Returns true if a field reference on this type will invalidate all
692 * references to that field as candidates for renaming. This is true if the
693 * type is unknown or all-inclusive, as variables with such a type could be
694 * references to any object.
695 */
696 boolean isInvalidatingType(T type);
697
698 /**
699 * Informs the given type system that a type is invalidating due to a type
700 * mismatch found during type checking.
701 */
702 void addInvalidatingType(JSType type);
703
704 /**
705 * Returns a set of types that should be skipped given the given type.
706 * This is necessary for interfaces when using JSTypes, as all super
707 * interfaces must also be skipped.
708 */
709 ImmutableSet<T> getTypesToSkipForType(T type);
710
711 /**
712 * Determines whether the given type is one whose properties should not be
713 * considered for renaming.
714 */
715 boolean isTypeToSkip(T type);
716
717 /** Remove null and undefined from the options in the given type. */
718 T restrictByNotNullOrUndefined(T type);
719
720 /**
721 * Returns the alternatives if this is a type that represents multiple
722 * types, and null if not. Union and interface types can correspond to
723 * multiple other types.
724 */
725 Iterable<T> getTypeAlternatives(T type);
726
727 /**
728 * Returns the type in the chain from the given type that contains the given
729 * field or null if it is not found anywhere.
730 */
731 T getTypeWithProperty(String field, T type);
732
733 /**
734 * Returns the type of the instance of which this is the prototype or null
735 * if this is not a function prototype.
736 */
737 T getInstanceFromPrototype(T type);
738
739 /**
740 * Records that this property could be referenced from any interface that
741 * this type, or any type in its superclass chain, implements.
742 */
743 void recordInterfaces(T type, T relatedType,
744 DisambiguateProperties<T>.Property p);
745 }
746
747 /** Implementation of TypeSystem using JSTypes. */
748 private static class JSTypeSystem implements TypeSystem<JSType> {
749 private final Set<JSType> invalidatingTypes;
750 private JSTypeRegistry registry;
751
752 public JSTypeSystem(AbstractCompiler compiler) {
753 registry = compiler.getTypeRegistry();
754 invalidatingTypes = Sets.newHashSet(
755 registry.getNativeType(JSTypeNative.ALL_TYPE),
756 registry.getNativeType(JSTypeNative.NO_OBJECT_TYPE),
757 registry.getNativeType(JSTypeNative.NO_TYPE),
758 registry.getNativeType(JSTypeNative.FUNCTION_PROTOTYPE),
759 registry.getNativeType(JSTypeNative.FUNCTION_INSTANCE_TYPE),
760 registry.getNativeType(JSTypeNative.OBJECT_PROTOTYPE),
761 registry.getNativeType(JSTypeNative.TOP_LEVEL_PROTOTYPE),
762 registry.getNativeType(JSTypeNative.UNKNOWN_TYPE));
763
764 }
765
766 @Override public void addInvalidatingType(JSType type) {
767 checkState(!type.isUnionType());
768 invalidatingTypes.add(type);
769 }
770
771 @Override public StaticScope<JSType> getRootScope() { return null; }
772
773 @Override public StaticScope<JSType> getFunctionScope(Node node) {
774 return null;
775 }
776
777 @Override public JSType getType(
778 StaticScope<JSType> scope, Node node, String prop) {
779 if (node.getJSType() == null) {
780 return registry.getNativeType(JSTypeNative.UNKNOWN_TYPE);
781 }
782 return node.getJSType();
783 }
784
785 @Override public boolean isInvalidatingType(JSType type) {
786 if (type == null || invalidatingTypes.contains(type) ||
787 type.isUnknownType() /* unresolved types */) {
788 return true;
789 }
790
791 ObjectType objType = ObjectType.cast(type);
792 return objType != null && !objType.hasReferenceName();
793 }
794
795 @Override public ImmutableSet<JSType> getTypesToSkipForType(JSType type) {
796 type = type.restrictByNotNullOrUndefined();
797 if (type.isUnionType()) {
798 Set<JSType> types = Sets.newHashSet(type);
799 for (JSType alt : type.toMaybeUnionType().getAlternates()) {
800 types.addAll(getTypesToSkipForTypeNonUnion(alt));
801 }
802 return ImmutableSet.copyOf(types);
803 } else if (type.isEnumElementType()) {
804 return getTypesToSkipForType(
805 type.toMaybeEnumElementType().getPrimitiveType());
806 }
807 return ImmutableSet.copyOf(getTypesToSkipForTypeNonUnion(type));
808 }
809
810 private Set<JSType> getTypesToSkipForTypeNonUnion(JSType type) {
811 Set<JSType> types = Sets.newHashSet();
812 JSType skipType = type;
813 while (skipType != null) {
814 types.add(skipType);
815
816 ObjectType objSkipType = skipType.toObjectType();
817 if (objSkipType != null) {
818 skipType = objSkipType.getImplicitPrototype();
819 } else {
820 break;
821 }
822 }
823 return types;
824 }
825
826 @Override public boolean isTypeToSkip(JSType type) {
827 return type.isEnumType() || (type.autoboxesTo() != null);
828 }
829
830 @Override public JSType restrictByNotNullOrUndefined(JSType type) {
831 return type.restrictByNotNullOrUndefined();
832 }
833
834 @Override public Iterable<JSType> getTypeAlternatives(JSType type) {
835 if (type.isUnionType()) {
836 return type.toMaybeUnionType().getAlternates();
837 } else {
838 ObjectType objType = type.toObjectType();
839 if (objType != null &&
840 objType.getConstructor() != null &&
841 objType.getConstructor().isInterface()) {
842 List<JSType> list = Lists.newArrayList();
843 for (FunctionType impl
844 : registry.getDirectImplementors(objType)) {
845 list.add(impl.getInstanceType());
846 }
847 return list;
848 } else {
849 return null;
850 }
851 }
852 }
853
854 @Override public ObjectType getTypeWithProperty(String field, JSType type) {
855 if (type == null) {
856 return null;
857 }
858
859 if (type.isEnumElementType()) {
860 return getTypeWithProperty(
861 field, type.toMaybeEnumElementType().getPrimitiveType());
862 }
863
864 if (!(type instanceof ObjectType)) {
865 if (type.autoboxesTo() != null) {
866 type = type.autoboxesTo();
867 } else {
868 return null;
869 }
870 }
871
872 // Ignore the prototype itself at all times.
873 if ("prototype".equals(field)) {
874 return null;
875 }
876
877 // We look up the prototype chain to find the highest place (if any) that
878 // this appears. This will make references to overridden properties look
879 // like references to the initial property, so they are renamed alike.
880 ObjectType foundType = null;
881 ObjectType objType = ObjectType.cast(type);
882 if (objType != null && objType.getConstructor() != null
883 && objType.getConstructor().isInterface()) {
884 ObjectType topInterface = FunctionType.getTopDefiningInterface(
885 objType, field);
886 if (topInterface != null && topInterface.getConstructor() != null) {
887 foundType = topInterface.getConstructor().getPrototype();
888 }
889 } else {
890 while (objType != null && objType.getImplicitPrototype() != objType) {
891 if (objType.hasOwnProperty(field)) {
892 foundType = objType;
893 }
894 objType = objType.getImplicitPrototype();
895 }
896 }
897
898 // If the property does not exist on the referenced type but the original
899 // type is an object type, see if any subtype has the property.
900 if (foundType == null) {
901 ObjectType maybeType = ObjectType.cast(
902 registry.getGreatestSubtypeWithProperty(type, field));
903 // getGreatestSubtypeWithProperty does not guarantee that the property
904 // is defined on the returned type, it just indicates that it might be,
905 // so we have to double check.
906 if (maybeType != null && maybeType.hasOwnProperty(field)) {
907 foundType = maybeType;
908 }
909 }
910 return foundType;
911 }
912
913 @Override public JSType getInstanceFromPrototype(JSType type) {
914 if (type.isFunctionPrototypeType()) {
915 ObjectType prototype = (ObjectType) type;
916 FunctionType owner = prototype.getOwnerFunction();
917 if (owner.isConstructor() || owner.isInterface()) {
918 return prototype.getOwnerFunction().getInstanceType();
919 }
920 }
921 return null;
922 }
923
924 @Override
925 public void recordInterfaces(JSType type, JSType relatedType,
926 DisambiguateProperties<JSType>.Property p) {
927 ObjectType objType = ObjectType.cast(type);
928 if (objType != null) {
929 FunctionType constructor;
930 if (objType.isFunctionType()) {
931 constructor = objType.toMaybeFunctionType();
932 } else if (objType.isFunctionPrototypeType()) {
933 constructor = objType.getOwnerFunction();
934 } else {
935 constructor = objType.getConstructor();
936 }
937 while (constructor != null) {
938 for (ObjectType itype : constructor.getImplementedInterfaces()) {
939 JSType top = getTypeWithProperty(p.name, itype);
940 if (top != null) {
941 p.addType(itype, top, relatedType);
942 } else {
943 recordInterfaces(itype, relatedType, p);
944 }
945
946 // If this interface invalidated this property, return now.
947 if (p.skipRenaming) return;
948 }
949 if (constructor.isInterface() || constructor.isConstructor()) {
950 constructor = constructor.getSuperClassConstructor();
951 } else {
952 constructor = null;
953 }
954 }
955 }
956 }
957 }
958
959 /** Implementation of TypeSystem using concrete types. */
960 private static class ConcreteTypeSystem implements TypeSystem<ConcreteType> {
961 private final TightenTypes tt;
962 private int nextUniqueId;
963 private CodingConvention codingConvention;
964 private final Set<JSType> invalidatingTypes = Sets.newHashSet();
965
966 // An array of native types that are not tracked by type tightening, and
967 // thus need to be added in if an unknown type is encountered.
968 private static final JSTypeNative [] nativeTypes = new JSTypeNative[] {
969 JSTypeNative.BOOLEAN_OBJECT_TYPE,
970 JSTypeNative.NUMBER_OBJECT_TYPE,
971 JSTypeNative.STRING_OBJECT_TYPE
972 };
973
974 public ConcreteTypeSystem(TightenTypes tt, CodingConvention convention) {
975 this.tt = tt;
976 this.codingConvention = convention;
977 }
978
979 @Override public void addInvalidatingType(JSType type) {
980 checkState(!type.isUnionType());
981 invalidatingTypes.add(type);
982 }
983
984 @Override public StaticScope<ConcreteType> getRootScope() {
985 return tt.getTopScope();
986 }
987
988 @Override public StaticScope<ConcreteType> getFunctionScope(Node decl) {
989 ConcreteFunctionType func = tt.getConcreteFunction(decl);
990 return (func != null) ?
991 func.getScope() : (StaticScope<ConcreteType>) null;
992 }
993
994 @Override
995 public ConcreteType getType(
996 StaticScope<ConcreteType> scope, Node node, String prop) {
997 if (scope != null) {
998 ConcreteType c = tt.inferConcreteType(
999 (TightenTypes.ConcreteScope) scope, node);
1000 return maybeAddAutoboxes(c, node, prop);
1001 } else {
1002 return null;
1003 }
1004 }
1005
1006 /**
1007 * Add concrete types for autoboxing types if necessary. The concrete type
1008 * system does not track native types, like string, so add them if they are
1009 * present in the JSType for the node.
1010 */
1011 private ConcreteType maybeAddAutoboxes(
1012 ConcreteType cType, Node node, String prop) {
1013 JSType jsType = node.getJSType();
1014 if (jsType == null) {
1015 return cType;
1016 } else if (jsType.isUnknownType()) {
1017 for (JSTypeNative nativeType : nativeTypes) {
1018 ConcreteType concrete = tt.getConcreteInstance(
1019 tt.getTypeRegistry().getNativeObjectType(nativeType));
1020 if (concrete != null && !concrete.getPropertyType(prop).isNone()) {
1021 cType = cType.unionWith(concrete);
1022 }
1023 }
1024 return cType;
1025 }
1026
1027 return maybeAddAutoboxes(cType, jsType, prop);
1028 }
1029
1030 private ConcreteType maybeAddAutoboxes(
1031 ConcreteType cType, JSType jsType, String prop) {
1032 jsType = jsType.restrictByNotNullOrUndefined();
1033 if (jsType.isUnionType()) {
1034 for (JSType alt : jsType.toMaybeUnionType().getAlternates()) {
1035 cType = maybeAddAutoboxes(cType, alt, prop);
1036 }
1037 return cType;
1038 } else if (jsType.isEnumElementType()) {
1039 return maybeAddAutoboxes(
1040 cType, jsType.toMaybeEnumElementType().getPrimitiveType(), prop);
1041 }
1042
1043 if (jsType.autoboxesTo() != null) {
1044 JSType autoboxed = jsType.autoboxesTo();
1045 return cType.unionWith(tt.getConcreteInstance((ObjectType) autoboxed));
1046 } else if (jsType.unboxesTo() != null) {
1047 return cType.unionWith(tt.getConcreteInstance((ObjectType) jsType));
1048 }
1049
1050 return cType;
1051 }
1052
1053 @Override public boolean isInvalidatingType(ConcreteType type) {
1054 // We will disallow types on functions so that 'prototype' is not renamed.
1055 // TODO(user): Support properties on functions as well.
1056 return (type == null) || type.isAll() || type.isFunction()
1057 || (type.isInstance()
1058 && invalidatingTypes.contains(type.toInstance().instanceType));
1059 }
1060
1061 @Override
1062 public ImmutableSet<ConcreteType> getTypesToSkipForType(ConcreteType type) {
1063 return ImmutableSet.of(type);
1064 }
1065
1066 @Override public boolean isTypeToSkip(ConcreteType type) {
1067 // Skip anonymous object literals and enum types.
1068 return type.isInstance()
1069 && !(type.toInstance().isFunctionPrototype()
1070 || type.toInstance().instanceType.isInstanceType());
1071 }
1072
1073 @Override
1074 public ConcreteType restrictByNotNullOrUndefined(ConcreteType type) {
1075 // These are not represented in concrete types.
1076 return type;
1077 }
1078
1079 @Override
1080 public Iterable<ConcreteType> getTypeAlternatives(ConcreteType type) {
1081 if (type.isUnion()) {
1082 return ((ConcreteUnionType) type).getAlternatives();
1083 } else {
1084 return null;
1085 }
1086 }
1087
1088 @Override public ConcreteType getTypeWithProperty(String field,
1089 ConcreteType type) {
1090 if (type.isInstance()) {
1091 ConcreteInstanceType instanceType = (ConcreteInstanceType) type;
1092 return instanceType.getInstanceTypeWithProperty(field);
1093 } else if (type.isFunction()) {
1094 if ("prototype".equals(field)
1095 || codingConvention.isSuperClassReference(field)) {
1096 return type;
1097 }
1098 } else if (type.isNone()) {
1099 // If the receiver is none, then this code is never reached. We will
1100 // return a new fake type to ensure that this access is renamed
1101 // differently from any other, so it can be easily removed.
1102 return new ConcreteUniqueType(++nextUniqueId);
1103 } else if (type.isUnion()) {
1104 // If only one has the property, return that.
1105 for (ConcreteType t : ((ConcreteUnionType) type).getAlternatives()) {
1106 ConcreteType ret = getTypeWithProperty(field, t);
1107 if (ret != null) {
1108 return ret;
1109 }
1110 }
1111 }
1112 return null;
1113 }
1114
1115 @Override public ConcreteType getInstanceFromPrototype(ConcreteType type) {
1116 if (type.isInstance()) {
1117 ConcreteInstanceType instanceType = (ConcreteInstanceType) type;
1118 if (instanceType.isFunctionPrototype()) {
1119 return instanceType.getConstructorType().getInstanceType();
1120 }
1121 }
1122 return null;
1123 }
1124
1125 @Override
1126 public void recordInterfaces(ConcreteType type, ConcreteType relatedType,
1127 DisambiguateProperties<ConcreteType>.Property p) {
1128 // No need to record interfaces when using concrete types.
1129 }
1130 }
1131 }