Stm --> Stm ";" Stm | id ":=" Exp | "print" Exp
Exp --> num | id | Exp Bop Exp
Bop --> "+" | "-" | "*" | "/"
//////////////////////////////////////////////////////////// abstract class Stm {} // Stm --> Stm ";" Stm (CmpStm) class CmpStm extends Stm { Stm stm1, stm2; CmpStm(Stm stm1, Stm stm2) { this.stm1 = stm1; this.stm2 = stm2; } } // Stm --> id "::=" Exp (AssStm) class AssStm extends Stm { String id; Exp exp; AssStm(String id, Exp exp) { this.id = id; this.exp = exp; } } // Stm --> "print" Exp (PrtStm) class PrtStm extends Stm { Exp exp; PrtStm(Exp exp) { this.exp = exp; } } //////////////////////////////////////////////////////////// abstract class Exp {} // Exp --> num (NumExp) class NumExp extends Exp { int num; NumExp(int num) { this.num = num; } } // Exp --> id (IdExp) class IdExp extends Exp { String id; IdExp(String id) { this.id = id; } } // Exp --> Exp BinOp Exp (OpExp) class OpExp extends Exp { Exp exp1, exp2; int op; OpExp(Exp exp1, int op, Exp exp2) { this.exp1 = exp1; this.op = op; this.exp2 = exp2; } } |
public void interprete(Stm stm) { if (stm instanceof CmpStm) { CmpStm cast = (CmpStm)stm; interprete(cast.stm1); interprete(cast.stm2); return; } if (stm instanceof AssStm) { AssStm cast = (AssStm)stm; int res = interprete(cast.exp); table = enter(cast.id, res, table); return; } if (stm instanceof PrtStm) { PrtStm cast = (PrtStm)stm; int res = interprete(cast.exp); System.out.println(res); return; } throw new Error("bad statement."); } public int interprete(Exp exp) { if (exp instanceof NumExp) { NumExp cast = (NumExp)exp; return cast.num; } if (exp instanceof IdExp) { IdExp cast = (IdExp)exp; return lookup(cast.id, table); } if (exp instanceof OpExp) { OpExp cast = (OpExp)exp; int res1 = interprete(cast.exp1); int res2 = interprete(cast.exp2); switch (cast.op) { case BinOp.Plus: return res1 + res2; case BinOp.Minus: return res1 - res2; case BinOp.Times: return res1 * res2; case BinOp.Div: return res1 / res2; default: throw new Error("unknown operator " + cast.op); } } throw new Error("bad expression."); } |