skip WHITESPACE '\s+' token NUM '[0-9]+' token VAR '[A-Za-z_][A-Za-z0-9_]*' token OP '\+|-' token MOP '\*|/' token IN '==>' token OUT '<==' token ASSIGN '->' token SEMI ';' % ::= **= InputStmt ::= OutputStmt ::= AssignStmt ::= ::= **= ::= **= NUMValue ::= VARValue ::= % Program:import %%% import java.util.*; %%% Program %%% public static Map hshmap = new HashMap<>(); public static Scanner scanner = new Scanner(System.in); public void $run() { stmtlist.execute(); } %%% Stmtlist %%% public void execute() { for (Stmt s : stmtList) s.execute(); } %%% Stmt %%% abstract public void execute(); %%% InputStmt %%% public void execute() { System.out.print("? "); Program.hshmap.put(var.toString(), Program.scanner.nextInt()); } %%% OutputStmt %%% public void execute() { System.out.println(exp.compute()); } %%% AssignStmt %%% public void execute() { Program.hshmap.put(var.toString(), exp.compute()); } %%% Exp %%% public int compute() { int v = mult.compute(); for (int i = 0; i < exprest.opList.size(); i++) v += exprest.opList.get(i).toString().equals("+") ? exprest.multList.get(i).compute() : -exprest.multList.get(i).compute(); return v; } %%% Mult %%% public int compute() { int v = value.compute(); for (int i = 0; i < multrest.mopList.size(); i++) v = multrest.mopList.get(i).toString().equals("*") ? v * multrest.valueList.get(i).compute() : v / multrest.valueList.get(i).compute(); return v; } %%% Value %%% abstract public int compute(); %%% NUMValue %%% public int compute() { return Integer.parseInt(num.toString()); } %%% VARValue %%% public int compute() { if (!Program.hshmap.containsKey(var.toString())) throw new RuntimeException("Undefined variable: " + var); return Program.hshmap.get(var.toString()); } %%%