Debian Codegraph @

src/com/google/javascript/jscomp/CollapseVariableDeclarations.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.collect.Lists;
21 import com.google.common.collect.Sets;
22 import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback;
23 import com.google.javascript.jscomp.Scope.Var;
24 import com.google.javascript.rhino.JSDocInfo;
25 import com.google.javascript.rhino.Node;
26 import com.google.javascript.rhino.Token;
27
28 import java.util.List;
29 import java.util.Set;
30
31 /**
32 * Collapses multiple variable declarations into a single one. i.e the
33 * following:
34 *
35 * <pre>
36 * var a;
37 * var b = 1;
38 * var c = 2;
39 * </pre>
40 *
41 * becomes:
42 *
43 * <pre>var a, b = 1, c = 2;</pre>
44 *
45 * This reduces the generated code size. More optimizations are possible:
46 * <li>Group all variable declarations inside a function into one such variable.
47 * declaration block.</li>
48 * <li>Re-use variables instead of declaring a new one if they are used for
49 * only part of a function.</li>
50 *
51 * Similarly, also collapses assigns like:
52 *
53 * <pre>
54 * a = true;
55 * b = true;
56 * var c = true;
57 * </pre>
58 *
59 * becomes:
60 *
61 * <pre>var c = b = a = true;</pre>
62 *
63 */
64 class CollapseVariableDeclarations implements CompilerPass {
65 /** Reference to JS Compiler */
66 private final AbstractCompiler compiler;
67
68 /** Encapsulation of information about a variable declaration collapse */
69 private static class Collapse {
70 /**
71 * Variable declaration that any following var nodes should be
72 * collapsed into
73 */
74 final Node startNode;
75
76 /**
77 * Last node (non-inclusive) of the chain of nodes to collapse.
78 */
79 final Node endNode;
80
81 /** Parent of the nodes to the collapse */
82 final Node parent;
83
84 Collapse(Node startNode, Node endNode, Node parent) {
85 this.startNode = startNode;
86 this.endNode = endNode;
87 this.parent = parent;
88 }
89 }
90
91 /**
92 * Collapses to do in this pass.
93 */
94 private final List<Collapse> collapses = Lists.newArrayList();
95
96 /**
97 * Nodes we've already looked at for collapsing, so that we don't look at them
98 * again (we look ahead when examining what nodes can be collapsed, and the
99 * node traversal may give them to us again)
100 */
101 private final Set<Node> nodesToCollapse = Sets.newHashSet();
102
103 CollapseVariableDeclarations(AbstractCompiler compiler) {
104 Preconditions.checkState(!compiler.getLifeCycleStage().isNormalized());
105 this.compiler = compiler;
106 }
107
108 @Override
109 public void process(Node externs, Node root) {
110 collapses.clear();
111 nodesToCollapse.clear();
112
113 NodeTraversal.traverse(compiler, root, new GatherCollapses());
114
115 if (!collapses.isEmpty()) {
116 applyCollapses();
117 compiler.reportCodeChange();
118 }
119 }
120
121 /**
122 * Gathers all of the variable declarations / assignments that should be
123 * collapsed into one.
124 *
125 * We do not do the collapsing as we go since node traversal would be affected
126 * by the changes we are making to the parse tree.
127 */
128 private class GatherCollapses extends AbstractPostOrderCallback {
129
130 // If a VAR is declared like
131 // var x;
132 // then we should not create new VAR nodes for it later in the tree.
133 // This is a workaround for a bug in Firefox.
134 private final Set<Var> blacklistedVars = Sets.newHashSet();
135
136 @Override
137 public void visit(NodeTraversal t, Node n, Node parent) {
138 if (n.isVar()) {
139 blacklistStubVars(t, n);
140 }
141
142 // Only care about var nodes
143 if (!n.isVar() && !canBeRedeclared(n, t.getScope())) return;
144
145 // If we've already looked at this node, skip it
146 if (nodesToCollapse.contains(n)) return;
147
148 // Adjacent VAR children of an IF node are the if and else parts and can't
149 // be collapsed
150 if (parent.isIf()) return;
151
152 Node varNode = n;
153
154 boolean hasVar = n.isVar();
155
156 // Find variable declarations that follow this one (if any)
157 n = n.getNext();
158
159 boolean hasNodesToCollapse = false;
160
161 while (n != null &&
162 (n.isVar() || canBeRedeclared(n, t.getScope()))) {
163
164 if (n.isVar()) {
165 blacklistStubVars(t, n);
166 hasVar = true;
167 }
168
169 nodesToCollapse.add(n);
170 hasNodesToCollapse = true;
171
172 n = n.getNext();
173 }
174
175 if (hasNodesToCollapse && hasVar) {
176 nodesToCollapse.add(varNode);
177 collapses.add(new Collapse(varNode, n, parent));
178 }
179 }
180
181 private void blacklistStubVars(NodeTraversal t, Node varNode) {
182 for (Node child = varNode.getFirstChild();
183 child != null; child = child.getNext()) {
184 if (child.getFirstChild() == null) {
185 blacklistedVars.add(t.getScope().getVar(child.getString()));
186 }
187 }
188 }
189
190 private boolean canBeRedeclared(Node n, Scope s) {
191 if (!NodeUtil.isExprAssign(n)) {
192 return false;
193 }
194 Node assign = n.getFirstChild();
195 Node lhs = assign.getFirstChild();
196
197 if (!lhs.isName()) {
198 return false;
199 }
200
201 Var var = s.getVar(lhs.getString());
202 return var != null
203 && var.getScope() == s
204 && !isNamedParameter(var)
205 && !blacklistedVars.contains(var);
206 }
207 }
208
209 private boolean isNamedParameter(Var v) {
210 return v.getParentNode().isParamList();
211 }
212
213 private void applyCollapses() {
214 for (Collapse collapse : collapses) {
215
216 Node var = new Node(Token.VAR);
217 var.copyInformationFrom(collapse.startNode);
218 collapse.parent.addChildBefore(var, collapse.startNode);
219
220 boolean redeclaration = false;
221 for (Node n = collapse.startNode; n != collapse.endNode;) {
222 Node next = n.getNext();
223
224 Preconditions.checkState(var.getNext() == n);
225 collapse.parent.removeChildAfter(var);
226
227 if (n.isVar()) {
228 while(n.hasChildren()) {
229 var.addChildToBack(n.removeFirstChild());
230 }
231 } else {
232 Node assign = n.getFirstChild();
233 Node lhs = assign.getFirstChild();
234 Preconditions.checkState(lhs.isName());
235 Node rhs = assign.getLastChild();
236 lhs.addChildToBack(rhs.detachFromParent());
237 var.addChildToBack(lhs.detachFromParent());
238 redeclaration = true;
239 }
240 n = next;
241 }
242
243 if (redeclaration) {
244 JSDocInfo info = new JSDocInfo();
245 info.addSuppression("duplicate");
246 var.setJSDocInfo(info);
247 }
248 }
249 }
250 }