|
|
@@ -0,0 +1,100 @@
|
|
|
+skip WHITESPACE '\s+'
|
|
|
+
|
|
|
+token OP '\+|-'
|
|
|
+token MOP '\*|/'
|
|
|
+token NUM '[0-9]+'
|
|
|
+
|
|
|
+%
|
|
|
+
|
|
|
+<start> ::= <exp>
|
|
|
+<exp> ::= <mult> <exprest>
|
|
|
+<exprest> **= <OP> <mult>
|
|
|
+<mult> ::= <value> <multrest>
|
|
|
+<multrest> **= <MOP> <value>
|
|
|
+<value> ::= <NUM>
|
|
|
+
|
|
|
+%
|
|
|
+
|
|
|
+Start
|
|
|
+%%{
|
|
|
+
|
|
|
+ public void $run() {
|
|
|
+ System.out.println(exp.calculate());
|
|
|
+ }
|
|
|
+
|
|
|
+%%}
|
|
|
+
|
|
|
+Exp
|
|
|
+%%{
|
|
|
+
|
|
|
+ public int calculate() {
|
|
|
+ int x = mult.calculate();
|
|
|
+ return exprest.calculate(x);
|
|
|
+ }
|
|
|
+
|
|
|
+%%}
|
|
|
+
|
|
|
+Exprest
|
|
|
+%%{
|
|
|
+
|
|
|
+ public int calculate(int resultSoFar) {
|
|
|
+ Iterator<Token> opIt = opList.iterator();
|
|
|
+ Iterator<Mult> multIt = multList.iterator();
|
|
|
+
|
|
|
+ while(opIt.hasNext()) {
|
|
|
+ String op = opIt.next().toString();
|
|
|
+ int n = multIt.next().calculate();
|
|
|
+
|
|
|
+ switch(op) {
|
|
|
+ case "+": resultSoFar += n; break;
|
|
|
+ case "-": resultSoFar -= n; break;
|
|
|
+ }
|
|
|
+
|
|
|
+ }
|
|
|
+
|
|
|
+ return resultSoFar;
|
|
|
+ }
|
|
|
+
|
|
|
+%%}
|
|
|
+
|
|
|
+Mult
|
|
|
+%%{
|
|
|
+
|
|
|
+ public int calculate() {
|
|
|
+ int x = value.getValue();
|
|
|
+ return multrest.calculate(x);
|
|
|
+ }
|
|
|
+
|
|
|
+%%}
|
|
|
+
|
|
|
+Multrest
|
|
|
+%%{
|
|
|
+
|
|
|
+ public int calculate(int resultSoFar) {
|
|
|
+ Iterator<Token> mopIt = mopList.iterator();
|
|
|
+ Iterator<Value> valueIt = valueList.iterator();
|
|
|
+
|
|
|
+ while(mopIt.hasNext()) {
|
|
|
+ String op = mopIt.next().toString();
|
|
|
+ int n = valueIt.next().getValue();
|
|
|
+
|
|
|
+ switch(op) {
|
|
|
+ case "*": resultSoFar *= n; break;
|
|
|
+ case "/": resultSoFar /= n; break;
|
|
|
+ }
|
|
|
+
|
|
|
+ }
|
|
|
+
|
|
|
+ return resultSoFar;
|
|
|
+ }
|
|
|
+
|
|
|
+%%}
|
|
|
+
|
|
|
+Value
|
|
|
+%%{
|
|
|
+
|
|
|
+ public int getValue() {
|
|
|
+ return Integer.parseInt(num.toString());
|
|
|
+ }
|
|
|
+
|
|
|
+%%}
|