Debian Codegraph @

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

raw symbols SCIP
1 /*
2 * Copyright 2004 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.InputId;
22 import com.google.javascript.rhino.Node;
23 import com.google.javascript.rhino.Token;
24
25 import java.util.ArrayDeque;
26 import java.util.Deque;
27 import java.util.Iterator;
28 import java.util.LinkedList;
29 import java.util.List;
30 import java.util.Set;
31
32
33 /**
34 * NodeTraversal allows an iteration through the nodes in the parse tree,
35 * and facilitates the optimizations on the parse tree.
36 *
37 */
38 public class NodeTraversal {
39 // Package protected for tests
40 private final AbstractCompiler compiler;
41 private final Callback callback;
42
43 /** Contains the current node*/
44 private Node curNode;
45
46 public static final DiagnosticType NODE_TRAVERSAL_ERROR =
47 DiagnosticType.error("JSC_NODE_TRAVERSAL_ERROR", "{0}");
48
49 /**
50 * Stack containing the Scopes that have been created. The Scope objects
51 * are lazily created; so the {@code scopeRoots} stack contains the
52 * Nodes for all Scopes that have not been created yet.
53 */
54 private final Deque<Scope> scopes = new ArrayDeque<Scope>();
55
56 /**
57 * A stack of scope roots. All scopes that have not been created
58 * are represented in this Deque.
59 */
60 private final Deque<Node> scopeRoots = new ArrayDeque<Node>();
61
62
63 /**
64 * Stack of control flow graphs (CFG). There is one CFG per scope. CFGs
65 * are lazily populated: elements are {@code null} until requested by
66 * {@link #getControlFlowGraph()}. Note that {@link ArrayDeque} does not allow
67 * {@code null} elements, so {@link LinkedList} is used instead.
68 */
69 Deque<ControlFlowGraph<Node>> cfgs = new LinkedList<ControlFlowGraph<Node>>();
70
71 /** The current source file name */
72 private String sourceName;
73
74 /** The current input */
75 private InputId inputId;
76
77 /** The scope creator */
78 private ScopeCreator scopeCreator;
79
80 /** Possible callback for scope entry and exist **/
81 private ScopedCallback scopeCallback;
82
83 /**
84 * Callback
85 */
86 public interface Callback {
87 /**
88 * <p>Visits a node in pre order (before visiting its children) and decides
89 * whether this node's children should be traversed. If children are
90 * traversed, they will be visited by
91 * {@link #visit(NodeTraversal, Node, Node)} in post order.</p>
92 * <p>Implementations can have side effects (e.g. modifying the parse
93 * tree).</p>
94 * @return whether the children of this node should be visited
95 */
96 boolean shouldTraverse(NodeTraversal nodeTraversal, Node n, Node parent);
97
98 /**
99 * <p>Visits a node in post order (after its children have been visited).
100 * A node is visited only if all its parents should be traversed
101 * ({@link #shouldTraverse(NodeTraversal, Node, Node)}).</p>
102 * <p>Implementations can have side effects (e.g. modifying the parse
103 * tree).</p>
104 */
105 void visit(NodeTraversal t, Node n, Node parent);
106 }
107
108 /**
109 * Callback that also knows about scope changes
110 */
111 public interface ScopedCallback extends Callback {
112
113 /**
114 * Called immediately after entering a new scope. The new scope can
115 * be accessed through t.getScope()
116 */
117 void enterScope(NodeTraversal t);
118
119 /**
120 * Called immediately before exiting a scope. The ending scope can
121 * be accessed through t.getScope()
122 */
123 void exitScope(NodeTraversal t);
124 }
125
126 /**
127 * Abstract callback to visit all nodes in post order.
128 */
129 public abstract static class AbstractPostOrderCallback implements Callback {
130 @Override
131 public final boolean shouldTraverse(NodeTraversal nodeTraversal, Node n,
132 Node parent) {
133 return true;
134 }
135 }
136
137 /**
138 * Abstract scoped callback to visit all nodes in post order.
139 */
140 public abstract static class AbstractScopedCallback
141 implements ScopedCallback {
142 @Override
143 public final boolean shouldTraverse(NodeTraversal nodeTraversal, Node n,
144 Node parent) {
145 return true;
146 }
147
148 @Override
149 public void enterScope(NodeTraversal t) {}
150
151 @Override
152 public void exitScope(NodeTraversal t) {}
153 }
154
155 /**
156 * Abstract callback to visit all nodes but not traverse into function
157 * bodies.
158 */
159 public abstract static class AbstractShallowCallback implements Callback {
160 @Override
161 public final boolean shouldTraverse(NodeTraversal nodeTraversal, Node n,
162 Node parent) {
163 // We do want to traverse the name of a named function, but we don't
164 // want to traverse the arguments or body.
165 return parent == null || !parent.isFunction() ||
166 n == parent.getFirstChild();
167 }
168 }
169
170 /**
171 * Abstract callback to visit all structure and statement nodes but doesn't
172 * traverse into functions or expressions.
173 */
174 public abstract static class AbstractShallowStatementCallback
175 implements Callback {
176 @Override
177 public final boolean shouldTraverse(NodeTraversal nodeTraversal, Node n,
178 Node parent) {
179 return parent == null || NodeUtil.isControlStructure(parent)
180 || NodeUtil.isStatementBlock(parent);
181 }
182 }
183
184 /**
185 * Abstract callback to visit a pruned set of nodes.
186 */
187 public abstract static class AbstractNodeTypePruningCallback
188 implements Callback {
189 private final Set<Integer> nodeTypes;
190 private final boolean include;
191
192 /**
193 * Creates an abstract pruned callback.
194 * @param nodeTypes the nodes to include in the traversal
195 */
196 public AbstractNodeTypePruningCallback(Set<Integer> nodeTypes) {
197 this(nodeTypes, true);
198 }
199
200 /**
201 * Creates an abstract pruned callback.
202 * @param nodeTypes the nodes to include/exclude in the traversal
203 * @param include whether to include or exclude the nodes in the traversal
204 */
205 public AbstractNodeTypePruningCallback(Set<Integer> nodeTypes,
206 boolean include) {
207 this.nodeTypes = nodeTypes;
208 this.include = include;
209 }
210
211 @Override
212 public boolean shouldTraverse(NodeTraversal nodeTraversal, Node n,
213 Node parent) {
214 return include == nodeTypes.contains(n.getType());
215 }
216 }
217
218 /**
219 * Creates a node traversal using the specified callback interface.
220 */
221 public NodeTraversal(AbstractCompiler compiler, Callback cb) {
222 this(compiler, cb, new SyntacticScopeCreator(compiler));
223 }
224
225 /**
226 * Creates a node traversal using the specified callback interface
227 * and the scope creator.
228 */
229 public NodeTraversal(AbstractCompiler compiler, Callback cb,
230 ScopeCreator scopeCreator) {
231 this.callback = cb;
232 if (cb instanceof ScopedCallback) {
233 this.scopeCallback = (ScopedCallback) cb;
234 }
235 this.compiler = compiler;
236 this.inputId = null;
237 this.sourceName = "";
238 this.scopeCreator = scopeCreator;
239 }
240
241 private void throwUnexpectedException(Exception unexpectedException) {
242 // If there's an unexpected exception, try to get the
243 // line number of the code that caused it.
244 String message = unexpectedException.getMessage();
245
246 // TODO(user): It is possible to get more information if curNode or
247 // its parent is missing. We still have the scope stack in which it is still
248 // very useful to find out at least which function caused the exception.
249 if (inputId != null) {
250 message =
251 unexpectedException.getMessage() + "\n" +
252 formatNodeContext("Node", curNode) +
253 (curNode == null ?
254 "" :
255 formatNodeContext("Parent", curNode.getParent()));
256 }
257 compiler.throwInternalError(message, unexpectedException);
258 }
259
260 private String formatNodeContext(String label, Node n) {
261 if (n == null) {
262 return " " + label + ": NULL";
263 }
264 return " " + label + "(" + n.toString(false, false, false) + "): "
265 + formatNodePosition(n);
266 }
267
268 /**
269 * Traverses a parse tree recursively.
270 */
271 public void traverse(Node root) {
272 try {
273 inputId = NodeUtil.getInputId(root);
274 sourceName = "";
275 curNode = root;
276 pushScope(root);
277 traverseBranch(root, null);
278 popScope();
279 } catch (Exception unexpectedException) {
280 throwUnexpectedException(unexpectedException);
281 }
282 }
283
284 public void traverseRoots(Node ... roots) {
285 traverseRoots(Lists.newArrayList(roots));
286 }
287
288 public void traverseRoots(List<Node> roots) {
289 if (roots.isEmpty()) {
290 return;
291 }
292
293 try {
294 Node scopeRoot = roots.get(0).getParent();
295 Preconditions.checkState(scopeRoot != null);
296
297 inputId = NodeUtil.getInputId(scopeRoot);
298 sourceName = "";
299 curNode = scopeRoot;
300 pushScope(scopeRoot);
301
302 for (Node root : roots) {
303 Preconditions.checkState(root.getParent() == scopeRoot);
304 traverseBranch(root, scopeRoot);
305 }
306
307 popScope();
308 } catch (Exception unexpectedException) {
309 throwUnexpectedException(unexpectedException);
310 }
311 }
312
313 private static final String MISSING_SOURCE = "[source unknown]";
314
315 private String formatNodePosition(Node n) {
316 String sourceFileName = getBestSourceFileName(n);
317 if (sourceFileName == null) {
318 return MISSING_SOURCE + "\n";
319 }
320
321 int lineNumber = n.getLineno();
322 int columnNumber = n.getCharno();
323 String src = compiler.getSourceLine(sourceFileName, lineNumber);
324 if (src == null) {
325 src = MISSING_SOURCE;
326 }
327 return sourceFileName + ":" + lineNumber + ":" + columnNumber + "\n"
328 + src + "\n";
329 }
330
331 /**
332 * Traverses a parse tree recursively with a scope, starting with the given
333 * root. This should only be used in the global scope. Otherwise, use
334 * {@link #traverseAtScope}.
335 */
336 void traverseWithScope(Node root, Scope s) {
337 Preconditions.checkState(s.isGlobal());
338
339 inputId = null;
340 sourceName = "";
341 curNode = root;
342 pushScope(s);
343 traverseBranch(root, null);
344 popScope();
345 }
346
347 /**
348 * Traverses a parse tree recursively with a scope, starting at that scope's
349 * root.
350 */
351 void traverseAtScope(Scope s) {
352 Node n = s.getRootNode();
353 if (n.isFunction()) {
354 // We need to do some extra magic to make sure that the scope doesn't
355 // get re-created when we dive into the function.
356 if (inputId == null) {
357 inputId = NodeUtil.getInputId(n);
358 }
359 sourceName = getSourceName(n);
360 curNode = n;
361 pushScope(s);
362
363 Node args = n.getFirstChild().getNext();
364 Node body = args.getNext();
365 traverseBranch(args, n);
366 traverseBranch(body, n);
367
368 popScope();
369 } else {
370 traverseWithScope(n, s);
371 }
372 }
373
374 /**
375 * Traverses an inner node recursively with a refined scope. An inner node may
376 * be any node with a non {@code null} parent (i.e. all nodes except the
377 * root).
378 *
379 * @param node the node to traverse
380 * @param parent the node's parent, it may not be {@code null}
381 * @param refinedScope the refined scope of the scope currently at the top of
382 * the scope stack or in trivial cases that very scope or {@code null}
383 */
384 protected void traverseInnerNode(Node node, Node parent, Scope refinedScope) {
385 Preconditions.checkNotNull(parent);
386 if (refinedScope != null && getScope() != refinedScope) {
387 curNode = node;
388 pushScope(refinedScope);
389 traverseBranch(node, parent);
390 popScope();
391 } else {
392 traverseBranch(node, parent);
393 }
394 }
395
396 /**
397 * Gets the compiler.
398 */
399 public Compiler getCompiler() {
400 // TODO(nicksantos): Remove this type cast. This is just temporary
401 // while refactoring.
402 return (Compiler) compiler;
403 }
404
405 /**
406 * Gets the current line number, or zero if it cannot be determined. The line
407 * number is retrieved lazily as a running time optimization.
408 */
409 public int getLineNumber() {
410 Node cur = curNode;
411 while (cur != null) {
412 int line = cur.getLineno();
413 if (line >=0) {
414 return line;
415 }
416 cur = cur.getParent();
417 }
418 return 0;
419 }
420
421 /**
422 * Gets the current input source name.
423 *
424 * @return A string that may be empty, but not null
425 */
426 public String getSourceName() {
427 return sourceName;
428 }
429
430 /**
431 * Gets the current input source.
432 */
433 public CompilerInput getInput() {
434 return compiler.getInput(inputId);
435 }
436
437 /**
438 * Gets the current input module.
439 */
440 public JSModule getModule() {
441 CompilerInput input = getInput();
442 return input == null ? null : input.getModule();
443 }
444
445 /** Returns the node currently being traversed. */
446 public Node getCurrentNode() {
447 return curNode;
448 }
449
450 /**
451 * Traverses a node recursively.
452 */
453 public static void traverse(
454 AbstractCompiler compiler, Node root, Callback cb) {
455 NodeTraversal t = new NodeTraversal(compiler, cb);
456 t.traverse(root);
457 }
458
459 /**
460 * Traverses a list of node trees.
461 */
462 public static void traverseRoots(
463 AbstractCompiler compiler, List<Node> roots, Callback cb) {
464 NodeTraversal t = new NodeTraversal(compiler, cb);
465 t.traverseRoots(roots);
466 }
467
468 public static void traverseRoots(
469 AbstractCompiler compiler, Callback cb, Node ... roots) {
470 NodeTraversal t = new NodeTraversal(compiler, cb);
471 t.traverseRoots(roots);
472 }
473
474 /**
475 * Traverses a branch.
476 */
477 @SuppressWarnings("fallthrough")
478 private void traverseBranch(Node n, Node parent) {
479 int type = n.getType();
480 if (type == Token.SCRIPT) {
481 inputId = n.getInputId();
482 sourceName = getSourceName(n);
483 }
484
485 curNode = n;
486 if (!callback.shouldTraverse(this, n, parent)) return;
487
488 switch (type) {
489 case Token.FUNCTION:
490 traverseFunction(n, parent);
491 break;
492
493 default:
494 for (Node child = n.getFirstChild(); child != null; ) {
495 // child could be replaced, in which case our child node
496 // would no longer point to the true next
497 Node next = child.getNext();
498 traverseBranch(child, n);
499 child = next;
500 }
501 break;
502 }
503
504 curNode = n;
505 callback.visit(this, n, parent);
506 }
507
508 /**
509 * Traverses a function.
510 */
511 private void traverseFunction(Node n, Node parent) {
512 Preconditions.checkState(n.getChildCount() == 3);
513 Preconditions.checkState(n.isFunction());
514
515 final Node fnName = n.getFirstChild();
516
517 boolean isFunctionExpression = (parent != null)
518 && NodeUtil.isFunctionExpression(n);
519
520 if (!isFunctionExpression) {
521 // Functions declarations are in the scope containing the declaration.
522 traverseBranch(fnName, n);
523 }
524
525 curNode = n;
526 pushScope(n);
527
528 if (isFunctionExpression) {
529 // Function expression names are only accessible within the function
530 // scope.
531 traverseBranch(fnName, n);
532 }
533
534 final Node args = fnName.getNext();
535 final Node body = args.getNext();
536
537 // Args
538 traverseBranch(args, n);
539
540 // Body
541 Preconditions.checkState(body.getNext() == null &&
542 body.isBlock(), body);
543 traverseBranch(body, n);
544
545 popScope();
546 }
547
548 /** Examines the functions stack for the last instance of a function node. */
549 @SuppressWarnings("unchecked")
550 public Node getEnclosingFunction() {
551 if (scopes.size() + scopeRoots.size() < 2) {
552 return null;
553 } else {
554 if (scopeRoots.isEmpty()) {
555 return scopes.peek().getRootNode();
556 } else {
557 return scopeRoots.peek();
558 }
559 }
560 }
561
562 /** Creates a new scope (e.g. when entering a function). */
563 private void pushScope(Node node) {
564 Preconditions.checkState(curNode != null);
565 scopeRoots.push(node);
566 cfgs.push(null);
567 if (scopeCallback != null) {
568 scopeCallback.enterScope(this);
569 }
570 }
571
572 /** Creates a new scope (e.g. when entering a function). */
573 private void pushScope(Scope s) {
574 Preconditions.checkState(curNode != null);
575 scopes.push(s);
576 cfgs.push(null);
577 if (scopeCallback != null) {
578 scopeCallback.enterScope(this);
579 }
580 }
581
582 /** Pops back to the previous scope (e.g. when leaving a function). */
583 private void popScope() {
584 if (scopeCallback != null) {
585 scopeCallback.exitScope(this);
586 }
587 if (scopeRoots.isEmpty()) {
588 scopes.pop();
589 } else {
590 scopeRoots.pop();
591 }
592 cfgs.pop();
593 }
594
595 /** Gets the current scope. */
596 public Scope getScope() {
597 Scope scope = scopes.isEmpty() ? null : scopes.peek();
598 if (scopeRoots.isEmpty()) {
599 return scope;
600 }
601
602 Iterator<Node> it = scopeRoots.descendingIterator();
603 while (it.hasNext()) {
604 scope = scopeCreator.createScope(it.next(), scope);
605 scopes.push(scope);
606 }
607 scopeRoots.clear();
608
609 return scope;
610 }
611
612 /** Gets the control flow graph for the current JS scope. */
613 public ControlFlowGraph<Node> getControlFlowGraph() {
614 if (cfgs.peek() == null) {
615 ControlFlowAnalysis cfa = new ControlFlowAnalysis(compiler, false, true);
616 cfa.process(null, getScopeRoot());
617 cfgs.pop();
618 cfgs.push(cfa.getCfg());
619 }
620 return cfgs.peek();
621 }
622
623 /** Returns the current scope's root. */
624 public Node getScopeRoot() {
625 if (scopeRoots.isEmpty()) {
626 return scopes.peek().getRootNode();
627 } else {
628 return scopeRoots.peek();
629 }
630 }
631
632 /**
633 * Determines whether the traversal is currently in the global scope.
634 */
635 boolean inGlobalScope() {
636 return getScopeDepth() <= 1;
637 }
638
639 int getScopeDepth() {
640 return scopes.size() + scopeRoots.size();
641 }
642
643 public boolean hasScope() {
644 return !(scopes.isEmpty() && scopeRoots.isEmpty());
645 }
646
647 /** Reports a diagnostic (error or warning) */
648 public void report(Node n, DiagnosticType diagnosticType,
649 String... arguments) {
650 JSError error = JSError.make(getBestSourceFileName(n),
651 n, diagnosticType, arguments);
652 compiler.report(error);
653 }
654
655 private static String getSourceName(Node n) {
656 String name = n.getSourceFileName();
657 return name == null ? "" : name;
658 }
659
660 InputId getInputId() {
661 return inputId;
662 }
663
664 /**
665 * Creates a JSError during NodeTraversal.
666 *
667 * @param n Determines the line and char position within the source file name
668 * @param type The DiagnosticType
669 * @param arguments Arguments to be incorporated into the message
670 */
671 public JSError makeError(Node n, CheckLevel level, DiagnosticType type,
672 String... arguments) {
673 return JSError.make(getBestSourceFileName(n), n, level, type, arguments);
674 }
675
676 /**
677 * Creates a JSError during NodeTraversal.
678 *
679 * @param n Determines the line and char position within the source file name
680 * @param type The DiagnosticType
681 * @param arguments Arguments to be incorporated into the message
682 */
683 public JSError makeError(Node n, DiagnosticType type, String... arguments) {
684 return JSError.make(getBestSourceFileName(n), n, type, arguments);
685 }
686
687 private String getBestSourceFileName(Node n) {
688 return n == null ? sourceName : n.getSourceFileName();
689 }
690 }