How to get AltNumber in ANTLR?

I am going to use ANTLR 4.5.3 to translate one notation to another. I already developed a grammar description using the plugin in IntelliJ IDEA.

In my grammar, one rule has several alternatives.

When I look at the results in the "Parsing Tree", each node consists of a "rule name": "line number".

How to get this information using the API? If I understand this clearly, the line number can be obtained from getAltNumber (), but this field is empty.

http://www.antlr.org/api/Java/org/antlr/v4/runtime/RuleContext.html#getAltNumber ()

The docs say that the default implementation does not compute and does not store this alt number.

How to get this information?

+4
source share
1 answer

I had exactly the same problem. The documentation should be a little more accurate, but it actually gives the key. Also looking directly at the plugin can lead to a solution: https://github.com/antlr/intellij-plugin-v4/blob/master/src/java/org/antlr/intellij/plugin/preview/AltLabelTextProvider.java

You can simply add a class superclass that implements setAltNumber and getAltNumber, as in the example: https://github.com/antlr/antlr4/blob/master/tool/src/org/antlr/v4/tool/GrammarInterpreterRuleContext.java

Then specify the class as a generator parameter, for example:

antlr4 -o output / path -listener -visitor -DcontextSuperclass = GrammarInterpreterRuleContext -Dlanguage = Java -lib lib / path grammar.g4

+1
source

Source: https://habr.com/ru/post/1654849/


All Articles