Question: Create an ANTLR 4 grammar for an easy calculator language based on the following specifications. program - - > declaration * statement * $$ declaration

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. 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. A printer file ParserApp. java is provided. This file should be in the and is used to test whether your created grammar is correct or not. 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*52>b and c>d;
$$
import java.util.*;
import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.tree.*;
import easycalc.grammar.*;
public class ParserApp {
public static void main(String[] args){
// Read in multiple lines of input//
StringBuilder sb = new StringBuilder();
Scanner scan = new Scanner(System.in);
String nextLine = scan.nextLine();
while (!nextLine.contains("$$")){
sb.append (nextLine);
scan = new Scanner(System.in);
nextLine = scan.nextLine();
}
scan.close();
sb.append(nextLine);
String str = sb.toString();
//Create the parse tree from the input
CharStream input = CharStreams.fromString(str);
EasyCalcLexer lexer = new EasyCalcLexer(input);
CommonTokenStream tokens = new CommonTokenStream(lexer);
EasyCalcParser parser = new EasyCalcParser(tokens);
ParseTree tree = parser.program(); //begin parsing at program rule
//Print out the LISP-style tree
System.out.println(tree.toStringTree(parser));
}
}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!