/** Our internal representation of a BinOp * in the X0 language. * See http://www.radford.edu/itec380/2019spring-ibarland/Homeworks/Project/ * * @author Ian Barland * @version 2018.Nov.16 */ import java.util.*; public class BinOp extends Expr { Expr left, right; String op; static final String START_TOKEN = "~"; static final String STOP_TOKEN = "!"; public static final List OPS = Arrays.asList( "add", "sub", "mlt" ); BinOp( Expr _left, String _op, Expr _right ) { this.op = _op; this.left = _left; this.right = _right; } @Override public String toString( /* BinOp this */) { return START_TOKEN + this.left.toString() + " " + this.op + " " + this.right.toString() + STOP_TOKEN ; } public static BinOp parse(java.util.Scanner s, String punctuation) { UtilIan.verifyToken( UtilIan.nextSplittingBy(s,punctuation), START_TOKEN); // Consume (&verify) opening punctuation. Expr lefty = Expr.parse(s,punctuation); // NOTE: recur with `Expr.parse` -- not `parse` = `BinOp.parse` which is NOT what we want! String op = UtilIan.nextSplittingBy(s,punctuation); if (!(OPS.contains(op))) throw new InputMismatchException(String.format("Unknown operator \"%s\".",op)); Expr righty = Expr.parse(s,punctuation); UtilIan.verifyToken( UtilIan.nextSplittingBy(s,punctuation), STOP_TOKEN); // Consume (&verify) closing punctuation. return new BinOp(lefty, op, righty ); } public Value eval( /* BinOp this */) { String theOp = this.op; double leftVal = ((Num)(this.left .eval())).doubleValue(); double rightVal = ((Num)(this.right.eval())).doubleValue(); return evalOp( theOp, leftVal, rightVal ); } /** Evaluate U's `op` w/ `l` and `r` */ static Value evalOp( String op, double l, double r ) { if (op.equals("add")) { return new Num(l + r); } else if (op.equals("sub")) { return new Num(l - r); } else if (op.equals("mlt")) { return new Num(l * r); } else { throw new RuntimeException("BinOp.eval(): unknown binary operator `" + op + "`"); } } @Override public boolean equals( /* BinOp this, */ Object that) { if (this==that) { return true; } else if (that==null) { return false; } else if (this.getClass() != that.getClass()) { return false; } else { BinOp thatt = (BinOp) that; return this.left.equals(thatt.left) && this.op.equals(thatt.op) && this.right.equals(thatt.right); } } @Override public int hashCode() { if (cachedHash == null) { int hashSoFar = 0; hashSoFar += this.left.hashCode(); hashSoFar *= 31; hashSoFar += this.op.hashCode(); hashSoFar *= 31; hashSoFar += this.right.hashCode(); cachedHash = hashSoFar; } return cachedHash; } private Integer cachedHash = null; }