Question

I have a grammer rule that is:

 type_specifier:INT | VOID

and INT and void are 2 regular expressions for lexical analysis that are:

 INT:'int';
 VOID:'void';

also I have another rule in my grammar that is:

 var_declaration:type_specifier ID SEMIC

I want to get type_specifier kind(int or void) after I reach this rule how can I get it in antlr?

Was it helpful?

Solution

Enable generating an AST which will allow to walk the tree (which is by default actually just a list) to get type and text of each found token. To do this set the output type in your grammar options:

options {
  ...
  output = AST;
  ...
}

In your code you can then use the runtime to ask for subnodes in the returned tree, their text and type etc. Details depend on your target language, but the principles are the same for all languages.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top