KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > polyglot > visit > DumpAst


1 package polyglot.visit;
2
3 import polyglot.ast.Node;
4 import polyglot.util.CodeWriter;
5 import polyglot.types.SemanticException;
6
7 import java.io.IOException JavaDoc;
8 import java.io.FileWriter JavaDoc;
9 import java.io.Writer JavaDoc;
10
11 /** Visitor which dumps the AST to a file. */
12 public class DumpAst extends NodeVisitor
13 {
14     protected Writer fw;
15     protected CodeWriter w;
16
17     public DumpAst(String JavaDoc name, int width) throws IOException JavaDoc {
18         this.fw = new FileWriter JavaDoc(name);
19     this.w = new CodeWriter(fw, width);
20     }
21
22     public DumpAst(CodeWriter w) {
23     this.w = w;
24     }
25
26     /**
27      * Visit each node before traversal of children. Call <code>dump</code> for
28      * that node. Then we begin a new <code>CodeWriter</code> block and traverse
29      * the children.
30      */

31     public NodeVisitor enter(Node n) {
32     w.write("(");
33     n.dump(w);
34     w.allowBreak(4," ");
35     w.begin(0);
36     return this;
37     }
38
39     /**
40      * This method is called only after normal traversal of the children. Thus
41      * we must end the <code>CodeWriter</code> block that was begun in
42      * <code>enter</code>.
43      */

44     public Node leave(Node old, Node n, NodeVisitor v) {
45     w.end();
46     w.write(")");
47     w.allowBreak(0, " ");
48     return n;
49     }
50
51     public void finish() {
52     try {
53         w.flush();
54
55         if (fw != null) {
56         fw.flush();
57         fw.close();
58         }
59     }
60     catch (IOException JavaDoc e) {
61         e.printStackTrace();
62     }
63     }
64 }
65
Popular Tags