DEV Community

Discussion on: Explain ANTLR like I'm five

rrampage profile image
Raunak Ramakrishnan • Edited on

tl;dr : ANTLR is a tool for generating parsers for any formally specified language.


What is a grammar

Programming languages have a grammar which tells us about the terms in the programming language. For example, java has expressions, variables, classes, methods, operators, lambdas. A grammar for Java will tell us how these various terms combine, what is expressible using these terms. e.g int i = 3.4; is not expressible in Java's grammar.

What is a parser

A parser is a tool for converting text i.e code into a form that allows a compiler to understand what the terms mean. e.g int i = 4; will be converted by a parser into a form like Assignment(Variable(name: i, type: int), Value(4)). Notice that this looks like a tree. It is called an Abstract Syntax Tree (AST) and is a intermediate form which is easier for the compiler or interpreter to make use of.

Why do we need grammars?

It is for telling the parser how to convert the text which is written in a way that the computer can understand (AST). You can write a parser in many ways. Many compilers use hand written parsers for performance.

What does ANTLR do and how does it help?

ANTLR is a tool for generating parsers for your own custom languages easily. All you need for generating a parser using ANTLR is a grammar file. ANTLR will convert the grammar file into generated Java classes which do the parsing. ANTLR follows the Visitor pattern which means you can then add custom behavior for each of the keywords in your language.

Here is an example ANTLR grammar for a scientific calculator : calculator.g4


In general, if you are creating a domain specific language, it is nice to formally specify the grammar. And if you have the grammar, ANTLR makes it very easy to generate a custom parser without any extra code.

There is a lot more discussion we can have on the parsing algorithm that ANTLR uses (LL*) and when to use/not use ANTLR.

vesusaso profile image
Sourab Author

Thanks Raunak.