I'm pretty new to ANTLR and I'm trying to understand what exactly Token
is in ATNLR4. Consider the following pretty nonsensical grammar:
grammar Tst;
init: A token=('+'|'-') B;
A: .+?;
B: .+?;
ADD: '+';
SUB: '-';
ANTLR4 generates the following TstParser.InitContext
for it:
public static class InitContext extends ParserRuleContext {
public Token token; //<---------------------------- HERE
public TerminalNode A() { return getToken(TstParser.A, 0); }
public TerminalNode B() { return getToken(TstParser.B, 0); }
public InitContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_init; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof TstListener ) ((TstListener)listener).enterInit(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof TstListener ) ((TstListener)listener).exitInit(this);
}
}
Now, all lexer rules are available as static constants in the parser class:
public static final int A=1, B=2, ADD=3, SUB=4;
How can we us them to identify lexer rules? All A
, B
, and ADD
rules may match '+'
. So what type should I use when testing it.
I mean this:
TstParser.InitContext ctx;
//...
ctx.token.getType() == //What type?
//TstParse.A
//TstParse.B
//or
//TstParse.ADD?
In general, I would like to learn how ANTLR4
knows the type of a Token
?