Debian Codegraph @

src/com/google/javascript/jscomp/RemoveUnusedVars.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.Preconditions;
20 import com.google.common.collect.ArrayListMultimap;
21 import com.google.common.collect.Lists;
22 import com.google.common.collect.Maps;
23 import com.google.common.collect.Multimap;
24 import com.google.common.collect.Sets;
25 import com.google.javascript.jscomp.CodingConvention.SubclassRelationship;
26 import com.google.javascript.jscomp.DefinitionsRemover.Definition;
27 import com.google.javascript.jscomp.Scope.Var;
28 import com.google.javascript.rhino.IR;
29 import com.google.javascript.rhino.Node;
30 import com.google.javascript.rhino.Token;
31
32 import java.util.*;
33
34 /**
35 * Garbage collection for variable and function definitions. Basically performs
36 * a mark-and-sweep type algorithm over the JavaScript parse tree.
37 *
38 * For each scope:
39 * (1) Scan the variable/function declarations at that scope.
40 * (2) Traverse the scope for references, marking all referenced variables.
41 * Unlike other compiler passes, this is a pre-order traversal, not a
42 * post-order traversal.
43 * (3) If the traversal encounters an assign without other side-effects,
44 * create a continuation. Continue the continuation iff the assigned
45 * variable is referenced.
46 * (4) When the traversal completes, remove all unreferenced variables.
47 *
48 * If it makes it easier, you can think of the continuations of the traversal
49 * as a reference graph. Each continuation represents a set of edges, where the
50 * source node is a known variable, and the destination nodes are lazily
51 * evaluated when the continuation is executed.
52 *
53 * This algorithm is similar to the algorithm used by {@code SmartNameRemoval}.
54 * {@code SmartNameRemoval} maintains an explicit graph of dependencies
55 * between global symbols. However, {@code SmartNameRemoval} cannot handle
56 * non-trivial edges in the reference graph ("A is referenced iff both B and C
57 * are referenced"), or local variables. {@code SmartNameRemoval} is also
58 * substantially more complicated because it tries to handle namespaces
59 * (which is largely unnecessary in the presence of {@code CollapseProperties}.
60 *
61 * This pass also uses a more complex analysis of assignments, where
62 * an assignment to a variable or a property of that variable does not
63 * necessarily count as a reference to that variable, unless we can prove
64 * that it modifies external state. This is similar to
65 * {@code FlowSensitiveInlineVariables}, except that it works for variables
66 * used across scopes.
67 *
68 */
69 class RemoveUnusedVars
70 implements CompilerPass, OptimizeCalls.CallGraphCompilerPass {
71
72 private final AbstractCompiler compiler;
73
74 private final CodingConvention codingConvention;
75
76 private final boolean removeGlobals;
77
78 private boolean preserveFunctionExpressionNames;
79
80 /**
81 * Keep track of variables that we've referenced.
82 */
83 private final Set<Var> referenced = Sets.newHashSet();
84
85 /**
86 * Keep track of variables that might be unreferenced.
87 */
88 private final List<Var> maybeUnreferenced = Lists.newArrayList();
89
90 /**
91 * Keep track of scopes that we've traversed.
92 */
93 private final List<Scope> allFunctionScopes = Lists.newArrayList();
94
95 /**
96 * Keep track of assigns to variables that we haven't referenced.
97 */
98 private final Multimap<Var, Assign> assignsByVar =
99 ArrayListMultimap.create();
100
101 /**
102 * The assigns, indexed by the NAME node that they assign to.
103 */
104 private final Map<Node, Assign> assignsByNode = Maps.newHashMap();
105
106 /**
107 * Subclass name -> class-defining call EXPR node. (like inherits)
108 */
109 private final Multimap<Var, Node> classDefiningCalls =
110 ArrayListMultimap.create();
111
112 /**
113 * Keep track of continuations that are finished iff the variable they're
114 * indexed by is referenced.
115 */
116 private final Multimap<Var, Continuation> continuations =
117 ArrayListMultimap.create();
118
119 private boolean modifyCallSites;
120
121 private CallSiteOptimizer callSiteOptimizer;
122
123 RemoveUnusedVars(
124 AbstractCompiler compiler,
125 boolean removeGlobals,
126 boolean preserveFunctionExpressionNames,
127 boolean modifyCallSites) {
128 this.compiler = compiler;
129 this.codingConvention = compiler.getCodingConvention();
130 this.removeGlobals = removeGlobals;
131 this.preserveFunctionExpressionNames = preserveFunctionExpressionNames;
132 this.modifyCallSites = modifyCallSites;
133 }
134
135 /**
136 * Traverses the root, removing all unused variables. Multiple traversals
137 * may occur to ensure all unused variables are removed.
138 */
139 @Override
140 public void process(Node externs, Node root) {
141 Preconditions.checkState(compiler.getLifeCycleStage().isNormalized());
142 SimpleDefinitionFinder defFinder = null;
143
144 if (modifyCallSites) {
145 // For testing, allow the SimpleDefinitionFinder to be build now.
146 defFinder = new SimpleDefinitionFinder(compiler);
147 defFinder.process(externs, root);
148 }
149 process(externs, root, defFinder);
150 }
151
152 @Override
153 public void process(
154 Node externs, Node root, SimpleDefinitionFinder defFinder) {
155 if (modifyCallSites) {
156 Preconditions.checkNotNull(defFinder);
157 callSiteOptimizer = new CallSiteOptimizer(compiler, defFinder);
158 }
159 traverseAndRemoveUnusedReferences(root);
160 if (callSiteOptimizer != null) {
161 callSiteOptimizer.applyChanges();
162 }
163 }
164
165 /**
166 * Traverses a node recursively. Call this once per pass.
167 */
168 private void traverseAndRemoveUnusedReferences(Node root) {
169 Scope scope = new SyntacticScopeCreator(compiler).createScope(root, null);
170 traverseNode(root, null, scope);
171
172 if (removeGlobals) {
173 collectMaybeUnreferencedVars(scope);
174 }
175
176 interpretAssigns();
177 removeUnreferencedVars();
178 for (Scope fnScope : allFunctionScopes) {
179 removeUnreferencedFunctionArgs(fnScope);
180 }
181 }
182
183 /**
184 * Traverses everything in the current scope and marks variables that
185 * are referenced.
186 *
187 * During traversal, we identify subtrees that will only be
188 * referenced if their enclosing variables are referenced. Instead of
189 * traversing those subtrees, we create a continuation for them,
190 * and traverse them lazily.
191 */
192 private void traverseNode(Node n, Node parent, Scope scope) {
193 int type = n.getType();
194 Var var = null;
195 switch (type) {
196 case Token.FUNCTION:
197 // If this function is a removable var, then create a continuation
198 // for it instead of traversing immediately.
199 if (NodeUtil.isFunctionDeclaration(n)) {
200 var = scope.getVar(n.getFirstChild().getString());
201 }
202
203 if (var != null && isRemovableVar(var)) {
204 continuations.put(var, new Continuation(n, scope));
205 } else {
206 traverseFunction(n, scope);
207 }
208 return;
209
210 case Token.ASSIGN:
211 Assign maybeAssign = Assign.maybeCreateAssign(n);
212 if (maybeAssign != null) {
213 // Put this in the assign map. It might count as a reference,
214 // but we won't know that until we have an index of all assigns.
215 var = scope.getVar(maybeAssign.nameNode.getString());
216 if (var != null) {
217 assignsByVar.put(var, maybeAssign);
218 assignsByNode.put(maybeAssign.nameNode, maybeAssign);
219
220 if (isRemovableVar(var) &&
221 !maybeAssign.mayHaveSecondarySideEffects) {
222 // If the var is unreferenced and performing this assign has
223 // no secondary side effects, then we can create a continuation
224 // for it instead of traversing immediately.
225 continuations.put(var, new Continuation(n, scope));
226 return;
227 }
228 }
229 }
230 break;
231
232 case Token.CALL:
233 Var modifiedVar = null;
234
235 // Look for calls to inheritance-defining calls (such as goog.inherits).
236 SubclassRelationship subclassRelationship =
237 codingConvention.getClassesDefinedByCall(n);
238 if (subclassRelationship != null) {
239 modifiedVar = scope.getVar(subclassRelationship.subclassName);
240 } else {
241 // Look for calls to addSingletonGetter calls.
242 String className = codingConvention.getSingletonGetterClassName(n);
243 if (className != null) {
244 modifiedVar = scope.getVar(className);
245 }
246 }
247
248 // Don't try to track the inheritance calls for non-globals. It would
249 // be more correct to only not track when the subclass does not
250 // reference a constructor, but checking that it is a global is
251 // easier and mostly the same.
252 if (modifiedVar != null && modifiedVar.isGlobal()
253 && !referenced.contains(modifiedVar)) {
254 // Save a reference to the EXPR node.
255 classDefiningCalls.put(modifiedVar, parent);
256 continuations.put(modifiedVar, new Continuation(n, scope));
257 return;
258 }
259 break;
260
261 case Token.NAME:
262 var = scope.getVar(n.getString());
263 if (parent.isVar()) {
264 Node value = n.getFirstChild();
265 if (value != null && var != null && isRemovableVar(var) &&
266 !NodeUtil.mayHaveSideEffects(value, compiler)) {
267 // If the var is unreferenced and creating its value has no side
268 // effects, then we can create a continuation for it instead
269 // of traversing immediately.
270 continuations.put(var, new Continuation(n, scope));
271 return;
272 }
273 } else {
274
275 // If arguments is escaped, we just assume the worst and continue
276 // on all the parameters.
277 if ("arguments".equals(n.getString()) && scope.isLocal()) {
278 Node lp = scope.getRootNode().getFirstChild().getNext();
279 for (Node a = lp.getFirstChild(); a != null; a = a.getNext()) {
280 markReferencedVar(scope.getVar(a.getString()));
281 }
282 }
283
284 // All name references that aren't declarations or assigns
285 // are references to other vars.
286 if (var != null) {
287 // If that var hasn't already been marked referenced, then
288 // start tracking it. If this is an assign, do nothing
289 // for now.
290 if (isRemovableVar(var)) {
291 if (!assignsByNode.containsKey(n)) {
292 markReferencedVar(var);
293 }
294 } else {
295 markReferencedVar(var);
296 }
297 }
298 }
299 break;
300 }
301
302 for (Node c = n.getFirstChild(); c != null; c = c.getNext()) {
303 traverseNode(c, n, scope);
304 }
305 }
306
307 private boolean isRemovableVar(Var var) {
308 // Global variables are off-limits if the user might be using them.
309 if (!removeGlobals && var.isGlobal()) {
310 return false;
311 }
312
313 // Referenced variables are off-limits.
314 if (referenced.contains(var)) {
315 return false;
316 }
317
318 // Exported variables are off-limits.
319 if (codingConvention.isExported(var.getName())) {
320 return false;
321 }
322
323 return true;
324 }
325
326 /**
327 * Traverses a function, which creates a new scope in JavaScript.
328 *
329 * Note that CATCH blocks also create a new scope, but only for the
330 * catch variable. Declarations within the block actually belong to the
331 * enclosing scope. Because we don't remove catch variables, there's
332 * no need to treat CATCH blocks differently like we do functions.
333 */
334 private void traverseFunction(Node n, Scope parentScope) {
335 Preconditions.checkState(n.getChildCount() == 3);
336 Preconditions.checkState(n.isFunction());
337
338 final Node body = n.getLastChild();
339 Preconditions.checkState(body.getNext() == null &&
340 body.isBlock());
341
342 Scope fnScope =
343 new SyntacticScopeCreator(compiler).createScope(n, parentScope);
344 traverseNode(body, n, fnScope);
345
346 collectMaybeUnreferencedVars(fnScope);
347 allFunctionScopes.add(fnScope);
348 }
349
350 /**
351 * For each variable in this scope that we haven't found a reference
352 * for yet, add it to the list of variables to check later.
353 */
354 private void collectMaybeUnreferencedVars(Scope scope) {
355 for (Iterator<Var> it = scope.getVars(); it.hasNext(); ) {
356 Var var = it.next();
357 if (isRemovableVar(var)) {
358 maybeUnreferenced.add(var);
359 }
360 }
361 }
362
363 /**
364 * Removes unreferenced arguments from a function declaration and when
365 * possible the function's callSites.
366 *
367 * @param fnScope The scope inside the function
368 */
369 private void removeUnreferencedFunctionArgs(Scope fnScope) {
370 // Notice that removing unreferenced function args breaks
371 // Function.prototype.length. In advanced mode, we don't really care
372 // about this: we consider "length" the equivalent of reflecting on
373 // the function's lexical source.
374 //
375 // Rather than create a new option for this, we assume that if the user
376 // is removing globals, then it's OK to remove unused function args.
377 //
378 // See http://code.google.com/p/closure-compiler/issues/detail?id=253
379 if (!removeGlobals) {
380 return;
381 }
382
383 Node function = fnScope.getRootNode();
384
385 Preconditions.checkState(function.isFunction());
386 if (NodeUtil.isGetOrSetKey(function.getParent())) {
387 // The parameters object literal setters can not be removed.
388 return;
389 }
390
391 Node argList = getFunctionArgList(function);
392 boolean modifyCallers = modifyCallSites
393 && callSiteOptimizer.canModifyCallers(function);
394 if (!modifyCallers) {
395 // Strip unreferenced args off the end of the function declaration.
396 Node lastArg;
397 while ((lastArg = argList.getLastChild()) != null) {
398 Var var = fnScope.getVar(lastArg.getString());
399 if (!referenced.contains(var)) {
400 argList.removeChild(lastArg);
401 compiler.reportCodeChange();
402 } else {
403 break;
404 }
405 }
406 } else {
407 callSiteOptimizer.optimize(fnScope, referenced);
408 }
409 }
410
411
412 /**
413 * @return the LP node containing the function parameters.
414 */
415 private static Node getFunctionArgList(Node function) {
416 return function.getFirstChild().getNext();
417 }
418
419 private static class CallSiteOptimizer {
420 private final AbstractCompiler compiler;
421 private final SimpleDefinitionFinder defFinder;
422 private final List<Node> toRemove = Lists.newArrayList();
423 private final List<Node> toReplaceWithZero = Lists.newArrayList();
424
425 CallSiteOptimizer(
426 AbstractCompiler compiler,
427 SimpleDefinitionFinder defFinder) {
428 this.compiler = compiler;
429 this.defFinder = defFinder;
430 }
431
432 public void optimize(Scope fnScope, Set<Var> referenced) {
433 Node function = fnScope.getRootNode();
434 Preconditions.checkState(function.isFunction());
435 Node argList = getFunctionArgList(function);
436
437 // In this path we try to modify all the call sites to remove unused
438 // function parameters.
439 boolean changeCallSignature = canChangeSignature(function);
440 markUnreferencedFunctionArgs(
441 fnScope, function, referenced,
442 argList.getFirstChild(), 0, changeCallSignature);
443 }
444
445 /**
446 * Applies optimizations to all previously marked nodes.
447 */
448 public void applyChanges() {
449 for (Node n : toRemove) {
450 n.getParent().removeChild(n);
451 compiler.reportCodeChange();
452 }
453 for (Node n : toReplaceWithZero) {
454 n.getParent().replaceChild(n, IR.number(0).srcref(n));
455 compiler.reportCodeChange();
456 }
457 }
458
459 /**
460 * For each unused function parameter, determine if it can be removed
461 * from all the call sites, if so, remove it from the function signature
462 * and the call sites otherwise replace the unused value where possible
463 * with a constant (0).
464 *
465 * @param scope The function scope
466 * @param function The function
467 * @param param The current parameter node in the parameter list.
468 * @param paramIndex The index of the current parameter
469 * @param canChangeSignature Whether function signature can be change.
470 * @return Whether there is a following function parameter.
471 */
472 private boolean markUnreferencedFunctionArgs(
473 Scope scope, Node function, Set<Var> referenced,
474 Node param, int paramIndex,
475 boolean canChangeSignature) {
476 if (param != null) {
477 // Take care of the following siblings first.
478 boolean hasFollowing = markUnreferencedFunctionArgs(
479 scope, function, referenced, param.getNext(), paramIndex+1,
480 canChangeSignature);
481
482 Var var = scope.getVar(param.getString());
483 if (!referenced.contains(var)) {
484 Preconditions.checkNotNull(var);
485
486 // Remove call parameter if we can generally change the signature
487 // or if it is the last parameter in the parameter list.
488 boolean modifyAllCallSites = canChangeSignature || !hasFollowing;
489 if (modifyAllCallSites) {
490 modifyAllCallSites = canRemoveArgFromCallSites(
491 function, paramIndex);
492 }
493
494 tryRemoveArgFromCallSites(function, paramIndex, modifyAllCallSites);
495
496 // Remove an unused function parameter if all the call sites can
497 // be modified to remove it, or if it is the last parameter.
498 if (modifyAllCallSites || !hasFollowing) {
499 toRemove.add(param);
500 return hasFollowing;
501 }
502 }
503 return true;
504 } else {
505 // Anything past the last formal parameter can be removed from the call
506 // sites.
507 tryRemoveAllFollowingArgs(function, paramIndex-1);
508 return false;
509 }
510 }
511
512 /**
513 * Remove all references to a parameter, otherwise simplify the known
514 * references.
515 * @return Whether all the references were removed.
516 */
517 private boolean canRemoveArgFromCallSites(Node function, int argIndex) {
518 Definition definition = getFunctionDefinition(function);
519
520 // Check all the call sites.
521 for (UseSite site : defFinder.getUseSites(definition)) {
522 if (isModifiableCallSite(site)) {
523 Node arg = getArgumentForCallOrNewOrDotCall(site, argIndex);
524 // TODO(johnlenz): try to remove parameters with side-effects by
525 // decomposing the call expression.
526 if (arg != null && NodeUtil.mayHaveSideEffects(arg, compiler)) {
527 return false;
528 }
529 } else {
530 return false;
531 }
532 }
533
534 return true;
535 }
536
537 /**
538 * Remove all references to a parameter if possible otherwise simplify the
539 * side-effect free parameters.
540 */
541 private void tryRemoveArgFromCallSites(
542 Node function, int argIndex, boolean canModifyAllSites) {
543 Definition definition = getFunctionDefinition(function);
544
545 for (UseSite site : defFinder.getUseSites(definition)) {
546 if (isModifiableCallSite(site)) {
547 Node arg = getArgumentForCallOrNewOrDotCall(site, argIndex);
548 if (arg != null) {
549 // Even if we can't change the signature in general we can always
550 // remove an unused value off the end of the parameter list.
551 if (canModifyAllSites
552 || (arg.getNext() == null
553 && !NodeUtil.mayHaveSideEffects(arg, compiler))) {
554 toRemove.add(arg);
555 } else {
556 // replace the node in the arg with 0
557 if (!NodeUtil.mayHaveSideEffects(arg, compiler)
558 && (!arg.isNumber() || arg.getDouble() != 0)) {
559 toReplaceWithZero.add(arg);
560 }
561 }
562 }
563 }
564 }
565 }
566
567 /**
568 * Remove all the following parameters without side-effects
569 */
570 private void tryRemoveAllFollowingArgs(Node function, final int argIndex) {
571 Definition definition = getFunctionDefinition(function);
572 for (UseSite site : defFinder.getUseSites(definition)) {
573 if (!isModifiableCallSite(site)) {
574 continue;
575 }
576 Node arg = getArgumentForCallOrNewOrDotCall(site, argIndex + 1);
577 while (arg != null) {
578 if (!NodeUtil.mayHaveSideEffects(arg)) {
579 toRemove.add(arg);
580 }
581 arg = arg.getNext();
582 }
583 }
584 }
585
586 /**
587 * Returns the nth argument node given a usage site for a direct function
588 * call or for a func.call() node.
589 */
590 private static Node getArgumentForCallOrNewOrDotCall(UseSite site,
591 final int argIndex) {
592 int adjustedArgIndex = argIndex;
593 Node parent = site.node.getParent();
594 if (NodeUtil.isFunctionObjectCall(parent)) {
595 adjustedArgIndex++;
596 }
597 return NodeUtil.getArgumentForCallOrNew(parent, adjustedArgIndex);
598 }
599
600 /**
601 * @param function
602 * @return Whether the callers to this function can be modified in any way.
603 */
604 boolean canModifyCallers(Node function) {
605 if (NodeUtil.isVarArgsFunction(function)) {
606 return false;
607 }
608
609 DefinitionSite defSite = defFinder.getDefinitionForFunction(function);
610 if (defSite == null) {
611 return false;
612 }
613
614 Definition definition = defSite.definition;
615
616 // Be conservative, don't try to optimize any declaration that isn't as
617 // simple function declaration or assignment.
618 if (!SimpleDefinitionFinder.isSimpleFunctionDeclaration(function)) {
619 return false;
620 }
621
622 return defFinder.canModifyDefinition(definition);
623 }
624
625 /**
626 * @param site The site to inspect
627 * @return Whether the call site is suitable for modification
628 */
629 private static boolean isModifiableCallSite(UseSite site) {
630 return SimpleDefinitionFinder.isCallOrNewSite(site)
631 && !NodeUtil.isFunctionObjectApply(site.node.getParent());
632 }
633
634 /**
635 * @return Whether the definitionSite represents a function whose call
636 * signature can be modified.
637 */
638 private boolean canChangeSignature(Node function) {
639 Definition definition = getFunctionDefinition(function);
640 CodingConvention convention = compiler.getCodingConvention();
641
642 Preconditions.checkState(!definition.isExtern());
643
644 Collection<UseSite> useSites = defFinder.getUseSites(definition);
645 for (UseSite site : useSites) {
646 Node parent = site.node.getParent();
647
648 // This was a use site removed by something else before we run.
649 // 1. By another pass before us which means the definition graph is
650 // no updated properly.
651 // 2. By the continuations algorithm above.
652 if (parent == null) {
653 continue; // Ignore it.
654 }
655
656 // Ignore references within goog.inherits calls.
657 if (parent.isCall() &&
658 convention.getClassesDefinedByCall(parent) != null) {
659 continue;
660 }
661
662 // Accessing the property directly prevents rewrite.
663 if (!SimpleDefinitionFinder.isCallOrNewSite(site)) {
664 if (!(parent.isGetProp() &&
665 NodeUtil.isFunctionObjectCall(parent.getParent()))) {
666 return false;
667 }
668 }
669
670 if (NodeUtil.isFunctionObjectApply(parent)) {
671 return false;
672 }
673
674 // TODO(johnlenz): support specialization
675
676 // Multiple definitions prevent rewrite.
677 // Attempt to validate the state of the simple definition finder.
678 Node nameNode = site.node;
679 Collection<Definition> singleSiteDefinitions =
680 defFinder.getDefinitionsReferencedAt(nameNode);
681 Preconditions.checkState(singleSiteDefinitions.size() == 1);
682 Preconditions.checkState(singleSiteDefinitions.contains(definition));
683 }
684
685 return true;
686 }
687
688 /**
689 * @param function
690 * @return the Definition object for the function.
691 */
692 private Definition getFunctionDefinition(Node function) {
693 DefinitionSite definitionSite = defFinder.getDefinitionForFunction(
694 function);
695 Preconditions.checkNotNull(definitionSite);
696 Definition definition = definitionSite.definition;
697 Preconditions.checkState(!definitionSite.inExterns);
698 Preconditions.checkState(definition.getRValue() == function);
699 return definition;
700 }
701 }
702
703
704 /**
705 * Look at all the property assigns to all variables.
706 * These may or may not count as references. For example,
707 *
708 * <code>
709 * var x = {};
710 * x.foo = 3; // not a reference.
711 * var y = foo();
712 * y.foo = 3; // is a reference.
713 * </code>
714 *
715 * Interpreting assignments could mark a variable as referenced that
716 * wasn't referenced before, in order to keep it alive. Because we find
717 * references by lazily traversing subtrees, marking a variable as
718 * referenced could trigger new traversals of new subtrees, which could
719 * find new references.
720 *
721 * Therefore, this interpretation needs to be run to a fixed point.
722 */
723 private void interpretAssigns() {
724 boolean changes = false;
725 do {
726 changes = false;
727
728 // We can't use traditional iterators and iterables for this list,
729 // because our lazily-evaluated continuations will modify it while
730 // we traverse it.
731 for (int current = 0; current < maybeUnreferenced.size(); current++) {
732 Var var = maybeUnreferenced.get(current);
733 if (referenced.contains(var)) {
734 maybeUnreferenced.remove(current);
735 current--;
736 } else {
737 boolean assignedToUnknownValue = false;
738 boolean hasPropertyAssign = false;
739
740 if (var.getParentNode().isVar() &&
741 !NodeUtil.isForIn(var.getParentNode().getParent())) {
742 Node value = var.getInitialValue();
743 assignedToUnknownValue = value != null &&
744 !NodeUtil.isLiteralValue(value, true);
745 } else {
746 // This was initialized to a function arg or a catch param
747 // or a for...in variable.
748 assignedToUnknownValue = true;
749 }
750
751 boolean maybeEscaped = false;
752 for (Assign assign : assignsByVar.get(var)) {
753 if (assign.isPropertyAssign) {
754 hasPropertyAssign = true;
755 } else if (!NodeUtil.isLiteralValue(
756 assign.assignNode.getLastChild(), true)) {
757 assignedToUnknownValue = true;
758 }
759 if (assign.maybeAliased) {
760 maybeEscaped = true;
761 }
762 }
763
764 if ((assignedToUnknownValue || maybeEscaped) && hasPropertyAssign) {
765 changes = markReferencedVar(var) || changes;
766 maybeUnreferenced.remove(current);
767 current--;
768 }
769 }
770 }
771 } while (changes);
772 }
773
774 /**
775 * Remove all assigns to a var.
776 */
777 private void removeAllAssigns(Var var) {
778 for (Assign assign : assignsByVar.get(var)) {
779 assign.remove();
780 compiler.reportCodeChange();
781 }
782 }
783
784 /**
785 * Marks a var as referenced, recursing into any values of this var
786 * that we skipped.
787 * @return True if this variable had not been referenced before.
788 */
789 private boolean markReferencedVar(Var var) {
790 if (referenced.add(var)) {
791 for (Continuation c : continuations.get(var)) {
792 c.apply();
793 }
794 return true;
795 }
796 return false;
797 }
798
799 /**
800 * Removes any vars in the scope that were not referenced. Removes any
801 * assignments to those variables as well.
802 */
803 private void removeUnreferencedVars() {
804 for (Iterator<Var> it = maybeUnreferenced.iterator(); it.hasNext(); ) {
805 Var var = it.next();
806
807 // Remove calls to inheritance-defining functions where the unreferenced
808 // class is the subclass.
809 for (Node exprCallNode : classDefiningCalls.get(var)) {
810 NodeUtil.removeChild(exprCallNode.getParent(), exprCallNode);
811 compiler.reportCodeChange();
812 }
813
814 // Regardless of what happens to the original declaration,
815 // we need to remove all assigns, because they may contain references
816 // to other unreferenced variables.
817 removeAllAssigns(var);
818
819 compiler.addToDebugLog("Unreferenced var: " + var.name);
820 Node nameNode = var.nameNode;
821 Node toRemove = nameNode.getParent();
822 Node parent = toRemove.getParent();
823
824 Preconditions.checkState(
825 toRemove.isVar() ||
826 toRemove.isFunction() ||
827 toRemove.isParamList() &&
828 parent.isFunction(),
829 "We should only declare vars and functions and function args");
830
831 if (toRemove.isParamList() &&
832 parent.isFunction()) {
833 // Don't remove function arguments here. That's a special case
834 // that's taken care of in removeUnreferencedFunctionArgs.
835 } else if (NodeUtil.isFunctionExpression(toRemove)) {
836 if (!preserveFunctionExpressionNames) {
837 toRemove.getFirstChild().setString("");
838 compiler.reportCodeChange();
839 }
840 // Don't remove bleeding functions.
841 } else if (parent != null &&
842 parent.isFor() &&
843 parent.getChildCount() < 4) {
844 // foreach iterations have 3 children. Leave them alone.
845 } else if (toRemove.isVar() &&
846 nameNode.hasChildren() &&
847 NodeUtil.mayHaveSideEffects(nameNode.getFirstChild(), compiler)) {
848 // If this is a single var declaration, we can at least remove the
849 // declaration itself and just leave the value, e.g.,
850 // var a = foo(); => foo();
851 if (toRemove.getChildCount() == 1) {
852 parent.replaceChild(toRemove,
853 IR.exprResult(nameNode.removeFirstChild()));
854 compiler.reportCodeChange();
855 }
856 } else if (toRemove.isVar() &&
857 toRemove.getChildCount() > 1) {
858 // For var declarations with multiple names (i.e. var a, b, c),
859 // only remove the unreferenced name
860 toRemove.removeChild(nameNode);
861 compiler.reportCodeChange();
862 } else if (parent != null) {
863 NodeUtil.removeChild(parent, toRemove);
864 compiler.reportCodeChange();
865 }
866 }
867 }
868
869 /**
870 * Our progress in a traversal can be expressed completely as the
871 * current node and scope. The continuation lets us save that
872 * information so that we can continue the traversal later.
873 */
874 private class Continuation {
875 private final Node node;
876 private final Scope scope;
877
878 Continuation(Node node, Scope scope) {
879 this.node = node;
880 this.scope = scope;
881 }
882
883 void apply() {
884 if (NodeUtil.isFunctionDeclaration(node)) {
885 traverseFunction(node, scope);
886 } else {
887 for (Node child = node.getFirstChild();
888 child != null; child = child.getNext()) {
889 traverseNode(child, node, scope);
890 }
891 }
892 }
893 }
894
895 private static class Assign {
896
897 final Node assignNode;
898
899 final Node nameNode;
900
901 // If false, then this is an assign to the normal variable. Otherwise,
902 // this is an assign to a property of that variable.
903 final boolean isPropertyAssign;
904
905 // Secondary side effects are any side effects in this assign statement
906 // that aren't caused by the assignment operation itself. For example,
907 // a().b = 3;
908 // a = b();
909 // var foo = (a = b);
910 // In the first two cases, the sides of the assignment have side-effects.
911 // In the last one, the result of the assignment is used, so we
912 // are conservative and assume that it may be used in a side-effecting
913 // way.
914 final boolean mayHaveSecondarySideEffects;
915
916 // If true, the value may have escaped and any modification is a use.
917 final boolean maybeAliased;
918
919 Assign(Node assignNode, Node nameNode, boolean isPropertyAssign) {
920 Preconditions.checkState(NodeUtil.isAssignmentOp(assignNode));
921 this.assignNode = assignNode;
922 this.nameNode = nameNode;
923 this.isPropertyAssign = isPropertyAssign;
924
925 this.maybeAliased = NodeUtil.isExpressionResultUsed(assignNode);
926 this.mayHaveSecondarySideEffects =
927 maybeAliased ||
928 NodeUtil.mayHaveSideEffects(assignNode.getFirstChild()) ||
929 NodeUtil.mayHaveSideEffects(assignNode.getLastChild());
930 }
931
932 /**
933 * If this is an assign to a variable or its property, return it.
934 * Otherwise, return null.
935 */
936 static Assign maybeCreateAssign(Node assignNode) {
937 Preconditions.checkState(NodeUtil.isAssignmentOp(assignNode));
938
939 // Skip one level of GETPROPs or GETELEMs.
940 //
941 // Don't skip more than one level, because then we get into
942 // situations where assigns to properties of properties will always
943 // trigger side-effects, and the variable they're on cannot be removed.
944 boolean isPropAssign = false;
945 Node current = assignNode.getFirstChild();
946 if (NodeUtil.isGet(current)) {
947 current = current.getFirstChild();
948 isPropAssign = true;
949
950 if (current.isGetProp() &&
951 current.getLastChild().getString().equals("prototype")) {
952 // Prototype properties sets should be considered like normal
953 // property sets.
954 current = current.getFirstChild();
955 }
956 }
957
958 if (current.isName()) {
959 return new Assign(assignNode, current, isPropAssign);
960 }
961 return null;
962 }
963
964 /**
965 * Replace the current assign with its right hand side.
966 */
967 void remove() {
968 Node parent = assignNode.getParent();
969 if (mayHaveSecondarySideEffects) {
970 Node replacement = assignNode.getLastChild().detachFromParent();
971
972 // Aggregate any expressions in GETELEMs.
973 for (Node current = assignNode.getFirstChild();
974 !current.isName();
975 current = current.getFirstChild()) {
976 if (current.isGetElem()) {
977 replacement = IR.comma(
978 current.getLastChild().detachFromParent(), replacement);
979 replacement.copyInformationFrom(current);
980 }
981 }
982
983 parent.replaceChild(assignNode, replacement);
984 } else {
985 Node gramps = parent.getParent();
986 if (parent.isExprResult()) {
987 gramps.removeChild(parent);
988 } else {
989 parent.replaceChild(assignNode,
990 assignNode.getLastChild().detachFromParent());
991 }
992 }
993 }
994 }
995 }