ANTLR4:带有 ParseTree 的 getFirstChildWithType

ANTLR4: getFirstChildWithType with a ParseTree

我一直在玩 ANTLR4,试图转换一个 ANTLR3 项目。

我已经从来自官方存储库的 ANLTR4 语法生成了一个词法分析器、一个解析器和一个访问者 class。在访问者中,我使用访问者提供的 ctx 调用我的 classes 之一:

myFunction(ctx.getChild(0))

然后,在 myFunction 中,我想检索具有特定类型的第一个 child,所以我尝试这样做:

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

其中节点是 myFunction 的参数,因此是一个 ParseTree。 getFirstChildWithType 似乎仅在 GrammarAST 中可用,因此进行了转换。

我收到错误消息:无法转换为 org.antlr。v4.tool.ast.GrammarAST

所以也许这是不可能的,我一定错过了一些东西,但我想从 ParseTree 中找到第一个具有特定类型的 child。

谢谢!

注意 GrammarAST 在 ANTLR tool 层次结构中。使用生成的解析树,您应该专门处理运行时。

要在解析树节点中搜索给定类型的子节点:

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;
}

这将获得给定类型的第一个直接终端,即子终端。如果需要绝对第一个类型,则需要递归到非 TerminalNodes。

如果后者确实是想要的功能,可以better/more直接使用parse-tree walker来获得想要的总体目标。