Debian Codegraph @

src/com/google/javascript/jscomp/GatherSideEffectSubexpressionsCallback.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.ImmutableSet;
21 import com.google.common.collect.Lists;
22 import com.google.javascript.jscomp.CodingConvention.SubclassRelationship;
23 import com.google.javascript.jscomp.NodeTraversal.Callback;
24 import com.google.javascript.rhino.IR;
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 * Callback that gathers subexpressions that may have side effects
33 * and appends copies of those subexpressions to the replacements
34 * list. In the case of branching subexpressions, it simplifies the
35 * subexpression before adding it to the replacement list.
36 *
37 */
38 class GatherSideEffectSubexpressionsCallback implements Callback {
39
40 /**
41 * Used by GatherSideEffectSubexpressionsCallback to notify client
42 * code about side effect expressions that should be kept.
43 */
44 interface SideEffectAccumulator {
45
46 /**
47 * Returns true if the "mixin" and "inherits" function calls
48 * should be treated as if they had side effects.
49 */
50 boolean classDefiningCallsHaveSideEffects();
51
52 /**
53 * Adds subtree to the list of nodes that have side effects.
54 *
55 * @param original - root of the tree.
56 */
57 void keepSubTree(Node original);
58
59 /**
60 * Simplifies a subtree whose root node is an AND or OR expression
61 * and adds the resulting subtree to the list of nodes that have
62 * side effects.
63 *
64 * @param original - root of the and/or expression.
65 */
66 void keepSimplifiedShortCircuitExpression(Node original);
67
68 /**
69 * Simplifies a subtree whose root node is a HOOK expression
70 * and adds the resulting subtree to the list of nodes that have
71 * side effects.
72 *
73 * @param hook - root of the hook expression.
74 * @param thenHasSideEffects - then branch has side effects
75 * @param elseHasSideEffects - else branch has side effects
76 */
77 void keepSimplifiedHookExpression(Node hook,
78 boolean thenHasSideEffects,
79 boolean elseHasSideEffects);
80 }
81
82 /**
83 * Populates the provided replacement list by appending copies of
84 * subtrees that have side effects.
85 *
86 * It is OK if this class tears up the original tree, because
87 * we're going to throw the tree out anyway.
88 */
89 static final class GetReplacementSideEffectSubexpressions
90 implements SideEffectAccumulator {
91 private final AbstractCompiler compiler;
92 private final List<Node> replacements;
93
94 /**
95 * Creates the accumulator.
96 *
97 * @param compiler - the AbstractCompiler
98 * @param replacements - list to accumulate into
99 */
100 GetReplacementSideEffectSubexpressions(AbstractCompiler compiler,
101 List<Node> replacements) {
102 this.compiler = compiler;
103 this.replacements = replacements;
104 }
105
106 @Override
107 public boolean classDefiningCallsHaveSideEffects() {
108 return true;
109 }
110
111 @Override
112 public void keepSubTree(Node original) {
113 if (original.getParent() != null) {
114 original.detachFromParent();
115 }
116 replacements.add(original);
117 }
118
119 @Override
120 public void keepSimplifiedShortCircuitExpression(Node original) {
121 Preconditions.checkArgument(
122 (original.isAnd()) || (original.isOr()),
123 "Expected: AND or OR, Got: %s", Token.name(original.getType()));
124 Node left = original.getFirstChild();
125 Node right = left.getNext();
126 Node simplifiedRight = simplifyShortCircuitBranch(right);
127 original.detachChildren();
128 original.addChildToBack(left);
129 original.addChildToBack(simplifiedRight);
130 keepSubTree(original);
131 }
132
133 @Override
134 public void keepSimplifiedHookExpression(Node hook,
135 boolean thenHasSideEffects,
136 boolean elseHasSideEffects) {
137 Preconditions.checkArgument(hook.isHook(),
138 "Expected: HOOK, Got: %s", Token.name(hook.getType()));
139 Node condition = hook.getFirstChild();
140 Node thenBranch = condition.getNext();
141 Node elseBranch = thenBranch.getNext();
142 if (thenHasSideEffects && elseHasSideEffects) {
143 hook.detachChildren();
144 hook.addChildToBack(condition);
145 hook.addChildToBack(simplifyShortCircuitBranch(thenBranch));
146 hook.addChildToBack(simplifyShortCircuitBranch(elseBranch));
147 keepSubTree(hook);
148 } else if (thenHasSideEffects || elseHasSideEffects) {
149 int type = thenHasSideEffects ? Token.AND : Token.OR;
150 Node body = thenHasSideEffects ? thenBranch : elseBranch;
151 Node simplified = new Node(
152 type, condition.detachFromParent(),
153 simplifyShortCircuitBranch(body))
154 .copyInformationFrom(hook);
155 keepSubTree(simplified);
156 } else {
157 throw new IllegalArgumentException(
158 "keepSimplifiedHookExpression must keep at least 1 branch");
159 }
160 }
161
162 private Node simplifyShortCircuitBranch(Node node) {
163 List<Node> parts = Lists.newArrayList();
164 NodeTraversal.traverse(
165 compiler, node,
166 new GatherSideEffectSubexpressionsCallback(
167 compiler,
168 new GetReplacementSideEffectSubexpressions(compiler, parts)));
169
170 Node ret = null;
171 for (Node part : parts) {
172 if (ret != null) {
173 ret = IR.comma(ret, part).srcref(node);
174 } else {
175 ret = part;
176 }
177 }
178
179 if (ret == null) {
180 throw new IllegalArgumentException(
181 "expected at least one side effect subexpression in short "
182 + "circuit branch.");
183 }
184
185 return ret;
186 }
187 }
188
189 private static final Set<Integer> FORBIDDEN_TYPES = ImmutableSet.of(
190 Token.BLOCK, Token.SCRIPT, Token.VAR, Token.EXPR_RESULT, Token.RETURN);
191 private final AbstractCompiler compiler;
192 private final SideEffectAccumulator accumulator;
193
194 /**
195 * @param compiler - AbstractCompiler object
196 * @param accumulator - object that will accumulate roots of
197 * subtrees that have side effects.
198 */
199 GatherSideEffectSubexpressionsCallback(AbstractCompiler compiler,
200 SideEffectAccumulator accumulator) {
201 this.compiler = compiler;
202 this.accumulator = accumulator;
203 }
204
205 /**
206 * Determines if a call defines a class inheritance or mixing
207 * relation, according to the current coding convention.
208 */
209 private boolean isClassDefiningCall(Node callNode) {
210 SubclassRelationship classes =
211 compiler.getCodingConvention().getClassesDefinedByCall(callNode);
212 return classes != null;
213 }
214
215 /**
216 * Computes the list of subtrees whose root nodes have side effects.
217 *
218 * <p>If the current subtree's root has side effects this method should
219 * call accumulator.keepSubTree and return 'false' to add the
220 * subtree to the result list and avoid avoid traversing the nodes children.
221 *
222 * <p>Branching nodes whose then or else branch contain side effects
223 * must be simplified by doing a recursive traversal; this method
224 * should call the appropriate accumulator 'keepSimplified' method
225 * and return 'false' to stop the regular traversal.
226 */
227 @Override
228 public boolean shouldTraverse(
229 NodeTraversal traversal, Node node, Node parent) {
230 if (FORBIDDEN_TYPES.contains(node.getType()) ||
231 NodeUtil.isControlStructure(node)) {
232 throw new IllegalArgumentException(
233 Token.name(node.getType()) + " nodes are not supported.");
234 }
235
236 // Do not recurse into nested functions.
237 if (node.isFunction()) {
238 return false;
239 }
240
241 // simplify and maybe keep hook expression.
242 if (node.isHook()) {
243 return processHook(node);
244 }
245
246 // simplify and maybe keep AND/OR expression.
247 if ((node.isAnd()) || (node.isOr())) {
248 return processShortCircuitExpression(node);
249 }
250
251 if (!NodeUtil.nodeTypeMayHaveSideEffects(node, compiler)) {
252 return true;
253 } else {
254
255 // Node type suggests that the expression has side effects.
256
257 if (node.isCall()) {
258 return processFunctionCall(node);
259 } else if (node.isNew()) {
260 return processConstructorCall(node);
261 } else {
262 accumulator.keepSubTree(node);
263 return false;
264 }
265 }
266 }
267
268 /**
269 * Processes an AND or OR expression.
270 *
271 * @return true to continue traversal, false otherwise
272 */
273 boolean processShortCircuitExpression(Node node) {
274 Preconditions.checkArgument(
275 (node.isAnd()) || (node.isOr()),
276 "Expected: AND or OR, Got: %s", Token.name(node.getType()));
277
278 // keep whole expression if RHS of the branching expression
279 // contains a call.
280 Node left = node.getFirstChild();
281 Node right = left.getNext();
282 if (NodeUtil.mayHaveSideEffects(right, compiler)) {
283 accumulator.keepSimplifiedShortCircuitExpression(node);
284 return false;
285 } else {
286 return true;
287 }
288 }
289
290 /**
291 * Processes a HOOK expression.
292 *
293 * @return true to continue traversal, false otherwise
294 */
295 boolean processHook(Node node) {
296 Preconditions.checkArgument(node.isHook(),
297 "Expected: HOOK, Got: %s", Token.name(node.getType()));
298
299 Node condition = node.getFirstChild();
300 Node ifBranch = condition.getNext();
301 Node elseBranch = ifBranch.getNext();
302 boolean thenHasSideEffects = NodeUtil.mayHaveSideEffects(
303 ifBranch, compiler);
304 boolean elseHasSideEffects = NodeUtil.mayHaveSideEffects(
305 elseBranch, compiler);
306 if (thenHasSideEffects || elseHasSideEffects) {
307 accumulator.keepSimplifiedHookExpression(
308 node, thenHasSideEffects, elseHasSideEffects);
309 return false;
310 } else {
311 return true;
312 }
313 }
314
315 /**
316 * Processes a CALL expression.
317 *
318 * @return true to continue traversal, false otherwise
319 */
320 boolean processFunctionCall(Node node) {
321 Preconditions.checkArgument(node.isCall(),
322 "Expected: CALL, Got: %s", Token.name(node.getType()));
323
324 // Calls to functions that are known to be "pure" have no side
325 // effects.
326 Node functionName = node.getFirstChild();
327 if (functionName.isName() || functionName.isGetProp()) {
328 if (!accumulator.classDefiningCallsHaveSideEffects() &&
329 isClassDefiningCall(node)) {
330 return true;
331 }
332 }
333
334 if (!NodeUtil.functionCallHasSideEffects(node)) {
335 return true;
336 }
337
338 accumulator.keepSubTree(node);
339 return false;
340 }
341
342 /**
343 * Processes a NEW expression.
344 *
345 * @return true to continue traversal, false otherwise
346 */
347 boolean processConstructorCall(Node node) {
348 Preconditions.checkArgument(node.isNew(),
349 "Expected: NEW, Got: %s", Token.name(node.getType()));
350
351 // Calls to constructors that are known to be "pure" have no
352 // side effects.
353 if (!NodeUtil.constructorCallHasSideEffects(node)) {
354 return true;
355 }
356
357 accumulator.keepSubTree(node);
358 return false;
359 }
360
361 @Override
362 public void visit(NodeTraversal traversal, Node node, Node parent) {}
363 }