ANTLR 4 tree inject/rewrite operator

As mentioned by Sam (280Z28), ANTLR 4 does not have rewrite operators. When generating the parser, ANTLR 4 creates some listener classes that you can use to listen for “enter” and “exit” events of all parser rules. Also, ANTLR 4 supports “direct left recursive rules”, so your expression rules can be defined in a single … Read more

Handling errors in ANTLR4

Since I’ve had a little bit of a struggle with the two existing answers, I’d like to share the solution I ended up with. First of all I created my own version of an ErrorListener like Sam Harwell suggested: public class ThrowingErrorListener extends BaseErrorListener { public static final ThrowingErrorListener INSTANCE = new ThrowingErrorListener(); @Override public … Read more

Compiling sample ANTRL4 output

There was 2 problems. One was the file has to be named “Hello.g4” not “hello.g4” because the grammar is specified as Hello. The second was the classpath, it requires the path and name of the jar file, as well as the current directory. The following command worked; javac -classpath .;C:\JavaLib\antlr-4.5-complete.jar *.java

Antlr 4.5 parser error during runtime

The error message means that the expected token type containing the value ‘void’ does not match the actual token type produced by consuming the string ‘void’ from the input. Looking at your lexer rules suggests that the input string ‘void’ is being consumed by the IDENTIFIER rule, producing a token of type IDENTIFIER, not VOID. … Read more

How does the ANTLR lexer disambiguate its rules (or why does my parser produce “mismatched input” errors)?

In ANTLR, the lexer is isolated from the parser, which means it will split the text into typed tokens according to the lexer grammar rules, and the parser has no influence on this process (it cannot say “give me an INTEGER now” for instance). It produces a token stream by itself. Furthermore, the parser doesn’t … Read more

If/else statements in ANTLR using listeners

By default, ANTLR 4 generates listeners. But if you give org.antlr.v4.Tool the command line parameter -visitor, ANTLR generates visitor classes for you. These work much like listeners, but give you more control over which (sub) trees are walked/visited. This is particularly useful if you want to exclude certain (sub) trees (like else/if blocks, as in … Read more