次のコードは、AST をウォークし、すべての AST ノードを stderr に出力します。同じツリー ウォーカーが、ツリー ノードを置き換えることができるツリー トランスフォーマーの基礎となります。
新しいツリー ノードを割り当てます: (pANTLR3_BASE_TREE)(psr->adaptor->nilNode(psr->adaptor));
次の方法で AST ノードを削除します。parentASTnode->deleteChild(parentASTnode, nodeIndex); [deleteChild は削除されたノードを解放しません]
ノードを次のように置き換えます。parentASTnode->replaceChildren(parentASTnode, nStartChildIndex, nStopChildIndex, newASTnode); [ASTツリーレベルの途中にノードを挿入することはできません。ノードを置き換えるか、親ノードの子リストの最後に追加することしかできません]
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;