Do a step-first walk, building up a buffer of tokens until
you've reached a particular step and print out any rule subroots
insteads of descending.
int numReplacements = 0;
if ( step<=0 ) {
buf.append(' ");
buf.append(toString());
return numReplacements;
}
AST child = getFirstChild();
numReplacements = 1;
// walk child printing them out, descending into at most one
while ( child!=null ) {
if ( numReplacements>=step || child instanceof ParseTreeToken ) {
buf.append(' ");
buf.append(child.toString());
}
else {
// descend for at least one more derivation; update count
int remainingReplacements = step-numReplacements;
int n = ((ParseTree)child).getLeftmostDerivation(buf,
remainingReplacements);
numReplacements += n;
}
child = child.getNextSibling();
}
return numReplacements;