Parser to Java Program Integration
Learn how an ANTLR-generated parser can be integrated with a Java program.
Now that we have learned about ANTLR grammar, parse trees, and parsers and used the ANTLR tool to generate parsers and lexers from various grammars, we still haven’t developed a full application, as we lack a main program. This lesson focuses on how to integrate the parsers generated by ANTLR into a Java program. Before beginning the integration, we will examine the contents of ANTLR’s JAR file.
ANTLR tool and parse-time API
The ANTLR JAR has two components: the ANTLR tool and ANTLR’s parse-time API. The ANTLR tool generates the lexer and parser for recognizing the sentences in a language described by the grammar. The parse-time API has the classes and methods required by that parser and lexer.
Let’s explore the files generated by ANTLR in more detail.
First, we will run the ANTLR tool on the given terminal below, and apply it to grammar, for example, ABC.g4
using the following steps:
Press “Click to Connect” in the terminal. Wait until a connection is established.
Write
antlr4 ABC.g4
and press the “Enter” key to compile theABC.g4
file.Write
ls
and press the “Enter” key to see the list of ANTLR-generated files.
Now we can see that the ANTLR tool has generated the following files:
ABCParser.java
The following parser class definition for grammar ABC is contained in this file. It also has a different method for each rule in the grammar:
public class ABCParser extends Parser {...}
ABCLexer.java
It contains a lexer class definition that tokenizes the input:
public class ABCLexer extends Lexer {...}
...