ParseTree traversal in antlr4

antlr, antlr4, c++

Solution

The differentiation between a `ParseTree` and a `Tree` is purely artificial and in fact of no real use. The children of a tree node are in fact all `ParseTree` instances. There are a few tree classes that are never used in the runtime, except for building the base classes of `ParseTree`. Hence later on I have removed `Tree`, `SyntaxTree` and `RuleNode` and put all that together into the ParseTree class.

To answer your question: you can safely cast the child nodes to `ParseTree` for your tree walk.

Problem

I am using antlr4 c++. I have a `ParseTree` and I am trying to recreate the tree structure. To to this I am using a Visitor `my_Visitor` and my own node object(s). My problem is that `visitChildren(tree::RuleNode*)` calls the visit functions of all children, so I am losing the information when one child tree is traversed and the next child tree is visited. Assume a tree like this: ``` A / \ B C ``` When I call `visitChildren(A)` (using overloaded `visitExpression(ExpressionContext*)` functions for B and C), I can extract the information that the visit sequence is A,B,C. This sequence could also result from: ``` A | B | C ``` To recreate the tree I think I would need something like ``` antlrcpp::Any my_Visitor::my_visitChildren(tree::RuleNode* A){ for(int i=0;i<A->children.size();i++){ //create a new node in my own tree representation as child of A visit(A->children[i]); } } ``` and call `my_visitChildren` in my overloaded `visitExpression` functions. The problem here is that `A->children[i]` is a `Tree` and `visit(.)` needs a `ParseTree`. Can I somehow create a `ParseTree` from `children[i]` or is there a better approach to do this? I am also thinking about using a map from `tree->parent` to my objects and just attach my new node there, but this is not optimal if I wanted to omit some nodes (e.g. for an AST).

Original source