Debian Codegraph @

src/com/google/javascript/jscomp/AmbiguateProperties.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 com.google.common.base.Joiner;
20 import com.google.common.base.Preconditions;
21 import com.google.common.collect.BiMap;
22 import com.google.common.collect.HashBiMap;
23 import com.google.common.collect.Lists;
24 import com.google.common.collect.Maps;
25 import com.google.common.collect.Sets;
26 import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback;
27 import com.google.javascript.jscomp.TypeValidator.TypeMismatch;
28 import com.google.javascript.jscomp.graph.AdjacencyGraph;
29 import com.google.javascript.jscomp.graph.Annotation;
30 import com.google.javascript.jscomp.graph.GraphColoring;
31 import com.google.javascript.jscomp.graph.GraphColoring.GreedyGraphColoring;
32 import com.google.javascript.jscomp.graph.GraphNode;
33 import com.google.javascript.jscomp.graph.SubGraph;
34 import com.google.javascript.rhino.Node;
35 import com.google.javascript.rhino.Token;
36 import com.google.javascript.rhino.jstype.FunctionType;
37 import com.google.javascript.rhino.jstype.JSType;
38 import com.google.javascript.rhino.jstype.JSTypeNative;
39 import com.google.javascript.rhino.jstype.JSTypeRegistry;
40 import com.google.javascript.rhino.jstype.ObjectType;
41
42 import java.util.BitSet;
43 import java.util.Collection;
44 import java.util.Comparator;
45 import java.util.HashSet;
46 import java.util.List;
47 import java.util.Map;
48 import java.util.Set;
49 import java.util.TreeSet;
50 import java.util.logging.Logger;
51
52 /**
53 * Renames unrelated properties to the same name, using type information.
54 * This allows better compression as more properties can be given short names.
55 *
56 * <p>Properties are considered unrelated if they are never referenced from the
57 * same type or from a subtype of each others' types, thus this pass is only
58 * effective if type checking is enabled.
59 *
60 * Example:
61 * <code>
62 * Foo.fooprop = 0;
63 * Foo.fooprop2 = 0;
64 * Bar.barprop = 0;
65 * </code>
66 *
67 * becomes:
68 *
69 * <code>
70 * Foo.a = 0;
71 * Foo.b = 0;
72 * Bar.a = 0;
73 * </code>
74 *
75 */
76 class AmbiguateProperties implements CompilerPass {
77 private static final Logger logger = Logger.getLogger(
78 AmbiguateProperties.class.getName());
79
80 private final AbstractCompiler compiler;
81
82 private final List<Node> stringNodesToRename = Lists.newArrayList();
83 private final char[] reservedCharacters;
84
85 /** Map from property name to Property object */
86 private final Map<String, Property> propertyMap = Maps.newHashMap();
87
88 /** Property names that don't get renamed */
89 private final Set<String> externedNames = Sets.newHashSet();
90
91 /** Names to which properties shouldn't be renamed, to avoid name conflicts */
92 private final Set<String> quotedNames = Sets.newHashSet();
93
94 /** Map from original property name to new name. */
95 private final Map<String, String> renamingMap = Maps.newHashMap();
96
97 /**
98 * Sorts Property objects by their count, breaking ties alphabetically to
99 * ensure a deterministic total ordering.
100 */
101 private static final Comparator<Property> FREQUENCY_COMPARATOR =
102 new Comparator<Property>() {
103 @Override
104 public int compare(Property p1, Property p2) {
105 if (p1.numOccurrences != p2.numOccurrences) {
106 return p2.numOccurrences - p1.numOccurrences;
107 }
108 return p1.oldName.compareTo(p2.oldName);
109 }
110 };
111
112 /** A map from JSType to a unique representative Integer. */
113 private BiMap<JSType, Integer> intForType = HashBiMap.create();
114
115 /**
116 * A map from JSType to JSTypeBitSet representing the types related
117 * to the type.
118 */
119 private Map<JSType, JSTypeBitSet> relatedBitsets = Maps.newHashMap();
120
121 /** A set of types that invalidate properties from ambiguation. */
122 private final Set<JSType> invalidatingTypes;
123
124 /**
125 * Prefix of properties to skip renaming. These should be renamed in the
126 * RenameProperties pass.
127 */
128 static final String SKIP_PREFIX = "JSAbstractCompiler";
129
130 AmbiguateProperties(AbstractCompiler compiler,
131 char[] reservedCharacters) {
132 Preconditions.checkState(compiler.getLifeCycleStage().isNormalized());
133 this.compiler = compiler;
134 this.reservedCharacters = reservedCharacters;
135
136 JSTypeRegistry r = compiler.getTypeRegistry();
137 invalidatingTypes = Sets.newHashSet(
138 r.getNativeType(JSTypeNative.ALL_TYPE),
139 r.getNativeType(JSTypeNative.NO_OBJECT_TYPE),
140 r.getNativeType(JSTypeNative.NO_TYPE),
141 r.getNativeType(JSTypeNative.NULL_TYPE),
142 r.getNativeType(JSTypeNative.VOID_TYPE),
143 r.getNativeType(JSTypeNative.FUNCTION_FUNCTION_TYPE),
144 r.getNativeType(JSTypeNative.FUNCTION_INSTANCE_TYPE),
145 r.getNativeType(JSTypeNative.FUNCTION_PROTOTYPE),
146 r.getNativeType(JSTypeNative.GLOBAL_THIS),
147 r.getNativeType(JSTypeNative.OBJECT_TYPE),
148 r.getNativeType(JSTypeNative.OBJECT_PROTOTYPE),
149 r.getNativeType(JSTypeNative.OBJECT_FUNCTION_TYPE),
150 r.getNativeType(JSTypeNative.TOP_LEVEL_PROTOTYPE),
151 r.getNativeType(JSTypeNative.UNKNOWN_TYPE));
152
153 for (TypeMismatch mis : compiler.getTypeValidator().getMismatches()) {
154 addInvalidatingType(mis.typeA);
155 addInvalidatingType(mis.typeB);
156 }
157 }
158
159 /**
160 * Invalidates the given type, so that no properties on it will be renamed.
161 */
162 private void addInvalidatingType(JSType type) {
163 type = type.restrictByNotNullOrUndefined();
164 if (type.isUnionType()) {
165 for (JSType alt : type.toMaybeUnionType().getAlternates()) {
166 addInvalidatingType(alt);
167 }
168 }
169
170 invalidatingTypes.add(type);
171 ObjectType objType = ObjectType.cast(type);
172 if (objType != null && objType.isInstanceType()) {
173 invalidatingTypes.add(objType.getImplicitPrototype());
174 }
175 }
176
177 Map<String, String> getRenamingMap() {
178 return renamingMap;
179 }
180
181 /** Returns an integer that uniquely identifies a JSType. */
182 private int getIntForType(JSType type) {
183 if (intForType.containsKey(type)) {
184 return intForType.get(type).intValue();
185 }
186 int newInt = intForType.size() + 1;
187 intForType.put(type, newInt);
188 return newInt;
189 }
190
191 @Override
192 public void process(Node externs, Node root) {
193 NodeTraversal.traverse(compiler, externs, new ProcessExterns());
194 NodeTraversal.traverse(compiler, root, new ProcessProperties());
195
196 Set<String> reservedNames =
197 new HashSet<String>(externedNames.size() + quotedNames.size());
198 reservedNames.addAll(externedNames);
199 reservedNames.addAll(quotedNames);
200
201 int numRenamedPropertyNames = 0;
202 int numSkippedPropertyNames = 0;
203 Set<Property> propsByFreq = new TreeSet<Property>(FREQUENCY_COMPARATOR);
204 for (Property p : propertyMap.values()) {
205 if (!p.skipAmbiguating) {
206 ++numRenamedPropertyNames;
207 propsByFreq.add(p);
208 } else {
209 ++numSkippedPropertyNames;
210 reservedNames.add(p.oldName);
211 }
212 }
213
214 PropertyGraph graph = new PropertyGraph(Lists.newLinkedList(propsByFreq));
215 GraphColoring<Property, Void> coloring =
216 new GreedyGraphColoring<Property, Void>(graph, FREQUENCY_COMPARATOR);
217 int numNewPropertyNames = coloring.color();
218
219 NameGenerator nameGen = new NameGenerator(
220 reservedNames, "", reservedCharacters);
221 Map<Integer, String> colorMap = Maps.newHashMap();
222 for (int i = 0; i < numNewPropertyNames; ++i) {
223 colorMap.put(i, nameGen.generateNextName());
224 }
225 for (GraphNode<Property, Void> node : graph.getNodes()) {
226 node.getValue().newName = colorMap.get(node.getAnnotation().hashCode());
227 renamingMap.put(node.getValue().oldName, node.getValue().newName);
228 }
229
230 // Update the string nodes.
231 for (Node n : stringNodesToRename) {
232 String oldName = n.getString();
233 Property p = propertyMap.get(oldName);
234 if (p != null && p.newName != null) {
235 Preconditions.checkState(oldName.equals(p.oldName));
236 if (!p.newName.equals(oldName)) {
237 n.setString(p.newName);
238 compiler.reportCodeChange();
239 }
240 }
241 }
242
243 logger.fine("Collapsed " + numRenamedPropertyNames + " properties into "
244 + numNewPropertyNames + " and skipped renaming "
245 + numSkippedPropertyNames + " properties.");
246 }
247
248 private BitSet getRelatedTypesOnNonUnion(JSType type) {
249 // All of the types we encounter should have been added to the
250 // relatedBitsets via computeRelatedTypes.
251 if (relatedBitsets.containsKey(type)) {
252 return relatedBitsets.get(type);
253 } else {
254 throw new RuntimeException("Related types should have been computed for"
255 + " type: " + type + " but have not been.");
256 }
257 }
258
259 /**
260 * Adds subtypes - and implementors, in the case of interfaces - of the type
261 * to its JSTypeBitSet of related types. Union types are decomposed into their
262 * alternative types.
263 *
264 * <p>The 'is related to' relationship is best understood graphically. Draw an
265 * arrow from each instance type to the prototype of each of its
266 * subclass. Draw an arrow from each prototype to its instance type. Draw an
267 * arrow from each interface to its implementors. A type is related to another
268 * if there is a directed path in the graph from the type to other. Thus, the
269 * 'is related to' relationship is reflexive and transitive.
270 *
271 * <p>Example with Foo extends Bar which extends Baz and Bar implements I:
272 * <pre>
273 * Foo -> Bar.prototype -> Bar -> Baz.prototype -> Baz
274 * ^
275 * |
276 * I
277 * </pre>
278 *
279 * <p>Note that we don't need to correctly handle the relationships between
280 * functions, because the function type is invalidating (i.e. its properties
281 * won't be ambiguated).
282 */
283 private void computeRelatedTypes(JSType type) {
284 if (type.isUnionType()) {
285 type = type.restrictByNotNullOrUndefined();
286 if (type.isUnionType()) {
287 for (JSType alt : type.toMaybeUnionType().getAlternates()) {
288 computeRelatedTypes(alt);
289 }
290 return;
291 }
292 }
293
294 if (relatedBitsets.containsKey(type)) {
295 // We only need to generate the bit set once.
296 return;
297 }
298
299 JSTypeBitSet related = new JSTypeBitSet(intForType.size());
300 relatedBitsets.put(type, related);
301 related.set(getIntForType(type));
302
303 // A prototype is related to its instance.
304 if (type.isFunctionPrototypeType()) {
305 addRelatedInstance(((ObjectType) type).getOwnerFunction(), related);
306 return;
307 }
308
309 // An instance is related to its subclasses.
310 FunctionType constructor = type.toObjectType().getConstructor();
311 if (constructor != null && constructor.getSubTypes() != null) {
312 for (FunctionType subType : constructor.getSubTypes()) {
313 addRelatedInstance(subType, related);
314 }
315 }
316
317 // An interface is related to its implementors.
318 for (FunctionType implementor : compiler.getTypeRegistry()
319 .getDirectImplementors(type.toObjectType())) {
320 addRelatedInstance(implementor, related);
321 }
322 }
323
324 /**
325 * Adds the instance of the given constructor, its implicit prototype and all
326 * its related types to the given bit set.
327 */
328 private void addRelatedInstance(
329 FunctionType constructor, JSTypeBitSet related) {
330 // TODO(user): A constructor which doesn't have an instance type
331 // (e.g. it's missing the @constructor annotation) should be an invalidating
332 // type which doesn't reach this code path.
333 if (constructor.hasInstanceType()) {
334 ObjectType instanceType = constructor.getInstanceType();
335 related.set(getIntForType(instanceType.getImplicitPrototype()));
336 computeRelatedTypes(instanceType);
337 related.or(relatedBitsets.get(instanceType));
338 }
339 }
340
341 class PropertyGraph implements AdjacencyGraph<Property, Void> {
342 protected final Map<Property, PropertyGraphNode> nodes = Maps.newHashMap();
343
344 PropertyGraph(Collection<Property> props) {
345 for (Property prop : props) {
346 nodes.put(prop, new PropertyGraphNode(prop));
347 }
348 }
349
350 @Override
351 public List<GraphNode<Property, Void>> getNodes() {
352 return Lists.<GraphNode<Property, Void>>newArrayList(nodes.values());
353 }
354
355 @Override
356 public GraphNode<Property, Void> getNode(Property property) {
357 return nodes.get(property);
358 }
359
360 @Override
361 public SubGraph<Property, Void> newSubGraph() {
362 return new PropertySubGraph();
363 }
364
365 @Override
366 public void clearNodeAnnotations() {
367 for (PropertyGraphNode node : nodes.values()) {
368 node.setAnnotation(null);
369 }
370 }
371
372 @Override
373 public int getWeight(Property value) {
374 return value.numOccurrences;
375 }
376 }
377
378 /**
379 * A {@link SubGraph} that represents properties. The related types of
380 * the properties are used to efficiently calculate adjacency information.
381 */
382 class PropertySubGraph implements SubGraph<Property, Void> {
383 /** Types related to properties referenced in this subgraph. */
384 JSTypeBitSet relatedTypes = new JSTypeBitSet(intForType.size());
385
386 /**
387 * Returns true if prop is in an independent set from all properties in this
388 * sub graph. That is, if none of its related types intersects with the
389 * related types for this sub graph.
390 */
391 @Override
392 public boolean isIndependentOf(Property prop) {
393 return !relatedTypes.intersects(prop.relatedTypes);
394 }
395
396 /**
397 * Adds the node to the sub graph, adding all its related types to the
398 * related types for the sub graph.
399 */
400 @Override
401 public void addNode(Property prop) {
402 relatedTypes.or(prop.relatedTypes);
403 }
404 }
405
406 class PropertyGraphNode implements GraphNode<Property, Void> {
407 Property property;
408 protected Annotation annotation;
409
410 PropertyGraphNode(Property property) {
411 this.property = property;
412 }
413
414 @Override
415 public Property getValue() {
416 return property;
417 }
418
419 @Override
420 @SuppressWarnings("unchecked")
421 public <A extends Annotation> A getAnnotation() {
422 return (A) annotation;
423 }
424
425 @Override
426 public void setAnnotation(Annotation data) {
427 annotation = data;
428 }
429 }
430
431 /** A traversal callback that collects externed property names. */
432 private class ProcessExterns extends AbstractPostOrderCallback {
433 @Override
434 public void visit(NodeTraversal t, Node n, Node parent) {
435 switch (n.getType()) {
436 case Token.GETPROP:
437 Node dest = n.getFirstChild().getNext();
438 externedNames.add(dest.getString());
439 break;
440 case Token.OBJECTLIT:
441 for (Node child = n.getFirstChild();
442 child != null;
443 child = child.getNext()) {
444 // names: STRING, GET, SET
445 externedNames.add(child.getString());
446 }
447 break;
448 }
449 }
450 }
451
452 /** Finds all property references, recording the types on which they occur. */
453 private class ProcessProperties extends AbstractPostOrderCallback {
454 @Override
455 public void visit(NodeTraversal t, Node n, Node parent) {
456 switch (n.getType()) {
457 case Token.GETPROP: {
458 Node propNode = n.getFirstChild().getNext();
459 JSType jstype = getJSType(n.getFirstChild());
460 maybeMarkCandidate(propNode, jstype, t);
461 break;
462 }
463 case Token.OBJECTLIT:
464 // The children of an OBJECTLIT node are keys, where the values
465 // are the children of the keys.
466 for (Node key = n.getFirstChild(); key != null;
467 key = key.getNext()) {
468 // We only want keys that were unquoted.
469 // Keys are STRING, GET, SET
470 if (!key.isQuotedString()) {
471 JSType jstype = getJSType(n.getFirstChild());
472 maybeMarkCandidate(key, jstype, t);
473 } else {
474 // Ensure that we never rename some other property in a way
475 // that could conflict with this quoted key.
476 quotedNames.add(key.getString());
477 }
478 }
479 break;
480 case Token.GETELEM:
481 // If this is a quoted property access (e.g. x['myprop']), we need to
482 // ensure that we never rename some other property in a way that
483 // could conflict with this quoted name.
484 Node child = n.getLastChild();
485 if (child.isString()) {
486 quotedNames.add(child.getString());
487 }
488 break;
489 }
490 }
491
492 /**
493 * If a property node is eligible for renaming, stashes a reference to it
494 * and increments the property name's access count.
495 *
496 * @param n The STRING node for a property
497 * @param t The traversal
498 */
499 private void maybeMarkCandidate(Node n, JSType type, NodeTraversal t) {
500 String name = n.getString();
501 if (!externedNames.contains(name)) {
502 stringNodesToRename.add(n);
503 recordProperty(name, type);
504 }
505 }
506
507 private Property recordProperty(String name, JSType type) {
508 Property prop = getProperty(name);
509 prop.addType(type);
510 return prop;
511 }
512 }
513
514 /** Returns true if properties on this type should not be renamed. */
515 private boolean isInvalidatingType(JSType type) {
516 if (type.isUnionType()) {
517 type = type.restrictByNotNullOrUndefined();
518 if (type.isUnionType()) {
519 for (JSType alt : type.toMaybeUnionType().getAlternates()) {
520 if (isInvalidatingType(alt)) {
521 return true;
522 }
523 }
524 return false;
525 }
526 }
527 ObjectType objType = ObjectType.cast(type);
528 return objType == null
529 || invalidatingTypes.contains(objType)
530 || !objType.hasReferenceName()
531 || objType.isUnknownType()
532 || objType.isEmptyType() /* unresolved types */
533 || objType.isEnumType()
534 || objType.autoboxesTo() != null;
535 }
536
537 private Property getProperty(String name) {
538 Property prop = propertyMap.get(name);
539 if (prop == null) {
540 prop = new Property(name);
541 propertyMap.put(name, prop);
542 }
543 return prop;
544 }
545
546 /**
547 * This method gets the JSType from the Node argument and verifies that it is
548 * present.
549 */
550 private JSType getJSType(Node n) {
551 JSType jsType = n.getJSType();
552 if (jsType == null) {
553 // TODO(user): This branch indicates a compiler bug, not worthy of
554 // halting the compilation but we should log this and analyze to track
555 // down why it happens. This is not critical and will be resolved over
556 // time as the type checker is extended.
557 return compiler.getTypeRegistry().getNativeType(
558 JSTypeNative.UNKNOWN_TYPE);
559 } else {
560 return jsType;
561 }
562 }
563
564 /** Encapsulates the information needed for renaming a property. */
565 private class Property {
566 final String oldName;
567 String newName;
568 int numOccurrences;
569 boolean skipAmbiguating;
570 JSTypeBitSet relatedTypes = new JSTypeBitSet(intForType.size());
571
572 Property(String name) {
573 this.oldName = name;
574
575 // Properties with this suffix are handled in RenameProperties.
576 if (name.startsWith(SKIP_PREFIX)) {
577 skipAmbiguating = true;
578 }
579 }
580
581 /** Add this type to this property, calculating */
582 void addType(JSType newType) {
583 if (skipAmbiguating) {
584 return;
585 }
586
587 ++numOccurrences;
588
589 if (newType.isUnionType()) {
590 newType = newType.restrictByNotNullOrUndefined();
591 if (newType.isUnionType()) {
592 for (JSType alt : newType.toMaybeUnionType().getAlternates()) {
593 addNonUnionType(alt);
594 }
595 return;
596 }
597 }
598 addNonUnionType(newType);
599 }
600
601 private void addNonUnionType(JSType newType) {
602 if (skipAmbiguating || isInvalidatingType(newType)) {
603 skipAmbiguating = true;
604 return;
605 }
606
607 if (!relatedTypes.get(getIntForType(newType))) {
608 computeRelatedTypes(newType);
609 relatedTypes.or(getRelatedTypesOnNonUnion(newType));
610 }
611 }
612 }
613
614 // A BitSet that stores type info. Adds pretty-print routines.
615 private class JSTypeBitSet extends BitSet {
616 private static final long serialVersionUID = 1L;
617
618 private JSTypeBitSet(int size) {
619 super(size);
620 }
621
622 private JSTypeBitSet() {
623 super();
624 }
625
626 /**
627 * Pretty-printing, for diagnostic purposes.
628 */
629 @Override
630 public String toString() {
631 int from = 0;
632 int current = 0;
633 List<String> types = Lists.newArrayList();
634 while (-1 != (current = nextSetBit(from))) {
635 types.add(intForType.inverse().get(current).toString());
636 from = current + 1;
637 }
638 return Joiner.on(" && ").join(types);
639 }
640 }
641 }