/** Our internal representation of a BinOp * in the T0 language. * See http://www.radford.edu/itec380/2018fall-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 = START_TOKEN; public static final java.util.List OPS = java.util.Arrays.asList( "boii", "boi", "boiii" ); BinOp( Expr _left, String _op, Expr _right ) { this.left = _left; this.op = _op; this.right = _right; } 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) { assert UtilIan.nextSplittingBy(s,punctuation).equals(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 operator = UtilIan.nextSplittingBy(s,punctuation); if (!(OPS.contains(operator))) throw new InputMismatchException(String.format("Unknown operator \"%s\".",operator)); Expr righty = Expr.parse(s,punctuation); assert UtilIan.nextSplittingBy(s,punctuation).equals(STOP_TOKEN); // Consume (&verify) closing punctuation. return new BinOp(lefty, operator, 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 T's `op` w/ `l` and `r` */ static Value evalOp( String op, double l, double r ) { if (op.equals("boii")) { return new Num(l + r); } else if (op.equals("boi")) { return new Num(l - r); } else if (op.equals("boiii")) { 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 = (int)0x3141834e907b1159L; // fingerprint hashSoFar += this.left.hashCode(); hashSoFar *= 31; hashSoFar += this.op.hashCode(); hashSoFar *= 31; hashSoFar += this.right.hashCode(); cachedHash = hashSoFar; } return cachedHash; } private Integer cachedHash = null; }