Debian Codegraph @

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

raw symbols SCIP
1 /*
2 * Copyright 2009 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 com.google.common.base.Preconditions;
19 import com.google.common.base.Supplier;
20 import com.google.common.collect.HashMultiset;
21 import com.google.common.collect.ImmutableSet;
22 import com.google.common.collect.Lists;
23 import com.google.common.collect.Maps;
24 import com.google.common.collect.Multiset;
25 import com.google.common.collect.Sets;
26 import com.google.javascript.jscomp.NodeTraversal.ScopedCallback;
27 import com.google.javascript.jscomp.Scope.Var;
28 import com.google.javascript.rhino.Node;
29 import com.google.javascript.rhino.Token;
30 import com.google.javascript.rhino.TokenStream;
31
32 import java.util.ArrayDeque;
33 import java.util.Deque;
34 import java.util.Iterator;
35 import java.util.List;
36 import java.util.Map;
37 import java.util.Set;
38
39 /**
40 * Find all Functions, VARs, and Exception names and make them
41 * unique. Specifically, it will not modify object properties.
42 * @author [email protected] (John Lenz)
43 * TODO(johnlenz): Try to merge this with the ScopeCreator.
44 */
45 class MakeDeclaredNamesUnique
46 implements NodeTraversal.ScopedCallback {
47
48 // Arguments is special cased to handle cases where a local name shadows
49 // the arguments declaration.
50 public static final String ARGUMENTS = "arguments";
51
52 // The name stack is similar to how we model scopes but handles some
53 // additional cases that are not handled by the current Scope object.
54 // Specifically, a Scope currently has only two concepts of scope (global,
55 // and function local). But there are in reality a couple of additional
56 // case to worry about:
57 // catch expressions
58 // function expressions names
59 // Both belong to a scope by themselves.
60 private Deque<Renamer> nameStack = new ArrayDeque<Renamer>();
61 private final Renamer rootRenamer;
62
63 MakeDeclaredNamesUnique() {
64 this(new ContextualRenamer());
65 }
66
67 MakeDeclaredNamesUnique(Renamer renamer) {
68 this.rootRenamer = renamer;
69 }
70
71 static CompilerPass getContextualRenameInverter(AbstractCompiler compiler) {
72 return new ContextualRenameInverter(compiler);
73 }
74
75 @Override
76 public void enterScope(NodeTraversal t) {
77 Node declarationRoot = t.getScopeRoot();
78 Renamer renamer;
79 if (nameStack.isEmpty()) {
80 // If the contextual renamer is being used, the starting context can not
81 // be a function.
82 Preconditions.checkState(
83 !declarationRoot.isFunction() ||
84 !(rootRenamer instanceof ContextualRenamer));
85 Preconditions.checkState(t.inGlobalScope());
86 renamer = rootRenamer;
87 } else {
88 renamer = nameStack.peek().forChildScope();
89 }
90
91 if (!declarationRoot.isFunction()) {
92 // Add the block declarations
93 findDeclaredNames(declarationRoot, null, renamer);
94 }
95 nameStack.push(renamer);
96 }
97
98 @Override
99 public void exitScope(NodeTraversal t) {
100 if (!t.inGlobalScope()) {
101 nameStack.pop();
102 }
103 }
104
105 @Override
106 public boolean shouldTraverse(NodeTraversal t, Node n, Node parent) {
107
108 switch (n.getType()) {
109 case Token.FUNCTION:
110 {
111 // Add recursive function name, if needed.
112 // NOTE: "enterScope" is called after we need to pick up this name.
113 Renamer renamer = nameStack.peek().forChildScope();
114
115 // If needed, add the function recursive name.
116 String name = n.getFirstChild().getString();
117 if (name != null && !name.isEmpty() && parent != null
118 && !NodeUtil.isFunctionDeclaration(n)) {
119 renamer.addDeclaredName(name);
120 }
121
122 nameStack.push(renamer);
123 }
124 break;
125
126 case Token.PARAM_LIST: {
127 Renamer renamer = nameStack.peek().forChildScope();
128
129 // Add the function parameters
130 for (Node c = n.getFirstChild(); c != null; c = c.getNext()) {
131 String name = c.getString();
132 renamer.addDeclaredName(name);
133 }
134
135 // Add the function body declarations
136 Node functionBody = n.getNext();
137 findDeclaredNames(functionBody, null, renamer);
138
139 nameStack.push(renamer);
140 }
141 break;
142
143 case Token.CATCH:
144 {
145 Renamer renamer = nameStack.peek().forChildScope();
146
147 String name = n.getFirstChild().getString();
148 renamer.addDeclaredName(name);
149
150 nameStack.push(renamer);
151 }
152 break;
153 }
154
155 return true;
156 }
157
158 @Override
159 public void visit(NodeTraversal t, Node n, Node parent) {
160 switch (n.getType()) {
161 case Token.NAME:
162 String newName = getReplacementName(n.getString());
163 if (newName != null) {
164 Renamer renamer = nameStack.peek();
165 if (renamer.stripConstIfReplaced()) {
166 // TODO(johnlenz): Do we need to do anything about the Javadoc?
167 n.removeProp(Node.IS_CONSTANT_NAME);
168 }
169 n.setString(newName);
170 t.getCompiler().reportCodeChange();
171 }
172 break;
173
174 case Token.FUNCTION:
175 // Remove the function body scope
176 nameStack.pop();
177 // Remove function recursive name (if any).
178 nameStack.pop();
179 break;
180
181 case Token.PARAM_LIST:
182 // Note: The parameters and function body variables live in the
183 // same scope, we introduce the scope when in the "shouldTraverse"
184 // visit of LP, but remove it when when we exit the function above.
185 break;
186
187 case Token.CATCH:
188 // Remove catch except name from the stack of names.
189 nameStack.pop();
190 break;
191 }
192 }
193
194 /**
195 * Walks the stack of name maps and finds the replacement name for the
196 * current scope.
197 */
198 private String getReplacementName(String oldName) {
199 for (Renamer names : nameStack) {
200 String newName = names.getReplacementName(oldName);
201 if (newName != null) {
202 return newName;
203 }
204 }
205 return null;
206 }
207
208 /**
209 * Traverses the current scope and collects declared names. Does not
210 * decent into functions or add CATCH exceptions.
211 */
212 private void findDeclaredNames(Node n, Node parent, Renamer renamer) {
213 // Do a shallow traversal, so don't traverse into function declarations,
214 // except for the name of the function itself.
215 if (parent == null
216 || !parent.isFunction()
217 || n == parent.getFirstChild()) {
218 if (NodeUtil.isVarDeclaration(n)) {
219 renamer.addDeclaredName(n.getString());
220 } else if (NodeUtil.isFunctionDeclaration(n)) {
221 Node nameNode = n.getFirstChild();
222 renamer.addDeclaredName(nameNode.getString());
223 }
224
225 for (Node c = n.getFirstChild(); c != null; c = c.getNext()) {
226 findDeclaredNames(c, n, renamer);
227 }
228 }
229 }
230
231 /**
232 * Declared names renaming policy interface.
233 */
234 interface Renamer {
235
236 /**
237 * Called when a declared name is found in the local current scope.
238 */
239 void addDeclaredName(String name);
240
241 /**
242 * @return A replacement name, null if oldName is unknown or should not
243 * be replaced.
244 */
245 String getReplacementName(String oldName);
246
247 /**
248 * @return Whether the constant-ness of a name should be removed.
249 */
250 boolean stripConstIfReplaced();
251
252 /**
253 * @return A Renamer for a scope within the scope of the current Renamer.
254 */
255 Renamer forChildScope();
256 }
257
258 /**
259 * Inverts the transformation by {@link ContextualRenamer}, when possible.
260 */
261 static class ContextualRenameInverter
262 implements ScopedCallback, CompilerPass {
263 private final AbstractCompiler compiler;
264
265 // The set of names referenced in the current scope.
266 private Set<String> referencedNames = ImmutableSet.of();
267
268 // Stack reference sets.
269 private Deque<Set<String>> referenceStack = new ArrayDeque<Set<String>>();
270
271 // Name are globally unique initially, so we don't need a per-scope map.
272 private Map<String, List<Node>> nameMap = Maps.newHashMap();
273
274 private ContextualRenameInverter(AbstractCompiler compiler) {
275 this.compiler = compiler;
276 }
277
278 @Override
279 public void process(Node externs, Node js) {
280 NodeTraversal.traverse(compiler, js, this);
281 }
282
283 public static String getOrginalName(String name) {
284 int index = indexOfSeparator(name);
285 return (index == -1) ? name : name.substring(0, index);
286 }
287
288 private static int indexOfSeparator(String name) {
289 return name.lastIndexOf(ContextualRenamer.UNIQUE_ID_SEPARATOR);
290 }
291
292 private boolean containsSeparator(String name) {
293 return name.indexOf(ContextualRenamer.UNIQUE_ID_SEPARATOR) != -1;
294 }
295
296 /**
297 * Prepare a set for the new scope.
298 */
299 @Override
300 public void enterScope(NodeTraversal t) {
301 if (t.inGlobalScope()) {
302 return;
303 }
304
305 referenceStack.push(referencedNames);
306 referencedNames = Sets.newHashSet();
307 }
308
309 /**
310 * Rename vars for the current scope, and merge any referenced
311 * names into the parent scope reference set.
312 */
313 @Override
314 public void exitScope(NodeTraversal t) {
315 if (t.inGlobalScope()) {
316 return;
317 }
318
319 for (Iterator<Var> it = t.getScope().getVars(); it.hasNext();) {
320 Var v = it.next();
321 handleScopeVar(v);
322 }
323
324 // Merge any names that were referenced but not declared in the current
325 // scope.
326 Set<String> current = referencedNames;
327 referencedNames = referenceStack.pop();
328 // If there isn't anything left in the stack we will be going into the
329 // global scope: don't try to build a set of referenced names for the
330 // global scope.
331 if (!referenceStack.isEmpty()) {
332 referencedNames.addAll(current);
333 }
334 }
335
336 /**
337 * For the Var declared in the current scope determine if it is possible
338 * to revert the name to its original form without conflicting with other
339 * values.
340 */
341 void handleScopeVar(Var v) {
342 String name = v.getName();
343 if (containsSeparator(name) && !getOrginalName(name).isEmpty()) {
344 String newName = findReplacementName(name);
345 referencedNames.remove(name);
346 // Adding a reference to the new name to prevent either the parent
347 // scopes or the current scope renaming another var to this new name.
348 referencedNames.add(newName);
349 List<Node> references = nameMap.get(name);
350 Preconditions.checkState(references != null);
351 for (Node n : references) {
352 Preconditions.checkState(n.isName());
353 n.setString(newName);
354 }
355 compiler.reportCodeChange();
356 nameMap.remove(name);
357 }
358 }
359
360 /**
361 * Find a name usable in the local scope.
362 */
363 private String findReplacementName(String name) {
364 String original = getOrginalName(name);
365 String newName = original;
366 int i = 0;
367 while (!isValidName(newName)) {
368 newName = original +
369 ContextualRenamer.UNIQUE_ID_SEPARATOR + String.valueOf(i++);
370 }
371 return newName;
372 }
373
374 /**
375 * @return Whether the name is valid to use in the local scope.
376 */
377 private boolean isValidName(String name) {
378 if (TokenStream.isJSIdentifier(name) &&
379 !referencedNames.contains(name) &&
380 !name.equals(ARGUMENTS)) {
381 return true;
382 }
383 return false;
384 }
385
386 @Override
387 public boolean shouldTraverse(NodeTraversal t, Node n, Node parent) {
388 return true;
389 }
390
391 @Override
392 public void visit(NodeTraversal t, Node node, Node parent) {
393 if (t.inGlobalScope()) {
394 return;
395 }
396
397 if (NodeUtil.isReferenceName(node)) {
398 String name = node.getString();
399 // Add all referenced names to the set so it is possible to check for
400 // conflicts.
401 referencedNames.add(name);
402 // Store only references to candidate names in the node map.
403 if (containsSeparator(name)) {
404 addCandidateNameReference(name, node);
405 }
406 }
407 }
408
409 private void addCandidateNameReference(String name, Node n) {
410 List<Node> nodes = nameMap.get(name);
411 if (null == nodes) {
412 nodes = Lists.newLinkedList();
413 nameMap.put(name, nodes);
414 }
415 nodes.add(n);
416 }
417 }
418
419 /**
420 * Rename every locally name to be unique, the first encountered declaration
421 * (specifically global names) are left in their original form. Those that are
422 * renamed are made unique by giving them a unique suffix based on
423 * the number of declarations of the name.
424 *
425 * The root ContextualRenamer is assumed to be in GlobalScope.
426 *
427 * Used by the Normalize pass.
428 * @see Normalize
429 */
430 static class ContextualRenamer implements Renamer {
431 private final Multiset<String> nameUsage;
432 private final Map<String, String> declarations = Maps.newHashMap();
433 private final boolean global;
434
435 final static String UNIQUE_ID_SEPARATOR = "$$";
436
437 ContextualRenamer() {
438 this.global = true;
439 nameUsage = HashMultiset.create();
440 }
441
442 /**
443 * Constructor for child scopes.
444 */
445 private ContextualRenamer(Multiset<String> nameUsage) {
446 this.global = false;
447 this.nameUsage = nameUsage;
448 }
449
450 /**
451 * Create a ContextualRenamer
452 */
453 @Override
454 public Renamer forChildScope() {
455 return new ContextualRenamer(nameUsage);
456 }
457
458 /**
459 * Adds a name to the map of names declared in this scope.
460 */
461 @Override
462 public void addDeclaredName(String name) {
463 if (!name.equals(ARGUMENTS)) {
464 if (global) {
465 reserveName(name);
466 } else {
467 // It hasn't been declared locally yet, so increment the count.
468 if (!declarations.containsKey(name)) {
469 int id = incrementNameCount(name);
470 String newName = null;
471 if (id != 0) {
472 newName = getUniqueName(name, id);
473 }
474 declarations.put(name, newName);
475 }
476 }
477 }
478 }
479
480 @Override
481 public String getReplacementName(String oldName) {
482 return declarations.get(oldName);
483 }
484
485 /**
486 * Given a name and the associated id, create a new unique name.
487 */
488 private String getUniqueName(String name, int id) {
489 return name + UNIQUE_ID_SEPARATOR + id;
490 }
491
492 private void reserveName(String name) {
493 nameUsage.setCount(name, 0, 1);
494 }
495
496 private int incrementNameCount(String name) {
497 return nameUsage.add(name, 1);
498 }
499
500 @Override
501 public boolean stripConstIfReplaced() {
502 return false;
503 }
504 }
505
506
507 /**
508 * Rename every declared name to be unique. Typically this would be used
509 * when injecting code to insure that names do not conflict with existing
510 * names.
511 *
512 * Used by the FunctionInjector
513 * @see FunctionInjector
514 */
515 static class InlineRenamer implements Renamer {
516 private final Map<String, String> declarations = Maps.newHashMap();
517 private final Supplier<String> uniqueIdSupplier;
518 private final String idPrefix;
519 private final boolean removeConstness;
520 private final CodingConvention convention;
521
522 InlineRenamer(
523 CodingConvention convention,
524 Supplier<String> uniqueIdSupplier,
525 String idPrefix,
526 boolean removeConstness) {
527 this.convention = convention;
528 this.uniqueIdSupplier = uniqueIdSupplier;
529 // To ensure that the id does not conflict with the id from the
530 // ContextualRenamer some prefix is needed.
531 Preconditions.checkArgument(!idPrefix.isEmpty());
532 this.idPrefix = idPrefix;
533 this.removeConstness = removeConstness;
534 }
535
536 @Override
537 public void addDeclaredName(String name) {
538 Preconditions.checkState(!name.equals(ARGUMENTS));
539 if (!declarations.containsKey(name)) {
540 declarations.put(name, getUniqueName(name));
541 }
542 }
543
544 private String getUniqueName(String name) {
545 if (name.isEmpty()) {
546 return name;
547 }
548
549 if (name.indexOf(ContextualRenamer.UNIQUE_ID_SEPARATOR) != -1) {
550 name = name.substring(
551 0, name.lastIndexOf(ContextualRenamer.UNIQUE_ID_SEPARATOR));
552 }
553
554 if (convention.isExported(name)) {
555 // The google internal coding convention includes a naming convention
556 // to export names starting with "_". Simply strip "_" those to avoid
557 // exporting names.
558 name = "JSCompiler_" + name;
559 }
560
561 // By using the same separator the id will be stripped if it isn't
562 // needed when variable renaming is turned off.
563 return name + ContextualRenamer.UNIQUE_ID_SEPARATOR
564 + idPrefix + uniqueIdSupplier.get();
565 }
566
567 @Override
568 public String getReplacementName(String oldName) {
569 return declarations.get(oldName);
570 }
571
572 @Override
573 public Renamer forChildScope() {
574 return new InlineRenamer(
575 convention, uniqueIdSupplier, idPrefix, removeConstness);
576 }
577
578 @Override
579 public boolean stripConstIfReplaced() {
580 return removeConstness;
581 }
582 }
583
584 /**
585 * For injecting boilerplate libraries. Leaves global names alone
586 * and renames local names like InlineRenamer.
587 */
588 static class BoilerplateRenamer extends ContextualRenamer {
589 private final Supplier<String> uniqueIdSupplier;
590 private final String idPrefix;
591 private final CodingConvention convention;
592
593 BoilerplateRenamer(
594 CodingConvention convention,
595 Supplier<String> uniqueIdSupplier,
596 String idPrefix) {
597 this.convention = convention;
598 this.uniqueIdSupplier = uniqueIdSupplier;
599 this.idPrefix = idPrefix;
600 }
601
602 @Override
603 public Renamer forChildScope() {
604 return new InlineRenamer(convention, uniqueIdSupplier, idPrefix, false);
605 }
606 }
607
608 /** Only rename things that match the whitelist. Wraps another renamer. */
609 static class WhitelistedRenamer implements Renamer {
610 private Renamer delegate;
611 private Set<String> whitelist;
612
613 WhitelistedRenamer(Renamer delegate, Set<String> whitelist) {
614 this.delegate = delegate;
615 this.whitelist = whitelist;
616 }
617
618 @Override public void addDeclaredName(String name) {
619 if (whitelist.contains(name)) {
620 delegate.addDeclaredName(name);
621 }
622 }
623
624 @Override public String getReplacementName(String oldName) {
625 return whitelist.contains(oldName)
626 ? delegate.getReplacementName(oldName) : null;
627 }
628
629 @Override public boolean stripConstIfReplaced() {
630 return delegate.stripConstIfReplaced();
631 }
632
633 @Override public Renamer forChildScope() {
634 return new WhitelistedRenamer(delegate.forChildScope(), whitelist);
635 }
636 }
637
638 }