01: // This file is part of KeY - Integrated Deductive Software Design
02: // Copyright (C) 2001-2007 Universitaet Karlsruhe, Germany
03: // Universitaet Koblenz-Landau, Germany
04: // Chalmers University of Technology, Sweden
05: //
06: // The KeY system is protected by the GNU General Public License.
07: // See LICENSE.TXT for details.
08: //
09: //
10:
11: package de.uka.ilkd.key.java.visitor;
12:
13: import de.uka.ilkd.key.java.NonTerminalProgramElement;
14: import de.uka.ilkd.key.java.ProgramElement;
15: import de.uka.ilkd.key.java.annotation.Annotation;
16:
17: /** walks through a java AST in depth-left-fist-order at default.
18: * Implementing method doAction specifies its behaviour at the
19: * different Nodes. The depth-left-fist behaviour can be changed by
20: * overwriting the method <code> walk(ProgramElement) </code>.
21: */
22: public abstract class JavaASTWalker {
23:
24: /** the root the walker starts */
25: private ProgramElement root;
26:
27: /** the current visited level */
28: private int depth = -1;
29:
30: /** create the JavaASTWalker
31: * @param root the ProgramElement where to begin
32: */
33: public JavaASTWalker(ProgramElement root) {
34: this .root = root;
35: }
36:
37: /** returns start point of the walker
38: * @return root of the AST to walk through
39: */
40: public ProgramElement root() {
41: return root;
42: }
43:
44: /** starts the walker*/
45: public void start() {
46: walk(root);
47: }
48:
49: /**
50: * returns the current vistted level
51: */
52: public int depth() {
53: return depth;
54: }
55:
56: /** walks through the AST. While keeping track of the current node
57: * @param node the JavaProgramElement the walker is at
58: */
59: protected void walk(ProgramElement node) {
60: if (node instanceof NonTerminalProgramElement) {
61: depth++;
62: NonTerminalProgramElement nonTerminalNode = (NonTerminalProgramElement) node;
63: // System.out.println("ASTWalker - node: "+node);
64: for (int i = 0; i < nonTerminalNode.getChildCount(); i++) {
65: //System.out.println("ASTWalker - node.childAt(i): "+nonTerminalNode.getChildAt(i));
66: if (nonTerminalNode.getChildAt(i) != null) {
67: walk(nonTerminalNode.getChildAt(i));
68: }
69: }
70: performActionOnAnnotationArray(node.getAnnotations());
71: depth--;
72: }
73: // otherwise the node is left, so perform the action
74: doAction(node);
75: }
76:
77: /** the action that is performed just before leaving the node the
78: * last time
79: */
80: protected abstract void doAction(ProgramElement node);
81:
82: /**
83: * Performs action on the annotations <code>a</code>.
84: */
85: protected void performActionOnAnnotationArray(Annotation[] a) {
86: // do nothing
87: }
88:
89: }
|