David
David

Reputation: 6162

How can I determine which alternative node was chosen in ANTLR

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

Upvotes: 8

Views: 2836

Answers (1)

GRosenberg
GRosenberg

Reputation: 6001

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:
     ...

Upvotes: 12

Related Questions