Debian Codegraph @

src/com/google/javascript/jscomp/MinimizeExitPoints.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.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback;
21 import com.google.javascript.rhino.IR;
22 import com.google.javascript.rhino.Node;
23 import com.google.javascript.rhino.Token;
24 import com.google.javascript.rhino.jstype.TernaryValue;
25
26 /**
27 * Transform the structure of the AST so that the number of explicit exits
28 * are minimized.
29 *
30 * @author [email protected] (John Lenz)
31 */
32 class MinimizeExitPoints
33 extends AbstractPostOrderCallback
34 implements CompilerPass {
35
36 AbstractCompiler compiler;
37
38 MinimizeExitPoints(AbstractCompiler compiler) {
39 this.compiler = compiler;
40 }
41
42 @Override
43 public void process(Node externs, Node root) {
44 NodeTraversal.traverse(compiler, root, this);
45 }
46
47 @Override
48 public void visit(NodeTraversal t, Node n, Node parent) {
49 switch (n.getType()) {
50 case Token.LABEL:
51 tryMinimizeExits(
52 n.getLastChild(), Token.BREAK, n.getFirstChild().getString());
53 break;
54
55 case Token.FOR:
56 case Token.WHILE:
57 tryMinimizeExits(NodeUtil.getLoopCodeBlock(n), Token.CONTINUE, null);
58 break;
59
60 case Token.DO:
61 tryMinimizeExits(NodeUtil.getLoopCodeBlock(n), Token.CONTINUE, null);
62
63 Node cond = NodeUtil.getConditionExpression(n);
64 if (NodeUtil.getImpureBooleanValue(cond) == TernaryValue.FALSE) {
65 // Normally, we wouldn't be able to optimize BREAKs inside a loop
66 // but as we know the condition will always false, we can treat them
67 // as we would a CONTINUE.
68 tryMinimizeExits(n.getFirstChild(), Token.BREAK, null);
69 }
70 break;
71
72 case Token.FUNCTION:
73 tryMinimizeExits(n.getLastChild(), Token.RETURN, null);
74 break;
75 }
76 }
77
78 /**
79 * Attempts to minimize the number of explicit exit points in a control
80 * structure to take advantage of the implied exit at the end of the
81 * structure. This is accomplished by removing redundant statements, and
82 * moving statements following a qualifying IF node into that node.
83 * For example:
84 *
85 * function () {
86 * if (x) return;
87 * else blah();
88 * foo();
89 * }
90 *
91 * becomes:
92 *
93 * function () {
94 * if (x) ;
95 * else {
96 * blah();
97 * foo();
98 * }
99 *
100 * @param n The execution node of a parent to inspect.
101 * @param exitType The type of exit to look for.
102 * @param labelName If parent is a label the name of the label to look for,
103 * null otherwise.
104 * @nullable labelName non-null only for breaks within labels.
105 */
106 void tryMinimizeExits(Node n, int exitType, String labelName) {
107
108 // Just an 'exit'.
109 if (matchingExitNode(n, exitType, labelName)) {
110 NodeUtil.removeChild(n.getParent(), n);
111 compiler.reportCodeChange();
112 return;
113 }
114
115 // Just an 'if'.
116 if (n.isIf()) {
117 Node ifBlock = n.getFirstChild().getNext();
118 tryMinimizeExits(ifBlock, exitType, labelName);
119 Node elseBlock = ifBlock.getNext();
120 if (elseBlock != null) {
121 tryMinimizeExits(elseBlock, exitType, labelName);
122 }
123 return;
124 }
125
126 // Just a 'try/catch/finally'.
127 if (n.isTry()) {
128 Node tryBlock = n.getFirstChild();
129 tryMinimizeExits(tryBlock, exitType, labelName);
130 Node allCatchNodes = NodeUtil.getCatchBlock(n);
131 if (NodeUtil.hasCatchHandler(allCatchNodes)) {
132 Preconditions.checkState(allCatchNodes.hasOneChild());
133 Node catchNode = allCatchNodes.getFirstChild();
134 Node catchCodeBlock = catchNode.getLastChild();
135 tryMinimizeExits(catchCodeBlock, exitType, labelName);
136 }
137 if (NodeUtil.hasFinally(n)) {
138 Node finallyBlock = n.getLastChild();
139 tryMinimizeExits(finallyBlock, exitType, labelName);
140 }
141 }
142
143 // Just a 'label'.
144 if (n.isLabel()) {
145 Node labelBlock = n.getLastChild();
146 tryMinimizeExits(labelBlock, exitType, labelName);
147 }
148
149 // TODO(johnlenz): The last case of SWITCH statement?
150
151 // The rest assumes a block with at least one child, bail on anything else.
152 if (!n.isBlock() || n.getLastChild() == null) {
153 return;
154 }
155
156 // Multiple if-exits can be converted in a single pass.
157 // Convert "if (blah) break; if (blah2) break; other_stmt;" to
158 // become "if (blah); else { if (blah2); else { other_stmt; } }"
159 // which will get converted to "if (!blah && !blah2) { other_stmt; }".
160 for (Node c : n.children()) {
161
162 // An 'if' block to process below.
163 if (c.isIf()) {
164 Node ifTree = c;
165 Node trueBlock, falseBlock;
166
167 // First, the true condition block.
168 trueBlock = ifTree.getFirstChild().getNext();
169 falseBlock = trueBlock.getNext();
170 tryMinimizeIfBlockExits(trueBlock, falseBlock,
171 ifTree, exitType, labelName);
172
173 // Now the else block.
174 // The if blocks may have changed, get them again.
175 trueBlock = ifTree.getFirstChild().getNext();
176 falseBlock = trueBlock.getNext();
177 if (falseBlock != null) {
178 tryMinimizeIfBlockExits(falseBlock, trueBlock,
179 ifTree, exitType, labelName);
180 }
181 }
182
183 if (c == n.getLastChild()) {
184 break;
185 }
186 }
187
188 // Now try to minimize the exits of the last child, if it is removed
189 // look at what has become the last child.
190 for (Node c = n.getLastChild(); c != null; c = n.getLastChild()) {
191 tryMinimizeExits(c, exitType, labelName);
192 // If the node is still the last child, we are done.
193 if (c == n.getLastChild()) {
194 break;
195 }
196 }
197 }
198
199 /**
200 * Look for exits (returns, breaks, or continues, depending on the context) at
201 * the end of a block and removes them by moving the if node's siblings,
202 * if any, into the opposite condition block.
203 *
204 * @param srcBlock The block to inspect.
205 * @param destBlock The block to move sibling nodes into.
206 * @param ifNode The if node to work with.
207 * @param exitType The type of exit to look for.
208 * @param labelName The name associated with the exit, if any.
209 * @nullable labelName null for anything excepted for named-break associated
210 * with a label.
211 */
212 private void tryMinimizeIfBlockExits(Node srcBlock, Node destBlock,
213 Node ifNode, int exitType, String labelName) {
214 Node exitNodeParent = null;
215 Node exitNode = null;
216
217 // Pick an exit node candidate.
218 if (srcBlock.isBlock()) {
219 if (!srcBlock.hasChildren()) {
220 return;
221 }
222 exitNodeParent = srcBlock;
223 exitNode = exitNodeParent.getLastChild();
224 } else {
225 // Just a single statement, if it isn't an exit bail.
226 exitNodeParent = ifNode;
227 exitNode = srcBlock;
228 }
229
230 // Verify the candidate.
231 if (!matchingExitNode(exitNode, exitType, labelName)) {
232 return;
233 }
234
235 // Take case of the if nodes siblings, if any.
236 if (ifNode.getNext() != null) {
237 // Move siblings of the if block into the opposite
238 // logic block of the exit.
239 Node newDestBlock = IR.block().srcref(ifNode);
240 if (destBlock == null) {
241 // Only possible if this is the false block.
242 ifNode.addChildToBack(newDestBlock);
243 } else if (destBlock.isEmpty()) {
244 // Use the new block.
245 ifNode.replaceChild(destBlock, newDestBlock);
246 } else if (destBlock.isBlock()) {
247 // Reuse the existing block.
248 newDestBlock = destBlock;
249 } else {
250 // Add the existing statement to the new block.
251 ifNode.replaceChild(destBlock, newDestBlock);
252 newDestBlock.addChildToBack(destBlock);
253 }
254
255 // Move all the if node's following siblings.
256 moveAllFollowing(ifNode, ifNode.getParent(), newDestBlock);
257 compiler.reportCodeChange();
258 }
259 }
260
261 /**
262 * Determines if n matches the type and name for the following types of
263 * "exits":
264 * - return without values
265 * - continues and breaks with or without names.
266 * @param n The node to inspect.
267 * @param type The Token type to look for.
268 * @param labelName The name that must be associated with the exit type.
269 * @nullable labelName non-null only for breaks associated with labels.
270 * @return Whether the node matches the specified block-exit type.
271 */
272 private static boolean matchingExitNode(Node n, int type, String labelName) {
273 if (n.getType() == type) {
274 if (type == Token.RETURN) {
275 // only returns without expressions.
276 return !n.hasChildren();
277 } else {
278 if (labelName == null) {
279 return !n.hasChildren();
280 } else {
281 return n.hasChildren()
282 && labelName.equals(n.getFirstChild().getString());
283 }
284 }
285 }
286 return false;
287 }
288
289 /**
290 * Move all the child nodes following start in srcParent to the end of
291 * destParent's child list.
292 * @param start The start point in the srcParent child list.
293 * @param srcParent The parent node of start.
294 * @param destParent The destination node.
295 */
296 private static void moveAllFollowing(
297 Node start, Node srcParent, Node destParent) {
298 for (Node n = start.getNext(); n != null; n = start.getNext()) {
299 boolean isFunctionDeclaration = NodeUtil.isFunctionDeclaration(n);
300 srcParent.removeChild(n);
301 if (isFunctionDeclaration) {
302 destParent.addChildToFront(n);
303 } else {
304 destParent.addChildToBack(n);
305 }
306 }
307 }
308 }