KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > antlr > DumpASTVisitor


1 package antlr;
2
3 /* ANTLR Translator Generator
4  * Project led by Terence Parr at http://www.jGuru.com
5  * Software rights: http://www.antlr.org/RIGHTS.html
6  *
7  * $Id: //depot/code/org.antlr/main/main/antlr/DumpASTVisitor.java#4 $
8  */

9
10 import java.io.*;
11
12 import antlr.collections.AST;
13
14 /** Simple class to dump the contents of an AST to the output */
15 public class DumpASTVisitor implements ASTVisitor {
16     protected int level = 0;
17
18
19     private void tabs() {
20         for (int i = 0; i < level; i++) {
21             System.out.print(" ");
22         }
23     }
24
25     public void visit(AST node) {
26         // Flatten this level of the tree if it has no children
27
boolean flatten = /*true*/ false;
28         AST node2;
29         for (node2 = node; node2 != null; node2 = node2.getNextSibling()) {
30             if (node2.getFirstChild() != null) {
31                 flatten = false;
32                 break;
33             }
34         }
35
36         for (node2 = node; node2 != null; node2 = node2.getNextSibling()) {
37             if (!flatten || node2 == node) {
38                 tabs();
39             }
40             if (node2.getText() == null) {
41                 System.out.print("nil");
42             }
43             else {
44                 System.out.print(node2.getText());
45             }
46
47             System.out.print(" [" + node2.getType() + "] ");
48
49             if (flatten) {
50                 System.out.print(" ");
51             }
52             else {
53                 System.out.println("");
54             }
55
56             if (node2.getFirstChild() != null) {
57                 level++;
58                 visit(node2.getFirstChild());
59                 level--;
60             }
61         }
62
63         if (flatten) {
64             System.out.println("");
65         }
66     }
67 }
68
Popular Tags