kodkod.ast.IntExpression Java Examples

The following examples show how to use kodkod.ast.IntExpression. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FOL2BoolTranslator.java    From kodkod with MIT License 6 votes vote down vote up
/**
 * Translates the given sum expression as follows 
 * (where A_0...A_|A| stand for boolean variables that represent the 
 * tuples of the expression A, etc.):
 * let sum = "sum a: A, b: B, ..., x: X | IE(a, b, ..., x) " |
 *     sum a: A, b: B, ..., x: X | if (a in A && b in B && ... && x in X) then IE(a, b, ..., x) else 0 }.
 * @param decls intexpr declarations
 * @param formula the formula body
 * @param currentDecl currently processed declaration; should be 0 initially
 * @param declConstraints the constraints implied by the declarations; should be Boolean.TRUE initially
 * @param values integer values computed so far
 */
private final void sum(Decls decls, IntExpression expr, int currentDecl, BooleanValue declConstraints,
		List<Int> values) {
	final BooleanFactory factory = interpreter.factory();
	if (decls.size()==currentDecl) {
		values.add( expr.accept(this).choice(declConstraints, factory.integer(0)) );
		return;
	}

	final Decl decl = decls.get(currentDecl);
	final BooleanMatrix declTransl = visit(decl);
	final BooleanMatrix groundValue = factory.matrix(declTransl.dimensions());
	env = env.extend(decl.variable(), groundValue);
	for(IndexedEntry<BooleanValue> entry : declTransl) {
		groundValue.set(entry.index(), BooleanConstant.TRUE);
		sum(decls, expr, currentDecl+1, factory.and(entry.value(), declConstraints), values);
		groundValue.set(entry.index(), BooleanConstant.FALSE);	
	}
	env = env.parent();
}
 
Example #2
Source File: IntTest.java    From org.alloytools.alloy with Apache License 2.0 6 votes vote down vote up
private boolean overflows(IntOperator op, IntExpression ei, IntExpression ej, int i, int j, int realResult) {
    if (!solver.options().noOverflow())
        return false;
    int bw = solver.options().bitwidth();
    if (ei.toString().contains("-#") && outOfBounds(-i, bw))
        return true;
    if (ej.toString().contains("-#") && outOfBounds(-j, bw))
        return true;
    if (op == SHA || op == SHR)
        return false;
    if (op == SHL) {
        if (i == 0 || j == 0)
            return false;
        if (j < 0 || j >= solver.options().bitwidth())
            return true;
    }
    if (outOfBounds(realResult, bw))
        return true;
    return false;
}
 
Example #3
Source File: AbstractReplacer.java    From org.alloytools.alloy with Apache License 2.0 6 votes vote down vote up
/**
 * Calls lookup(intExpr) and returns the cached value, if any. If a replacement
 * has not been cached, visits the intExpr's children. If nothing changes, the
 * argument is cached and returned, otherwise a replacement intExpr is cached
 * and returned.
 *
 * @return { e: IntExpression | e.op = intExpr.op && #e.children =
 *         #intExpr.children && all i: [0..intExpr.children) | e.child(i) =
 *         intExpr.child(i).accept(delegate) }
 */
@Override
public IntExpression visit(NaryIntExpression intExpr) {
    IntExpression ret = lookup(intExpr);
    if (ret != null)
        return ret;

    final IntExpression[] visited = new IntExpression[intExpr.size()];
    boolean allSame = true;
    for (int i = 0; i < visited.length; i++) {
        final IntExpression child = intExpr.child(i);
        visited[i] = child.accept(delegate);
        allSame = allSame && visited[i] == child;
    }

    ret = allSame ? intExpr : IntExpression.compose(intExpr.op(), visited);
    return cache(intExpr, ret);
}
 
Example #4
Source File: Simplifier.java    From quetzal with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * @requires op.nary
 * @return simplification of the given operand list
 **/
final List<IntExpression> simplify(IntOperator op, List<IntExpression> children) { 
	final IntExpression zero = constant(0);
	switch(op) { 
	case PLUS : case OR : 
		for(Iterator<IntExpression> itr = children.iterator(); itr.hasNext(); ) { 
			if (itr.next()==zero)
				itr.remove();
		}
		break;
	case MULTIPLY : case AND :
		for(IntExpression child : children) { 
			if (child==zero)
				return Collections.singletonList(zero);
		}
		break;
	default : 
		Assertions.UNREACHABLE();
	}
	return children;
}
 
Example #5
Source File: TranslatorTest.java    From kodkod with MIT License 6 votes vote down vote up
private final void testNary(IntOperator op) { 
	bounds.bound(r1[0], factory.range(factory.tuple(1, 0), factory.tuple(1, 3)));
	bounds.bound(r1[1], factory.range(factory.tuple(1, 2), factory.tuple(1, 5)));
	bounds.bound(r1[3], factory.range(factory.tuple(1, 3), factory.tuple(1, 6)));
	
	for(int i = 2; i <= 5; i++) { 
		final IntExpression[] exprs = new IntExpression[i];
		exprs[0] = r1[0].count();
		IntExpression binExpr = r1[0].count();
		for(int j = 1; j < i; j++) { 
			binExpr = binExpr.compose(op, r1[j%4].count());
			exprs[j] = r1[j%4].count();
		}
		IntExpression nExpr = IntExpression.compose(op, exprs);
		final Solution sol = solver.solve(binExpr.eq(nExpr).not(), bounds);
		assertNull(sol.instance());	
	}
	
}
 
Example #6
Source File: PartialCannonicalizer.java    From quetzal with Eclipse Public License 2.0 6 votes vote down vote up
public IntExpression visit(IfIntExpression expr) { 
	IntExpression ret = lookup(expr);
	if (ret!=null) return ret;
	
	final Formula cond = expr.condition().accept(this);
	final IntExpression thenExpr = expr.thenExpr().accept(this);
	final IntExpression elseExpr = expr.elseExpr().accept(this);
	
	ret = simplify(cond,thenExpr,elseExpr);
	
	if (ret==null) { 
		final int hash = hash(IfIntExpression.class, cond, thenExpr, elseExpr);
		for(Iterator<PartialCannonicalizer.Holder<IntExpression>> itr = intExprs.get(hash); itr.hasNext(); ) {
			final IntExpression next = itr.next().obj;
			if (next.getClass()==IfIntExpression.class) { 
				final IfIntExpression hit = (IfIntExpression) next;
				if (hit.condition()==cond && hit.thenExpr()==thenExpr && hit.elseExpr()==elseExpr) { 
					return cache(expr, hit);
				}
			}
		}
		ret = cond==expr.condition()&&thenExpr==expr.thenExpr()&&elseExpr==expr.elseExpr() ? expr : cond.thenElse(thenExpr, elseExpr);
		intExprs.add(new PartialCannonicalizer.Holder<IntExpression>(ret, hash));
	}
	return cache(expr,ret);
}
 
Example #7
Source File: AbstractReplacer.java    From kodkod with MIT License 6 votes vote down vote up
/** 
* Calls lookup(intExpr) and returns the cached value, if any.  
* If a replacement has not been cached, visits the intExpr's 
* children.  If nothing changes, the argument is cached and
* returned, otherwise a replacement intExpr is cached and returned.
* @return { e: IntExpression | e.op = intExpr.op && #e.children = #intExpr.children && all i: [0..intExpr.children) | e.child(i) = intExpr.child(i).accept(this) }
*/
  public IntExpression visit(NaryIntExpression intExpr) {
IntExpression ret = lookup(intExpr);
if (ret!=null) return ret;
	
final IntExpression[] visited = new IntExpression[intExpr.size()];
boolean allSame = true;
for(int i = 0 ; i < visited.length; i++) { 
	final IntExpression child = intExpr.child(i);
	visited[i] = child.accept(this);
	allSame = allSame && visited[i]==child;
}

ret = allSame ? intExpr : IntExpression.compose(intExpr.op(), visited);
return cache(intExpr,ret);
  }
 
Example #8
Source File: PrettyPrinter.java    From kodkod with MIT License 6 votes vote down vote up
/** @ensures appends the tokenization of the given node to this.tokens */
public void visit(ProjectExpression node) {
	append("project");
	append("[");
	node.expression().accept(this);
	comma();
	append("<");
	final Iterator<IntExpression> cols = node.columns();
	cols.next().accept(this);
	while(cols.hasNext()) { 
		comma();
		cols.next().accept(this);
	}
	append(">");
	append("]");
}
 
Example #9
Source File: FloatingPoint.java    From quetzal with Eclipse Public License 2.0 6 votes vote down vote up
public static IntExpression floatMultiply(IntExpression l, IntExpression r) {
	IntExpression le = exponent(l);
	IntExpression re = exponent(r);
	IntExpression e = le.plus(re);
	
	IntExpression lv = mantissa(l);
	IntExpression rv = mantissa(r);
	Pair<IntExpression,IntExpression> p = fullUnsignedIntegerMultiply(lv, rv);
	IntExpression shift = IntConstant.constant(23).minus(maxSetBit(p.snd));
	IntExpression m = adjustRight(p.fst, IntConstant.constant(32).minus(shift)).or(p.snd.shl(shift));
	e = e.plus(IntConstant.constant(9).minus(shift));
	
	// hide implicit one
	m = m.and(IntConstant.constant(mantissaMask));
	
	IntExpression s = sign(l).eq(sign(r)).thenElse(zero, one);
	
	return l.eq(zero).or(r.eq(zero)).thenElse(zero, s.shl(IntConstant.constant(exponentBits+mantissaBits))
		.or(e.plus(IntConstant.constant(exponentBias)).shl(IntConstant.constant(mantissaBits)))
		.or(m));
}
 
Example #10
Source File: Viktor.java    From org.alloytools.alloy with Apache License 2.0 6 votes vote down vote up
/**
 * Constructs an instance of Viktor for n = 3.
 */
public Viktor() {
    rows = 3;
    cols = 1 << rows;
    a = new Relation[rows][cols];
    x = new Relation[cols];
    b = new IntExpression[rows];
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            a[i][j] = Relation.unary("a" + String.valueOf(i) + String.valueOf(j));
        }
    }
    for (int j = 0; j < cols; j++) {
        x[j] = Relation.unary("x" + j);
    }
    for (int i = 0; i < rows; i++) {
        b[i] = conditionalSum(a[i], x, 0, cols - 1);
    }
}
 
Example #11
Source File: FOL2BoolTranslator.java    From org.alloytools.alloy with Apache License 2.0 6 votes vote down vote up
/**
 * Translates the given sum expression as follows (where A_0...A_|A| stand for
 * boolean variables that represent the tuples of the expression A, etc.): let
 * sum = "sum a: A, b: B, ..., x: X | IE(a, b, ..., x) " | sum a: A, b: B, ...,
 * x: X | if (a in A && b in B && ... && x in X) then IE(a, b, ..., x) else 0 }.
 *
 * @param decls intexpr declarations
 * @param formula the formula body
 * @param currentDecl currently processed declaration; should be 0 initially
 * @param declConstraints the constraints implied by the declarations; should be
 *            Boolean.TRUE intially
 * @param values integer values computed so far
 */
private final void sum(Decls decls, IntExpression expr, int currentDecl, BooleanValue declConstraints, List<Int> values) {
    final BooleanFactory factory = interpreter.factory();
    if (decls.size() == currentDecl) {
        Int intExpr = expr.accept(this);
        Int newInt = intExpr.choice(declConstraints, factory.integer(0));
        values.add(newInt);
        return;
    }

    final Decl decl = decls.get(currentDecl);
    final BooleanMatrix declTransl = visit(decl);
    final BooleanMatrix groundValue = factory.matrix(declTransl.dimensions());
    env = env.extend(decl.variable(), decl.expression(), groundValue);
    for (IndexedEntry<BooleanValue> entry : declTransl) {
        groundValue.set(entry.index(), BooleanConstant.TRUE);
        sum(decls, expr, currentDecl + 1, factory.and(entry.value(), declConstraints), values);
        groundValue.set(entry.index(), BooleanConstant.FALSE);
    }
    env = env.parent();
}
 
Example #12
Source File: Viktor.java    From kodkod with MIT License 6 votes vote down vote up
/**
 * Constructs an instance of Viktor for n = 3.
 */
public Viktor() {
	rows = 3;
	cols = 1<<rows;
	a = new Relation[rows][cols];
	x = new Relation[cols];
	b = new IntExpression[rows];
	for(int i = 0; i < rows; i++) {
		for(int j = 0; j < cols; j++) {
			a[i][j] = Relation.unary("a"+String.valueOf(i)+String.valueOf(j));
		}
	}
	for(int j = 0; j < cols; j++) {
		x[j] = Relation.unary("x"+j);
	}
	for(int i = 0; i < rows; i++) {
		b[i] = conditionalSum(a[i], x, 0, cols-1);
	}
}
 
Example #13
Source File: PartialCannonicalizer.java    From quetzal with Eclipse Public License 2.0 6 votes vote down vote up
public IntExpression visit(UnaryIntExpression expr) { 
	IntExpression ret = lookup(expr);
	if (ret!=null) return ret;
	
	final IntOperator op = expr.op();
	final IntExpression child = expr.intExpr().accept(this);
	
	ret = simplify(op, child);
	if (ret==null) {
		final int hash = hash(op, child);
		for(Iterator<PartialCannonicalizer.Holder<IntExpression>> itr = intExprs.get(hash); itr.hasNext(); ) {
			final IntExpression next = itr.next().obj;
			if (next.getClass()==UnaryIntExpression.class) { 
				if (((UnaryIntExpression)next).intExpr()==child)
					return cache(expr, next);
			}
		}
		ret = child==expr.intExpr() ? expr : child.apply(op);
		intExprs.add(new PartialCannonicalizer.Holder<IntExpression>(ret, hash));
	}
	return cache(expr,ret);
}
 
Example #14
Source File: PartialCannonicalizer.java    From quetzal with Eclipse Public License 2.0 6 votes vote down vote up
public Formula visit(IntComparisonFormula formula) { 
	Formula ret = lookup(formula);
	if (ret!=null) return ret;
	
	final IntCompOperator op = formula.op();
	final IntExpression left = formula.left().accept(this);
	final IntExpression right = formula.right().accept(this);
	
	if (left==right) return cache(formula,Formula.TRUE);
	
	final int hash = hash(op, left, right);
	for(Iterator<PartialCannonicalizer.Holder<Formula>> itr = formulas.get(hash); itr.hasNext(); ) {
		final Formula next = itr.next().obj;
		if (next instanceof IntComparisonFormula) { 
			final IntComparisonFormula hit = (IntComparisonFormula) next;
			if (hit.op()==op && hit.left()==left && hit.right()==right) { 
				return cache(formula, hit);
			}
		}
	}

	ret = left==formula.left()&&right==formula.right() ? formula : left.compare(op, right);
	formulas.add(new PartialCannonicalizer.Holder<Formula>(ret, hash));
	return cache(formula,ret);
}
 
Example #15
Source File: FloatingPoint.java    From quetzal with Eclipse Public License 2.0 6 votes vote down vote up
public static IntExpression intToFloat(IntExpression intValue) {
	IntExpression abs = intValue.abs();
	IntExpression maxSetBit = maxSetBit(abs);
	Formula shiftRight = maxSetBit.gt(IntConstant.constant(mantissaBits));
	
	IntExpression re = maxSetBit.minus(IntConstant.constant(mantissaBits));
	IntExpression adjustRight = adjustRight(abs, re);
	
	IntExpression le = IntConstant.constant(mantissaBits).minus(maxSetBit);
	IntExpression adjustLeft = abs.shl(le);

	IntExpression mantissa = 
		shiftRight.thenElse(adjustRight, adjustLeft).xor(implicitOne);
		
	IntExpression exponent = maxSetBit.plus(IntConstant.constant(exponentBias));
				
	IntExpression sign = intValue.lt(IntConstant.constant(0))
			.thenElse(IntConstant.constant(1<<(exponentBits+mantissaBits)), zero);

	return intValue.eq(zero)
		.thenElse(zero,
			sign.or(exponent.shl(IntConstant.constant(mantissaBits))).or(mantissa));
}
 
Example #16
Source File: FloatExpressionTests.java    From quetzal with Eclipse Public License 2.0 6 votes vote down vote up
private void testMultiply(float l, float r) {
	IntExpression lv = IntConstant.constant(Float.floatToIntBits(l));
	IntExpression rv = IntConstant.constant(Float.floatToIntBits(r));
	
	IntExpression computedSum = floatMultiply(lv, rv);
	IntExpression expectedSum = IntConstant.constant(Float.floatToIntBits(((float)l)*((float)r)));

	System.err.println(eval.evaluate(computedSum));
	dumpFloat(computedSum, "computed");
	dumpFloat(expectedSum, "expected");
	
	dumpFloat(lv, "left");
	dumpFloat(rv, "right");

	Assert.assertEquals("expected " + eval.evaluate(expectedSum) + " but got " + eval.evaluate(computedSum), eval.evaluate(expectedSum), eval.evaluate(computedSum));
}
 
Example #17
Source File: NQueens.java    From kodkod with MIT License 6 votes vote down vote up
/**
 * Prints the given solution
 */
void print(Instance instance, Options options) { 
	final Evaluator eval = new Evaluator(instance, options);
	for(int i = 0; i < n; i++) { 
		IntExpression ci = IntConstant.constant(i);
		for(int j = 0; j < n; j++) { 
			IntExpression cj = IntConstant.constant(j);
			Variable q = Variable.unary("q");
			if (eval.evaluate(q.join(x).sum().eq(ci).and(q.join(y).sum().eq(cj)).forSome(q.oneOf(queen)))) { 
				System.out.print(" Q");
			} else {
				System.out.print(" .");
			}
		}
		System.out.println();
	}
}
 
Example #18
Source File: PartialCannonicalizer.java    From quetzal with Eclipse Public License 2.0 6 votes vote down vote up
public IntExpression visit(ExprToIntCast expr) { 
	IntExpression ret = lookup(expr);
	if (ret!=null) return ret;
	
	final ExprCastOperator op = expr.op();
	final Expression child = expr.expression().accept(this);
	
	final int hash = hash(op, child);
	for(Iterator<PartialCannonicalizer.Holder<IntExpression>> itr = intExprs.get(hash); itr.hasNext(); ) {
		final IntExpression next = itr.next().obj;
		if (next.getClass()==ExprToIntCast.class) { 
			if (((ExprToIntCast)next).expression()==child)
				return cache(expr, next);
		}
	}
	ret = child==expr.expression() ? expr : child.apply(op);
	intExprs.add(new PartialCannonicalizer.Holder<IntExpression>(ret, hash));
	return cache(expr,ret);
}
 
Example #19
Source File: FloatingPoint.java    From quetzal with Eclipse Public License 2.0 5 votes vote down vote up
public static IntExpression floatDivide(IntExpression l, IntExpression r) {
	IntExpression sign = sign(l).xor(sign(r));
	
	l = floatAbs(l);
	IntExpression le = exponent(l).minus(exponent(r).plus(one)).plus(IntConstant.constant(exponentBias));
	l = l.and(IntConstant.constant(exponentMask).not()).or(le.shl(IntConstant.constant(mantissaBits)));
	
	r = floatAbs(r);
	r = r.and(IntConstant.constant(exponentMask).not()).or(minusOne.plus(IntConstant.constant(exponentBias)).shl(IntConstant.constant(mantissaBits)));
	
	IntExpression xi = 
		floatMinus(
			IntConstant.constant(Float.floatToIntBits((float)48/(float)17)), 
			floatMultiply(
				IntConstant.constant(Float.floatToIntBits((float)32/(float)17)), 
				r));
	
	IntExpression two = IntConstant.constant(Float.floatToIntBits(2f));
	
	// find out why this does not work...
	//int steps = newtonSteps(bitWidth);
	for(int i = 0; i < 7; i++) {
		xi = floatMultiply(xi, floatMinus(two, floatMultiply(r, xi)));
	}
	
	IntExpression answer = floatMultiply(xi, l);
	return answer.and(IntConstant.constant(signMask).not()).or(sign.shl(IntConstant.constant(exponentBits+mantissaBits)));
}
 
Example #20
Source File: PartialCannonicalizer.java    From quetzal with Eclipse Public License 2.0 5 votes vote down vote up
public IntExpression visit(BinaryIntExpression expr) { 
	IntExpression ret = lookup(expr);
	if (ret!=null) return ret;
	final IntOperator op = expr.op();
	final IntExpression left = expr.left().accept(this);
	final IntExpression right = expr.right().accept(this);
	
	ret = simplify(op, left, right);
	
	if (ret==null) {
	
		final int hash = hash(op, left, right);
		for(Iterator<PartialCannonicalizer.Holder<IntExpression>> itr = intExprs.get(hash); itr.hasNext(); ) {
			final IntExpression next = itr.next().obj;
			if (next instanceof BinaryIntExpression) { 
				final BinaryIntExpression hit = (BinaryIntExpression) next;
				if (hit.op()==op && hit.left()==left && hit.right()==right) { 
					return cache(expr, hit);
				}
			}
		}

		ret = left==expr.left()&&right==expr.right() ? expr : left.compose(op, right);
		intExprs.add(new PartialCannonicalizer.Holder<IntExpression>(ret, hash));
	}
	
	return cache(expr,ret);
}
 
Example #21
Source File: OverflowTheoremTest.java    From org.alloytools.alloy with Apache License 2.0 5 votes vote down vote up
/**
 * all s, t : set univ | #(s + t) >= #s && #(s + t) >= #t
 */
@Test
public void testCardinality2() {
    Variable s = Variable.unary("s");
    Variable t = Variable.unary("t");
    IntExpression sutCnt = s.union(t).count();
    Decls dcls = s.setOf(Expression.UNIV).and(t.setOf(Expression.UNIV));
    Formula f = sutCnt.gte(s.count()).and(sutCnt.gte(t.count())).forAll(dcls);
    checkTrue(f);
}
 
Example #22
Source File: IntTest.java    From org.alloytools.alloy with Apache License 2.0 5 votes vote down vote up
/**
 * Tests all binary ops for this.solver.options and range of vals.
 *
 * @requires this.solver.options.intEncoding = binary
 * @requires vals contains int expressions that represent all integers allowed
 *           by this.solver.options, in proper sequence
 */
private final void test2sComplementBinOps(IntExpression[] vals) {
    final Options options = solver.options();

    final IntRange range = options.integers();
    final int min = range.min(), max = range.max();
    final int mask = ~(-1 << options.bitwidth());
    final int shiftmask = ~(-1 << (32 - Integer.numberOfLeadingZeros(options.bitwidth() - 1)));

    for (int i = min; i <= max; i++) {
        IntExpression vi = vals[i - min];
        for (int j = min; j <= max; j++) {
            IntExpression vj = vals[j - min];
            testBinOp(PLUS, vi, vj, i, j, i + j, mask);
            testBinOp(MINUS, vi, vj, i, j, i - j, mask);
            testBinOp(MULTIPLY, vi, vj, i, j, i * j, mask);

            if (j != 0) {
                testBinOp(DIVIDE, vi, vj, i, j, i / j, mask);
                testBinOp(MODULO, vi, vj, i, j, i % j, mask);
            }

            testBinOp(AND, vi, vj, i, j, i & j, mask);
            testBinOp(OR, vi, vj, i, j, i | j, mask);
            testBinOp(XOR, vi, vj, i, j, i ^ j, mask);

            testBinOp(SHL, vi, vj, i, j, i << (j & shiftmask), i << j, mask);
            testBinOp(SHR, vi, vj, i, j, (i & mask) >>> (j & shiftmask), mask);
            testBinOp(SHA, vi, vj, i, j, i >> (j & shiftmask), mask);
        }
    }

}
 
Example #23
Source File: AbstractVoidVisitor.java    From kodkod with MIT License 5 votes vote down vote up
/**
 * Visits the children if this.visited(intExpr) returns false.  Otherwise does nothing.
 * @ensures all i: [0..#intExpr.children) | intExpr.child(i).accept(this)
 */
public void visit(NaryIntExpression intExpr) {
	if (visited(intExpr)) return;
	for(IntExpression child : intExpr) { 
		child.accept(this);
	}
}
 
Example #24
Source File: IntTest.java    From kodkod with MIT License 5 votes vote down vote up
private final void test2sComplementUnOps(IntExpression[] vals) {
	final Options options = solver.options();
	
	final IntRange range = options.integers();
	final int min = range.min(), max = range.max();
	final int mask = ~(-1 << options.bitwidth());
	
	for(int i = min; i <= max; i++) {
		IntExpression vi = vals[i-min];
		testUnOp(IntOperator.NEG, vi, i, -i, mask);
		testUnOp(IntOperator.NOT, vi, i, ~i, mask);
		testUnOp(IntOperator.ABS, vi, i, Math.abs(i), mask);
		testUnOp(IntOperator.SGN, vi, i, i < 0 ? -1 : i > 0 ? 1 : 0, mask);
	}		
}
 
Example #25
Source File: Simplifier.java    From quetzal with Eclipse Public License 2.0 5 votes vote down vote up
/** @return a simplification of left op right, if possible, or null otherwise. */
final IntExpression simplify(IntOperator op, IntExpression left, IntExpression right) { 
	final boolean lzero = left==constant(0), rzero = right==constant(0);
	
	switch(op) { 
	case PLUS : case OR : case XOR : 
		if (lzero)		{ return right; }
		else if (rzero)	{ return left; }
		break;
	case MULTIPLY : case AND : 
		if (lzero)		{ return left; }
		else if (rzero) { return right; }
		break;
	case MINUS : 
		if (lzero)		{ return right.negate().accept(this); }
		else if (rzero) { return left; }
		break;
	case SHA : case SHL : case SHR : 
		if (lzero || rzero)	{ return left; }
		break;
	case DIVIDE : case MODULO : 
		if (lzero) 		{ return left; }
		break;
	default :
		Assertions.UNREACHABLE();
	}
	
	return null;
}
 
Example #26
Source File: IntTest.java    From org.alloytools.alloy with Apache License 2.0 5 votes vote down vote up
private IntExpression[] nonConstants() {
    final Options options = solver.options();

    final IntRange range = options.integers();
    final int min = range.min(), max = range.max();
    final int size = range.size();

    final Relation[] r = new Relation[size];

    final TupleFactory f = bounds.universe().factory();
    for (int i = 0; i < size; i++) {
        int arity = i % 3 + 1;
        r[i] = Relation.nary("r" + i, arity);

        TupleSet b = f.noneOf(arity);
        for (int j = (i / 3) * ((int) Math.pow(SIZE, arity - 1)), jmax = j + size; j < jmax; j++) {
            b.add(f.tuple(arity, j % b.capacity()));
        }

        bounds.bound(r[i], b);
    }

    final IntExpression[] vals = new IntExpression[max - min + 1];
    for (int i = 0; i < size; i++) {
        vals[i] = i + min < 0 ? r[i].count().negate() : r[i].count();
    }

    return vals;
}
 
Example #27
Source File: Simplifier.java    From quetzal with Eclipse Public License 2.0 5 votes vote down vote up
public Formula visit(IntComparisonFormula formula) { 
	Formula ret = lookup(formula);
	if (ret!=null) return ret;
	
	final IntCompOperator op = formula.op();
	final IntExpression left = formula.left().accept(this);
	final IntExpression right = formula.right().accept(this);
	
	if (left==right) return cache(formula,Formula.TRUE);
	
	ret = left==formula.left()&&right==formula.right() ? formula : left.compare(op, right);
	return cache(formula,ret);
}
 
Example #28
Source File: AbstractReplacer.java    From kodkod with MIT License 5 votes vote down vote up
/** 
* Calls lookup(intExpr) and returns the cached value, if any.  
* If a replacement has not been cached, visits the expression's 
* children.  If nothing changes, the argument is cached and
* returned, otherwise a replacement expression is cached and returned.
* @return { c: IntExpression | [[c]] = sum intExpr.decls.accept(this) | intExpr.intExpr.accept(this) }
*/
  public IntExpression visit(SumExpression intExpr) {
IntExpression ret = lookup(intExpr);
if (ret!=null) return ret;
	
final Decls decls  = intExpr.decls().accept(this);
final IntExpression expr = intExpr.intExpr().accept(this);
ret =  (decls==intExpr.decls() && expr==intExpr.intExpr()) ? 
		intExpr : expr.sum(decls);
return cache(intExpr,ret);
  }
 
Example #29
Source File: IntTest.java    From org.alloytools.alloy with Apache License 2.0 5 votes vote down vote up
private final void testCompOp(IntCompOperator op, IntExpression ei, IntExpression ej, int i, int j, boolean result) {
    final Formula e = ei.compare(op, ej);
    final Formula f = ei.eq(constant(i)).and(ej.eq(constant(j))).and(result ? e : e.not());
    final Solution s = solve(f);
    if (overflows(ei, i, 0) || overflows(ej, j, 0)) {
        assertNull(f.toString(), s.instance());
    } else {
        assertNotNull(f.toString(), s.instance());
        final Evaluator eval = new Evaluator(s.instance(), solver.options());
        assertFalse(result ^ eval.evaluate(e));
    }
}
 
Example #30
Source File: IntTest.java    From org.alloytools.alloy with Apache License 2.0 5 votes vote down vote up
private final void testUnOp(IntOperator op, IntExpression ei, int i, int result, int mask) {
    final IntExpression e = ei.apply(op);
    final Formula f = ei.eq(constant(i)).and(e.eq(constant(result)));
    final Solution s = solve(f);
    if (overflows(ei, i, result)) {
        assertNull(f.toString(), s.instance());
    } else {
        assertNotNull(f.toString(), s.instance());
        final Evaluator eval = new Evaluator(s.instance(), solver.options());
        assertEquals(result & mask, eval.evaluate(e) & mask);
    }
}