001package org.clafer.ir;
002
003import org.clafer.common.Check;
004import org.clafer.domain.Domain;
005
006/**
007 * Multiplication or division of decimals scaled by {@code one}, rounded half
008 * away from zero: {@code round(left * right / one)} or
009 * {@code round(left * one / right)}.
010 *
011 * @author MichaƂ Antkiewicz
012 */
013public class IrDecimalArithm extends IrAbstractInt {
014
015    private final Op op;
016    private final IrIntExpr left, right;
017    private final int one;
018    /**
019     * The range of decimals, which limits the domain like the intRange of
020     * {@link IrMul}, and is kept for rewriting.
021     */
022    private final Domain decimalRange;
023
024    IrDecimalArithm(Op op, IrIntExpr left, IrIntExpr right, int one, Domain decimalRange, Domain domain) {
025        super(domain);
026        this.op = Check.notNull(op);
027        this.left = Check.notNull(left);
028        this.right = Check.notNull(right);
029        this.one = one;
030        this.decimalRange = Check.notNull(decimalRange);
031    }
032
033    public Op getOp() {
034        return op;
035    }
036
037    public IrIntExpr getLeft() {
038        return left;
039    }
040
041    public IrIntExpr getRight() {
042        return right;
043    }
044
045    public int getOne() {
046        return one;
047    }
048
049    public Domain getDecimalRange() {
050        return decimalRange;
051    }
052
053    @Override
054    public <A, B> B accept(IrIntExprVisitor<A, B> visitor, A a) {
055        return visitor.visit(this, a);
056    }
057
058    @Override
059    public boolean equals(Object obj) {
060        if (obj instanceof IrDecimalArithm) {
061            IrDecimalArithm other = (IrDecimalArithm) obj;
062            return op.equals(other.op) && left.equals(other.left) && right.equals(other.right)
063                    && one == other.one && decimalRange.equals(other.decimalRange);
064        }
065        return false;
066    }
067
068    @Override
069    public int hashCode() {
070        return op.ordinal() ^ left.hashCode() ^ right.hashCode() ^ one;
071    }
072
073    @Override
074    public String toString() {
075        return "round((" + left + ") " + (op == Op.Mul ? "*" : "/") + " (" + right + ") @ " + one + ")";
076    }
077
078    public static enum Op {
079
080        Mul,
081        Div
082    }
083}