Evaluator

The evaluator implements the semantics defined by the function eval: Expr * V -> Z, where V = Id -> Z is the set of all variable valuations to the set Z set of integers. eval is inductively defined as follows:

eval(e1 "+" e2, v) = eval(e1, v) + eval(e2, v)
eval(e1 "-" e2, v) = eval(e1, v) − eval(e2, v)
eval(x, v) = v(x)
eval(z, v) = z

with

  • expressions e, e1, e2,
  • a variable valuation v,
  • and identifier x and
  • an integer z.
------------------Show Header Code ( lines)------------------
package interpreter;

import expression.*;

import java.util.HashMap;
import java.util.Map;
1

The Evaluator implements the evaluation function defined above with the help of the Visitor. The Evaluator takes an Expression in the constructor and provides a method eval() which evaluates the given expression and returns the result as an integer. For a given expression of type Expression it can be used as follows

Evaluator evaluator = new Evaluator(expression, valuation)
System.out.println(evaluator.getValue());

The evaluation function eval takes the variable valuation v, which is passed on recursively. As the valuation is not changed during the evaluation process, it can be stored in a global variable which is not changed.

public class Evaluator extends Visitor<Integer> {
    private final int value;
    private final Map<String, Integer> valuation = new HashMap<String, Integer>();

    public Evaluator(Expression expression, Map<String, Integer> valuation) {
        this.valuation.putAll(valuation);
        value = visit(expression);
    }

    public int getValue() {
        return value;
    }
2
eval(e1 "+" e2, v) = eval(e1, v) + eval(e2, v)
    public Integer visitAddition(Addition addition) {
        return visit(addition.leftHandSide) + visit(addition.rightHandSide);
    }
3
eval(e1 "-" e2, v) = eval(e1, v) - eval(e2, v)
    public Integer visitSubtraction(Subtraction subtraction) {
        return visit(subtraction.leftHandSide) - visit(subtraction.rightHandSide);
    }
4
eval(x, v) = v(x)
    public Integer visitInt(Int integer) {
        return integer.value;
    }

    public Integer visitIdentifier(Identifier identifier) {
5

Make sure that the identifier actually exists in the valuation and raise an exception otherwise.

        if (valuation.containsKey(identifier.name)) {
6
eval(z, v) = z
            return valuation.get(identifier.name);
        } else {
            throw new InterpreterException("Identifier " + identifier.name + " not found.");
        }
    }
}