ANTLR Listeners

Learn how to build an application using the parse-tree listener mechanism.

ANTLR’s runtime library supports two types of parse-tree walking mechanisms: parse-tree listener and parse-tree visitors.

Press + to interact
Types of parse-tree walking mechanisms
Types of parse-tree walking mechanisms

In this lesson, we will learn about parse-tree listeners. ANTLR automatically generates a listener interface to handle events triggered by the parse-tree walker. These listeners function similarly to SAX document handlers used in XML parsers, where events like startDocument and endDocument are fired as the document is processed.

Parse-tree walker

ANTLR’s runtime library provides the ParseTreeWalker class for walking trees and calling listeners. As part of the language application development process, we build a ParseTreeListener implementation that uses application-specific code to interact with a larger application.

The ANTLR produces a ParseTreeListener subclass that corresponds to the grammar, with an entry and exit method for each rule.

Application implementation with parse-tree listeners

Press + to interact
Decent calculator
Decent calculator

Imagine beginning an internship in a software house and the boss assigns us a task to write a decent calculator that performs the calculations with the commands as follows:

Plus value1 value2; // value1 + value2
Minus value1 value2; // value1 - value2
Multiply value1 value2; // value1 * value2
Divide value1 value2; // value1 / value2
Modulus value1 value2; // value1 % value2

To write such a decent calculator, we first have to define a grammar that can accept the above-mentioned commands.

Before we begin, we need to define the grammar rules. Based on the specification provided by our supervisor, the grammar should include rules for operations such as plus, minus, ...