以下代码将遍历 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;