Compiler Lab Antlr
Compiler Lab Antlr
$ cd /usr/local/lib
$ sudo curl -O https://www.antlr.org/download/antlr-4.13.1-complete.jar
$ java org.antlr.v4.Tool
ANTLR Parser Generator Version 4.13.1
-o ___ specify output directory where all output is generated
-lib ___ specify location of .tokens files
Two grammars
Two grammars
1. Lexer Grammar
2. Parser Grammar
Let's create our first parser
Let's create a lexer and parser grammar for input that consists of a greeting ('Hello' or 'Greetings')
followed by the name of a person. Here are two valid input strings:
Hello Maitri
Greetings Maitri
The lexer grammar describes how to break the input into two tokens:
(1) The greeting (Hello or Greetings), and
(2) The name of the person.
The parser grammar describes how to structure the tokens as shown by the below graphic (the
input is: Hello Maitri):
The lexer grammar
options { tokenVocab=MyLexer; } This parser will use the tokens generated by MyLexer
message : GREETING ID; If the input is valid, it must contain a token of type GREETING
followed by a token of type ID.
MyParser.g4
(Note: ^D means control-D and indicates "end of input" on Unix; use ^Z on Windows.)
Here's how to get the tokens and trace through the parse:
$ antlr4-parse Expr.g4 prog -tokens -trace
10+20*30
^D
[@0,0:1='10',<INT>,1:0]
[@1,2:2='+',<'+'>,1:2]
…..
enter prog, LT(1)=10
enter expr, LT(1)=10
consume [@0,0:1='10',<8>,1:0] rule expr
enter expr, LT(1)=+
…..