Installing ANTLR

You need to have Java installed on your system (e.g., in Ubuntu: sudo apt install openjdk-21-jdk).

Example run of ANTLR

Let us go through an example step by step. We assume a UNIX-like command-line and that the file antlr-4.13.2-complete.jar is located in directory ~/ANTLR/. Everything below assumes that ~/ANTLR is the working directory (no CLASSPATH variable is set, and only minimal -cp options are passed to javac and java).

In the working directory we have three files:

% ls 
antlr-4.13.2-complete.jar
SimpleExample.g4  
helloworld.greeting

The first file is the ANTLR jar file. The second file, SimpleExample.g4, written in ANTLR syntax that we will understand later, describes the language to be lexed/parsed, in this case a trivial language that describes a greeting of the form “Hello name!”:

grammar SimpleExample;

greeting: Hello Name Bang ;

// TOKENS
Hello:	'Hello' ;
Bang:	'!' ;
Name:   [A-Z][a-z]* ;

WS : [ \t\r\n]+ -> skip ; // skip spaces, tabs, newlines

There is some “parsing” stuff in the file above (like the grammar statement), because in ANTLR we can’t just generate a lexer without also a parser. But for the lexer, what we care about for now is just what’s bellow the “// TOKENS” comment.

The third file is “source code” written using the above language, with the following content:

Hello World !

We can now run ANTLR to generate the code of our lexer/parser by typing the following command:

% java -jar ./antlr-4.13.2-complete.jar SimpleExample.g4

The above command produces a bunch of files, including .java files. These java files we can now compile with:

% javac -cp antlr-4.13.2-complete.jar SimpleExample*.java

We can now finally run our lexer/parser on the source code (don’t forget the “.:” in the classpath!)

% java -cp .:antlr-4.13.2-complete.jar org.antlr.v4.gui.TestRig SimpleExample greeting helloworld.greeting -tokens
[@0,0:4='Hello',<1>,1:0]
[@1,6:10='World',<3>,1:6]
[@2,12:12='!',<2>,1:12]
[@3,14:13='<EOF>',<-1>,2:0]
(greeting Hello World !)

In the above we asked ANTLR to print the set of tokens. We’ll do much more, but you can already try to modify helloworld.greeting and create lexing errors! For instance, if you add a ‘+’ at the end of the line, you should get some “token recognition error”.

Even if you don’t quite understand the above, make sure you can get it to work as described.