Antlr4:如何确定匹配了哪个规则选项?

Antlr4: How to identify which rule alternative was matched?

我的语法如下:

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

现在在我的访问者中,我实现了方法 visitNode(Parser.NodeContext ctx) 并希望访问 rightSide 规则的正确方法,无论哪个匹配。 # 标签用于为每个备选方案生成专用方法,而 righSide 规则不再有访问方法。还有visitNode中的ctx只有ctx.rightSide(),没有ctx.callAlternative()and/orctx.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();
}

您不要直接调用 visitIdentifierAlternativevisitCallAlternative。您只需调用 visit,然后它将 select 自己的适当方法。