Texas Christian University
COSC 30403 Spring 2025
Project 1 Part A
Due: Feb 4th, Tuesday, at 11:30 PM
Submission: EasyCalc.g4 through TCU Online
Create an ANTLR4 grammar for an easy calculator language based on the following
specifications.
program --> declaration* statement* $$
declaration --> bool identifier ; | int identifier ; | real
identifier ;
statement --> identifier := expression ; | read identifier ; |
write expression ;
expression --> expression operator expression | identifier |
literal | ( expression ) | to_int ( expression ) | to_real
( expression ) | if expression then expression else expression
operator --> * | / | + | - | and | or | < | > | ==
literal --> real_number | int_number | true | false
Use precedence from C language to get the precedence of the operators. See Figure 6.1 on Page
228 of the textbook.
An identifier starts with a letter and can contain letters, numbers, and underscores. An integer
number is one or more digits. A real number contains a dot and at least one digit.
The ANTLR4 grammar should be called EasyCalc.g4 and should be in a package called
easycalc.grammar.
A printer file ParserApp.java is provided. This file should be in the package easycalc,
and is used to test whether your created grammar is correct or not. There is NO need to include
ParserApp.java in your submission.
Here are the test cases you can use to test your results. Note that you should also check whether
the parsing follows correct operator precedence.
Test 1 (should NOT parse)
int a;
a := 2 + 3;
bool b;
$$
Test 2 (should parse)
int a;
bool b;
a := 2 + 3;
b := false;
$$
Test 3 (should parse)
a := ((2 + 3));
$$
Test 4 (should parse)
a := if true then 2 else 4;
$$
Test 5 (should parse)
bool a;
int b;
real c;
$$
Test 6 (should parse)
a := 2 + 3;
read a;
write 2 + 3;
$$
Test 7 (should NOT parse)
read 2 + 3;
$$
Test 8 (should parse)
a := 2 + 3 - 4 * 5 / 2 > b and c > d;
$$
Test 9 (should NOT parse)
if true then 2 else 4;
$$
Test 10 (should NOT parse)
a := (b + ( c - d );
$$