KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > nfunk > jep > ParserDumpVisitor


1 /**
2  *
3  * Copyright (c) 1996-1997 Sun Microsystems, Inc.
4  *
5  * Use of this file and the system it is part of is constrained by the
6  * file COPYRIGHT in the root directory of this system.
7  *
8  */

9
10 /* This is an example of how the Visitor pattern might be used to
11    implement the dumping code that comes with SimpleNode. It's a bit
12    long-winded, but it does illustrate a couple of the main points.
13
14    1) the visitor can maintain state between the nodes that it visits
15    (for example the current indentation level).
16
17    2) if you don't implement a jjtAccept() method for a subclass of
18    SimpleNode, then SimpleNode's acceptor will get called.
19
20    3) the utility method childrenAccept() can be useful when
21    implementing preorder or postorder tree walks.
22
23    Err, that's it. */

24    
25 package org.nfunk.jep;
26
27 public class ParserDumpVisitor implements ParserVisitor
28 {
29   private int indent = 0;
30
31   private String JavaDoc indentString() {
32     StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
33     for (int i = 0; i < indent; ++i) {
34       sb.append(" ");
35     }
36     return sb.toString();
37   }
38
39   public Object JavaDoc visit(SimpleNode node, Object JavaDoc data) throws ParseException {
40     System.out.println(indentString() + node +
41                ": acceptor not unimplemented in subclass?");
42     ++indent;
43     data = node.childrenAccept(this, data);
44     --indent;
45     return data;
46   }
47
48   public Object JavaDoc visit(ASTStart node, Object JavaDoc data) throws ParseException {
49     System.out.println(indentString() + node);
50     ++indent;
51     data = node.childrenAccept(this, data);
52     --indent;
53     return data;
54   }
55
56   public Object JavaDoc visit(ASTFunNode node, Object JavaDoc data) throws ParseException {
57     System.out.println(indentString() + node);
58     ++indent;
59     data = node.childrenAccept(this, data);
60     --indent;
61     return data;
62   }
63
64   public Object JavaDoc visit(ASTVarNode node, Object JavaDoc data) throws ParseException {
65     System.out.println(indentString() + node);
66     ++indent;
67     data = node.childrenAccept(this, data);
68     --indent;
69     return data;
70   }
71
72   public Object JavaDoc visit(ASTConstant node, Object JavaDoc data) throws ParseException {
73     System.out.println(indentString() + node);
74     ++indent;
75     data = node.childrenAccept(this, data);
76     --indent;
77     return data;
78   }
79 }
80
81 /*end*/
82
Popular Tags