Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I determine which alternative node was chosen in ANTLR

Tags:

java

antlr4

Suppose I have the following:

variableDeclaration: Identifier COLON Type SEMICOLON;
Type: T_INTEGER | T_CHAR | T_STRING | T_DOUBLE | T_BOOLEAN;

where those T_ names are just defined as "integer", "char" etc.

Now suppose I'm in the exitVariableDeclaration method of a test program called LittleLanguage. I can refer to LittleLanguageLexer.T_INTEGER (etc.) but I can't see how determine which of these types was found through the context.

I had thought it would be context.Type().getSymbol().getType() but that doesn't return the right value. I know that I COULD use context.Type().getText() but I really don't want to be doing string comparisons.

What am I missing?

Thanks

like image 503
David Avatar asked Oct 18 '15 13:10

David


1 Answers

You are loosing information in the lexer by combining the tokens prematurely. Better to combine in a parser rule:

variableDeclaration: Identifier COLON type SEMICOLON;
type: T_INTEGER | T_CHAR | T_STRING | T_DOUBLE | T_BOOLEAN;

Now, type is a TerminalNode whose underlying token instance has a unique type:

variableDeclarationContext ctx = .... ;
TerminalNode typeNode = (TerminalNode) ctx.type().getChild(0);

switch(typeNode.getSymbol().getType()) {
  case YourLexer.T_INTEGER:
     ...
like image 199
GRosenberg Avatar answered Oct 19 '22 01:10

GRosenberg