This practical session focused on building and testing simple grammars using ANTLR.
-
Designed a non-ambiguous context-free grammar named
Mot_Eg. -
The grammar recognizes the language:
L = { w ∈ {a, b, c}* | number of a in w = number of b in w }
-
Ensured that:
- All non-terminals are written in lowercase (ANTLR convention).
- The start rule ends with
EOF.
-
Compiled the grammar using
antlr4. -
Generated lexer and parser in Java.
-
Tested the grammar using
grun:- Token visualization with
-tokens - Parse tree visualization with
-gui
- Token visualization with
-
Verified correctness using valid and invalid words.
- Created
Calculette.g4for arithmetic expressions. - Initially supported:
- Integer literals
- Addition (+)
- Multiplication (*)
- Identified parser rules (
start,expr) and lexer rules (ENTIER,WS,NEWLINE). - Observed whitespace removal via lexer
-> skip. - Tested operator precedence behavior.
- Swapped rule order to observe precedence effects.
- Extended grammar to include:
- Subtraction
- Division
- Unary minus
- Parenthesized expressions
- Enforced correct operator precedence.
- Modified grammar so programs may contain multiple expressions separated by newline or semicolon.
- Structure of
.g4grammar files. - Difference between parser and lexer rules.
- Importance of
EOFin start rules. - Automatic generation of lexer and parser code.
- Grammar creation.
- Code generation with
antlr4. - Java compilation.
- Testing with
grun.
- Designing non-ambiguous grammars.
- Managing ambiguity and precedence.
- Understanding left recursion.
- Token definition using regular expressions.
- Use of
skipto remove irrelevant tokens. - Separation between lexical and syntactic analysis.
- Handling unary and binary operators.
- Enforcing precedence and associativity.
- Testing ambiguous vs structured grammars.
-
Install ANTLR4 and ensure
antlr4andgrunare available in the terminal. -
Generate lexer and parser files:
antlr4 Mot_Eg.g4 antlr4 Calculette.g4
-
Compile generated Java files:
javac *.java -
Test using
grun, for example:grun Calculette start -gui
or
grun Mot_Eg start -tokens
.
├── Mot_Eg.g4
├── Calculette.g4
├── *.java # Generated ANTLR files
├── *.class # Compiled Java files
└── README.md
This TP established the foundations for future work in syntax analysis, semantic processing, and code generation.