| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114 |
- 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 ';'
- %
- <program> ::= <stmtlist>
- <stmtlist> **= <stmt>
- <stmt>InputStmt ::= <IN> <VAR> <SEMI>
- <stmt>OutputStmt ::= <OUT> <exp> <SEMI>
- <stmt>AssignStmt ::= <VAR> <ASSIGN> <exp> <SEMI>
- <exp> ::= <mult> <exprest>
- <exprest> **= <OP> <mult>
- <mult> ::= <value> <multrest>
- <multrest> **= <MOP> <value>
- <value>NUMValue ::= <NUM>
- <value>VARValue ::= <VAR>
- %
- Program:import
- %%%
- import java.util.*;
- %%%
- Program
- %%%
- public static Map<String, Integer> 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());
- }
- %%%
|