This practical session focused on extending ANTLR grammars to support boolean expressions and generating executable behavior through grammar decoration.
- Implemented a grammar named
Expr_Boolto parse boolean expressions. - Supported operators:
not(highest precedence)andor(lowest precedence)
- Added support for parenthesized expressions.
- Ensured correct operator precedence: not > and > or.
- Tested the grammar using multiple valid boolean expressions.
- Modified the grammar so that a program can contain:
- Multiple boolean expressions
- Expressions separated by newline and/or semicolon.
-
Used the teacher-provided grammar:
S → true | false | not S | and S S | or S S
-
Decorated
Expr_Boolso each expression produces an equivalent word in the language generated by grammar G. -
Ensured programs with multiple expressions output transformed expressions line by line.
-
Built an attributed grammar
Eval_Gto simulate evaluation of expressions generated in grammar G. -
Computed the boolean value of each expression.
-
Modified output format to print results as:
valeur_expr_N = v
where:
- N is the line number
- v is the computed boolean value.
-
Enabled the compiler to act as a simulator executing boolean programs.
- Using grammar decoration to generate equivalent expressions.
- Linking parsing with evaluation behavior.
- Producing executable outputs from parsed structures.
- Managing operator precedence in grammars.
- Handling unary and binary logical operators.
- Parsing nested expressions using parentheses.
- Using attributes to propagate computed values.
- Decorating grammar rules to compute semantic results.
- Combining syntax analysis and semantic evaluation.
- Supporting multiple expressions within one program.
- Managing line-based execution outputs.
- Using grammars as interpreters for expression evaluation.
- Building simple execution simulators from parsers.
-
Install ANTLR4 and ensure
antlr4andgrunare available in the terminal. -
Generate lexer and parser files:
antlr4 Expr_Bool.g4 antlr4 G_Expr_Bool.g4 antlr4 Eval_G.g4
-
Compile generated Java files:
javac *.java -
Run evaluation or parsing tests using:
grun Expr_Bool start -gui
or
grun Eval_G start
.
├── Expr_Bool.g4
├── G_Expr_Bool.g4
├── Eval_G.g4
├── *.java # Generated ANTLR files
├── *.class # Compiled Java files
└── README.md
This TP reinforced the transition from grammar construction to semantic evaluation and demonstrated how parsers can be extended into executable simulators.