haoxp
haoxp

Reputation: 3

ANTLR4: getFirstChildWithType with a ParseTree

I've been playing around with ANTLR4, trying to convert an ANTLR3 project.

I have generated a lexer, a parser and a visitor class from an ANLTR4 grammar coming from the official repository. In the visitor, I am calling one of my classes using the ctx available from the visitor:

myFunction(ctx.getChild(0))

Then, in myFunction, I want to retrieve the first child having a specific type, so I tried doing:

final ParseTree classNameElement =
            (ParseTree) ((GrammarAST) node).getFirstChildWithType(MyParser.IDENTIFIER);

where node is the argument of myFunction, thus a ParseTree. getFirstChildWithType seems to be available only in GrammarAST, hence the cast.

I am getting the error: cannot be cast to org.antlr.v4.tool.ast.GrammarAST

So maybe this is not possible as is and I must have missed something, but I want to find the first child having a specific type from a ParseTree.

Thank you!

Upvotes: 0

Views: 703

Answers (1)

GRosenberg
GRosenberg

Reputation: 6001

Notice that GrammarAST is in the ANTLR tool hierarchy. With a generated parse-tree, you should be dealing exclusively with the runtime.

To search a parse-tree node for a child of a given type:

public ParseTree getFirstChildOfType(ParseTree node, int tokentype) {
    for (int idx = 0; idx < node.getChildCount(); idx++) {
        ParseTree child = node.getChild(idx);
        if (child instanceof TerminalNode) {
            Token token = (Token) child.getPayload();
            if (token.getType() == tokentype) {
                return child;
            }
        }
    }
    return null;
}

This will get the first direct, i.e., child terminal, of the given type. Will need to recurse into non-TerminalNodes if the absolute first of type is desired.

If the latter is actually the desired function, there may be a better/more direct use of parse-tree walker to obtain the desired overall goal.

Upvotes: 1

Related Questions