Debian Codegraph @

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

raw symbols SCIP
1 /*
2 * Copyright 2009 The Closure Compiler Authors.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
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.javascript.rhino.Node;
22 import com.google.javascript.rhino.Token;
23
24 import java.util.Collections;
25 import java.util.Iterator;
26 import java.util.List;
27 import java.util.Stack;
28
29 /**
30 * A package for common iteration patterns.
31 *
32 * All iterators are forward, post-order traversals unless otherwise noted.
33 *
34 * @author [email protected] (Nick Santos)
35 */
36 class NodeIterators {
37
38 private NodeIterators() {} /* all static */
39
40 /**
41 * Traverses the local scope, skipping all function nodes.
42 */
43 static class FunctionlessLocalScope implements Iterator<Node> {
44 private final Stack<Node> ancestors = new Stack<Node>();
45
46 /**
47 * @param ancestors The ancestors of the point where iteration will start,
48 * beginning with the deepest ancestor. The start node will not be
49 * exposed in the iteration.
50 */
51 FunctionlessLocalScope(Node ... ancestors) {
52 Preconditions.checkArgument(ancestors.length > 0);
53
54 for (Node n : ancestors) {
55 if (n.isFunction()) {
56 break;
57 }
58
59 this.ancestors.add(0, n);
60 }
61 }
62
63 @Override
64 public boolean hasNext() {
65 // Check if the current node has any nodes after it.
66 return !(ancestors.size() == 1 && ancestors.peek().getNext() == null);
67 }
68
69 @Override
70 public Node next() {
71 Node current = ancestors.pop();
72 if (current.getNext() == null) {
73 current = ancestors.peek();
74
75 // If this is a function node, skip it.
76 if (current.isFunction()) {
77 return next();
78 }
79 } else {
80 current = current.getNext();
81 ancestors.push(current);
82
83 // If this is a function node, skip it.
84 if (current.isFunction()) {
85 return next();
86 }
87
88 while (current.hasChildren()) {
89 current = current.getFirstChild();
90 ancestors.push(current);
91
92 // If this is a function node, skip it.
93 if (current.isFunction()) {
94 return next();
95 }
96 }
97 }
98
99 return current;
100 }
101
102 @Override
103 public void remove() {
104 throw new UnsupportedOperationException("Not implemented");
105 }
106
107 /**
108 * Gets the node most recently returned by next().
109 */
110 protected Node current() {
111 return ancestors.peek();
112 }
113
114 /**
115 * Gets the parent of the node most recently returned by next().
116 */
117 protected Node currentParent() {
118 return ancestors.size() >= 2 ?
119 ancestors.get(ancestors.size() - 2) : null;
120 }
121
122 /**
123 * Gets the ancestors of the current node, with the deepest node first.
124 * Only exposed for testing purposes.
125 */
126 List<Node> currentAncestors() {
127 List<Node> list = Lists.newArrayList(ancestors);
128 Collections.reverse(list);
129 return list;
130 }
131 }
132
133 /**
134 * An iterator to help with variable inlining. Given a variable declaration,
135 * find all the nodes in post-order where the variable is guaranteed to
136 * retain its original value.
137 *
138 * Consider:
139 * <pre>
140 * var X = 1;
141 * var Y = 3; // X is still 1
142 * if (Y) {
143 * // X is still 1
144 * } else {
145 * X = 5;
146 * }
147 * // X may not be 1
148 * </pre>
149 * In the above example, the iterator will iterate past the declaration of
150 * Y and into the first block of the IF branch, and will stop at the
151 * assignment {@code X = 5}.
152 */
153 static class LocalVarMotion implements Iterator<Node> {
154 private final boolean valueHasSideEffects;
155 private final FunctionlessLocalScope iterator;
156 private final String varName;
157 private Node lookAhead;
158
159 /**
160 * @return Create a LocalVarMotion for use with moving a value assigned
161 * at a variable declaration.
162 */
163 static LocalVarMotion forVar(
164 Node name, Node var, Node block) {
165 Preconditions.checkArgument(var.isVar());
166 Preconditions.checkArgument(NodeUtil.isStatement(var));
167 // The FunctionlessLocalScope must start at "name" as this may be used
168 // before the Normalize pass, and thus the VAR node may define multiple
169 // names and the "name" node may have siblings. The actual assigned
170 // value is skipped as it is a child of name.
171 return new LocalVarMotion(
172 name, new FunctionlessLocalScope(name, var, block));
173 }
174
175 /**
176 * @return Create a LocalVarMotion for use with moving a value assigned
177 * as part of a simple assignment expression ("a = b;").
178 */
179 static LocalVarMotion forAssign(
180 Node name, Node assign, Node expr, Node block) {
181 Preconditions.checkArgument(assign.isAssign());
182 Preconditions.checkArgument(expr.isExprResult());
183 // The FunctionlessLocalScope must start at "assign", to skip the value
184 // assigned to "name" (which would be its sibling).
185 return new LocalVarMotion(
186 name, new FunctionlessLocalScope(assign, expr, block));
187 }
188
189 /**
190 * @param iterator The iterator to use while inspecting the node
191 * beginning with the deepest ancestor.
192 */
193 private LocalVarMotion(Node nameNode, FunctionlessLocalScope iterator) {
194 Preconditions.checkArgument(nameNode.isName());
195 Node valueNode = NodeUtil.getAssignedValue(nameNode);
196 this.varName = nameNode.getString();
197 this.valueHasSideEffects = valueNode != null &&
198 NodeUtil.mayHaveSideEffects(valueNode);
199 this.iterator = iterator;
200 advanceLookAhead(true);
201 }
202
203 @Override
204 public boolean hasNext() {
205 return lookAhead != null;
206 }
207
208 @Override
209 public Node next() {
210 Node next = lookAhead;
211 advanceLookAhead(false);
212 return next;
213 }
214
215 @Override
216 public void remove() {
217 throw new UnsupportedOperationException("Not implemented");
218 }
219
220 private void advanceLookAhead(boolean atStart) {
221 if (!atStart) {
222 if (lookAhead == null) {
223 return;
224 }
225
226 // Don't advance past a reference to the variable that we're trying
227 // to inline.
228 Node curNode = iterator.current();
229 if (curNode.isName() &&
230 varName.equals(curNode.getString())) {
231 lookAhead = null;
232 return;
233 }
234 }
235
236 if (!iterator.hasNext()) {
237 lookAhead = null;
238 return;
239 }
240
241 Node nextNode = iterator.next();
242 Node nextParent = iterator.currentParent();
243 int type = nextNode.getType();
244
245 if (valueHasSideEffects) {
246 // Reject anything that might read state
247 boolean readsState = false;
248
249 if (// Any read of a different variable.
250 (nextNode.isName() && !varName.equals(nextNode.getString())) ||
251 // Any read of a property.
252 (nextNode.isGetProp() || nextNode.isGetElem())) {
253
254 // If this is a simple assign, we'll be ok.
255 if (nextParent == null ||
256 !NodeUtil.isVarOrSimpleAssignLhs(nextNode, nextParent)) {
257 readsState = true;
258 }
259
260 } else if (nextNode.isCall() || nextNode.isNew()) {
261 // This isn't really an important case. In most cases when we use
262 // CALL or NEW, we're invoking it on a NAME or a GETPROP. And in the
263 // few cases where we're not, it's because we have an anonymous
264 // function that escapes the variable we're worried about. But we
265 // include this for completeness.
266 readsState = true;
267 }
268
269 if (readsState) {
270 lookAhead = null;
271 return;
272 }
273 }
274
275 // Reject anything that might modify relevant state. We assume that
276 // nobody relies on variables being undeclared, which will break
277 // constructions like:
278 // var a = b;
279 // var b = 3;
280 // alert(a);
281 if (NodeUtil.nodeTypeMayHaveSideEffects(nextNode) && type != Token.NAME
282 || type == Token.NAME && nextParent.isCatch()) {
283 lookAhead = null;
284 return;
285 }
286
287 lookAhead = nextNode;
288 }
289 }
290 }