Debian Codegraph @

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

raw symbols SCIP
1 /*
2 * Copyright 2006 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.base.Predicate;
21 import com.google.common.collect.ImmutableSet;
22 import com.google.common.collect.LinkedListMultimap;
23 import com.google.common.collect.ListMultimap;
24 import com.google.common.collect.Lists;
25 import com.google.common.collect.Maps;
26 import com.google.common.collect.Sets;
27 import com.google.javascript.jscomp.CodingConvention.SubclassRelationship;
28 import com.google.javascript.jscomp.GatherSideEffectSubexpressionsCallback.GetReplacementSideEffectSubexpressions;
29 import com.google.javascript.jscomp.GatherSideEffectSubexpressionsCallback.SideEffectAccumulator;
30 import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback;
31 import com.google.javascript.jscomp.NodeTraversal.Callback;
32 import com.google.javascript.jscomp.Scope.Var;
33 import com.google.javascript.jscomp.graph.DiGraph;
34 import com.google.javascript.jscomp.graph.DiGraph.DiGraphEdge;
35 import com.google.javascript.jscomp.graph.FixedPointGraphTraversal;
36 import com.google.javascript.jscomp.graph.FixedPointGraphTraversal.EdgeCallback;
37 import com.google.javascript.jscomp.graph.LinkedDirectedGraph;
38 import com.google.javascript.rhino.IR;
39 import com.google.javascript.rhino.Node;
40 import com.google.javascript.rhino.Token;
41
42 import java.util.Collections;
43 import java.util.Iterator;
44 import java.util.List;
45 import java.util.Map;
46 import java.util.Set;
47
48 /**
49 * This pass identifies all global names, simple (e.g. <code>a</code>) or
50 * qualified (e.g. <code>a.b.c</code>), and the dependencies between them, then
51 * removes code associated with unreferenced names. It starts by assuming that
52 * only externally accessible names (e.g. <code>window</code>) are referenced,
53 * then iteratively marks additional names as referenced (e.g. <code>Foo</code>
54 * in <code>window['foo'] = new Foo();</code>). This makes it possible to
55 * eliminate code containing circular references.
56 *
57 * <p>Qualified names can be defined using dotted or object literal syntax
58 * (<code>a.b.c = x;</code> or <code>a.b = {c: x};</code>, respectively).
59 *
60 * <p>Removal of prototype classes is currently all or nothing. In other words,
61 * prototype properties and methods are never individually removed.
62 *
63 * <p>Optionally generates pretty HTML output of data so that it is easy to
64 * analyze dependencies.
65 *
66 * <p>Only operates on names defined in the global scope, but it would be easy
67 * to extend the pass to names defined in local scopes.
68 *
69 * TODO(nicksantos): In the initial implementation of this pass, it was
70 * important to understand namespaced names (e.g., that a.b is distinct from
71 * a.b.c). Now that this pass comes after CollapseProperties, this is no longer
72 * necessary. For now, I've changed so that {@code referenceParentNames}
73 * creates a two-way reference between a.b and a.b.c, so that they're
74 * effectively the same name. When someone has the time, we should completely
75 * rip out all the logic that understands namespaces.
76 *
77 */
78 final class NameAnalyzer implements CompilerPass {
79
80 /** Reference to the JS compiler */
81 private final AbstractCompiler compiler;
82
83 /** Map of all JS names found */
84 private final Map<String, JsName> allNames = Maps.newTreeMap();
85
86 /** Reference dependency graph */
87 private DiGraph<JsName, RefType> referenceGraph =
88 LinkedDirectedGraph.createWithoutAnnotations();
89
90 /**
91 * Map of name scopes - all children of the Node key have a dependency on the
92 * name value.
93 *
94 * If scopes.get(node).equals(name) && node2 is a child of node, then node2
95 * will not get executed unless name is referenced via a get operation
96 */
97 private final ListMultimap<Node, NameInformation> scopes =
98 LinkedListMultimap.create();
99
100 /** Used to parse prototype names */
101 private static final String PROTOTYPE_SUBSTRING = ".prototype.";
102
103 private static final int PROTOTYPE_SUBSTRING_LEN =
104 PROTOTYPE_SUBSTRING.length();
105
106 private static final int PROTOTYPE_SUFFIX_LEN = ".prototype".length();
107
108 /** Window root */
109 private static final String WINDOW = "window";
110
111 /** Function class name */
112 private static final String FUNCTION = "Function";
113
114 /** All of these refer to global scope. These can be moved to config */
115 static final Set<String> DEFAULT_GLOBAL_NAMES = ImmutableSet.of(
116 "window", "goog.global");
117
118 /** Whether to remove unreferenced variables in main pass */
119 private final boolean removeUnreferenced;
120
121 /** Names that refer to the global scope */
122 private final Set<String> globalNames;
123
124 /** Ast change helper */
125 private final AstChangeProxy changeProxy;
126
127 /** Names that are externally defined */
128 private final Set<String> externalNames = Sets.newHashSet();
129
130 /** Name declarations or assignments, in post-order traversal order */
131 private final List<RefNode> refNodes = Lists.newArrayList();
132
133 /**
134 * When multiple names in the global scope point to the same object, we
135 * call them aliases. Store a map from each alias name to the alias set.
136 */
137 private final Map<String, AliasSet> aliases = Maps.newHashMap();
138
139 /**
140 * All the aliases in a program form a graph, where each global name is
141 * a node in the graph, and two names are connected if one directly aliases
142 * the other.
143 *
144 * An {@code AliasSet} represents a connected component in that graph. We do
145 * not explicitly track the graph--we just track the connected components.
146 */
147 private static class AliasSet {
148 Set<String> names = Sets.newHashSet();
149
150 // Every alias set starts with exactly 2 names.
151 AliasSet(String name1, String name2) {
152 names.add(name1);
153 names.add(name2);
154 }
155 }
156
157 /**
158 * Relationship between the two names.
159 * Currently only two different reference types exists:
160 * goog.inherits class relations and all other references.
161 */
162 private static enum RefType {
163 REGULAR,
164 INHERITANCE,
165 }
166
167 /**
168 * Callback that propagates reference information.
169 */
170 private static class ReferencePropagationCallback
171 implements EdgeCallback<JsName, RefType> {
172 @Override
173 public boolean traverseEdge(JsName from,
174 RefType callSite,
175 JsName to) {
176 if (from.referenced && !to.referenced) {
177 to.referenced = true;
178 return true;
179 } else {
180 return false;
181 }
182 }
183 }
184
185 /**
186 * Class to hold information that can be determined from a node tree about a
187 * given name
188 */
189 private static class NameInformation {
190 /** Fully qualified name */
191 String name;
192
193 /** Whether the name is guaranteed to be externally referenceable */
194 boolean isExternallyReferenceable = false;
195
196 /** Whether this name is a prototype function */
197 boolean isPrototype = false;
198
199 /** Name of the prototype class, i.e. "a" if name is "a.prototype.b" */
200 String prototypeClass = null;
201
202 /** Local name of prototype property i.e. "b" if name is "a.prototype.b" */
203 String prototypeProperty = null;
204
205 /** Name of the super class of name */
206 String superclass = null;
207
208 /** Whether this is a call that only affects the class definition */
209 boolean onlyAffectsClassDef = false;
210 }
211
212 /**
213 * Struct to hold information about a fully qualified JS name
214 */
215 private static class JsName implements Comparable<JsName> {
216 /** Fully qualified name */
217 String name;
218
219 /** Name of prototype functions attached to this name */
220 List<String> prototypeNames = Lists.newArrayList();
221
222 /** Whether this is an externally defined name */
223 boolean externallyDefined = false;
224
225 /** Whether this node is referenced */
226 boolean referenced = false;
227
228 /** Whether the name has descendants that are written to. */
229 boolean hasWrittenDescendants = false;
230
231 /** Whether the name is used in a instanceof check */
232 boolean hasInstanceOfReference = false;
233
234 /**
235 * Output the node as a string
236 *
237 * @return Node as a string
238 */
239 @Override
240 public String toString() {
241 StringBuilder out = new StringBuilder();
242 out.append(name);
243
244 if (prototypeNames.size() > 0) {
245 out.append(" (CLASS)\n");
246 out.append(" - FUNCTIONS: ");
247 Iterator<String> pIter = prototypeNames.iterator();
248 while (pIter.hasNext()) {
249 out.append(pIter.next());
250 if (pIter.hasNext()) {
251 out.append(", ");
252 }
253 }
254 }
255
256 return out.toString();
257 }
258
259 @Override
260 public int compareTo(JsName rhs) {
261 return this.name.compareTo(rhs.name);
262 }
263 }
264
265 /**
266 * Interface to get information about and remove unreferenced names.
267 */
268 interface RefNode {
269 JsName name();
270 void remove();
271 }
272
273 /**
274 * Class for nodes that reference a fully-qualified JS name. Fully qualified
275 * names are of form A or A.B (A.B.C, etc.). References can get the value or
276 * set the value of the JS name.
277 */
278 private class JsNameRefNode implements RefNode {
279 /** JsName node for this reference */
280 JsName name;
281
282 /**
283 * Top GETPROP or NAME or STRING [objlit key] node defining the name of
284 * this node
285 */
286 @SuppressWarnings("unused")
287 Node node;
288
289 /**
290 * Parent node of the name access
291 * (ASSIGN, VAR, FUNCTION, OBJECTLIT, or CALL)
292 */
293 Node parent;
294
295
296 /**
297 * Create a node that refers to a name
298 *
299 * @param name The name
300 * @param node The top node representing the name (GETPROP, NAME, STRING)
301 */
302 JsNameRefNode(JsName name, Node node) {
303 this.name = name;
304 this.node = node;
305 this.parent = node.getParent();
306 }
307
308 @Override
309 public JsName name() {
310 return name;
311 }
312
313 @Override
314 public void remove() {
315 // Setters have VAR, FUNCTION, or ASSIGN parent nodes. CALL parent
316 // nodes are global refs, and are handled later in this function.
317 Node containingNode = parent.getParent();
318 switch (parent.getType()) {
319 case Token.VAR:
320 Preconditions.checkState(parent.hasOneChild());
321 replaceWithRhs(containingNode, parent);
322 break;
323 case Token.FUNCTION:
324 replaceWithRhs(containingNode, parent);
325 break;
326 case Token.ASSIGN:
327 if (containingNode.isExprResult()) {
328 replaceWithRhs(containingNode.getParent(), containingNode);
329 } else {
330 replaceWithRhs(containingNode, parent);
331 }
332 break;
333 case Token.OBJECTLIT:
334 // TODO(nicksantos): Come up with a way to remove this.
335 // If we remove object lit keys, then we will need to also
336 // create dependency scopes for them.
337 break;
338 }
339 }
340 }
341
342
343 /**
344 * Class for nodes that set prototype properties or methods.
345 */
346 private class PrototypeSetNode extends JsNameRefNode {
347 /**
348 * Create a set node from the name & setter node
349 *
350 * @param name The name
351 * @param parent Parent node that assigns the expression (an ASSIGN)
352 */
353 PrototypeSetNode(JsName name, Node parent) {
354 super(name, parent.getFirstChild());
355
356 Preconditions.checkState(parent.isAssign());
357 }
358
359 @Override public void remove() {
360 Node gramps = parent.getParent();
361 if (gramps.isExprResult()) {
362 // name.prototype.foo = function() { ... };
363 changeProxy.removeChild(gramps.getParent(), gramps);
364 } else {
365 // ... name.prototype.foo = function() { ... } ...
366 changeProxy.replaceWith(gramps, parent,
367 parent.getLastChild().detachFromParent());
368 }
369 }
370 }
371
372 /**
373 * Base class for special reference nodes.
374 */
375 private abstract class SpecialReferenceNode implements RefNode {
376 /** JsName node for the function */
377 JsName name;
378
379 /** The CALL node */
380 Node node;
381
382 /**
383 * Create a special reference node.
384 *
385 * @param name The name
386 * @param node The CALL node
387 */
388 SpecialReferenceNode(JsName name, Node node) {
389 this.name = name;
390 this.node = node;
391 }
392
393 @Override
394 public JsName name() {
395 return name;
396 }
397
398 Node getParent() {
399 return node.getParent();
400 }
401
402 Node getGramps() {
403 return node.getParent() == null ? null : node.getParent().getParent();
404 }
405 }
406
407
408
409 /**
410 * Class for nodes that are function calls that may change a function's
411 * prototype
412 */
413 private class ClassDefiningFunctionNode extends SpecialReferenceNode {
414 /**
415 * Create a class defining function node from the name & setter node
416 *
417 * @param name The name
418 * @param node The CALL node
419 */
420 ClassDefiningFunctionNode(JsName name, Node node) {
421 super(name, node);
422 Preconditions.checkState(node.isCall());
423 }
424
425 @Override
426 public void remove() {
427 Preconditions.checkState(node.isCall());
428 Node parent = getParent();
429 if (parent.isExprResult()) {
430 changeProxy.removeChild(getGramps(), parent);
431 } else {
432 changeProxy.replaceWith(parent, node, IR.voidNode(IR.number(0)));
433 }
434 }
435 }
436
437
438
439 /**
440 * Class for nodes that check instanceof
441 */
442 private class InstanceOfCheckNode extends SpecialReferenceNode {
443 /**
444 * Create an instanceof node from the name and parent node
445 *
446 * @param name The name
447 * @param node The qualified name node
448 */
449 InstanceOfCheckNode(JsName name, Node node) {
450 super(name, node);
451 Preconditions.checkState(node.isQualifiedName());
452 Preconditions.checkState(getParent().isInstanceOf());
453 }
454
455 @Override
456 public void remove() {
457 changeProxy.replaceWith(getGramps(), getParent(), IR.falseNode());
458 }
459 }
460
461 /**
462 * Walk through externs and mark nodes as externally declared if declared
463 */
464 private class ProcessExternals extends AbstractPostOrderCallback {
465 @Override
466 public void visit(NodeTraversal t, Node n, Node parent) {
467 NameInformation ns = null;
468 if (NodeUtil.isVarDeclaration(n)) {
469 ns = createNameInformation(t, n);
470 } else if (NodeUtil.isFunctionDeclaration(n)) {
471 ns = createNameInformation(t, n.getFirstChild());
472 }
473 if (ns != null) {
474 JsName jsName = getName(ns.name, true);
475 jsName.externallyDefined = true;
476 externalNames.add(ns.name);
477 }
478 }
479 }
480
481 /**
482 * <p>Identifies all dependency scopes.
483 *
484 * <p>A dependency scope is a relationship between a node tree and a name that
485 * implies that the node tree will not execute (and thus can be eliminated) if
486 * the name is never referenced.
487 *
488 * <p>The entire parse tree is ultimately in a dependency scope relationship
489 * with <code>window</code> (or an equivalent name for the global scope), but
490 * the goal here is to find finer-grained relationships. This callback creates
491 * dependency scopes for every assignment statement, variable declaration, and
492 * function call in the global scope.
493 *
494 * <p>Note that dependency scope node trees aren't necessarily disjoint.
495 * In the following code snippet, for example, the function definition
496 * forms a dependency scope with the name <code>f</code> and the assignment
497 * inside the function forms a dependency scope with the name <code>x</code>.
498 * <pre>
499 * var x; function f() { x = 1; }
500 * </pre>
501 */
502 private class FindDependencyScopes extends AbstractPostOrderCallback {
503 @Override
504 public void visit(NodeTraversal t, Node n, Node parent) {
505 if (!t.inGlobalScope()) {
506 return;
507 }
508
509 if (n.isAssign()) {
510 recordAssignment(t, n, n);
511 if (!NodeUtil.isImmutableResult(n.getLastChild())) {
512 recordConsumers(t, n, n);
513 }
514 } else if (NodeUtil.isVarDeclaration(n)) {
515 NameInformation ns = createNameInformation(t, n);
516 recordDepScope(n, ns);
517 } else if (NodeUtil.isFunctionDeclaration(n)) {
518 NameInformation ns = createNameInformation(t, n.getFirstChild());
519 recordDepScope(n, ns);
520 } else if (NodeUtil.isExprCall(n)) {
521 Node callNode = n.getFirstChild();
522 Node nameNode = callNode.getFirstChild();
523 NameInformation ns = createNameInformation(t, nameNode);
524 if (ns != null && ns.onlyAffectsClassDef) {
525 recordDepScope(n, ns);
526 }
527 }
528 }
529
530 private void recordConsumers(NodeTraversal t, Node n, Node recordNode) {
531 Node parent = n.getParent();
532 switch (parent.getType()) {
533 case Token.ASSIGN:
534 if (n == parent.getLastChild()) {
535 recordAssignment(t, parent, recordNode);
536 }
537 recordConsumers(t, parent, recordNode);
538 break;
539 case Token.NAME:
540 NameInformation ns = createNameInformation(t, parent);
541 recordDepScope(recordNode, ns);
542 break;
543 case Token.OR:
544 recordConsumers(t, parent, recordNode);
545 break;
546 case Token.AND:
547 // In "a && b" only "b" can be meaningfully aliased.
548 // "a" must be falsy, which it must be an immutable, non-Object
549 case Token.COMMA:
550 case Token.HOOK:
551 if (n != parent.getFirstChild()) {
552 recordConsumers(t, parent, recordNode);
553 }
554 break;
555 }
556 }
557
558 private void recordAssignment(NodeTraversal t, Node n, Node recordNode) {
559 Node nameNode = n.getFirstChild();
560 Node parent = n.getParent();
561 NameInformation ns = createNameInformation(t, nameNode);
562 if (ns != null) {
563 if (parent.isFor() && !NodeUtil.isForIn(parent)) {
564 // Patch for assignments that appear in the init,
565 // condition or iteration part of a FOR loop. Without
566 // this change, all 3 of those parts try to claim the for
567 // loop as their dependency scope. The last assignment in
568 // those three fields wins, which can result in incorrect
569 // reference edges between referenced and assigned variables.
570 //
571 // TODO(user) revisit the dependency scope calculation
572 // logic.
573 if (parent.getFirstChild().getNext() != n) {
574 recordDepScope(recordNode, ns);
575 } else {
576 recordDepScope(nameNode, ns);
577 }
578 } else {
579 recordDepScope(recordNode, ns);
580 }
581 }
582 }
583
584 /**
585 * Defines a dependency scope.
586 */
587 private void recordDepScope(Node node, NameInformation name) {
588 Preconditions.checkNotNull(name);
589 scopes.put(node, name);
590 }
591 }
592
593 /**
594 * Create JsName objects for variable and function declarations in
595 * the global scope before computing name references. In JavaScript
596 * it is legal to refer to variable and function names before the
597 * actual declaration.
598 */
599 private class HoistVariableAndFunctionDeclarations
600 extends NodeTraversal.AbstractShallowCallback {
601
602 @Override
603 public void visit(NodeTraversal t, Node n, Node parent) {
604 if (NodeUtil.isVarDeclaration(n)) {
605 NameInformation ns = createNameInformation(t, n);
606 Preconditions.checkNotNull(ns, "NameInformation is null");
607 createName(ns.name);
608 } else if (NodeUtil.isFunctionDeclaration(n)) {
609 Node nameNode = n.getFirstChild();
610 NameInformation ns = createNameInformation(t, nameNode);
611 Preconditions.checkNotNull(ns, "NameInformation is null");
612 createName(nameNode.getString());
613 }
614 }
615 }
616
617 /**
618 * Identifies all declarations of global names and setter statements
619 * affecting global symbols (assignments to global names).
620 *
621 * All declarations and setters must be gathered in a single
622 * traversal and stored in traversal order so "removeUnreferenced"
623 * can perform modifications in traversal order.
624 */
625 private class FindDeclarationsAndSetters extends AbstractPostOrderCallback {
626
627 @Override
628 public void visit(NodeTraversal t, Node n, Node parent) {
629
630 // Record global variable and function declarations
631 if (t.inGlobalScope()) {
632 if (NodeUtil.isVarDeclaration(n)) {
633 NameInformation ns = createNameInformation(t, n);
634 Preconditions.checkNotNull(ns);
635 recordSet(ns.name, n);
636 } else if (NodeUtil.isFunctionDeclaration(n)) {
637 Node nameNode = n.getFirstChild();
638 NameInformation ns = createNameInformation(t, nameNode);
639 if (ns != null) {
640 JsName nameInfo = getName(nameNode.getString(), true);
641 recordSet(nameInfo.name, nameNode);
642 }
643 } else if (NodeUtil.isObjectLitKey(n)) {
644 NameInformation ns = createNameInformation(t, n);
645 if (ns != null) {
646 recordSet(ns.name, n);
647 }
648 }
649 }
650
651 // Record assignments and call sites
652 if (n.isAssign()) {
653 Node nameNode = n.getFirstChild();
654
655 NameInformation ns = createNameInformation(t, nameNode);
656 if (ns != null) {
657 if (ns.isPrototype) {
658 recordPrototypeSet(ns.prototypeClass, ns.prototypeProperty, n);
659 } else {
660 recordSet(ns.name, nameNode);
661 }
662 }
663 } else if (n.isCall()) {
664 Node nameNode = n.getFirstChild();
665 NameInformation ns = createNameInformation(t, nameNode);
666 if (ns != null && ns.onlyAffectsClassDef) {
667 JsName name = getName(ns.name, true);
668 refNodes.add(new ClassDefiningFunctionNode(name, n));
669 }
670 }
671 }
672
673 /**
674 * Records the assignment of a value to a global name.
675 *
676 * @param name Fully qualified name
677 * @param node The top node representing the name (GETPROP, NAME, or STRING
678 * [objlit key])
679 */
680 private void recordSet(String name, Node node) {
681 JsName jsn = getName(name, true);
682 JsNameRefNode nameRefNode = new JsNameRefNode(jsn, node);
683 refNodes.add(nameRefNode);
684
685 // Now, look at all parent names and record that their properties have
686 // been written to.
687 if (node.isGetElem()) {
688 recordWriteOnProperties(name);
689 } else if (name.indexOf('.') != -1) {
690 recordWriteOnProperties(name.substring(0, name.lastIndexOf('.')));
691 }
692 }
693
694 /**
695 * Records the assignment to a prototype property of a global name,
696 * if possible.
697 *
698 * @param className The name of the class.
699 * @param prototypeProperty The name of the prototype property.
700 * @param node The top node representing the name (GETPROP)
701 */
702 private void recordPrototypeSet(String className, String prototypeProperty,
703 Node node) {
704 JsName name = getName(className, true);
705 name.prototypeNames.add(prototypeProperty);
706 refNodes.add(new PrototypeSetNode(name, node));
707 recordWriteOnProperties(className);
708 }
709
710 /**
711 * Record that the properties of this name have been written to.
712 */
713 private void recordWriteOnProperties(String parentName) {
714 do {
715 JsName parent = getName(parentName, true);
716 if (parent.hasWrittenDescendants) {
717 // If we already recorded this name, then all its parents must
718 // also be recorded. short-circuit this loop.
719 return;
720 } else {
721 parent.hasWrittenDescendants = true;
722 }
723
724 if (parentName.indexOf('.') == -1) {
725 return;
726 }
727 parentName = parentName.substring(0, parentName.lastIndexOf('.'));
728 } while(true);
729 }
730 }
731
732 private static final Predicate<Node> NON_LOCAL_RESULT_PREDICATE =
733 new Predicate<Node>() {
734 @Override
735 public boolean apply(Node input) {
736 if (input.isCall()) {
737 return false;
738 }
739 // TODO(johnlenz): handle NEW calls that record their 'this'
740 // in global scope and effectively return an alias.
741 // Other non-local references are handled by this pass.
742 return true;
743 }
744 };
745
746 /**
747 * <p>Identifies all references between global names.
748 *
749 * <p>A reference from a name <code>f</code> to a name <code>g</code> means
750 * that if the name <code>f</code> must be defined, then the name
751 * <code>g</code> must also be defined. This would be the case if, for
752 * example, <code>f</code> were a function that called <code>g</code>.
753 */
754 private class FindReferences implements Callback {
755 Set<Node> nodesToKeep;
756 FindReferences() {
757 nodesToKeep = Sets.newHashSet();
758 }
759
760 private void addAllChildren(Node n) {
761 nodesToKeep.add(n);
762 for (Node child = n.getFirstChild();
763 child != null;
764 child = child.getNext()) {
765 addAllChildren(child);
766 }
767 }
768
769 private void addSimplifiedChildren(Node n) {
770 NodeTraversal.traverse(
771 compiler, n,
772 new GatherSideEffectSubexpressionsCallback(
773 compiler, new NodeAccumulator()));
774 }
775
776 private void addSimplifiedExpression(Node n, Node parent) {
777 if (parent.isVar()) {
778 Node value = n.getFirstChild();
779 if (value != null) {
780 addSimplifiedChildren(value);
781 }
782 } else if (n.isAssign() &&
783 (parent.isExprResult() ||
784 parent.isFor() ||
785 parent.isReturn())) {
786 for (Node child : n.children()) {
787 addSimplifiedChildren(child);
788 }
789 } else if (n.isCall() &&
790 parent.isExprResult()) {
791 addSimplifiedChildren(n);
792 } else {
793 addAllChildren(n);
794 }
795 }
796
797 @Override
798 public boolean shouldTraverse(NodeTraversal t, Node n, Node parent) {
799 if (parent == null) {
800 return true;
801 }
802
803 // Gather the list of nodes that either have side effects, are
804 // arguments to function calls with side effects or are used in
805 // control structure predicates. These names are always
806 // referenced when the enclosing function is called.
807 if (n.isFor()) {
808 if (!NodeUtil.isForIn(n)) {
809 Node decl = n.getFirstChild();
810 Node pred = decl.getNext();
811 Node step = pred.getNext();
812 addSimplifiedExpression(decl, n);
813 addSimplifiedExpression(pred, n);
814 addSimplifiedExpression(step, n);
815 } else { // n.getChildCount() == 3
816 Node decl = n.getFirstChild();
817 Node iter = decl.getNext();
818 addAllChildren(decl);
819 addAllChildren(iter);
820 }
821 }
822
823 if (parent.isVar() ||
824 parent.isExprResult() ||
825 parent.isReturn() ||
826 parent.isThrow()) {
827 addSimplifiedExpression(n, parent);
828 }
829
830 if ((parent.isIf() ||
831 parent.isWhile() ||
832 parent.isWith() ||
833 parent.isSwitch() ||
834 parent.isCase()) &&
835 parent.getFirstChild() == n) {
836 addAllChildren(n);
837 }
838
839 if (parent.isDo() && parent.getLastChild() == n) {
840 addAllChildren(n);
841 }
842
843 return true;
844 }
845
846 @Override
847 public void visit(NodeTraversal t, Node n, Node parent) {
848 if (!(n.isName() ||
849 NodeUtil.isGet(n) && !parent.isGetProp())) {
850 // This is not a simple or qualified name.
851 return;
852 }
853
854 NameInformation nameInfo = createNameInformation(t, n);
855 if (nameInfo == null) {
856 // The name is not a global name
857 return;
858 }
859
860 if (nameInfo.onlyAffectsClassDef) {
861 if (nameInfo.superclass != null) {
862 recordReference(
863 nameInfo.name, nameInfo.superclass, RefType.INHERITANCE);
864 }
865
866 // Make sure that we record a reference to the function that does
867 // the inheritance, so that the inherits() function itself does
868 // not get stripped.
869 String nodeName = n.getQualifiedName();
870 if (nodeName != null) {
871 recordReference(
872 nameInfo.name, nodeName, RefType.REGULAR);
873 }
874
875 return;
876 }
877
878 if (parent.isInstanceOf() &&
879 parent.getLastChild() == n &&
880 // Don't cover GETELEMs with a global root node.
881 n.isQualifiedName()) {
882 JsName checkedClass = getName(nameInfo.name, true);
883 refNodes.add(new InstanceOfCheckNode(checkedClass, n));
884 checkedClass.hasInstanceOfReference = true;
885 return;
886 }
887
888 // Determine which name might be potentially referring to this one by
889 // looking up the nearest enclosing dependency scope. It's unnecessary to
890 // determine all enclosing dependency scopes because this callback should
891 // create a chain of references between them.
892 List<NameInformation> referers = getDependencyScope(n);
893 if (referers.isEmpty()) {
894 maybeRecordReferenceOrAlias(t, n, parent, nameInfo, null);
895 } else {
896 for (NameInformation referring : referers) {
897 maybeRecordReferenceOrAlias(t, n, parent, nameInfo, referring);
898 }
899 recordAliases(referers);
900 }
901 }
902
903 private void maybeRecordReferenceOrAlias(
904 NodeTraversal t, Node n, Node parent,
905 NameInformation nameInfo, NameInformation referring) {
906 String referringName = "";
907 if (referring != null) {
908 referringName = referring.isPrototype
909 ? referring.prototypeClass
910 : referring.name;
911 }
912
913 String name = nameInfo.name;
914
915 // A value whose result is the return value of a function call
916 // can be an alias to global object.
917 // Here we add a alias to the general "global" object
918 // to act as a placeholder for the actual (unnamed) value.
919 if (maybeHiddenAlias(n)) {
920 recordAlias(name, WINDOW);
921 }
922
923 // An externally referenceable name must always be defined, so we add a
924 // reference to it from the global scope (a.k.a. window).
925 if (nameInfo.isExternallyReferenceable) {
926 recordReference(WINDOW, name, RefType.REGULAR);
927 maybeRecordAlias(name, parent, referring, referringName);
928 return;
929 }
930
931 // An assignment implies a reference from the enclosing dependency scope.
932 // For example, foo references bar in: function foo() {bar=5}.
933 if (NodeUtil.isVarOrSimpleAssignLhs(n, parent)) {
934 if (referring != null) {
935 recordReference(referringName, name, RefType.REGULAR);
936 }
937 return;
938 }
939
940 if (nodesToKeep.contains(n)) {
941 List<NameInformation> functionScopes =
942 getEnclosingFunctionDependencyScope(t);
943 if (!functionScopes.isEmpty()) {
944 for (NameInformation functionScope : functionScopes) {
945 recordReference(functionScope.name, name, RefType.REGULAR);
946 }
947 } else {
948 recordReference(WINDOW, name, RefType.REGULAR);
949 if (referring != null) {
950 maybeRecordAlias(name, parent, referring, referringName);
951 }
952 }
953 } else if (referring != null) {
954 if (!maybeRecordAlias(name, parent, referring, referringName)) {
955 RefType depType = referring.onlyAffectsClassDef ?
956 RefType.INHERITANCE : RefType.REGULAR;
957 recordReference(referringName, name, depType);
958 }
959 } else {
960 // No named dependency scope found. Unfortunately that might
961 // mean that the expression is a child of an function expression
962 // or assignment with a complex lhs. In those cases,
963 // protect this node by creating a reference to WINDOW.
964 for (Node ancestor : n.getAncestors()) {
965 if (NodeUtil.isAssignmentOp(ancestor) ||
966 ancestor.isFunction()) {
967 recordReference(WINDOW, name, RefType.REGULAR);
968 break;
969 }
970 }
971 }
972 }
973
974 private void recordAliases(List<NameInformation> referers) {
975 int size = referers.size();
976 for (int i = 0; i < size; i++) {
977 for (int j = i + 1; j < size; j++) {
978 recordAlias(referers.get(i).name, referers.get(j).name);
979 recordAlias(referers.get(j).name, referers.get(i).name);
980 }
981 }
982 }
983
984 /**
985 * A value whose result is the return value of a function call
986 * can be an alias to global object. The dependency on the call target will
987 * prevent the removal of the function and its dependent values, but won't
988 * prevent the alias' removal.
989 */
990 private boolean maybeHiddenAlias(Node n) {
991 Node parent = n.getParent();
992 if (NodeUtil.isVarOrSimpleAssignLhs(n, parent)) {
993 Node rhs = (parent.isVar())
994 ? n.getFirstChild() : parent.getLastChild();
995 return (rhs != null && !NodeUtil.evaluatesToLocalValue(
996 rhs, NON_LOCAL_RESULT_PREDICATE));
997 }
998 return false;
999 }
1000
1001 /**
1002 * @return Whether the alias was recorded.
1003 */
1004 private boolean maybeRecordAlias(
1005 String name, Node parent,
1006 NameInformation referring, String referringName) {
1007 // A common type of reference is
1008 // function F() {}
1009 // F.prototype.bar = goog.nullFunction;
1010 //
1011 // In this specific case, we do not want a reference to goog.nullFunction
1012 // to preserve F.
1013 //
1014 // In the general case, the user could do something like
1015 // function F() {}
1016 // F.prototype.bar = goog.nullFunction;
1017 // F.prototype.bar.baz = 3;
1018 // where it would not be safe to remove F.
1019 //
1020 // So we do not treat this alias as a backdoor for people to mutate the
1021 // original object. We think that this heuristic will always be
1022 // OK in real code.
1023 boolean isPrototypePropAssignment =
1024 parent.isAssign()
1025 && NodeUtil.isPrototypeProperty(parent.getFirstChild());
1026
1027 if ((parent.isName() ||
1028 parent.isAssign()) &&
1029 !isPrototypePropAssignment &&
1030 referring != null &&
1031 scopes.get(parent).contains(referring)) {
1032 recordAlias(referringName, name);
1033 return true;
1034 }
1035 return false;
1036 }
1037
1038 /**
1039 * Helper class that gathers the list of nodes that would be left
1040 * behind after simplification.
1041 */
1042 private class NodeAccumulator
1043 implements SideEffectAccumulator {
1044
1045 @Override
1046 public boolean classDefiningCallsHaveSideEffects() {
1047 return false;
1048 }
1049
1050 @Override
1051 public void keepSubTree(Node original) {
1052 addAllChildren(original);
1053 }
1054
1055 @Override
1056 public void keepSimplifiedShortCircuitExpression(Node original) {
1057 Node condition = original.getFirstChild();
1058 Node thenBranch = condition.getNext();
1059 addAllChildren(condition);
1060 addSimplifiedChildren(thenBranch);
1061 }
1062
1063 @Override
1064 public void keepSimplifiedHookExpression(Node hook,
1065 boolean thenHasSideEffects,
1066 boolean elseHasSideEffects) {
1067 Node condition = hook.getFirstChild();
1068 Node thenBranch = condition.getNext();
1069 Node elseBranch = thenBranch.getNext();
1070 addAllChildren(condition);
1071 if (thenHasSideEffects) {
1072 addSimplifiedChildren(thenBranch);
1073 }
1074 if (elseHasSideEffects) {
1075 addSimplifiedChildren(elseBranch);
1076 }
1077 }
1078 }
1079 }
1080
1081 private class RemoveListener implements AstChangeProxy.ChangeListener {
1082 @Override
1083 public void nodeRemoved(Node n) {
1084 compiler.reportCodeChange();
1085 }
1086 }
1087
1088 /**
1089 * Creates a name analyzer, with option to remove unreferenced variables when
1090 * calling process().
1091 *
1092 * The analyzer make a best guess at whether functions affect global scope
1093 * based on usage (no assignment of return value means that a function has
1094 * side effects).
1095 *
1096 * @param compiler The AbstractCompiler
1097 * @param removeUnreferenced If true, remove unreferenced variables during
1098 * process()
1099 */
1100 NameAnalyzer(AbstractCompiler compiler, boolean removeUnreferenced) {
1101 this.compiler = compiler;
1102 this.removeUnreferenced = removeUnreferenced;
1103 this.globalNames = DEFAULT_GLOBAL_NAMES;
1104 this.changeProxy = new AstChangeProxy();
1105 }
1106
1107 @Override
1108 public void process(Node externs, Node root) {
1109 NodeTraversal.traverse(compiler, externs, new ProcessExternals());
1110 NodeTraversal.traverse(compiler, root, new FindDependencyScopes());
1111 NodeTraversal.traverse(
1112 compiler, root, new HoistVariableAndFunctionDeclarations());
1113 NodeTraversal.traverse(compiler, root, new FindDeclarationsAndSetters());
1114 NodeTraversal.traverse(compiler, root, new FindReferences());
1115
1116 // Create bi-directional references between parent names and their
1117 // descendants. This may create new names.
1118 referenceParentNames();
1119
1120 // If we modify the property of an alias, make sure that modification
1121 // gets reflected in the original object.
1122 referenceAliases();
1123
1124 calculateReferences();
1125
1126 if (removeUnreferenced) {
1127 removeUnreferenced();
1128 }
1129 }
1130
1131 /**
1132 * Records an alias of one name to another name.
1133 */
1134 private void recordAlias(String fromName, String toName) {
1135 recordReference(fromName, toName, RefType.REGULAR);
1136
1137 // We need to add an edge to the alias graph. The alias graph is expressed
1138 // implicitly as a set of connected components, called AliasSets.
1139 //
1140 // There are three possibilities:
1141 // 1) Neither name is part of a connected component. Create a new one.
1142 // 2) Exactly one name is part of a connected component. Merge the new
1143 // name into the component.
1144 // 3) The two names are already part of connected components. Merge
1145 // those components together.
1146 AliasSet toNameAliasSet = aliases.get(toName);
1147 AliasSet fromNameAliasSet = aliases.get(fromName);
1148 AliasSet resultSet = null;
1149 if (toNameAliasSet == null && fromNameAliasSet == null) {
1150 resultSet = new AliasSet(toName, fromName);
1151 } else if (toNameAliasSet != null && fromNameAliasSet != null) {
1152 resultSet = toNameAliasSet;
1153 resultSet.names.addAll(fromNameAliasSet.names);
1154 for (String name : fromNameAliasSet.names) {
1155 aliases.put(name, resultSet);
1156 }
1157 } else if (toNameAliasSet != null) {
1158 resultSet = toNameAliasSet;
1159 resultSet.names.add(fromName);
1160 } else {
1161 resultSet = fromNameAliasSet;
1162 resultSet.names.add(toName);
1163 }
1164 aliases.put(fromName, resultSet);
1165 aliases.put(toName, resultSet);
1166 }
1167
1168 /**
1169 * Records a reference from one name to another name.
1170 */
1171 private void recordReference(String fromName, String toName,
1172 RefType depType) {
1173 if (fromName.equals(toName)) {
1174 // Don't bother recording self-references.
1175 return;
1176 }
1177
1178 JsName from = getName(fromName, true);
1179 JsName to = getName(toName, true);
1180 referenceGraph.createNode(from);
1181 referenceGraph.createNode(to);
1182 if (!referenceGraph.isConnectedInDirection(from, depType, to)) {
1183 referenceGraph.connect(from, depType, to);
1184 }
1185 }
1186
1187 /**
1188 * Removes all unreferenced variables.
1189 */
1190 void removeUnreferenced() {
1191 RemoveListener listener = new RemoveListener();
1192 changeProxy.registerListener(listener);
1193
1194 for (RefNode refNode : refNodes) {
1195 JsName name = refNode.name();
1196 if (!name.referenced && !name.externallyDefined) {
1197 refNode.remove();
1198 }
1199 }
1200
1201 changeProxy.unregisterListener(listener);
1202 }
1203
1204 /**
1205 * Generates an HTML report
1206 *
1207 * @return The report
1208 */
1209 String getHtmlReport() {
1210 StringBuilder sb = new StringBuilder();
1211 sb.append("<html><body><style type=\"text/css\">"
1212 + "body, td, p {font-family: Arial; font-size: 83%} "
1213 + "ul {margin-top:2px; margin-left:0px; padding-left:1em;} "
1214 + "li {margin-top:3px; margin-left:24px; padding-left:0px;"
1215 + "padding-bottom: 4px}</style>");
1216 sb.append("OVERALL STATS<ul>");
1217 appendListItem(sb, "Total Names: " + countOf(TriState.BOTH, TriState.BOTH));
1218 appendListItem(sb, "Total Classes: "
1219 + countOf(TriState.TRUE, TriState.BOTH));
1220 appendListItem(sb, "Total Static Functions: "
1221 + countOf(TriState.FALSE, TriState.BOTH));
1222 appendListItem(sb, "Referenced Names: "
1223 + countOf(TriState.BOTH, TriState.TRUE));
1224 appendListItem(sb, "Referenced Classes: "
1225 + countOf(TriState.TRUE, TriState.TRUE));
1226 appendListItem(sb, "Referenced Functions: "
1227 + countOf(TriState.FALSE, TriState.TRUE));
1228 sb.append("</ul>");
1229
1230 sb.append("ALL NAMES<ul>\n");
1231 for (JsName node : allNames.values()) {
1232 sb.append("<li>" + nameAnchor(node.name) + "<ul>");
1233 if (node.prototypeNames.size() > 0) {
1234 sb.append("<li>PROTOTYPES: ");
1235 Iterator<String> protoIter = node.prototypeNames.iterator();
1236 while (protoIter.hasNext()) {
1237 sb.append(protoIter.next());
1238 if (protoIter.hasNext()) {
1239 sb.append(", ");
1240 }
1241 }
1242 }
1243
1244 if (referenceGraph.hasNode(node)) {
1245 List<DiGraphEdge<JsName, RefType>> refersTo =
1246 referenceGraph.getOutEdges(node);
1247 if (refersTo.size() > 0) {
1248 sb.append("<li>REFERS TO: ");
1249 Iterator<DiGraphEdge<JsName, RefType>> toIter = refersTo.iterator();
1250 while (toIter.hasNext()) {
1251 sb.append(nameLink(toIter.next().getDestination().getValue().name));
1252 if (toIter.hasNext()) {
1253 sb.append(", ");
1254 }
1255 }
1256 }
1257
1258 List<DiGraphEdge<JsName, RefType>> referencedBy =
1259 referenceGraph.getInEdges(node);
1260 if (referencedBy.size() > 0) {
1261 sb.append("<li>REFERENCED BY: ");
1262 Iterator<DiGraphEdge<JsName, RefType>> fromIter = refersTo.iterator();
1263 while (fromIter.hasNext()) {
1264 sb.append(
1265 nameLink(fromIter.next().getDestination().getValue().name));
1266 if (fromIter.hasNext()) {
1267 sb.append(", ");
1268 }
1269 }
1270 }
1271 }
1272 sb.append("</li>");
1273 sb.append("</ul></li>");
1274 }
1275 sb.append("</ul>");
1276 sb.append("</body></html>");
1277
1278 return sb.toString();
1279 }
1280
1281 private void appendListItem(StringBuilder sb, String text) {
1282 sb.append("<li>" + text + "</li>\n");
1283 }
1284
1285 private String nameLink(String name) {
1286 return "<a href=\"#" + name + "\">" + name + "</a>";
1287 }
1288
1289 private String nameAnchor(String name) {
1290 return "<a name=\"" + name + "\">" + name + "</a>";
1291 }
1292
1293 /**
1294 * Looks up a {@link JsName} by name, optionally creating one if it doesn't
1295 * already exist.
1296 *
1297 * @param name A fully qualified name
1298 * @param canCreate Whether to create the object if necessary
1299 * @return The {@code JsName} object, or null if one can't be found and
1300 * can't be created.
1301 */
1302 private JsName getName(String name, boolean canCreate) {
1303 if (canCreate) {
1304 createName(name);
1305 }
1306 return allNames.get(name);
1307 }
1308
1309 /**
1310 * Creates a {@link JsName} for the given name if it doesn't already
1311 * exist.
1312 *
1313 * @param name A fully qualified name
1314 */
1315 private void createName(String name) {
1316 JsName jsn = allNames.get(name);
1317 if (jsn == null) {
1318 jsn = new JsName();
1319 jsn.name = name;
1320 allNames.put(name, jsn);
1321 }
1322 }
1323
1324 /**
1325 * The NameAnalyzer algorithm works best when all objects have a canonical
1326 * name in the global scope. When multiple names in the global scope
1327 * point to the same object, things start to break down.
1328 *
1329 * For example, if we have
1330 * <code>
1331 * var a = {};
1332 * var b = a;
1333 * a.foo = 3;
1334 * alert(b.foo);
1335 * </code>
1336 * then a.foo and b.foo are the same name, even though NameAnalyzer doesn't
1337 * represent them as such.
1338 *
1339 * To handle this case, we look at all the aliases in the program.
1340 * If descendant properties of that alias are assigned, then we create a
1341 * directional reference from the original name to the alias. For example,
1342 * in this case, the assign to {@code a.foo} triggers a reference from
1343 * {@code b} to {@code a}, but NOT from a to b.
1344 *
1345 * Similarly, "instanceof" checks do not prevent the removal
1346 * of a unaliased name but an instanceof check on an alias can only be removed
1347 * if the other aliases are also removed, so we add a connection here.
1348 */
1349 private void referenceAliases() {
1350 for (Map.Entry<String, AliasSet> entry : aliases.entrySet()) {
1351 JsName name = getName(entry.getKey(), false);
1352 if (name.hasWrittenDescendants || name.hasInstanceOfReference) {
1353 for (String alias : entry.getValue().names) {
1354 recordReference(alias, entry.getKey(), RefType.REGULAR);
1355 }
1356 }
1357 }
1358 }
1359
1360 /**
1361 * Adds mutual references between all known global names and their parent
1362 * names. (e.g. between <code>a.b.c</code> and <code>a.b</code>).
1363 */
1364 private void referenceParentNames() {
1365 // Duplicate set of nodes to process so we don't modify set we are
1366 // currently iterating over
1367 Set<JsName> allNamesCopy = Sets.newHashSet(allNames.values());
1368
1369 for (JsName name : allNamesCopy) {
1370 String curName = name.name;
1371 JsName curJsName = name;
1372 while (curName.indexOf('.') != -1) {
1373 String parentName = curName.substring(0, curName.lastIndexOf('.'));
1374 if (!globalNames.contains(parentName)) {
1375
1376 JsName parentJsName = getName(parentName, true);
1377
1378 recordReference(curJsName.name, parentJsName.name, RefType.REGULAR);
1379 recordReference(parentJsName.name, curJsName.name, RefType.REGULAR);
1380
1381 curJsName = parentJsName;
1382 }
1383 curName = parentName;
1384 }
1385 }
1386 }
1387
1388 /**
1389 * Creates name information for the current node during a traversal.
1390 *
1391 * @param t The node traversal
1392 * @param n The current node
1393 * @return The name information, or null if the name is irrelevant to this
1394 * pass
1395 */
1396 private NameInformation createNameInformation(NodeTraversal t, Node n) {
1397 Node parent = n.getParent();
1398 // Build the full name and find its root node by iterating down through all
1399 // GETPROP/GETELEM nodes.
1400 String name = "";
1401 Node rootNameNode = n;
1402 boolean bNameWasShortened = false;
1403 while (true) {
1404 if (NodeUtil.isGet(rootNameNode)) {
1405 Node prop = rootNameNode.getLastChild();
1406 if (rootNameNode.isGetProp()) {
1407 name = "." + prop.getString() + name;
1408 } else {
1409 // We consider the name to be "a.b" in a.b['c'] or a.b[x].d.
1410 bNameWasShortened = true;
1411 name = "";
1412 }
1413 rootNameNode = rootNameNode.getFirstChild();
1414 } else if (NodeUtil.isObjectLitKey(rootNameNode)) {
1415 name = "." + rootNameNode.getString() + name;
1416
1417 // Check if this is an object literal assigned to something.
1418 Node objLit = rootNameNode.getParent();
1419 Node objLitParent = objLit.getParent();
1420 if (objLitParent.isAssign()) {
1421 // This must be the right side of the assign.
1422 rootNameNode = objLitParent.getFirstChild();
1423 } else if (objLitParent.isName()) {
1424 // This must be a VAR initialization.
1425 rootNameNode = objLitParent;
1426 } else if (objLitParent.isStringKey()) {
1427 // This must be a object literal key initialization.
1428 rootNameNode = objLitParent;
1429 } else {
1430 return null;
1431 }
1432 } else {
1433 break;
1434 }
1435 }
1436
1437 // Check whether this is a class-defining call. Classes may only be defined
1438 // in the global scope.
1439 if (parent.isCall() && t.inGlobalScope()) {
1440 CodingConvention convention = compiler.getCodingConvention();
1441 SubclassRelationship classes = convention.getClassesDefinedByCall(parent);
1442 if (classes != null) {
1443 NameInformation nameInfo = new NameInformation();
1444 nameInfo.name = classes.subclassName;
1445 nameInfo.onlyAffectsClassDef = true;
1446 nameInfo.superclass = classes.superclassName;
1447 return nameInfo;
1448 }
1449
1450 String singletonGetterClass =
1451 convention.getSingletonGetterClassName(parent);
1452 if (singletonGetterClass != null) {
1453 NameInformation nameInfo = new NameInformation();
1454 nameInfo.name = singletonGetterClass;
1455 nameInfo.onlyAffectsClassDef = true;
1456 return nameInfo;
1457 }
1458 }
1459
1460 switch (rootNameNode.getType()) {
1461 case Token.NAME:
1462 // Check whether this is an assignment to a prototype property
1463 // of an object defined in the global scope.
1464 if (!bNameWasShortened &&
1465 n.isGetProp() &&
1466 parent.isAssign() &&
1467 "prototype".equals(n.getLastChild().getString())) {
1468 if (createNameInformation(t, n.getFirstChild()) != null) {
1469 name = rootNameNode.getString() + name;
1470 name = name.substring(0, name.length() - PROTOTYPE_SUFFIX_LEN);
1471 NameInformation nameInfo = new NameInformation();
1472 nameInfo.name = name;
1473 return nameInfo;
1474 } else {
1475 return null;
1476 }
1477 }
1478 return createNameInformation(
1479 rootNameNode.getString() + name, t.getScope(), rootNameNode);
1480 case Token.THIS:
1481 if (t.inGlobalScope()) {
1482 NameInformation nameInfo = new NameInformation();
1483 if (name.indexOf('.') == 0) {
1484 nameInfo.name = name.substring(1); // strip leading "."
1485 } else {
1486 nameInfo.name = name;
1487 }
1488 nameInfo.isExternallyReferenceable = true;
1489 return nameInfo;
1490 }
1491 return null;
1492 default:
1493 return null;
1494 }
1495 }
1496
1497 /**
1498 * Creates name information for a particular qualified name that occurs in a
1499 * particular scope.
1500 *
1501 * @param name A qualified name (e.g. "x" or "a.b.c")
1502 * @param scope The scope in which {@code name} occurs
1503 * @param rootNameNode The NAME node for the first token of {@code name}
1504 * @return The name information, or null if the name is irrelevant to this
1505 * pass
1506 */
1507 private NameInformation createNameInformation(
1508 String name, Scope scope, Node rootNameNode) {
1509 // Check the scope. Currently we're only looking at globally scoped vars.
1510 String rootName = rootNameNode.getString();
1511 Var v = scope.getVar(rootName);
1512 boolean isExtern = (v == null && externalNames.contains(rootName));
1513 boolean isGlobalRef = (v != null && v.isGlobal()) || isExtern ||
1514 rootName.equals(WINDOW);
1515 if (!isGlobalRef) {
1516 return null;
1517 }
1518
1519 NameInformation nameInfo = new NameInformation();
1520
1521 // If a prototype property or method, fill in prototype information.
1522 int idx = name.indexOf(PROTOTYPE_SUBSTRING);
1523 if (idx != -1) {
1524 nameInfo.isPrototype = true;
1525 nameInfo.prototypeClass = name.substring(0, idx);
1526 nameInfo.prototypeProperty = name.substring(
1527 idx + PROTOTYPE_SUBSTRING_LEN);
1528 }
1529
1530 nameInfo.name = name;
1531 nameInfo.isExternallyReferenceable =
1532 isExtern || isExternallyReferenceable(scope, name);
1533 return nameInfo;
1534 }
1535
1536 /**
1537 * Checks whether a name can be referenced outside of the compiled code.
1538 * These names will be the root of dependency trees.
1539 *
1540 * @param scope The current variable scope
1541 * @param name The name
1542 * @return True if can be referenced outside
1543 */
1544 private boolean isExternallyReferenceable(Scope scope, String name) {
1545 if (compiler.getCodingConvention().isExported(name)) {
1546 return true;
1547 }
1548 if (scope.isLocal()) {
1549 return false;
1550 }
1551 for (String s : globalNames) {
1552 if (name.startsWith(s)) {
1553 return true;
1554 }
1555 }
1556 return false;
1557 }
1558
1559 /**
1560 * Gets the nearest enclosing dependency scope, or null if there isn't one.
1561 */
1562 private List<NameInformation> getDependencyScope(Node n) {
1563 for (Node node : n.getAncestors()) {
1564 List<NameInformation> refs = scopes.get(node);
1565 if (!refs.isEmpty()) {
1566 return refs;
1567 }
1568 }
1569
1570 return Collections.emptyList();
1571 }
1572
1573 /**
1574 * Get dependency scope defined by the enclosing function, or null.
1575 * If enclosing function is a function expression, determine scope based on
1576 * its parent if the parent node is a variable declaration or
1577 * assignment.
1578 */
1579 private List<NameInformation> getEnclosingFunctionDependencyScope(
1580 NodeTraversal t) {
1581 Node function = t.getEnclosingFunction();
1582 if (function == null) {
1583 return Collections.emptyList();
1584 }
1585
1586 List<NameInformation> refs = scopes.get(function);
1587 if (!refs.isEmpty()) {
1588 return refs;
1589 }
1590
1591 // Function expression. try to get a name from the parent var
1592 // declaration or assignment.
1593 Node parent = function.getParent();
1594 if (parent != null) {
1595 // Account for functions defined in the form:
1596 // var a = cond ? function a() {} : function b() {};
1597 while (parent.isHook()) {
1598 parent = parent.getParent();
1599 }
1600
1601 if (parent.isName()) {
1602 return scopes.get(parent);
1603 }
1604
1605 if (parent.isAssign()) {
1606 return scopes.get(parent);
1607 }
1608 }
1609
1610 return Collections.emptyList();
1611 }
1612
1613 /**
1614 * Propagate "referenced" property down the graph.
1615 */
1616 private void calculateReferences() {
1617 JsName window = getName(WINDOW, true);
1618 window.referenced = true;
1619 JsName function = getName(FUNCTION, true);
1620 function.referenced = true;
1621
1622 // Propagate "referenced" property to a fixed point.
1623 FixedPointGraphTraversal.newTraversal(new ReferencePropagationCallback())
1624 .computeFixedPoint(referenceGraph);
1625 }
1626
1627
1628 /**
1629 * Enum for saying a value can be true, false, or either (cleaner than using a
1630 * Boolean with null)
1631 */
1632 private enum TriState {
1633 /** If value is true */
1634 TRUE,
1635 /** If value is false */
1636 FALSE,
1637 /** If value can be true or false */
1638 BOTH
1639 }
1640
1641 /**
1642 * Gets the count of nodes matching the criteria
1643 *
1644 * @param isClass Whether the node is a class
1645 * @param referenced Whether the node is referenced
1646 * @return Number of matches
1647 */
1648 private int countOf(TriState isClass, TriState referenced) {
1649 int count = 0;
1650 for (JsName name : allNames.values()) {
1651
1652 boolean nodeIsClass = name.prototypeNames.size() > 0;
1653
1654 boolean classMatch = isClass == TriState.BOTH
1655 || (nodeIsClass && isClass == TriState.TRUE)
1656 || (!nodeIsClass && isClass == TriState.FALSE);
1657
1658 boolean referenceMatch = referenced == TriState.BOTH
1659 || (name.referenced && referenced == TriState.TRUE)
1660 || (!name.referenced && referenced == TriState.FALSE);
1661
1662 if (classMatch && referenceMatch && !name.externallyDefined) {
1663 count++;
1664 }
1665 }
1666 return count;
1667 }
1668
1669
1670 /**
1671 * Extract a list of replacement nodes to use.
1672 */
1673 private List<Node> getSideEffectNodes(Node n) {
1674 List<Node> subexpressions = Lists.newArrayList();
1675 NodeTraversal.traverse(
1676 compiler, n,
1677 new GatherSideEffectSubexpressionsCallback(
1678 compiler,
1679 new GetReplacementSideEffectSubexpressions(
1680 compiler, subexpressions)));
1681
1682 List<Node> replacements =
1683 Lists.newArrayListWithExpectedSize(subexpressions.size());
1684 for (Node subexpression : subexpressions) {
1685 replacements.add(NodeUtil.newExpr(subexpression));
1686 }
1687 return replacements;
1688 }
1689
1690 /**
1691 * Replace n with a simpler expression, while preserving program
1692 * behavior.
1693 *
1694 * If the n's value is used, replace it with its RHS; otherwise
1695 * replace it with the subexpressions that have side effects.
1696 */
1697 private void replaceWithRhs(Node parent, Node n) {
1698 if (valueConsumedByParent(n, parent)) {
1699 // parent reads from n directly; replace it with n's rhs + lhs
1700 // subexpressions with side effects.
1701 List<Node> replacements = getRhsSubexpressions(n);
1702 List<Node> newReplacements = Lists.newArrayList();
1703 for (int i = 0; i < replacements.size() - 1; i++) {
1704 newReplacements.addAll(getSideEffectNodes(replacements.get(i)));
1705 }
1706 Node valueExpr = replacements.get(replacements.size() - 1);
1707 valueExpr.detachFromParent();
1708 newReplacements.add(valueExpr);
1709 changeProxy.replaceWith(
1710 parent, n, collapseReplacements(newReplacements));
1711 } else if (n.isAssign() && !parent.isFor()) {
1712 // assignment appears in a RHS expression. we have already
1713 // considered names in the assignment's RHS as being referenced;
1714 // replace the assignment with its RHS.
1715 // TODO(user) make the pass smarter about these cases and/or run
1716 // this pass and RemoveConstantExpressions together in a loop.
1717 Node replacement = n.getLastChild();
1718 replacement.detachFromParent();
1719 changeProxy.replaceWith(parent, n, replacement);
1720 } else {
1721 replaceTopLevelExpressionWithRhs(parent, n);
1722 }
1723 }
1724
1725 /**
1726 * Simplify a toplevel expression, while preserving program
1727 * behavior.
1728 */
1729 private void replaceTopLevelExpressionWithRhs(Node parent, Node n) {
1730 // validate inputs
1731 switch (parent.getType()) {
1732 case Token.BLOCK:
1733 case Token.SCRIPT:
1734 case Token.FOR:
1735 case Token.LABEL:
1736 break;
1737 default:
1738 throw new IllegalArgumentException(
1739 "Unsupported parent node type in replaceWithRhs " +
1740 Token.name(parent.getType()));
1741 }
1742
1743 switch (n.getType()) {
1744 case Token.EXPR_RESULT:
1745 case Token.FUNCTION:
1746 case Token.VAR:
1747 break;
1748 case Token.ASSIGN:
1749 Preconditions.checkArgument(parent.isFor(),
1750 "Unsupported assignment in replaceWithRhs. parent: %s",
1751 Token.name(parent.getType()));
1752 break;
1753 default:
1754 throw new IllegalArgumentException(
1755 "Unsupported node type in replaceWithRhs " +
1756 Token.name(n.getType()));
1757 }
1758
1759 // gather replacements
1760 List<Node> replacements = Lists.newArrayList();
1761 for (Node rhs : getRhsSubexpressions(n)) {
1762 replacements.addAll(getSideEffectNodes(rhs));
1763 }
1764
1765 if (parent.isFor()) {
1766 // tweak replacements array s.t. it is a single expression node.
1767 if (replacements.isEmpty()) {
1768 replacements.add(IR.empty());
1769 } else {
1770 Node expr = collapseReplacements(replacements);
1771 replacements.clear();
1772 replacements.add(expr);
1773 }
1774 }
1775
1776 changeProxy.replaceWith(parent, n, replacements);
1777 }
1778
1779 /**
1780 * Determine if the parent reads the value of a child expression
1781 * directly. This is true children used in predicates, RETURN
1782 * statements and, RHS of variable declarations and assignments.
1783 *
1784 * In the case of:
1785 * if (a) b else c
1786 *
1787 * This method returns true for "a", and false for "b" and "c": the
1788 * IF expression does something special based on "a"'s value. "b"
1789 * and "c" are effectively outputs. Same logic applies to FOR,
1790 * WHILE and DO loop predicates. AND/OR/HOOK expressions are
1791 * syntactic sugar for IF statements; therefore this method returns
1792 * true for the predicate and false otherwise.
1793 */
1794 private boolean valueConsumedByParent(Node n, Node parent) {
1795 if (NodeUtil.isAssignmentOp(parent)) {
1796 return parent.getLastChild() == n;
1797 }
1798
1799 switch (parent.getType()) {
1800 case Token.NAME:
1801 case Token.RETURN:
1802 return true;
1803 case Token.AND:
1804 case Token.OR:
1805 case Token.HOOK:
1806 return parent.getFirstChild() == n;
1807 case Token.FOR:
1808 return parent.getFirstChild().getNext() == n;
1809 case Token.IF:
1810 case Token.WHILE:
1811 return parent.getFirstChild() == n;
1812 case Token.DO:
1813 return parent.getLastChild() == n;
1814 default:
1815 return false;
1816 }
1817 }
1818
1819 /**
1820 * Merge a list of nodes into a single expression. The value of the
1821 * new expression is determined by the last expression in the list.
1822 */
1823 private Node collapseReplacements(List<Node> replacements) {
1824 Node expr = null;
1825 for (Node rep : replacements) {
1826 if (rep.isExprResult()) {
1827 rep = rep.getFirstChild();
1828 rep.detachFromParent();
1829 }
1830
1831 if (expr == null) {
1832 expr = rep;
1833 } else {
1834 expr = IR.comma(expr, rep);
1835 }
1836 }
1837
1838 return expr;
1839 }
1840
1841 /**
1842 * Extract a list of subexpressions that act as right hand sides.
1843 */
1844 private List<Node> getRhsSubexpressions(Node n) {
1845 switch (n.getType()) {
1846 case Token.EXPR_RESULT:
1847 // process body
1848 return getRhsSubexpressions(n.getFirstChild());
1849 case Token.FUNCTION:
1850 // function nodes have no RHS
1851 return Collections.emptyList();
1852 case Token.NAME:
1853 {
1854 // parent is a var node. RHS is the first child
1855 Node rhs = n.getFirstChild();
1856 if (rhs != null) {
1857 return Lists.newArrayList(rhs);
1858 } else {
1859 return Collections.emptyList();
1860 }
1861 }
1862 case Token.ASSIGN:
1863 {
1864 // add LHS and RHS expressions - LHS may be a complex expression
1865 Node lhs = n.getFirstChild();
1866 Node rhs = lhs.getNext();
1867 return Lists.newArrayList(lhs, rhs);
1868 }
1869 case Token.VAR:
1870 {
1871 // recurse on all children
1872 List<Node> nodes = Lists.newArrayList();
1873 for (Node child : n.children()) {
1874 nodes.addAll(getRhsSubexpressions(child));
1875 }
1876 return nodes;
1877 }
1878 default:
1879 throw new IllegalArgumentException("AstChangeProxy::getRhs " + n);
1880 }
1881 }
1882 }