【问题标题】:Antlr4: How to identify which rule alternative was matched?Antlr4:如何识别匹配了哪个规则替代项?
【发布时间】:2021-01-15 16:21:44
【问题描述】:

我的语法如下:

node: '{' type ',' '"expression"' ':' rightSide '}' ;
rightSide:
    call         # callAlternative
    | identifier # identifierAlternative
    ;

现在在我的访问者中,我实现了 visitNode(Parser.NodeContext ctx) 方法,并希望访问 rightSide 规则的正确方法,无论匹配哪个替代。 # 标签用于为每个备选方案生成专用方法,righSide 规则不再有访问方法。同样visitNode中的ctx只有ctx.rightSide(),没有ctx.callAlternative()和/或ctx.identifierAlternative()

如何做到这一点?

@Override
public SomeObj visitNode(Parser.NodeContext ctx) {
    // how to detect which of the two alternatives was matched? ctx only has ctx.rightSide()
    // What is the something in ctx.something ?
    if(....){ // how to decide here??
        visitIdentifierAlternative(ctx.something);
    } else visitCallAlternative(ctx.something);
    return new SomeObj();
}
@Override
public SomeObj visitIdentifierAlternative(Parser.IdentifierAlternativeContext ctx) {
    // Do things only to be done for IdentifierAlternative
    return new SomeObj();
}
@Override
public SomeObj visitCallAlternative(Parser.CallAlternativeContext ctx) {
    // Do things only to be done for CallAlternative
    return new SomeObj();
}

【问题讨论】:

    标签: java parsing antlr antlr4 grammar


    【解决方案1】:

    您不会直接致电visitIdentifierAlternativevisitCallAlternative。您只需调用visit,它会自行选择合适的方法。

    【讨论】:

    • 我确实从概念的角度理解您的意思(仅实现访问者模式并使用visit() 的双重调度)。但是当涉及到实际实现时,由于 Antlr 的自动生成的类/方法,我无法让它工作。 visit(ParseTree tree) 需要一个 ParseTree 对象,但只有 Context 对象可用。这应该如何正确完成?你能为给定的语法提供一个 MVCE 吗?我已经用谷歌搜索了,但找不到任何有用的东西。
    • @avermaet 所有Context 类都继承自ParseTree。你实际上只是用visit(ctx.something); 替换你的if 语句,就是这样。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-22
    • 1970-01-01
    • 2022-12-09
    • 1970-01-01
    • 2022-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多