01: package persistence.antlr;
02:
03: /* ANTLR Translator Generator
04: * Project led by Terence Parr at http://www.jGuru.com
05: * Software rights: http://www.antlr.org/license.html
06: */
07:
08: import persistence.antlr.Token;
09: import persistence.antlr.collections.AST;
10:
11: public class ParseTreeRule extends ParseTree {
12: public static final int INVALID_ALT = -1;
13:
14: protected String ruleName;
15: protected int altNumber; // unused until I modify antlr to record this
16:
17: public ParseTreeRule(String ruleName) {
18: this (ruleName, INVALID_ALT);
19: }
20:
21: public ParseTreeRule(String ruleName, int altNumber) {
22: this .ruleName = ruleName;
23: this .altNumber = altNumber;
24: }
25:
26: public String 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 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
46: || child instanceof ParseTreeToken) {
47: buf.append(' ');
48: buf.append(child.toString());
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 toString() {
62: if (altNumber == INVALID_ALT) {
63: return '<' + ruleName + '>';
64: } else {
65: return '<' + ruleName + "[" + altNumber + "]>";
66: }
67: }
68: }
|