Question: grammar EasyCalc; program : declar * stmt * ' $$ ' ; declar : type = ( ' bool ' | 'int' | 'real' )
grammar EasyCalc;
program : declar stmt$$;
declar : typebool 'int' 'real' ID ;;
stmt : ID : expr ; # AssignStmt
'read' ID ; # ReadStmt
'write' expr ; # WriteStmt
;
expr : LIT # LitExpr
ID # IdExpr
expr # ParenExpr
optoint'toreal' expr # ToExpr
expr op expr # MulDivExpr
expr op expr # AddSubExpr
expr op expr # LessGrtrExpr
expr op expr # EqualExpr
expr op'and' expr # AndExpr
expr opor expr # OrExpr
if expr 'then' expr 'else' expr # IfExpr
;
DSTOP : $$;
SSTOP : ;;
BOOL : 'bool';
INT : 'int';
REAL : 'real';
ASSIGN : :;
READ : 'read';
WRITE : 'write';
LPAREN : ;
RRAPEN : ;
TINT : toint';
TREAL : toreal';
MUL : ;
DIV : ;
ADD : ;
SUB : ;
LESS : ;
GRTR : ;
EQUAL : ;
AND : 'and';
OR : or;
IF : if;
THEN : 'then';
ELSE : 'else';
LIT : 'true' false;
ID : azAZazAZ;
WS : tr
skip;
package easycalc;
import java.util.;
import org.antlr.vruntime.;
import org.antlr.vruntime.tree.;
import easycalc.grammar.;
public class PrettyPrinterApp
public static void mainString args
Read in multiple lines of input
StringBuilder sb new StringBuilder;
Scanner scan new ScannerSystemin;
String nextLine scan.nextLine;
while nextLine.contains$$
sbappendnextLine;
scan new ScannerSystemin;
nextLine scan.nextLine;
scan.close;
sbappendnextLine;
String str sbtoString;
Create the parse tree from the input stream
CharStream input CharStreams.fromStringstr;
EasyCalcLexer lexer new EasyCalcLexerinput;
CommonTokenStream tokens new CommonTokenStreamlexer;
EasyCalcParser parser new EasyCalcParsertokens;
ParseTree tree parser.program; begin parsing at program rule
Walk the tree with the prettyprint listener
ParseTreeWalker walker new ParseTreeWalker; create standard walker
PrettyPrinterListener printer new PrettyPrinterListener;
walker.walkprinter tree; initiate walk of tree with listener
System.out.printlnprintergetProgramString; pretty print program
package easycalc;
import easycalc.grammar.EasyCalcBaseListener;
import easycalc.grammar.;
import java.util.Scanner;
public class PrettyPrinterListener extends EasyCalcBaseListener
Read in Multiple lines of input
private final StringBuilder sb new StringBuilder;
public String getProgramString
return sbtoString;
public void exitDeclarEasyCalcParserDeclarContext ctx
sbappendctxtype.getTextappendappendctxIDgetTextappend;
;
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
