Debian Codegraph @

src/com/google/javascript/jscomp/RenameVars.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.ArrayListMultimap;
21 import com.google.common.collect.ImmutableMap;
22 import com.google.common.collect.Maps;
23 import com.google.common.collect.Sets;
24 import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback;
25 import com.google.javascript.jscomp.NodeTraversal.ScopedCallback;
26 import com.google.javascript.jscomp.Scope.Var;
27 import com.google.javascript.rhino.Node;
28 import java.util.ArrayList;
29 import java.util.Comparator;
30 import java.util.HashMap;
31 import java.util.HashSet;
32 import java.util.Iterator;
33 import java.util.List;
34 import java.util.Map;
35 import java.util.Set;
36 import java.util.SortedSet;
37 import java.util.TreeSet;
38
39 import javax.annotation.Nullable;
40
41 /**
42 * RenameVars renames all the variables names into short names, to reduce code
43 * size and also to obfuscate the code.
44 *
45 */
46 final class RenameVars implements CompilerPass {
47 private final AbstractCompiler compiler;
48
49 /** List of global NAME nodes */
50 private final ArrayList<Node> globalNameNodes = new ArrayList<Node>();
51
52 /** List of local NAME nodes */
53 private final ArrayList<Node> localNameNodes = new ArrayList<Node>();
54
55 /**
56 * Maps a name node to its pseudo name, null if we are not generating so
57 * there will be no overhead unless we are debugging.
58 */
59 private final Map<Node, String> pseudoNameMap;
60
61 /** Set of extern variable names */
62 private final Set<String> externNames = new HashSet<String>();
63
64 /** Set of reserved variable names */
65 private final Set<String> reservedNames;
66
67 /** The renaming map */
68 private final Map<String, String> renameMap = new HashMap<String, String>();
69
70 /** The previously used rename map. */
71 private final VariableMap prevUsedRenameMap;
72
73 /** The global name prefix */
74 private final String prefix;
75
76 /** Counter for each assignment */
77 private int assignmentCount = 0;
78
79 /** Logs all name assignments */
80 private StringBuilder assignmentLog;
81
82 // Logic for bleeding functions, where the name leaks into the outer
83 // scope on IE but not on other browsers.
84 private Set<Var> localBleedingFunctions = Sets.newHashSet();
85 private ArrayListMultimap<Scope, Var> localBleedingFunctionsPerScope =
86 ArrayListMultimap.create();
87
88 class Assignment {
89 final String oldName;
90 final int orderOfOccurrence;
91 String newName;
92 int count; // Number of times this is referenced
93
94 Assignment(String name) {
95 this.oldName = name;
96 this.newName = null;
97 this.count = 0;
98
99 // Represents the order at which a symbol appears in the source.
100 this.orderOfOccurrence = assignmentCount++;
101 }
102
103 /**
104 * Assigns the new name.
105 */
106 void setNewName(String newName) {
107 Preconditions.checkState(this.newName == null);
108 this.newName = newName;
109 }
110 }
111
112 /** Maps an old name to a new name assignment */
113 private final Map<String, Assignment> assignments =
114 new HashMap<String, Assignment>();
115
116 /** Whether renaming should apply to local variables only. */
117 private final boolean localRenamingOnly;
118
119 /**
120 * Whether function expression names should be preserved. Typically, for
121 * debugging purposes.
122 *
123 * @see NameAnonymousFunctions
124 */
125 private boolean preserveFunctionExpressionNames;
126
127 private final boolean shouldShadow;
128
129 /** Characters that shouldn't be used in variable names. */
130 private final char[] reservedCharacters;
131
132 /** A prefix to distinguish temporary local names from global names */
133 // TODO(user): No longer needs to be public when shadowing doesn't use it.
134 public static final String LOCAL_VAR_PREFIX = "L ";
135
136 RenameVars(AbstractCompiler compiler, String prefix,
137 boolean localRenamingOnly, boolean preserveFunctionExpressionNames,
138 boolean generatePseudoNames, boolean shouldShadow,
139 VariableMap prevUsedRenameMap,
140 @Nullable char[] reservedCharacters,
141 @Nullable Set<String> reservedNames) {
142 this.compiler = compiler;
143 this.prefix = prefix == null ? "" : prefix;
144 this.localRenamingOnly = localRenamingOnly;
145 this.preserveFunctionExpressionNames = preserveFunctionExpressionNames;
146 if (generatePseudoNames) {
147 this.pseudoNameMap = Maps.newHashMap();
148 } else {
149 this.pseudoNameMap = null;
150 }
151 this.prevUsedRenameMap = prevUsedRenameMap;
152 this.reservedCharacters = reservedCharacters;
153 this.shouldShadow = shouldShadow;
154 if (reservedNames == null) {
155 this.reservedNames = Sets.newHashSet();
156 } else {
157 this.reservedNames = Sets.newHashSet(reservedNames);
158 }
159 }
160
161 /**
162 * Iterate through the nodes, collect all the NAME nodes that need to be
163 * renamed, and count how many times each variable name is referenced.
164 *
165 * There are 2 passes:
166 * - externs: keep track of the global vars in the externNames_ map.
167 * - source: keep track of all name references in globalNameNodes_, and
168 * localNameNodes_.
169 *
170 * To get shorter local variable renaming, we rename local variables to a
171 * temporary name "LOCAL_VAR_PREFIX + index" where index is the index of the
172 * variable declared in the local scope stack.
173 * e.g.
174 * Foo(fa, fb) {
175 * var c = function(d, e) { return fa; }
176 * }
177 * The indexes are: fa:0, fb:1, c:2, d:3, e:4
178 *
179 * In that way, local variable names are reused in each global function.
180 * e.g. the final code might look like
181 * function x(a,b) { ... }
182 * function y(a,b,c) { ... }
183 */
184 class ProcessVars extends AbstractPostOrderCallback
185 implements ScopedCallback {
186 private final boolean isExternsPass_;
187
188 ProcessVars(boolean isExterns) {
189 isExternsPass_ = isExterns;
190 }
191
192 @Override
193 public void enterScope(NodeTraversal t) {
194 if (t.inGlobalScope()) return;
195
196 Iterator<Var> it = t.getScope().getVars();
197 while (it.hasNext()) {
198 Var current = it.next();
199 if (current.isBleedingFunction()) {
200 localBleedingFunctions.add(current);
201 localBleedingFunctionsPerScope.put(
202 t.getScope().getParent(), current);
203 }
204 }
205 }
206
207 @Override
208 public void exitScope(NodeTraversal t) {}
209
210 @Override
211 public void visit(NodeTraversal t, Node n, Node parent) {
212 if (!n.isName()) {
213 return;
214 }
215
216 String name = n.getString();
217
218 // Ignore anonymous functions
219 if (name.length() == 0) {
220 return;
221 }
222
223 // Is this local or Global?
224 // Bleeding functions should be treated as part of their outer
225 // scope, because IE has bugs in how it handles bleeding
226 // functions.
227 Scope.Var var = t.getScope().getVar(name);
228 boolean local = (var != null) && var.isLocal() &&
229 (!var.scope.getParent().isGlobal() ||
230 !var.isBleedingFunction());
231
232 // Are we renaming global variables?
233 if (!local && localRenamingOnly) {
234 reservedNames.add(name);
235 return;
236 }
237
238 // Are we renaming function expression names?
239 if (preserveFunctionExpressionNames && var != null
240 && NodeUtil.isFunctionExpression(var.getParentNode())) {
241 reservedNames.add(name);
242 return;
243 }
244
245 // Check if we can rename this.
246 if (!okToRenameVar(name, local)) {
247 if (local) {
248 // Blindly de-uniquify for the Prototype library for issue 103.
249 String newName = MakeDeclaredNamesUnique.ContextualRenameInverter
250 .getOrginalName(name);
251 if (!newName.equals(name)) {
252 n.setString(newName);
253 }
254 }
255 return;
256 }
257
258 if (isExternsPass_) {
259 // Keep track of extern globals.
260 if (!local) {
261 externNames.add(name);
262 }
263 return;
264 }
265
266 if (pseudoNameMap != null) {
267 recordPseudoName(n);
268 }
269
270 if (local) {
271 // Local var: assign a new name
272 String tempName = LOCAL_VAR_PREFIX + getLocalVarIndex(var);
273 incCount(tempName);
274 localNameNodes.add(n);
275 n.setString(tempName);
276 } else if (var != null) { // Not an extern
277 // If it's global, increment global count
278 incCount(name);
279 globalNameNodes.add(n);
280 }
281 }
282
283 // Increment count of an assignment
284 void incCount(String name) {
285 Assignment s = assignments.get(name);
286 if (s == null) {
287 s = new Assignment(name);
288 assignments.put(name, s);
289 }
290 s.count++;
291 }
292 }
293
294 /**
295 * Sorts Assignment objects by their count, breaking ties by their order of
296 * occurrence in the source to ensure a deterministic total ordering.
297 */
298 private static final Comparator<Assignment> FREQUENCY_COMPARATOR =
299 new Comparator<Assignment>() {
300 @Override
301 public int compare(Assignment a1, Assignment a2) {
302 if (a1.count != a2.count) {
303 return a2.count - a1.count;
304 }
305 // Break a tie using the order in which the variable first appears in
306 // the source.
307 return ORDER_OF_OCCURRENCE_COMPARATOR.compare(a1, a2);
308 }
309 };
310
311 /**
312 * Sorts Assignment objects by the order the variable name first appears in
313 * the source.
314 */
315 private static final Comparator<Assignment> ORDER_OF_OCCURRENCE_COMPARATOR =
316 new Comparator<Assignment>() {
317 @Override
318 public int compare(Assignment a1, Assignment a2) {
319 return a1.orderOfOccurrence - a2.orderOfOccurrence;
320 }
321 };
322
323 @Override
324 public void process(Node externs, Node root) {
325 assignmentLog = new StringBuilder();
326
327 // Do variable reference counting.
328 NodeTraversal.traverse(compiler, externs, new ProcessVars(true));
329 NodeTraversal.traverse(compiler, root, new ProcessVars(false));
330
331 // Make sure that new names don't overlap with extern names.
332 reservedNames.addAll(externNames);
333
334 // Rename vars, sorted by frequency of occurrence to minimize code size.
335 SortedSet<Assignment> varsByFrequency =
336 new TreeSet<Assignment>(FREQUENCY_COMPARATOR);
337 varsByFrequency.addAll(assignments.values());
338
339 if (shouldShadow) {
340 new ShadowVariables(
341 compiler, assignments, varsByFrequency, pseudoNameMap).process(
342 externs, root);
343 }
344
345 // First try to reuse names from an earlier compilation.
346 if (prevUsedRenameMap != null) {
347 reusePreviouslyUsedVariableMap();
348 }
349
350 // Assign names, sorted by descending frequency to minimize code size.
351 assignNames(varsByFrequency);
352
353 boolean changed = false;
354
355 // Rename the globals!
356 for (Node n : globalNameNodes) {
357 String newName = getNewGlobalName(n);
358 // Note: if newName is null, then oldName is an extern.
359 if (newName != null) {
360 n.setString(newName);
361 changed = true;
362 }
363 }
364
365 // Rename the locals!
366 for (Node n : localNameNodes) {
367 String newName = getNewLocalName(n);
368 if (newName != null) {
369 n.setString(newName);
370 changed = true;
371 }
372 }
373
374 if (changed) {
375 compiler.reportCodeChange();
376 }
377
378 // Lastly, write the name assignments to the debug log.
379 compiler.addToDebugLog("JS var assignments:\n" + assignmentLog);
380 assignmentLog = null;
381 }
382
383 private String getNewGlobalName(Node n) {
384 String oldName = n.getString();
385 Assignment a = assignments.get(oldName);
386 if (a.newName != null && !a.newName.equals(oldName)) {
387 if (pseudoNameMap != null) {
388 return pseudoNameMap.get(n);
389 }
390 return a.newName;
391 } else {
392 return null;
393 }
394 }
395
396 private String getNewLocalName(Node n) {
397 String oldTempName = n.getString();
398 Assignment a = assignments.get(oldTempName);
399 if (!a.newName.equals(oldTempName)) {
400 if (pseudoNameMap != null) {
401 return pseudoNameMap.get(n);
402 }
403 return a.newName;
404 }
405 return null;
406 }
407
408 private void recordPseudoName(Node n) {
409 // Variable names should be in a different name space than
410 // property pseudo names.
411 pseudoNameMap.put(n, '$' + n.getString() + "$$" );
412 }
413
414 /**
415 * Runs through the assignments and reuses as many names as possible from the
416 * previously used variable map. Updates reservedNames with the set of names
417 * that were reused.
418 */
419 private void reusePreviouslyUsedVariableMap() {
420 // If prevUsedRenameMap had duplicate values then this pass would be
421 // non-deterministic.
422 // In such a case, the following will throw an IllegalArgumentException.
423 Preconditions.checkState(
424 prevUsedRenameMap.getNewNameToOriginalNameMap() instanceof Map);
425 for (Assignment a : assignments.values()) {
426 String prevNewName = prevUsedRenameMap.lookupNewName(a.oldName);
427 if (prevNewName == null || reservedNames.contains(prevNewName)) {
428 continue;
429 }
430
431 if (a.oldName.startsWith(LOCAL_VAR_PREFIX)
432 || (!externNames.contains(a.oldName)
433 && prevNewName.startsWith(prefix))) {
434 reservedNames.add(prevNewName);
435 finalizeNameAssignment(a, prevNewName);
436 }
437 }
438 }
439
440 /**
441 * Determines which new names to substitute for the original names.
442 */
443 private void assignNames(SortedSet<Assignment> varsToRename) {
444 NameGenerator globalNameGenerator =
445 new NameGenerator(reservedNames, prefix, reservedCharacters);
446
447 // Local variables never need a prefix.
448 NameGenerator localNameGenerator =
449 prefix.isEmpty() ? globalNameGenerator : new NameGenerator(
450 reservedNames, "", reservedCharacters);
451
452 // Generated names and the assignments for non-local vars.
453 List<Assignment> pendingAssignments = new ArrayList<Assignment>();
454 List<String> generatedNamesForAssignments = new ArrayList<String>();
455
456 for (Assignment a : varsToRename) {
457 if (a.newName != null) {
458 continue;
459 }
460
461 if (externNames.contains(a.oldName)) {
462 continue;
463 }
464
465 String newName;
466 if (a.oldName.startsWith(LOCAL_VAR_PREFIX)) {
467 // For local variable, we make the assignment right away.
468 newName = localNameGenerator.generateNextName();
469 finalizeNameAssignment(a, newName);
470 } else {
471 // For non-local variable, delay finalizing the name assignment
472 // until we know how many new names we'll have of length 2, 3, etc.
473 newName = globalNameGenerator.generateNextName();
474 pendingAssignments.add(a);
475 generatedNamesForAssignments.add(newName);
476 }
477 reservedNames.add(newName);
478 }
479
480 // Now that we have a list of generated names, and a list of variable
481 // Assignment objects, we assign the generated names to the vars as
482 // follows:
483 // 1) The most frequent vars get the shorter names.
484 // 2) If N number of vars are going to be assigned names of the same
485 // length, we assign the N names based on the order at which the vars
486 // first appear in the source. This makes the output somewhat less
487 // random, because symbols declared close together are assigned names
488 // that are quite similar. With this heuristic, the output is more
489 // compressible.
490 // For instance, the output may look like:
491 // var da = "..", ea = "..";
492 // function fa() { .. } function ga() { .. }
493
494 int numPendingAssignments = generatedNamesForAssignments.size();
495 for (int i = 0; i < numPendingAssignments;) {
496 SortedSet<Assignment> varsByOrderOfOccurrence =
497 new TreeSet<Assignment>(ORDER_OF_OCCURRENCE_COMPARATOR);
498
499 // Add k number of Assignment to the set, where k is the number of
500 // generated names of the same length.
501 int len = generatedNamesForAssignments.get(i).length();
502 for (int j = i; j < numPendingAssignments
503 && generatedNamesForAssignments.get(j).length() == len; j++) {
504 varsByOrderOfOccurrence.add(pendingAssignments.get(j));
505 }
506
507 // Now, make the assignments
508 for (Assignment a : varsByOrderOfOccurrence) {
509 finalizeNameAssignment(a, generatedNamesForAssignments.get(i));
510 ++i;
511 }
512 }
513 }
514
515 /**
516 * Makes a final name assignment.
517 */
518 private void finalizeNameAssignment(Assignment a, String newName) {
519 a.setNewName(newName);
520
521 // Keep track of the mapping
522 renameMap.put(a.oldName, newName);
523
524 // Log the mapping
525 assignmentLog.append(a.oldName).append(" => ").append(newName).append('\n');
526 }
527
528 /**
529 * Gets the variable map.
530 */
531 VariableMap getVariableMap() {
532 return new VariableMap(ImmutableMap.copyOf(renameMap));
533 }
534
535 /**
536 * Determines whether a variable name is okay to rename.
537 */
538 private boolean okToRenameVar(String name, boolean isLocal) {
539 return !compiler.getCodingConvention().isExported(name, isLocal);
540 }
541
542 /**
543 * Returns the index within the scope stack.
544 * e.g. function Foo(a) { var b; function c(d) { } }
545 * a = 0, b = 1, c = 2, d = 3
546 */
547 private int getLocalVarIndex(Var v) {
548 int num = v.index;
549 Scope s = v.scope.getParent();
550 if (s == null) {
551 throw new IllegalArgumentException("Var is not local");
552 }
553
554 boolean isBleedingIntoScope = s.getParent() != null &&
555 localBleedingFunctions.contains(v);
556
557 while (s.getParent() != null) {
558 if (isBleedingIntoScope) {
559 num += localBleedingFunctionsPerScope.get(s).indexOf(v) + 1;
560 isBleedingIntoScope = false;
561 } else {
562 num += localBleedingFunctionsPerScope.get(s).size();
563 }
564
565 num += s.getVarCount();
566 s = s.getParent();
567 }
568 return num;
569 }
570 }