KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > persistence > antlr > ParseTreeRule


1 package persistence.antlr;
2
3 /* ANTLR Translator Generator
4  * Project led by Terence Parr at http://www.jGuru.com
5  * Software rights: http://www.antlr.org/license.html
6  */

7
8 import persistence.antlr.Token;
9 import persistence.antlr.collections.AST;
10
11 public class ParseTreeRule extends ParseTree {
12     public static final int INVALID_ALT = -1;
13
14     protected String JavaDoc ruleName;
15     protected int altNumber; // unused until I modify antlr to record this
16

17     public ParseTreeRule(String JavaDoc ruleName) {
18         this(ruleName,INVALID_ALT);
19     }
20
21     public ParseTreeRule(String JavaDoc ruleName, int altNumber) {
22         this.ruleName = ruleName;
23         this.altNumber = altNumber;
24     }
25
26     public String JavaDoc getRuleName() {
27         return ruleName;
28     }
29
30     /** Do a step-first walk, building up a buffer of tokens until
31      * you've reached a particular step and print out any rule subroots
32      * insteads of descending.
33      */

34     protected int getLeftmostDerivation(StringBuffer JavaDoc buf, int step) {
35         int numReplacements = 0;
36         if ( step<=0 ) {
37             buf.append(' ');
38             buf.append(toString());
39             return numReplacements;
40         }
41         AST child = getFirstChild();
42         numReplacements = 1;
43         // walk child printing them out, descending into at most one
44
while ( child!=null ) {
45             if ( numReplacements>=step || child instanceof ParseTreeToken ) {
46                 buf.append(' ');
47                 buf.append(child.toString());
48             }
49             else {
50                 // descend for at least one more derivation; update count
51
int remainingReplacements = step-numReplacements;
52                 int n = ((ParseTree)child).getLeftmostDerivation(buf,
53                                                                  remainingReplacements);
54                 numReplacements += n;
55             }
56             child = child.getNextSibling();
57         }
58         return numReplacements;
59     }
60
61     public String JavaDoc toString() {
62         if ( altNumber==INVALID_ALT ) {
63             return '<'+ruleName+'>';
64         }
65         else {
66             return '<'+ruleName+"["+altNumber+"]>";
67         }
68     }
69 }
70
Popular Tags