00001: import java.util.List;
00002: import java.util.HashMap;
00003: import java.util.Map;
00004: 
00005: 
00006: public class Interpreter
00007: {
00008:   public Map<String, Integer> evaluateDecls (List<Decl> decls)
00009:   {
00010:     Map<String, Integer> bindings = new HashMap<String, Integer> ();
00011:     
00012:     for (Decl decl : decls) {
00013:       int value = evaluateExp (bindings, decl.exp);
00014:       bindings.put (decl.var, new Integer (value));
00015:     }
00016:     
00017:     return bindings;
00018:   }
00019: 
00020: 
00021:   int evaluateExp (Map<String, Integer> bindings, Exp exp) 
00022:   {
00023:     if (exp instanceof ExpInt) {
00024:       ExpInt expI = (ExpInt) exp;
00025:       return expI.value;
00026: 
00027:     } else if (exp instanceof ExpVar) {
00028:       ExpVar expV = (ExpVar) exp;
00029:       Integer value = bindings.get (expV.var);
00030:       if (value == null) {
00031:         throw new RuntimeException ("Variable " + expV.var + " not defined");
00032:       } else {
00033:         return value.intValue ();
00034:       }
00035: 
00036:     } else if (exp instanceof ExpBinOp) {
00037:       ExpBinOp expB = (ExpBinOp) exp;
00038:       int left = evaluateExp (bindings, expB.left);
00039:       int right = evaluateExp (bindings, expB.right);
00040:       if (expB.op.equals (ExpBinOp.BinOp.PLUS)) {
00041:         return left+right;
00042:       } else if (expB.op.equals (ExpBinOp.BinOp.MINUS)) {
00043:         return left-right;
00044:       } else if (expB.op.equals (ExpBinOp.BinOp.TIMES)) {
00045:         return left*right;
00046:       } else if (expB.op.equals (ExpBinOp.BinOp.DIVIDE)) {
00047:         return left/right;
00048:       } else {
00049:         throw new RuntimeException ("Missing case for BinOp " + expB.op);
00050:       }
00051: 
00052:     } else {
00053:       throw new RuntimeException ("Missing case for Exp " + exp);
00054:     }
00055:   }
00056: }
00057: