Debian Codegraph @

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

raw symbols SCIP
1 /*
2 * Copyright 2008 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.HashMultimap;
21 import com.google.common.collect.Maps;
22 import com.google.common.collect.Multimap;
23 import com.google.javascript.jscomp.ControlFlowGraph.Branch;
24 import com.google.javascript.jscomp.NodeTraversal.Callback;
25 import com.google.javascript.jscomp.graph.DiGraph.DiGraphNode;
26 import com.google.javascript.rhino.Node;
27 import com.google.javascript.rhino.Token;
28
29 import java.util.ArrayDeque;
30 import java.util.Comparator;
31 import java.util.Deque;
32 import java.util.Iterator;
33 import java.util.List;
34 import java.util.Map;
35 import java.util.PriorityQueue;
36
37 /**
38 * This is a compiler pass that computes a control flow graph.
39 *
40 */
41 final class ControlFlowAnalysis implements Callback, CompilerPass {
42
43 /**
44 * Based roughly on the first few pages of
45 *
46 * "Declarative Intraprocedural Flow Analysis of Java Source Code by
47 * Nilsson-Nyman, Hedin, Magnusson & Ekman",
48 *
49 * this pass computes the control flow graph from the AST. However, a full
50 * attribute grammar is not necessary. We will compute the flow edges with a
51 * single post order traversal. The "follow()" of a given node will be
52 * computed recursively in a demand driven fashion.
53 *
54 * As of this moment, we are not performing any inter-procedural analysis
55 * within our framework.
56 */
57
58 private final AbstractCompiler compiler;
59
60 private ControlFlowGraph<Node> cfg;
61
62 private Map<Node, Integer> astPosition;
63
64 // TODO(nicksantos): should these be node annotations?
65 private Map<DiGraphNode<Node, Branch>, Integer> nodePriorities;
66
67 // We order CFG nodes by by looking at the AST positions.
68 // CFG nodes that come first lexically should be visited first, because
69 // they will often be executed first in the source program.
70 private final Comparator<DiGraphNode<Node, Branch>> priorityComparator =
71 new Comparator<DiGraphNode<Node, Branch>>() {
72 @Override
73 public int compare(
74 DiGraphNode<Node, Branch> a, DiGraphNode<Node, Branch> b) {
75 return astPosition.get(a.getValue()) - astPosition.get(b.getValue());
76 }
77 };
78
79 private int astPositionCounter;
80 private int priorityCounter;
81
82 private final boolean shouldTraverseFunctions;
83 private final boolean edgeAnnotations;
84
85 // We need to store where we started, in case we aren't doing a flow analysis
86 // for the whole scope. This happens, for example, when running type inference
87 // on only the externs.
88 private Node root;
89
90 /*
91 * This stack captures the structure of nested TRY blocks. The top of the
92 * stack is the inner most TRY block. A FUNCTION node in this stack implies
93 * that the handler is determined by the caller of the function at runtime.
94 */
95 private final Deque<Node> exceptionHandler = new ArrayDeque<Node>();
96
97 /*
98 * This map is used to handle the follow of FINALLY. For example:
99 *
100 * while(x) {
101 * try {
102 * try {
103 * break;
104 * } catch (a) {
105 * } finally {
106 * foo();
107 * }
108 * fooFollow();
109 * } catch (b) {
110 * } finally {
111 * bar();
112 * }
113 * barFollow();
114 * }
115 * END();
116 *
117 * In this case finallyMap will contain a map from:
118 * first FINALLY -> bar()
119 * second FINALLY -> END()
120 *
121 * When we are connecting foo() and bar() to to their respective follow, we
122 * must also look up this map and connect:
123 * foo() -> bar()
124 * bar() -> END
125 */
126 private final Multimap<Node, Node> finallyMap = HashMultimap.create();
127
128 /**
129 * Constructor.
130 *
131 * @param compiler Compiler instance.
132 * @param shouldTraverseFunctions Whether functions should be traversed (true
133 * by default).
134 * @param edgeAnnotations Whether to allow edge annotations. By default,
135 * only node annotations are allowed.
136 */
137 ControlFlowAnalysis(AbstractCompiler compiler,
138 boolean shouldTraverseFunctions, boolean edgeAnnotations) {
139 this.compiler = compiler;
140 this.shouldTraverseFunctions = shouldTraverseFunctions;
141 this.edgeAnnotations = edgeAnnotations;
142 }
143
144 ControlFlowGraph<Node> getCfg() {
145 return cfg;
146 }
147
148 @Override
149 public void process(Node externs, Node root) {
150 this.root = root;
151 astPositionCounter = 0;
152 astPosition = Maps.newHashMap();
153 nodePriorities = Maps.newHashMap();
154 cfg = new AstControlFlowGraph(computeFallThrough(root), nodePriorities,
155 edgeAnnotations);
156 NodeTraversal.traverse(compiler, root, this);
157 astPosition.put(null, ++astPositionCounter); // the implicit return is last.
158
159 // Now, generate the priority of nodes by doing a depth-first
160 // search on the CFG.
161 priorityCounter = 0;
162 DiGraphNode<Node, Branch> entry = cfg.getEntry();
163 prioritizeFromEntryNode(entry);
164
165 if (shouldTraverseFunctions) {
166 // If we're traversing inner functions, we need to rank the
167 // priority of them too.
168 for (DiGraphNode<Node, Branch> candidate : cfg.getDirectedGraphNodes()) {
169 Node value = candidate.getValue();
170 if (value != null && value.isFunction()) {
171 Preconditions.checkState(
172 !nodePriorities.containsKey(candidate) || candidate == entry);
173 prioritizeFromEntryNode(candidate);
174 }
175 }
176 }
177
178 // At this point, all reachable nodes have been given a priority, but
179 // unreachable nodes have not been given a priority. Put them last.
180 // Presumably, it doesn't really matter what priority they get, since
181 // this shouldn't happen in real code.
182 for (DiGraphNode<Node, Branch> candidate : cfg.getDirectedGraphNodes()) {
183 if (!nodePriorities.containsKey(candidate)) {
184 nodePriorities.put(candidate, ++priorityCounter);
185 }
186 }
187
188 // Again, the implicit return node is always last.
189 nodePriorities.put(cfg.getImplicitReturn(), ++priorityCounter);
190 }
191
192 /**
193 * Given an entry node, find all the nodes reachable from that node
194 * and prioritize them.
195 */
196 private void prioritizeFromEntryNode(DiGraphNode<Node, Branch> entry) {
197 PriorityQueue<DiGraphNode<Node, Branch>> worklist =
198 new PriorityQueue<DiGraphNode<Node, Branch>>(10, priorityComparator);
199 worklist.add(entry);
200
201 while (!worklist.isEmpty()) {
202 DiGraphNode<Node, Branch> current = worklist.remove();
203 if (nodePriorities.containsKey(current)) {
204 continue;
205 }
206
207 nodePriorities.put(current, ++priorityCounter);
208
209 List<DiGraphNode<Node, Branch>> successors =
210 cfg.getDirectedSuccNodes(current);
211 for (DiGraphNode<Node, Branch> candidate : successors) {
212 worklist.add(candidate);
213 }
214 }
215 }
216
217 @Override
218 public boolean shouldTraverse(
219 NodeTraversal nodeTraversal, Node n, Node parent) {
220 astPosition.put(n, astPositionCounter++);
221
222 switch (n.getType()) {
223 case Token.FUNCTION:
224 if (shouldTraverseFunctions || n == cfg.getEntry().getValue()) {
225 exceptionHandler.push(n);
226 return true;
227 }
228 return false;
229 case Token.TRY:
230 exceptionHandler.push(n);
231 return true;
232 }
233
234 /*
235 * We are going to stop the traversal depending on what the node's parent
236 * is.
237 *
238 * We are only interested in adding edges between nodes that change control
239 * flow. The most obvious ones are loops and IF-ELSE's. A statement
240 * transfers control to its next sibling.
241 *
242 * In case of an expression tree, there is no control flow within the tree
243 * even when there are short circuited operators and conditionals. When we
244 * are doing data flow analysis, we will simply synthesize lattices up the
245 * expression tree by finding the meet at each expression node.
246 *
247 * For example: within a Token.SWITCH, the expression in question does not
248 * change the control flow and need not to be considered.
249 */
250 if (parent != null) {
251 switch (parent.getType()) {
252 case Token.FOR:
253 // Only traverse the body of the for loop.
254 return n == parent.getLastChild();
255
256 // Skip the conditions.
257 case Token.IF:
258 case Token.WHILE:
259 case Token.WITH:
260 return n != parent.getFirstChild();
261 case Token.DO:
262 return n != parent.getFirstChild().getNext();
263 // Only traverse the body of the cases
264 case Token.SWITCH:
265 case Token.CASE:
266 case Token.CATCH:
267 case Token.LABEL:
268 return n != parent.getFirstChild();
269 case Token.FUNCTION:
270 return n == parent.getFirstChild().getNext().getNext();
271 case Token.CONTINUE:
272 case Token.BREAK:
273 case Token.EXPR_RESULT:
274 case Token.VAR:
275 case Token.RETURN:
276 case Token.THROW:
277 return false;
278 case Token.TRY:
279 /* Just before we are about to visit the second child of the TRY node,
280 * we know that we will be visiting either the CATCH or the FINALLY.
281 * In other words, we know that the post order traversal of the TRY
282 * block has been finished, no more exceptions can be caught by the
283 * handler at this TRY block and should be taken out of the stack.
284 */
285 if (n == parent.getFirstChild().getNext()) {
286 Preconditions.checkState(exceptionHandler.peek() == parent);
287 exceptionHandler.pop();
288 }
289 }
290 }
291 return true;
292 }
293
294 @Override
295 public void visit(NodeTraversal t, Node n, Node parent) {
296 switch (n.getType()) {
297 case Token.IF:
298 handleIf(n);
299 return;
300 case Token.WHILE:
301 handleWhile(n);
302 return;
303 case Token.DO:
304 handleDo(n);
305 return;
306 case Token.FOR:
307 handleFor(n);
308 return;
309 case Token.SWITCH:
310 handleSwitch(n);
311 return;
312 case Token.CASE:
313 handleCase(n);
314 return;
315 case Token.DEFAULT_CASE:
316 handleDefault(n);
317 return;
318 case Token.BLOCK:
319 case Token.SCRIPT:
320 handleStmtList(n);
321 return;
322 case Token.FUNCTION:
323 handleFunction(n);
324 return;
325 case Token.EXPR_RESULT:
326 handleExpr(n);
327 return;
328 case Token.THROW:
329 handleThrow(n);
330 return;
331 case Token.TRY:
332 handleTry(n);
333 return;
334 case Token.CATCH:
335 handleCatch(n);
336 return;
337 case Token.BREAK:
338 handleBreak(n);
339 return;
340 case Token.CONTINUE:
341 handleContinue(n);
342 return;
343 case Token.RETURN:
344 handleReturn(n);
345 return;
346 case Token.WITH:
347 handleWith(n);
348 return;
349 case Token.LABEL:
350 return;
351 default:
352 handleStmt(n);
353 return;
354 }
355 }
356
357 private void handleIf(Node node) {
358 Node thenBlock = node.getFirstChild().getNext();
359 Node elseBlock = thenBlock.getNext();
360 createEdge(node, Branch.ON_TRUE, computeFallThrough(thenBlock));
361
362 if (elseBlock == null) {
363 createEdge(node, Branch.ON_FALSE,
364 computeFollowNode(node, this)); // not taken branch
365 } else {
366 createEdge(node, Branch.ON_FALSE, computeFallThrough(elseBlock));
367 }
368 connectToPossibleExceptionHandler(
369 node, NodeUtil.getConditionExpression(node));
370 }
371
372 private void handleWhile(Node node) {
373 // Control goes to the first statement if the condition evaluates to true.
374 createEdge(node, Branch.ON_TRUE,
375 computeFallThrough(node.getFirstChild().getNext()));
376
377 // Control goes to the follow() if the condition evaluates to false.
378 createEdge(node, Branch.ON_FALSE,
379 computeFollowNode(node, this));
380 connectToPossibleExceptionHandler(
381 node, NodeUtil.getConditionExpression(node));
382 }
383
384 private void handleDo(Node node) {
385 // The first edge can be the initial iteration as well as the iterations
386 // after.
387 createEdge(node, Branch.ON_TRUE, computeFallThrough(node.getFirstChild()));
388 // The edge that leaves the do loop if the condition fails.
389 createEdge(node, Branch.ON_FALSE,
390 computeFollowNode(node, this));
391 connectToPossibleExceptionHandler(
392 node, NodeUtil.getConditionExpression(node));
393 }
394
395 private void handleFor(Node forNode) {
396 if (forNode.getChildCount() == 4) {
397 // We have for (init; cond; iter) { body }
398 Node init = forNode.getFirstChild();
399 Node cond = init.getNext();
400 Node iter = cond.getNext();
401 Node body = iter.getNext();
402 // After initialization, we transfer to the FOR which is in charge of
403 // checking the condition (for the first time).
404 createEdge(init, Branch.UNCOND, forNode);
405 // The edge that transfer control to the beginning of the loop body.
406 createEdge(forNode, Branch.ON_TRUE, computeFallThrough(body));
407 // The edge to end of the loop.
408 createEdge(forNode, Branch.ON_FALSE,
409 computeFollowNode(forNode, this));
410 // The end of the body will have a unconditional branch to our iter
411 // (handled by calling computeFollowNode of the last instruction of the
412 // body. Our iter will jump to the forNode again to another condition
413 // check.
414 createEdge(iter, Branch.UNCOND, forNode);
415 connectToPossibleExceptionHandler(init, init);
416 connectToPossibleExceptionHandler(forNode, cond);
417 connectToPossibleExceptionHandler(iter, iter);
418 } else {
419 // We have for (item in collection) { body }
420 Node item = forNode.getFirstChild();
421 Node collection = item.getNext();
422 Node body = collection.getNext();
423 // The collection behaves like init.
424 createEdge(collection, Branch.UNCOND, forNode);
425 // The edge that transfer control to the beginning of the loop body.
426 createEdge(forNode, Branch.ON_TRUE, computeFallThrough(body));
427 // The edge to end of the loop.
428 createEdge(forNode, Branch.ON_FALSE,
429 computeFollowNode(forNode, this));
430 connectToPossibleExceptionHandler(forNode, collection);
431 }
432 }
433
434 private void handleSwitch(Node node) {
435 // Transfer to the first non-DEFAULT CASE. if there are none, transfer
436 // to the DEFAULT or the EMPTY node.
437 Node next = getNextSiblingOfType(
438 node.getFirstChild().getNext(), Token.CASE, Token.EMPTY);
439 if (next != null) { // Has at least one CASE or EMPTY
440 createEdge(node, Branch.UNCOND, next);
441 } else { // Has no CASE but possibly a DEFAULT
442 if (node.getFirstChild().getNext() != null) {
443 createEdge(node, Branch.UNCOND, node.getFirstChild().getNext());
444 } else { // No CASE, no DEFAULT
445 createEdge(node, Branch.UNCOND, computeFollowNode(node, this));
446 }
447 }
448 connectToPossibleExceptionHandler(node, node.getFirstChild());
449 }
450
451 private void handleCase(Node node) {
452 // Case is a bit tricky....First it goes into the body if condition is true.
453 createEdge(node, Branch.ON_TRUE,
454 node.getFirstChild().getNext());
455 // Look for the next CASE, skipping over DEFAULT.
456 Node next = getNextSiblingOfType(node.getNext(), Token.CASE);
457 if (next != null) { // Found a CASE
458 Preconditions.checkState(next.isCase());
459 createEdge(node, Branch.ON_FALSE, next);
460 } else { // No more CASE found, go back and search for a DEFAULT.
461 Node parent = node.getParent();
462 Node deflt = getNextSiblingOfType(
463 parent.getFirstChild().getNext(), Token.DEFAULT_CASE);
464 if (deflt != null) { // Has a DEFAULT
465 createEdge(node, Branch.ON_FALSE, deflt);
466 } else { // No DEFAULT found, go to the follow of the SWITCH.
467 createEdge(node, Branch.ON_FALSE, computeFollowNode(node, this));
468 }
469 }
470 connectToPossibleExceptionHandler(node, node.getFirstChild());
471 }
472
473 private void handleDefault(Node node) {
474 // Directly goes to the body. It should not transfer to the next case.
475 createEdge(node, Branch.UNCOND, node.getFirstChild());
476 }
477
478 private void handleWith(Node node) {
479 // Directly goes to the body. It should not transfer to the next case.
480 createEdge(node, Branch.UNCOND, node.getLastChild());
481 connectToPossibleExceptionHandler(node, node.getFirstChild());
482 }
483
484 private void handleStmtList(Node node) {
485 Node parent = node.getParent();
486 // Special case, don't add a block of empty CATCH block to the graph.
487 if (node.isBlock() && parent != null &&
488 parent.isTry() &&
489 NodeUtil.getCatchBlock(parent) == node &&
490 !NodeUtil.hasCatchHandler(node)) {
491 return;
492 }
493
494 // A block transfer control to its first child if it is not empty.
495 Node child = node.getFirstChild();
496
497 // Function declarations are skipped since control doesn't go into that
498 // function (unless it is called)
499 while (child != null && child.isFunction()) {
500 child = child.getNext();
501 }
502
503 if (child != null) {
504 createEdge(node, Branch.UNCOND, computeFallThrough(child));
505 } else {
506 createEdge(node, Branch.UNCOND, computeFollowNode(node, this));
507 }
508
509 // Synthetic blocks
510 if (parent != null) {
511 switch (parent.getType()) {
512 case Token.DEFAULT_CASE:
513 case Token.CASE:
514 case Token.TRY:
515 break;
516 default:
517 if (node.isBlock() && node.isSyntheticBlock()) {
518 createEdge(node, Branch.SYN_BLOCK, computeFollowNode(node, this));
519 }
520 break;
521 }
522 }
523 }
524
525 private void handleFunction(Node node) {
526 // A block transfer control to its first child if it is not empty.
527 Preconditions.checkState(node.getChildCount() >= 3);
528 createEdge(node, Branch.UNCOND,
529 computeFallThrough(node.getFirstChild().getNext().getNext()));
530 Preconditions.checkState(exceptionHandler.peek() == node);
531 exceptionHandler.pop();
532 }
533
534 private void handleExpr(Node node) {
535 createEdge(node, Branch.UNCOND, computeFollowNode(node, this));
536 connectToPossibleExceptionHandler(node, node);
537 }
538
539 private void handleThrow(Node node) {
540 connectToPossibleExceptionHandler(node, node);
541 }
542
543 private void handleTry(Node node) {
544 createEdge(node, Branch.UNCOND, node.getFirstChild());
545 }
546
547 private void handleCatch(Node node) {
548 createEdge(node, Branch.UNCOND, node.getLastChild());
549 }
550
551 private void handleBreak(Node node) {
552 String label = null;
553 // See if it is a break with label.
554 if (node.hasChildren()) {
555 label = node.getFirstChild().getString();
556 }
557 Node cur;
558 Node previous = null;
559 Node lastJump;
560 Node parent = node.getParent();
561 /*
562 * Continuously look up the ancestor tree for the BREAK target or the target
563 * with the corresponding label and connect to it. If along the path we
564 * discover a FINALLY, we will connect the BREAK to that FINALLY. From then
565 * on, we will just record the control flow changes in the finallyMap. This
566 * is due to the fact that we need to connect any node that leaves its own
567 * FINALLY block to the outer FINALLY or the BREAK's target but those nodes
568 * are not known yet due to the way we traverse the nodes.
569 */
570 for (cur = node, lastJump = node;
571 !isBreakTarget(cur, label);
572 cur = parent, parent = parent.getParent()) {
573 if (cur.isTry() && NodeUtil.hasFinally(cur)
574 && cur.getLastChild() != previous) {
575 if (lastJump == node) {
576 createEdge(lastJump, Branch.UNCOND, computeFallThrough(
577 cur.getLastChild()));
578 } else {
579 finallyMap.put(lastJump, computeFallThrough(cur.getLastChild()));
580 }
581 lastJump = cur;
582 }
583 if (parent == null) {
584 if (compiler.isIdeMode()) {
585 // In IDE mode, we expect that the data flow graph may
586 // not be well-formed.
587 return;
588 } else {
589 throw new IllegalStateException("Cannot find break target.");
590 }
591 }
592 previous = cur;
593 }
594 if (lastJump == node) {
595 createEdge(lastJump, Branch.UNCOND, computeFollowNode(cur, this));
596 } else {
597 finallyMap.put(lastJump, computeFollowNode(cur, this));
598 }
599 }
600
601 private void handleContinue(Node node) {
602 String label = null;
603 if (node.hasChildren()) {
604 label = node.getFirstChild().getString();
605 }
606 Node cur;
607 Node previous = null;
608 Node lastJump;
609
610 // Similar to handBreak's logic with a few minor variation.
611 Node parent = node.getParent();
612 for (cur = node, lastJump = node;
613 !isContinueTarget(cur, parent, label);
614 cur = parent, parent = parent.getParent()) {
615 if (cur.isTry() && NodeUtil.hasFinally(cur)
616 && cur.getLastChild() != previous) {
617 if (lastJump == node) {
618 createEdge(lastJump, Branch.UNCOND, cur.getLastChild());
619 } else {
620 finallyMap.put(lastJump, computeFallThrough(cur.getLastChild()));
621 }
622 lastJump = cur;
623 }
624 Preconditions.checkState(parent != null, "Cannot find continue target.");
625 previous = cur;
626 }
627 Node iter = cur;
628 if (cur.getChildCount() == 4) {
629 iter = cur.getFirstChild().getNext().getNext();
630 }
631
632 if (lastJump == node) {
633 createEdge(node, Branch.UNCOND, iter);
634 } else {
635 finallyMap.put(lastJump, iter);
636 }
637 }
638
639 private void handleReturn(Node node) {
640 Node lastJump = null;
641 for (Iterator<Node> iter = exceptionHandler.iterator(); iter.hasNext();) {
642 Node curHandler = iter.next();
643 if (curHandler.isFunction()) {
644 break;
645 }
646 if (NodeUtil.hasFinally(curHandler)) {
647 if (lastJump == null) {
648 createEdge(node, Branch.UNCOND, curHandler.getLastChild());
649 } else {
650 finallyMap.put(lastJump,
651 computeFallThrough(curHandler.getLastChild()));
652 }
653 lastJump = curHandler;
654 }
655 }
656
657 if (node.hasChildren()) {
658 connectToPossibleExceptionHandler(node, node.getFirstChild());
659 }
660
661 if (lastJump == null) {
662 createEdge(node, Branch.UNCOND, null);
663 } else {
664 finallyMap.put(lastJump, null);
665 }
666 }
667
668 private void handleStmt(Node node) {
669 // Simply transfer to the next line.
670 createEdge(node, Branch.UNCOND, computeFollowNode(node, this));
671 connectToPossibleExceptionHandler(node, node);
672 }
673
674 static Node computeFollowNode(Node node, ControlFlowAnalysis cfa) {
675 return computeFollowNode(node, node, cfa);
676 }
677
678 static Node computeFollowNode(Node node) {
679 return computeFollowNode(node, node, null);
680 }
681
682 /**
683 * Computes the follow() node of a given node and its parent. There is a side
684 * effect when calling this function. If this function computed an edge that
685 * exists a FINALLY, it'll attempt to connect the fromNode to the outer
686 * FINALLY according to the finallyMap.
687 *
688 * @param fromNode The original source node since {@code node} is changed
689 * during recursion.
690 * @param node The node that follow() should compute.
691 */
692 private static Node computeFollowNode(
693 Node fromNode, Node node, ControlFlowAnalysis cfa) {
694 /*
695 * This is the case where:
696 *
697 * 1. Parent is null implies that we are transferring control to the end of
698 * the script.
699 *
700 * 2. Parent is a function implies that we are transferring control back to
701 * the caller of the function.
702 *
703 * 3. If the node is a return statement, we should also transfer control
704 * back to the caller of the function.
705 *
706 * 4. If the node is root then we have reached the end of what we have been
707 * asked to traverse.
708 *
709 * In all cases we should transfer control to a "symbolic return" node.
710 * This will make life easier for DFAs.
711 */
712 Node parent = node.getParent();
713 if (parent == null || parent.isFunction() ||
714 (cfa != null && node == cfa.root)) {
715 return null;
716 }
717
718 // If we are just before a IF/WHILE/DO/FOR:
719 switch (parent.getType()) {
720 // The follow() of any of the path from IF would be what follows IF.
721 case Token.IF:
722 return computeFollowNode(fromNode, parent, cfa);
723 case Token.CASE:
724 case Token.DEFAULT_CASE:
725 // After the body of a CASE, the control goes to the body of the next
726 // case, without having to go to the case condition.
727 if (parent.getNext() != null) {
728 if (parent.getNext().isCase()) {
729 return parent.getNext().getFirstChild().getNext();
730 } else if (parent.getNext().isDefaultCase()) {
731 return parent.getNext().getFirstChild();
732 } else {
733 Preconditions.checkState(false, "Not reachable");
734 }
735 } else {
736 return computeFollowNode(fromNode, parent, cfa);
737 }
738 break;
739 case Token.FOR:
740 if (NodeUtil.isForIn(parent)) {
741 return parent;
742 } else {
743 return parent.getFirstChild().getNext().getNext();
744 }
745 case Token.WHILE:
746 case Token.DO:
747 return parent;
748 case Token.TRY:
749 // If we are coming out of the TRY block...
750 if (parent.getFirstChild() == node) {
751 if (NodeUtil.hasFinally(parent)) { // and have FINALLY block.
752 return computeFallThrough(parent.getLastChild());
753 } else { // and have no FINALLY.
754 return computeFollowNode(fromNode, parent, cfa);
755 }
756 // CATCH block.
757 } else if (NodeUtil.getCatchBlock(parent) == node){
758 if (NodeUtil.hasFinally(parent)) { // and have FINALLY block.
759 return computeFallThrough(node.getNext());
760 } else {
761 return computeFollowNode(fromNode, parent, cfa);
762 }
763 // If we are coming out of the FINALLY block...
764 } else if (parent.getLastChild() == node){
765 if (cfa != null) {
766 for (Node finallyNode : cfa.finallyMap.get(parent)) {
767 cfa.createEdge(fromNode, Branch.ON_EX, finallyNode);
768 }
769 }
770 return computeFollowNode(fromNode, parent, cfa);
771 }
772 }
773
774 // Now that we are done with the special cases follow should be its
775 // immediate sibling, unless its sibling is a function
776 Node nextSibling = node.getNext();
777
778 // Skip function declarations because control doesn't get pass into it.
779 while (nextSibling != null && nextSibling.isFunction()) {
780 nextSibling = nextSibling.getNext();
781 }
782
783 if (nextSibling != null) {
784 return computeFallThrough(nextSibling);
785 } else {
786 // If there are no more siblings, control is transferred up the AST.
787 return computeFollowNode(fromNode, parent, cfa);
788 }
789 }
790
791 /**
792 * Computes the destination node of n when we want to fallthrough into the
793 * subtree of n. We don't always create a CFG edge into n itself because of
794 * DOs and FORs.
795 */
796 static Node computeFallThrough(Node n) {
797 switch (n.getType()) {
798 case Token.DO:
799 return computeFallThrough(n.getFirstChild());
800 case Token.FOR:
801 if (NodeUtil.isForIn(n)) {
802 return n.getFirstChild().getNext();
803 }
804 return computeFallThrough(n.getFirstChild());
805 case Token.LABEL:
806 return computeFallThrough(n.getLastChild());
807 default:
808 return n;
809 }
810 }
811
812 /**
813 * Connects the two nodes in the control flow graph.
814 *
815 * @param fromNode Source.
816 * @param toNode Destination.
817 */
818 private void createEdge(Node fromNode, ControlFlowGraph.Branch branch,
819 Node toNode) {
820 cfg.createNode(fromNode);
821 cfg.createNode(toNode);
822 cfg.connectIfNotFound(fromNode, branch, toNode);
823 }
824
825 /**
826 * Connects cfgNode to the proper CATCH block if target subtree might throw
827 * an exception. If there are FINALLY blocks reached before a CATCH, it will
828 * make the corresponding entry in finallyMap.
829 */
830 private void connectToPossibleExceptionHandler(Node cfgNode, Node target) {
831 if (mayThrowException(target) && !exceptionHandler.isEmpty()) {
832 Node lastJump = cfgNode;
833 for (Node handler : exceptionHandler) {
834 if (handler.isFunction()) {
835 return;
836 }
837 Preconditions.checkState(handler.isTry());
838 Node catchBlock = NodeUtil.getCatchBlock(handler);
839
840 if (!NodeUtil.hasCatchHandler(catchBlock)) { // No catch but a FINALLY.
841 if (lastJump == cfgNode) {
842 createEdge(cfgNode, Branch.ON_EX, handler.getLastChild());
843 } else {
844 finallyMap.put(lastJump, handler.getLastChild());
845 }
846 } else { // Has a catch.
847 if (lastJump == cfgNode) {
848 createEdge(cfgNode, Branch.ON_EX, catchBlock);
849 return;
850 } else {
851 finallyMap.put(lastJump, catchBlock);
852 }
853 }
854 lastJump = handler;
855 }
856 }
857 }
858
859 /**
860 * Get the next sibling (including itself) of one of the given types.
861 */
862 private static Node getNextSiblingOfType(Node first, int ... types) {
863 for (Node c = first; c != null; c = c.getNext()) {
864 for (int type : types) {
865 if (c.getType() == type) {
866 return c;
867 }
868 }
869 }
870 return null;
871 }
872
873 /**
874 * Checks if target is actually the break target of labeled continue. The
875 * label can be null if it is an unlabeled break.
876 */
877 public static boolean isBreakTarget(Node target, String label) {
878 return isBreakStructure(target, label != null) &&
879 matchLabel(target.getParent(), label);
880 }
881
882 /**
883 * Checks if target is actually the continue target of labeled continue. The
884 * label can be null if it is an unlabeled continue.
885 */
886 private static boolean isContinueTarget(
887 Node target, Node parent, String label) {
888 return isContinueStructure(target) && matchLabel(parent, label);
889 }
890 /**
891 * Check if label is actually referencing the target control structure. If
892 * label is null, it always returns true.
893 */
894 private static boolean matchLabel(Node target, String label) {
895 if (label == null) {
896 return true;
897 }
898 while (target.isLabel()) {
899 if (target.getFirstChild().getString().equals(label)) {
900 return true;
901 }
902 target = target.getParent();
903 }
904 return false;
905 }
906
907 /**
908 * Determines if the subtree might throw an exception.
909 */
910 public static boolean mayThrowException(Node n) {
911 switch (n.getType()) {
912 case Token.CALL:
913 case Token.GETPROP:
914 case Token.GETELEM:
915 case Token.THROW:
916 case Token.NEW:
917 case Token.ASSIGN:
918 case Token.INC:
919 case Token.DEC:
920 case Token.INSTANCEOF:
921 return true;
922 case Token.FUNCTION:
923 return false;
924 }
925 for (Node c = n.getFirstChild(); c != null; c = c.getNext()) {
926 if (!ControlFlowGraph.isEnteringNewCfgNode(c) && mayThrowException(c)) {
927 return true;
928 }
929 }
930 return false;
931 }
932
933 /**
934 * Determines whether the given node can be terminated with a BREAK node.
935 */
936 static boolean isBreakStructure(Node n, boolean labeled) {
937 switch (n.getType()) {
938 case Token.FOR:
939 case Token.DO:
940 case Token.WHILE:
941 case Token.SWITCH:
942 return true;
943 case Token.BLOCK:
944 case Token.IF:
945 case Token.TRY:
946 return labeled;
947 default:
948 return false;
949 }
950 }
951
952 /**
953 * Determines whether the given node can be advanced with a CONTINUE node.
954 */
955 static boolean isContinueStructure(Node n) {
956 switch (n.getType()) {
957 case Token.FOR:
958 case Token.DO:
959 case Token.WHILE:
960 return true;
961 default:
962 return false;
963 }
964 }
965
966 /**
967 * Get the TRY block with a CATCH that would be run if n throws an exception.
968 * @return The CATCH node or null if it there isn't a CATCH before the
969 * the function terminates.
970 */
971 static Node getExceptionHandler(Node n) {
972 for (Node cur = n;
973 !cur.isScript() && !cur.isFunction();
974 cur = cur.getParent()) {
975 Node catchNode = getCatchHandlerForBlock(cur);
976 if (catchNode != null) {
977 return catchNode;
978 }
979 }
980 return null;
981 }
982
983 /**
984 * Locate the catch BLOCK given the first block in a TRY.
985 * @return The CATCH node or null there is no catch handler.
986 */
987 static Node getCatchHandlerForBlock(Node block) {
988 if (block.isBlock() &&
989 block.getParent().isTry() &&
990 block.getParent().getFirstChild() == block) {
991 for (Node s = block.getNext(); s != null; s = s.getNext()) {
992 if (NodeUtil.hasCatchHandler(s)) {
993 return s.getFirstChild();
994 }
995 }
996 }
997 return null;
998 }
999
1000 /**
1001 * A {@link ControlFlowGraph} which provides a node comparator based on the
1002 * pre-order traversal of the AST.
1003 */
1004 private static class AstControlFlowGraph extends ControlFlowGraph<Node> {
1005 private final Map<DiGraphNode<Node, Branch>, Integer> priorities;
1006
1007 /**
1008 * Constructor.
1009 * @param entry The entry node.
1010 * @param priorities The map from nodes to position in the AST (to be
1011 * filled by the {@link ControlFlowAnalysis#shouldTraverse}).
1012 */
1013 private AstControlFlowGraph(Node entry,
1014 Map<DiGraphNode<Node, Branch>, Integer> priorities,
1015 boolean edgeAnnotations) {
1016 super(entry,
1017 true /* node annotations */, edgeAnnotations);
1018 this.priorities = priorities;
1019 }
1020
1021 @Override
1022 /**
1023 * Returns a node comparator based on the pre-order traversal of the AST.
1024 * @param isForward x 'before' y in the pre-order traversal implies
1025 * x 'less than' y (if true) and x 'greater than' y (if false).
1026 */
1027 public Comparator<DiGraphNode<Node, Branch>> getOptionalNodeComparator(
1028 boolean isForward) {
1029 if (isForward) {
1030 return new Comparator<DiGraphNode<Node, Branch>>() {
1031 @Override
1032 public int compare(
1033 DiGraphNode<Node, Branch> n1, DiGraphNode<Node, Branch> n2) {
1034 return getPosition(n1) - getPosition(n2);
1035 }
1036 };
1037 } else {
1038 return new Comparator<DiGraphNode<Node, Branch>>() {
1039 @Override
1040 public int compare(
1041 DiGraphNode<Node, Branch> n1, DiGraphNode<Node, Branch> n2) {
1042 return getPosition(n2) - getPosition(n1);
1043 }
1044 };
1045 }
1046 }
1047
1048 /**
1049 * Gets the pre-order traversal position of the given node.
1050 * @return An arbitrary counter used for comparing positions.
1051 */
1052 private int getPosition(DiGraphNode<Node, Branch> n) {
1053 Integer priority = priorities.get(n);
1054 Preconditions.checkNotNull(priority);
1055 return priority;
1056 }
1057 }
1058 }