antlrantlr4

How to get the corresponding TerminalNode of a token?


export class TestContext extends ParserRuleContext {
    public _id1!: Token;
    public _id2!: Token;
    public ID(): TerminalNode[];
}

I use "labeled rule element" in my ANTLR4 grammar file:

(id1 = ID) "::" (id2 = ID)

How can I get the corresponding "ID" TerminalNode with token "_id1" or "_id2"?

I use "ctx._id1" to get the token, I want to get the corresponding "ID" TerminalNode with this token.


Solution

  • In your particular situation, the grammar rule will successfully match only expressions of the form id1::id2. Therefore, you already know that calling ID() will return a TerminalNode array with precisely two values: the first one, ID()[0] is the TerminalNode corresponding to _id1 and ID()[1] is the TerminalNode corresponding to _id2.