Compiler Design: ANTLR, Tool For Language Recognition

Why do we need to design compiler? We can get things done using machine language but then it is very tedious and error prone programming. Instead languages were developed which use syntax much like our daily spoken language,called high-level programming language. But again this needs to be converted into machine language . That’s where compiler comes.Helping us translate our English-like program to Computer-understandable one.

The compiling process is divided into phases and in initial phases, we need to check if given statement is grammatically is correct or not. ANTLR (ANother Tool for Language Recognition) is a tool which reads a grammar and generates a recognizer for the language defined by the grammar. For example, you can define grammar for arithmetic expressions and it will check given input expression can be defined by given grammar or not.

Know more about Basics of Compiler Design here.


Installing ANTLR in Ubuntu

Execute following commands in terminal:

$sudo bash
#cd /usr/local/lib
#export CLASSPATH=".:/usr/local/lib/antlr-4.5 complete.jar:$CLASSPATH"
#alias antlr4='java -jar /usr/local/lib/antlr-4.5-complete.jar'
#alias grun='java org.antlr.v4.runtime.misc.TestRig'

Now the aliases created are temporary and will evaporate as soon as you log out. To make them permanent you need to edit .bashrc file located in your home folder.

Execute following commands or just add those two lines in the file.

$cd ~/
$echo "alias antlr4='java -jar /usr/local/lib/antlr-4.5-complete.jar'" >> .bashrc
$echo "alias grun='java org.antlr.v4.runtime.misc.TestRig'" >> .bashrc
$echo 'export CLASSPATH=".:/usr/local/lib/antlr-4.5-complete.jar:$CLASSPATH"export CLASSPATH=".:/usr/local/lib/antlr-4.5-complete.jar:$CLASSPATH"' >> .bashrc

And you are done. Type antlr4 in terminal and you will see this.




Presuming that you have JDK-JRE installed, you’re all set to run an example code.(If you don’t have it installed follow this guide).

Now make a file named Expr.g4 containing this.

grammar Expr;     
prog:   (expr NEWLINE)* ;
expr:   expr ('*'|'/') expr
    |   expr ('+'|'-') expr
    |   INT
    |   '(' expr ')'
NEWLINE : [\r\n]+ ;
INT     : [0-9]+ ;

Execute following commands and press CTRL+D twice in the end.

$ antlr4 Expr.g4
$ javac Expr*.java
$ grun Expr prog -gui

You’ll see parse tree generated for given input



For other distributions of Linux, the process will remain almost same except the installing java part and downloading jar file (wget command).

Discover more about ANTLR in this Book or it’s official Documentation.



Leave a Reply