Debian Codegraph @

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

raw symbols SCIP
1 /*
2 * Copyright 2004 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.Preconditions;
20 import com.google.common.collect.ImmutableMap;
21 import com.google.common.collect.Sets;
22 import com.google.javascript.jscomp.AbstractCompiler.LifeCycleStage;
23 import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback;
24 import com.google.javascript.jscomp.NodeTraversal.ScopedCallback;
25 import com.google.javascript.jscomp.graph.Graph.GraphEdge;
26 import com.google.javascript.jscomp.graph.LinkedUndirectedGraph;
27 import com.google.javascript.jscomp.graph.UndiGraph;
28 import com.google.javascript.jscomp.graph.UndiGraph.UndiGraphEdge;
29 import com.google.javascript.jscomp.graph.UndiGraph.UndiGraphNode;
30 import com.google.javascript.rhino.IR;
31 import com.google.javascript.rhino.Node;
32 import com.google.javascript.rhino.Token;
33 import com.google.javascript.rhino.TokenStream;
34
35 import java.util.ArrayList;
36 import java.util.Arrays;
37 import java.util.Collection;
38 import java.util.Comparator;
39 import java.util.HashMap;
40 import java.util.HashSet;
41 import java.util.Iterator;
42 import java.util.List;
43 import java.util.Map;
44 import java.util.Set;
45 import java.util.TreeSet;
46
47 import javax.annotation.Nullable;
48
49 /**
50 * RenameProperties renames properties (including methods) of all JavaScript
51 * objects. This includes prototypes, functions, object literals, etc.
52 *
53 * <p> If provided a VariableMap of previously used names, it tries to reuse
54 * those names.
55 *
56 * <p> To prevent a property from getting renamed you may extern it (add it to
57 * your externs file) or put it in quotes.
58 *
59 * <p> To avoid run-time JavaScript errors, use quotes when accessing properties
60 * that are defined using quotes.
61 *
62 * <pre>
63 * var a = {'myprop': 0}, b = a['myprop']; // correct
64 * var x = {'myprop': 0}, y = x.myprop; // incorrect
65 * </pre>
66 *
67 */
68 class RenameProperties implements CompilerPass {
69
70 private final AbstractCompiler compiler;
71 private final boolean generatePseudoNames;
72
73 /** Property renaming map from a previous compilation. */
74 private final VariableMap prevUsedPropertyMap;
75
76 private final List<Node> stringNodesToRename = new ArrayList<Node>();
77 private final Map<Node, Node> callNodeToParentMap =
78 new HashMap<Node, Node>();
79 private final char[] reservedCharacters;
80
81 // Map from property name to Property object
82 private final Map<String, Property> propertyMap =
83 new HashMap<String, Property>();
84
85 /**
86 * A graph of property affinity information.
87 *
88 * Suppose property X and Y are access in the same function N times.
89 *
90 * The graph would have X -> Y with the edge of N.
91 */
92 private final UndiGraph<Property, PropertyAffinity> affinityGraph;
93
94 // Property names that don't get renamed
95 private final Set<String> externedNames = new HashSet<String>(
96 Arrays.asList("prototype"));
97
98 // Names to which properties shouldn't be renamed, to avoid name conflicts
99 private final Set<String> quotedNames = new HashSet<String>();
100
101 private static final Comparator<Property> FREQUENCY_COMPARATOR =
102 new Comparator<Property>() {
103 @Override
104 public int compare(Property p1, Property p2) {
105
106 /**
107 * First a frequently used names would always be picked first.
108 */
109 if (p1.numOccurrences != p2.numOccurrences) {
110 return p2.numOccurrences - p1.numOccurrences;
111
112 /**
113 * If both properties are used equally frequent. We'll let the property
114 * with a high affinity score get a name first.
115 *
116 * see #computeAffinityScores() for how the score is computed.
117 */
118 } else if (p1.affinityScore != p2.affinityScore) {
119 return p2.affinityScore - p1.affinityScore;
120 }
121
122 /**
123 * Finally, for determinism, we compare them based on the old name.
124 */
125 return p1.oldName.compareTo(p2.oldName);
126 }
127 };
128
129 /**
130 * The name of a special function that this pass replaces. It takes one
131 * argument: a string literal containing one or more dot-separated JS
132 * identifiers. This pass will replace them as though they were JS property
133 * references. Here are two examples:
134 * JSCompiler_renameProperty('propertyName') -> 'jYq'
135 * JSCompiler_renameProperty('myProp.nestedProp.innerProp') -> 'e4.sW.C$'
136 */
137 static final String RENAME_PROPERTY_FUNCTION_NAME =
138 "JSCompiler_renameProperty";
139
140 static final DiagnosticType BAD_CALL = DiagnosticType.error(
141 "JSC_BAD_RENAME_PROPERTY_FUNCTION_NAME_CALL",
142 "Bad " + RENAME_PROPERTY_FUNCTION_NAME + " call - " +
143 "argument must be a string literal");
144
145 static final DiagnosticType BAD_ARG = DiagnosticType.error(
146 "JSC_BAD_RENAME_PROPERTY_FUNCTION_NAME_ARG",
147 "Bad " + RENAME_PROPERTY_FUNCTION_NAME + " argument - " +
148 "'{0}' is not a valid JavaScript identifier");
149
150 /**
151 * Creates an instance.
152 *
153 * @param compiler The JSCompiler
154 * @param affinity Optimize for affinity information.
155 * @param generatePseudoNames Generate pseudo names. e.g foo -> $foo$ instead
156 * of compact obfuscated names. This is used for debugging.
157 */
158 RenameProperties(AbstractCompiler compiler, boolean affinity,
159 boolean generatePseudoNames) {
160 this(compiler, affinity, generatePseudoNames, null, null);
161 }
162
163 /**
164 * Creates an instance.
165 *
166 * @param compiler The JSCompiler.
167 * @param affinity Optimize for affinity information.
168 * @param generatePseudoNames Generate pseudo names. e.g foo -> $foo$ instead
169 * of compact obfuscated names. This is used for debugging.
170 * @param prevUsedPropertyMap The property renaming map used in a previous
171 * compilation.
172 */
173 RenameProperties(AbstractCompiler compiler, boolean affinity,
174 boolean generatePseudoNames, VariableMap prevUsedPropertyMap) {
175 this(compiler, affinity, generatePseudoNames, prevUsedPropertyMap, null);
176 }
177
178 /**
179 * Creates an instance.
180 *
181 * @param compiler The JSCompiler.
182 * @param affinity Optimize for affinity information.
183 * @param generatePseudoNames Generate pseudo names. e.g foo -> $foo$ instead
184 * of compact obfuscated names. This is used for debugging.
185 * @param prevUsedPropertyMap The property renaming map used in a previous
186 * compilation.
187 * @param reservedCharacters If specified these characters won't be used in
188 * generated names
189 */
190 RenameProperties(AbstractCompiler compiler,
191 boolean affinity,
192 boolean generatePseudoNames,
193 VariableMap prevUsedPropertyMap,
194 @Nullable char[] reservedCharacters) {
195 this.compiler = compiler;
196 this.generatePseudoNames = generatePseudoNames;
197 this.prevUsedPropertyMap = prevUsedPropertyMap;
198 this.reservedCharacters = reservedCharacters;
199 if (affinity) {
200 this.affinityGraph = LinkedUndirectedGraph.createWithoutAnnotations();
201 } else {
202 this.affinityGraph = null;
203 }
204 }
205
206 @Override
207 public void process(Node externs, Node root) {
208 Preconditions.checkState(compiler.getLifeCycleStage().isNormalized());
209
210 NodeTraversal.traverse(compiler, externs, new ProcessExterns());
211 NodeTraversal.traverse(compiler, root, new ProcessProperties());
212
213 Set<String> reservedNames =
214 new HashSet<String>(externedNames.size() + quotedNames.size());
215 reservedNames.addAll(externedNames);
216 reservedNames.addAll(quotedNames);
217
218 // First, try and reuse as many property names from the previous compilation
219 // as possible.
220 if (prevUsedPropertyMap != null) {
221 reusePropertyNames(reservedNames, propertyMap.values());
222 }
223
224 compiler.addToDebugLog("JS property assignments:");
225 if (affinityGraph != null) {
226 computeAffinityScores();
227 }
228
229 // Assign names, sorted by descending frequency to minimize code size.
230 Set<Property> propsByFreq = new TreeSet<Property>(FREQUENCY_COMPARATOR);
231 propsByFreq.addAll(propertyMap.values());
232 generateNames(propsByFreq, reservedNames);
233
234 // Update the string nodes.
235 boolean changed = false;
236 for (Node n : stringNodesToRename) {
237 String oldName = n.getString();
238 Property p = propertyMap.get(oldName);
239 if (p != null && p.newName != null) {
240 Preconditions.checkState(oldName.equals(p.oldName));
241 n.setString(p.newName);
242 changed = changed || !p.newName.equals(oldName);
243 }
244 }
245
246 // Update the call nodes.
247 for (Map.Entry<Node, Node> nodeEntry : callNodeToParentMap.entrySet()) {
248 Node parent = nodeEntry.getValue();
249 Node firstArg = nodeEntry.getKey().getFirstChild().getNext();
250 StringBuilder sb = new StringBuilder();
251 for (String oldName : firstArg.getString().split("[.]")) {
252 Property p = propertyMap.get(oldName);
253 String replacement;
254 if (p != null && p.newName != null) {
255 Preconditions.checkState(oldName.equals(p.oldName));
256 replacement = p.newName;
257 } else {
258 replacement = oldName;
259 }
260 if (sb.length() > 0) {
261 sb.append('.');
262 }
263 sb.append(replacement);
264 }
265 parent.replaceChild(nodeEntry.getKey(), IR.string(sb.toString()));
266 changed = true;
267 }
268
269 if (changed) {
270 compiler.reportCodeChange();
271 }
272
273 compiler.setLifeCycleStage(LifeCycleStage.NORMALIZED_OBFUSCATED);
274 }
275
276 /**
277 * Runs through the list of properties and renames as many as possible with
278 * names from the previous compilation. Also, updates reservedNames with the
279 * set of reused names.
280 * @param reservedNames Reserved names to use during renaming.
281 * @param allProps Properties to rename.
282 */
283 private void reusePropertyNames(Set<String> reservedNames,
284 Collection<Property> allProps) {
285 for (Property prop : allProps) {
286 // Check if this node can reuse a name from a previous compilation - if
287 // it can set the newName for the property too.
288 String prevName = prevUsedPropertyMap.lookupNewName(prop.oldName);
289 if (!generatePseudoNames && prevName != null) {
290 // We can reuse prevName if it's not reserved.
291 if (reservedNames.contains(prevName)) {
292 continue;
293 }
294
295 prop.newName = prevName;
296 reservedNames.add(prevName);
297 }
298 }
299 }
300
301 /**
302 * A X property gets an affinity score:
303 *
304 * score = sum (# of times X appears Y * frequency(Y)) for all Y where
305 * frequency(Y) > frequency (X).
306 *
307 * This way a property would have a name closer to all high frequency names.
308 * Also two property of the same frequency would have very close names if
309 * they always appear together.
310 */
311 private void computeAffinityScores() {
312 for (Property p : propertyMap.values()) {
313 UndiGraphNode<Property, PropertyAffinity> node =
314 affinityGraph.getUndirectedGraphNode(p);
315
316 int affinityScore = 0;
317 for (Iterator<UndiGraphEdge<Property, PropertyAffinity>> edgeIterator =
318 node.getNeighborEdgesIterator(); edgeIterator.hasNext();) {
319 UndiGraphEdge<Property,PropertyAffinity> edge = edgeIterator.next();
320 affinityScore += edge.getValue().affinity +
321 (node == edge.getNodeA() ?
322 edge.getNodeB().getValue().numOccurrences :
323 edge.getNodeA().getValue().numOccurrences);
324 }
325 node.getValue().affinityScore = affinityScore;
326 }
327 }
328
329 /**
330 * Generates new names for properties.
331 *
332 * @param props Properties to generate new names for
333 * @param reservedNames A set of names to which properties should not be
334 * renamed
335 */
336 private void generateNames(Set<Property> props, Set<String> reservedNames) {
337 NameGenerator nameGen = new NameGenerator(
338 reservedNames, "", reservedCharacters);
339 for (Property p : props) {
340 if (generatePseudoNames) {
341 p.newName = "$" + p.oldName + "$";
342 } else {
343 // If we haven't already given this property a reusable name.
344 if (p.newName == null) {
345 p.newName = nameGen.generateNextName();
346 }
347 }
348 reservedNames.add(p.newName);
349 compiler.addToDebugLog(p.oldName + " => " + p.newName);
350 }
351 }
352
353 /**
354 * Gets the property renaming map (the "answer key").
355 *
356 * @return A mapping from original names to new names
357 */
358 VariableMap getPropertyMap() {
359 ImmutableMap.Builder<String, String> map = ImmutableMap.builder();
360 for (Property p : propertyMap.values()) {
361 if (p.newName != null) {
362 map.put(p.oldName, p.newName);
363 }
364 }
365 return new VariableMap(map.build());
366 }
367
368 // -------------------------------------------------------------------------
369
370 /**
371 * A traversal callback that collects externed property names.
372 */
373 private class ProcessExterns extends AbstractPostOrderCallback {
374
375 @Override
376 public void visit(NodeTraversal t, Node n, Node parent) {
377 switch (n.getType()) {
378 case Token.GETPROP:
379 Node dest = n.getFirstChild().getNext();
380 if (dest.isString()) {
381 externedNames.add(dest.getString());
382 }
383 break;
384 case Token.OBJECTLIT:
385 for (Node child = n.getFirstChild();
386 child != null;
387 child = child.getNext()) {
388 externedNames.add(child.getString());
389 }
390 break;
391 }
392 }
393 }
394
395
396 // -------------------------------------------------------------------------
397
398 /**
399 * A traversal callback that collects property names and counts how
400 * frequently each property name occurs.
401 */
402 private class ProcessProperties extends AbstractPostOrderCallback implements
403 ScopedCallback {
404
405 private Set<Property> currentHighAffinityProperties = null;
406
407 @Override
408 public void visit(NodeTraversal t, Node n, Node parent) {
409 switch (n.getType()) {
410 case Token.GETPROP:
411 Node propNode = n.getFirstChild().getNext();
412 if (propNode.isString()) {
413 maybeMarkCandidate(propNode);
414 }
415 break;
416 case Token.OBJECTLIT:
417 for (Node key = n.getFirstChild(); key != null; key = key.getNext()) {
418 if (!key.isQuotedString()) {
419 maybeMarkCandidate(key);
420 } else {
421 // Ensure that we never rename some other property in a way
422 // that could conflict with this quoted key.
423 quotedNames.add(key.getString());
424 }
425 }
426 break;
427 case Token.GETELEM:
428 // If this is a quoted property access (e.g. x['myprop']), we need to
429 // ensure that we never rename some other property in a way that
430 // could conflict with this quoted name.
431 Node child = n.getLastChild();
432 if (child != null && child.isString()) {
433 quotedNames.add(child.getString());
434 }
435 break;
436 case Token.CALL:
437 // We replace a JSCompiler_renameProperty function call with a string
438 // containing the renamed property.
439 Node fnName = n.getFirstChild();
440 if (fnName.isName() &&
441 RENAME_PROPERTY_FUNCTION_NAME.equals(fnName.getString())) {
442 callNodeToParentMap.put(n, parent);
443 countCallCandidates(t, n);
444 }
445 break;
446 case Token.FUNCTION:
447 // We eliminate any stub implementations of JSCompiler_renameProperty
448 // that we encounter.
449 if (NodeUtil.isFunctionDeclaration(n)) {
450 String name = n.getFirstChild().getString();
451 if (RENAME_PROPERTY_FUNCTION_NAME.equals(name)) {
452 if (parent.isExprResult()) {
453 parent.detachFromParent();
454 } else {
455 parent.removeChild(n);
456 }
457 compiler.reportCodeChange();
458 }
459 } else if (parent.isName() &&
460 RENAME_PROPERTY_FUNCTION_NAME.equals(parent.getString())) {
461 Node varNode = parent.getParent();
462 if (varNode.isVar()) {
463 varNode.removeChild(parent);
464 if (!varNode.hasChildren()) {
465 varNode.detachFromParent();
466 }
467 compiler.reportCodeChange();
468 }
469 }
470 break;
471 }
472 }
473
474 /**
475 * If a property node is eligible for renaming, stashes a reference to it
476 * and increments the property name's access count.
477 *
478 * @param n The STRING node for a property
479 */
480 private void maybeMarkCandidate(Node n) {
481 String name = n.getString();
482 if (!externedNames.contains(name)) {
483 stringNodesToRename.add(n);
484 countPropertyOccurrence(name);
485 }
486 }
487
488 /**
489 * Counts references to property names that occur in a special function
490 * call.
491 *
492 * @param callNode The CALL node for a property
493 * @param t The traversal
494 */
495 private void countCallCandidates(NodeTraversal t, Node callNode) {
496 Node firstArg = callNode.getFirstChild().getNext();
497 if (!firstArg.isString()) {
498 t.report(callNode, BAD_CALL);
499 return;
500 }
501
502 for (String name : firstArg.getString().split("[.]")) {
503 if (!TokenStream.isJSIdentifier(name)) {
504 t.report(callNode, BAD_ARG, name);
505 continue;
506 }
507 if (!externedNames.contains(name)) {
508 countPropertyOccurrence(name);
509 }
510 }
511 }
512
513 /**
514 * Increments the occurrence count for a property name.
515 *
516 * @param name The property name
517 */
518 private void countPropertyOccurrence(String name) {
519 Property prop = propertyMap.get(name);
520 if (prop == null) {
521 prop = new Property(name);
522 propertyMap.put(name, prop);
523 if (affinityGraph != null) {
524 affinityGraph.createNode(prop);
525 }
526 }
527 prop.numOccurrences++;
528 if (currentHighAffinityProperties != null) {
529 currentHighAffinityProperties.add(prop);
530 }
531 }
532
533 @Override
534 public void enterScope(NodeTraversal t) {
535 if (!t.inGlobalScope() && t.getScope().getParent().isGlobal()) {
536 currentHighAffinityProperties = Sets.newHashSet();
537 }
538 }
539
540 @Override
541 public void exitScope(NodeTraversal t) {
542 if (affinityGraph == null) {
543 return;
544 }
545 if (!t.inGlobalScope() && t.getScope().getParent().isGlobal()) {
546 for (Property p1 : currentHighAffinityProperties) {
547 for (Property p2 : currentHighAffinityProperties) {
548 if (p1.oldName.compareTo(p2.oldName) < 0) {
549 GraphEdge<Property,PropertyAffinity> edge =
550 affinityGraph.getFirstEdge(p1, p2);
551 if (edge == null) {
552 affinityGraph.connect(p1, new PropertyAffinity(1), p2);
553 } else {
554 edge.getValue().increase();
555 }
556 }
557 }
558 }
559 currentHighAffinityProperties = null;
560 }
561 }
562 }
563
564 // -------------------------------------------------------------------------
565
566 /**
567 * Encapsulates the information needed for renaming a property.
568 */
569 private class Property {
570 final String oldName;
571 String newName;
572 int numOccurrences;
573 int affinityScore = 0;
574
575 Property(String name) {
576 this.oldName = name;
577 }
578 }
579
580 private class PropertyAffinity {
581 // This will forever be zero if no affinity information was gathered.
582 private int affinity = 0;
583
584 private PropertyAffinity(int affinity) {
585 this.affinity = affinity;
586 }
587
588 private void increase() {
589 affinity++;
590 }
591 }
592 }