avermaet
avermaet

Reputation: 1593

Antlr4: How to identify which rule alternative was matched?

I have a grammar like the following:

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

Now in my visitor, I implement the method visitNode(Parser.NodeContext ctx) and want to visit the correct method for the rightSide rule, whichever alternative is matched. The # labels are used to generate a dedicated method for each alternative and the righSide rule does not have a visit-method anymore. Also the ctx in visitNode only has ctx.rightSide(), no ctx.callAlternative() and/or ctx.identifierAlternative().

How can this be done?

@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();
}

Upvotes: 0

Views: 696

Answers (1)

sepp2k
sepp2k

Reputation: 370162

You don't call visitIdentifierAlternative or visitCallAlternative directly. You just call visit, which will then select the appropriate method on its own.

Upvotes: 2

Related Questions