The following code will walk the AST and print all AST nodes to stderr.
The same tree walker is the basis for a tree transformer that can replace tree nodes.
Allocate new tree nodes with: (pANTLR3_BASE_TREE)(psr->adaptor->nilNode(psr->adaptor));
Delete AST nodes with: parentASTnode->deleteChild(parentASTnode, nodeIndex);
[deleteChild does not free the deleted nodes]
Replace nodes with: parentASTnode->replaceChildren(parentASTnode, nStartChildIndex, nStopChildIndex, newASTnode);
[you cannot insert nodes in the middle of an AST tree level, you can only replace nodes or add to the end of the parent nodes child list]
void printTree(pANTLR3_BASE_TREE t, int indent)
{
pANTLR3_BASE_TREE child = NULL;
int children = 0;
char * tokenText = NULL;
string ind = "";
int i = 0;
if ( t != NULL )
{
children = t->getChildCount(t);
for ( i = 0; i < indent; i++ )
ind += " ";
for ( i = 0; i < children; i++ )
{
child = (pANTLR3_BASE_TREE)(t->getChild(t, i));
tokenText = (char *)child->toString(child)->chars;
fprintf(stderr, "%s%s\n", ind.c_str(), tokenText);
if (tokenText == "<EOF>")
break;
printTree(child, indent+1);
}
}
}
// Run the parser
pANTLR3_BASE_TREE langAST = (psr->start_rule(psr)).tree;
// Print the AST
printTree(langAST, 0);
// Get the Parser Errors
int nErrors = psr->pParser->rec->state->errorCount;