kodkod.ast.Decls Java Examples

The following examples show how to use kodkod.ast.Decls. 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 comprehension as follows 
 * (where A_0...A_|A| stand for boolean variables that represent the 
 * tuples of the expression A, etc.):
 * let comprehension = "{ a: A, b: B, ..., x: X | F(a, b, ..., x) }" |
 *     { a: A, b: B, ..., x: X | a in A && b in B && ... && x in X && F(a, b, ..., x) }.
 * @param decls the declarations comprehension
 * @param param formula the body of the comprehension
 * @param currentDecl currently processed declaration; should be 0 initially
 * @param declConstraints the constraints implied by the declarations; should be Boolean.TRUE initially
 * @param partialIndex partial index into the provided matrix; should be 0 initially
 * @param matrix boolean matrix that will retain the final results; should be an empty matrix of dimensions universe.size^decls.length initially
 * @ensures the given matrix contains the translation of the comprehension "{ decls | formula }"
 */
private final void comprehension(Decls decls, Formula formula, int currentDecl, 
		BooleanValue declConstraints, int partialIndex, BooleanMatrix matrix) {
	final BooleanFactory factory = interpreter.factory();

	if (currentDecl==decls.size()) {
		matrix.set(partialIndex, factory.and(declConstraints, formula.accept(this)));
		return;
	}

	final Decl decl = decls.get(currentDecl);
	final BooleanMatrix declTransl = visit(decl);
	final int position = (int)StrictMath.pow(interpreter.universe().size(), decls.size()-currentDecl-1);
	final BooleanMatrix groundValue = factory.matrix(declTransl.dimensions());
	env = env.extend(decl.variable(), groundValue);
	for(IndexedEntry<BooleanValue> entry : declTransl) {
		groundValue.set(entry.index(), BooleanConstant.TRUE);
		comprehension(decls, formula, currentDecl+1, factory.and(entry.value(), declConstraints), 
				partialIndex + entry.index()*position, matrix);
		groundValue.set(entry.index(), BooleanConstant.FALSE);	
	}
	env = env.parent();
}
 
Example #2
Source File: GRA013_026.java    From org.alloytools.alloy with Apache License 2.0 6 votes vote down vote up
private final Formula cliqueAxiom(Expression color) {
    final Variable[] vars = new Variable[cliqueSize];
    for (int i = 0; i < cliqueSize; i++) {
        vars[i] = Variable.unary("V" + i);
    }
    final List<Expression> members = new ArrayList<Expression>(cliqueSize);
    for (int i = 0, max = cliqueSize - 1; i < max; i++) {
        final List<Expression> tmp = new ArrayList<Expression>();
        for (int j = i + 1; j < cliqueSize; j++) {
            tmp.add(vars[j]);
        }
        members.add(vars[i].product(Expression.union(tmp)));
    }
    Decls d = vars[0].oneOf(node);
    for (int i = 1; i < cliqueSize; i++) {
        d = d.and(vars[i].oneOf(vars[i - 1].join(lessThan)));
    }
    return Expression.union(members).in(color).implies(goalToBeProved()).forAll(d);
}
 
Example #3
Source File: AbstractReplacer.java    From kodkod with MIT License 6 votes vote down vote up
/** 
 * Calls lookup(decls) and returns the cached value, if any.  
 * If a replacement has not been cached, visits each of the children's 
 * variable and expression.  If nothing changes, the argument is cached and
 * returned, otherwise a replacement Decls object is cached and returned.
 * @return { d: Decls | d.size = decls.size && 
 *                      all i: [0..d.size) | d.declarations[i] = decls.declarations[i].accept(this) } 
 */
public Decls visit(Decls decls) { 
	Decls ret = lookup(decls);
	if (ret!=null) return ret;
	
	Decls visitedDecls = null;
	boolean allSame = true;
	for(Decl decl : decls) {
		Decls newDecl = visit(decl);
		if (newDecl != decl) 
			allSame = false;
		visitedDecls = (visitedDecls==null) ? newDecl : visitedDecls.and(newDecl);
	}
	ret = allSame ? decls : visitedDecls;
	return cache(decls, ret);
}
 
Example #4
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 #5
Source File: AnnotatedNode.java    From org.alloytools.alloy with Apache License 2.0 6 votes vote down vote up
/**
 * Visits the given comprehension, quantified formula, or sum expression. The
 * method returns TRUE if the creator body contains any variable not bound by
 * the decls; otherwise returns FALSE.
 */
private Boolean visit(Node creator, Decls decls, Node body) {
    Boolean ret = lookup(creator);
    if (ret != null)
        return ret;
    boolean retVal = false;
    for (Decl decl : decls) {
        retVal = decl.expression().accept(this) || retVal;
        varsInScope.push(decl.variable());
    }
    retVal = ((Boolean) body.accept(this)) || retVal;
    for (int i = decls.size(); i > 0; i--) {
        varsInScope.pop();
    }
    return cache(creator, retVal);
}
 
Example #6
Source File: GRA013_026.java    From kodkod with MIT License 6 votes vote down vote up
private final Formula cliqueAxiom(Expression color) {
	final Variable[] vars = new Variable[cliqueSize];
	for(int i = 0; i < cliqueSize; i++) { 
		vars[i] = Variable.unary("V"+i);
	}
	final List<Expression> members = new ArrayList<Expression>(cliqueSize);
	for(int i = 0, max = cliqueSize-1; i < max; i++) { 
		final List<Expression> tmp = new ArrayList<Expression>();
		for(int j = i+1; j < cliqueSize; j++) { 
			tmp.add(vars[j]);
		}
		members.add(vars[i].product(Expression.union(tmp)));
	}
	Decls d = vars[0].oneOf(node);
	for(int i = 1; i < cliqueSize; i++) { 
		d = d.and(vars[i].oneOf(vars[i-1].join(lessThan)));
	}
	return Expression.union(members).in(color).implies(goalToBeProved()).forAll(d);
}
 
Example #7
Source File: FOL2BoolTranslator.java    From org.alloytools.alloy with Apache License 2.0 6 votes vote down vote up
/**
 * Translates the given comprehension as follows (where A_0...A_|A| stand for
 * boolean variables that represent the tuples of the expression A, etc.): let
 * comprehension = "{ a: A, b: B, ..., x: X | F(a, b, ..., x) }" | { a: A, b: B,
 * ..., x: X | a in A && b in B && ... && x in X && F(a, b, ..., x) }.
 *
 * @param decls the declarations comprehension
 * @param param formula the body of the comprehension
 * @param currentDecl currently processed declaration; should be 0 initially
 * @param declConstraints the constraints implied by the declarations; should be
 *            Boolean.TRUE intially
 * @param partialIndex partial index into the provided matrix; should be 0
 *            initially
 * @param matrix boolean matrix that will retain the final results; should be an
 *            empty matrix of dimensions universe.size^decls.length initially
 * @ensures the given matrix contains the translation of the comprehension "{
 *          decls | formula }"
 */
private final void comprehension(Decls decls, Formula formula, int currentDecl, BooleanValue declConstraints, int partialIndex, BooleanMatrix matrix) {
    final BooleanFactory factory = interpreter.factory();

    if (currentDecl == decls.size()) {
        // TODO: what about this and overflow???
        matrix.set(partialIndex, factory.and(declConstraints, formula.accept(this)));
        return;
    }

    final Decl decl = decls.get(currentDecl);
    final BooleanMatrix declTransl = visit(decl);
    final int position = (int) StrictMath.pow(interpreter.universe().size(), decls.size() - currentDecl - 1);
    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);
        comprehension(decls, formula, currentDecl + 1, factory.and(entry.value(), declConstraints), partialIndex + entry.index() * position, matrix);
        groundValue.set(entry.index(), BooleanConstant.FALSE);
    }
    env = env.parent();
}
 
Example #8
Source File: Skolemizer.java    From org.alloytools.alloy with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a formula that properly constrains the given skolem's domain.
 *
 * @requires !nonSkolems.isEmpty()
 * @return a formula that properly constrains the given skolem's domain.
 */
private Formula domainConstraint(Decl skolemDecl, Relation skolem) {
    final Iterator<DeclInfo> itr = nonSkolems.iterator();
    Decls rangeDecls = null;
    while (itr.hasNext()) {
        Decl d = itr.next().decl;
        Decl dd = d.variable().oneOf(d.expression());
        rangeDecls = rangeDecls != null ? rangeDecls.and(dd) : dd;
    }
    // System.out.println(skolemDecl.expression());
    Expression skolemDomain = skolem;
    for (int i = 0, max = skolemDecl.variable().arity(); i < max; i++) {
        skolemDomain = skolemDomain.join(Expression.UNIV);
    }
    return skolemDomain.in(Formula.TRUE.comprehension(rangeDecls));
}
 
Example #9
Source File: Skolemizer.java    From org.alloytools.alloy with Apache License 2.0 6 votes vote down vote up
/**
 * @see kodkod.ast.visitor.AbstractReplacer#visit(kodkod.ast.SumExpression)
 */
@Override
public final IntExpression visit(SumExpression intExpr) {
    IntExpression ret = lookup(intExpr);
    if (ret != null)
        return ret;
    final Environment<Expression,Expression> oldRepEnv = repEnv; // skolemDepth
                                                                // < 0
                                                                // at
                                                                // this
                                                                // point
    final Decls decls = visit(intExpr.decls());
    final IntExpression expr = intExpr.intExpr().accept(this);
    ret = (decls == intExpr.decls() && expr == intExpr.intExpr()) ? intExpr : expr.sum(decls);
    repEnv = oldRepEnv;
    return cache(intExpr, ret);
}
 
Example #10
Source File: Skolemizer.java    From org.alloytools.alloy with Apache License 2.0 6 votes vote down vote up
/**
 * @see kodkod.ast.visitor.AbstractReplacer#visit(kodkod.ast.Comprehension)
 */
@Override
public final Expression visit(Comprehension expr) {
    Expression ret = lookup(expr);
    if (ret != null)
        return ret;
    final Environment<Expression,Expression> oldRepEnv = repEnv; // skolemDepth
                                                                // < 0
                                                                // at
                                                                // this
                                                                // point
    final Decls decls = visit(expr.decls());
    final Formula formula = expr.formula().accept(this);
    ret = (decls == expr.decls() && formula == expr.formula()) ? expr : formula.comprehension(decls);
    repEnv = oldRepEnv;
    return cache(expr, ret);
}
 
Example #11
Source File: FOL2BoolTranslator.java    From kodkod with MIT License 6 votes vote down vote up
/**
 * Translates the given universally quantified formula as follows 
 * (where A_0...A_|A| stand for boolean variables that represent the 
 * tuples of the expression A, etc.):
 * let quantFormula = "all a: A, b: B, ..., x: X | F(a, b, ..., x)" |
 *     (A_0 && B_0 && ... && X_0 => translate(F(A_0, B_0, ..., X_0))) && ... && 
 *     (A_|A| && B_|B| && ... && X_|X| => translate(F(A_|A|, B_|B|, ..., X_|X|))
 * @param decls formula 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.FALSE initially
 * @param acc the accumulator that contains the top level conjunction; should be an empty AND accumulator initially
 * @ensures the given accumulator contains the translation of the formula "all decls | formula"
 */
private void all(Decls decls, Formula formula, int currentDecl, BooleanValue declConstraints, BooleanAccumulator acc) {
	if (acc.isShortCircuited()) return;
	final BooleanFactory factory = interpreter.factory();

	if (decls.size()==currentDecl) {
		acc.add(factory.or(declConstraints, formula.accept(this)));
		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);
		all(decls, formula, currentDecl+1, factory.or(factory.not(entry.value()), declConstraints), acc);
		groundValue.set(entry.index(), BooleanConstant.FALSE);	
	}
	env = env.parent();
	
}
 
Example #12
Source File: FOL2BoolTranslator.java    From kodkod with MIT License 6 votes vote down vote up
/**
 * Translates the given existentially quantified formula as follows 
 * (where A_0...A_|A| stand for boolean variables that represent the 
 * tuples of the expression A, etc.):
 * let quantFormula = "some a: A, b: B, ..., x: X | F(a, b, ..., x)" |
 *     (A_0 && B_0 && ... && X_0 && translate(F(A_0, B_0, ..., X_0))) || ... || 
 *     (A_|A| && B_|B| && ... && X_|X| && translate(F(A_|A|, B_|B|, ..., X_|X|))
 * @param decls formula 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 acc the accumulator that contains the top level conjunction; should be an empty OR accumulator initially
 * @ensures the given accumulator contains the translation of the formula "some decls | formula"
 */
private void some(Decls decls, Formula formula, int currentDecl, BooleanValue declConstraints, BooleanAccumulator acc) {
	if (acc.isShortCircuited()) return;
	final BooleanFactory factory = interpreter.factory();

	if (decls.size()==currentDecl) {
		acc.add(factory.and(declConstraints, formula.accept(this)));
		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);
		some(decls, formula, currentDecl+1, factory.and(entry.value(), declConstraints), acc);
		groundValue.set(entry.index(), BooleanConstant.FALSE);	
	}
	env = env.parent();

}
 
Example #13
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 #14
Source File: Sudoku.java    From kodkod with MIT License 6 votes vote down vote up
/**
 * Returns a slightly different version of the rules that yields
 * better performance than {@linkplain #rules()}.
 * @return rules of the game
 */
public final Formula fastRules() { 
	final List<Formula> rules = new ArrayList<Formula>(3+region.length*region.length);

	final Variable x = Variable.unary("x"), y = Variable.unary("y");
	final Decls decls = x.oneOf(number).and(y.oneOf(number));

	rules.add( grid(x,y).one().forAll(decls) );
	rules.add( grid(x,y).intersection(grid(x, number.difference(y))).no().forAll(decls) );	
	rules.add( grid(x,y).intersection(grid(number.difference(x), y)).no().forAll(decls) );

	for(Relation rx : region) { 
		for(Relation ry: region) { 
			rules.add( complete(rx, ry) );
		}
	}
	return and(rules); 
}
 
Example #15
Source File: AbstractReplacer.java    From org.alloytools.alloy with Apache License 2.0 6 votes vote down vote up
/**
 * Calls lookup(decls) and returns the cached value, if any. If a replacement
 * has not been cached, visits each of the children's variable and expression.
 * If nothing changes, the argument is cached and returned, otherwise a
 * replacement Decls object is cached and returned.
 *
 * @return { d: Decls | d.size = decls.size && all i: [0..d.size) |
 *         d.declarations[i] = decls.declarations[i].accept(delegate) }
 */
@Override
public Decls visit(Decls decls) {
    Decls ret = lookup(decls);
    if (ret != null)
        return ret;

    Decls visitedDecls = null;
    boolean allSame = true;
    for (Decl decl : decls) {
        Decls newDecl = visit(decl);
        if (newDecl != decl)
            allSame = false;
        visitedDecls = (visitedDecls == null) ? newDecl : visitedDecls.and(newDecl);
    }
    ret = allSame ? decls : visitedDecls;
    return cache(decls, ret);
}
 
Example #16
Source File: EvaluatorTest.java    From org.alloytools.alloy with Apache License 2.0 6 votes vote down vote up
public final void testQuantifiedFormula() {

        final Variable p = Variable.unary("p"), q = Variable.unary("q");
        final Decl pdecl = p.oneOf(person), qdecl = q.oneOf(person);
        final Decls pqdecls = pdecl.and(qdecl);
        // all p: Person | some p.spouse = true
        assertTrue(eval(p.join(spouse).some().forAll(pdecl)));
        // all p, q: Person | (p.spouse = q) => ! (q in p.shaken) = true
        assertTrue(eval((p.join(spouse).eq(q).implies(q.in(p.join(shaken)).not()).forAll(pqdecls))));
        // some p: Person | no p.shaken = true
        assertTrue(eval(p.join(shaken).no().forSome(pdecl)));
        // all p: Person | some q: Person | p.shaken = q = false
        assertFalse(eval((p.join(shaken).eq(q).forSome(qdecl)).forAll(pdecl)));
        // some p, q: Person | !(p = q) && (p.shaken = q.shaken) = true
        assertTrue(eval(p.eq(q).not().and(p.join(shaken).eq(q.join(shaken))).forSome(pqdecls)));
        // some p: Person | all q: Person-p | p in q.shaken = false
        assertFalse(eval((p.in(q.join(shaken)).forAll(q.oneOf(person.difference(p)))).forSome(pdecl)));
    }
 
Example #17
Source File: EvaluatorTest.java    From kodkod with MIT License 6 votes vote down vote up
@Test
public final void testQuantifiedFormula() {

	final Variable p = Variable.unary("p"), q = Variable.unary("q");
	final Decl pdecl = p.oneOf(person), qdecl = q.oneOf(person);
	final Decls pqdecls = pdecl.and(qdecl);
	// all p: Person | some p.spouse                            = true
	assertTrue(eval(p.join(spouse).some().forAll(pdecl)));
	// all p, q: Person | (p.spouse = q) => ! (q in p.shaken)   = true
	assertTrue(eval((p.join(spouse).eq(q).implies(q.in(p.join(shaken)).not()).forAll(pqdecls))));
	// some p: Person | no p.shaken                             = true
	assertTrue(eval(p.join(shaken).no().forSome(pdecl)));
	// all p: Person | some q: Person | p.shaken = q            = false
	assertFalse(eval((p.join(shaken).eq(q).forSome(qdecl)).forAll(pdecl)));
	// some p, q: Person | !(p = q) && (p.shaken = q.shaken)    = true
	assertTrue(eval(p.eq(q).not().and(p.join(shaken).eq(q.join(shaken))).forSome(pqdecls)));
	// some p: Person | all q: Person-p | p in q.shaken         = false
	assertFalse(eval((p.in(q.join(shaken)).forAll(q.oneOf(person.difference(p)))).forSome(pdecl)));
}
 
Example #18
Source File: NUM378.java    From kodkod with MIT License 5 votes vote down vote up
private final Decls decls(Variable[] vars) {
	Decls d = vars[0].oneOf(UNIV);
	for(int i = 1; i < vars.length; i++) {
		d = d.and(vars[i].oneOf(UNIV));
	}
	return d;
}
 
Example #19
Source File: FormulaFlattener.java    From kodkod with MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 * @see kodkod.ast.visitor.AbstractVoidVisitor#visit(kodkod.ast.QuantifiedFormula)
 */
public final void visit(QuantifiedFormula qf) {
	if (visited(qf)) return;
	
	if (breakupQuantifiers) {
		
		final Quantifier quant = qf.quantifier();
		
		if ((!negated && quant==ALL) || (negated && quant==SOME)) { // may break down further
			final Map<Formula, Node> oldConjuncts = conjuncts;
			conjuncts = new LinkedHashMap<Formula, Node>();
			qf.formula().accept(this);
			if (conjuncts.size()>1) { // was broken down further
				final Decls decls = qf.decls();
				for(Map.Entry<Formula, Node> entry : conjuncts.entrySet()) { 
					oldConjuncts.put(entry.getKey().forAll(decls), entry.getValue());
				}
				conjuncts = oldConjuncts;
				return;
			} else { // wasn't broken down further
				conjuncts = oldConjuncts;
			}
		} // won't break down further
	} 

	addConjunct(qf);
	
}
 
Example #20
Source File: PrettyPrinter.java    From kodkod with MIT License 5 votes vote down vote up
/** 
 * @ensures this.tokens' = 
 *   concat[ this.tokens, tokenize[ node.declarations[0] ], ",", 
 *    ..., tokenize[ node.declarations[ node.size() - 1 ] ] ] 
 **/
public void visit(Decls node) {
	Iterator<Decl> decls = node.iterator();
	decls.next().accept(this);
	while(decls.hasNext()) { 
		comma();
		decls.next().accept(this);
	}
}
 
Example #21
Source File: AnnotatedNode.java    From kodkod with MIT License 5 votes vote down vote up
/**
 * Visits the given comprehension, quantified formula, or sum expression.  
 * The method returns TRUE if the creator body contains any 
 * variable not bound by the decls; otherwise returns FALSE.  
 */
private Boolean visit(Node creator, Decls decls, Node body) {
	Boolean ret = lookup(creator);
	if (ret!=null) return ret;
	boolean retVal = false;
	for(Decl decl : decls) {
		retVal = decl.expression().accept(this) || retVal;
		varsInScope.push(decl.variable());
	}
	retVal = ((Boolean)body.accept(this)) || retVal;
	for(int i = decls.size(); i > 0; i--) {
		varsInScope.pop();
	}
	return cache(creator, retVal);
}
 
Example #22
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 #23
Source File: FOL2BoolTranslator.java    From kodkod with MIT License 5 votes vote down vote up
/** 
 * Calls lookup(decls) and returns the cached value, if any.  
 * If a translation has not been cached, translates decls into a list
 * of translations of its children,
 * calls cache(...) on it and returns it.
 * @return let t = lookup(decls) | 
 *   some t => t, cache(decl, decls.declarations.expression.accept(this))
 */
public final List<BooleanMatrix> visit(Decls decls) {
	List<BooleanMatrix> ret = lookup(decls);
	if (ret!=null) return ret;
	ret = new ArrayList<BooleanMatrix>(decls.size());
	for(Decl decl : decls) {
		ret.add(visit(decl));
	}
	return cache(decls, ret);
}
 
Example #24
Source File: AbstractReplacer.java    From kodkod with MIT License 5 votes vote down vote up
/** 
 * Calls lookup(comprehension) 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: Comprehension | c.declarations = comprehension.declarations.accept(this) &&
 *                              c.formula = comprehension.formula.accept(this) }
 */
public Expression visit(Comprehension comprehension) {
	Expression ret = lookup(comprehension);
	if (ret!=null) return ret;
	
	final Decls decls = (Decls)comprehension.decls().accept(this);
	final Formula formula = comprehension.formula().accept(this);
	ret = (decls==comprehension.decls() && formula==comprehension.formula()) ? 
		  comprehension : formula.comprehension(decls); 
	return cache(comprehension,ret);
}
 
Example #25
Source File: Toughnut.java    From kodkod with MIT License 5 votes vote down vote up
/**
 * Returns the covering predicate.  Note that we don't 
 * need to specify the first two lines of the predicate,
 * since they can be expressed as bounds constraints.
 * @return the covering predicate
 */
public Formula checkBelowTooDoublePrime() {
	final Variable x = Variable.unary("x");
	final Variable y = Variable.unary("y");
	final Decls d = x.oneOf(Cell).and(y.oneOf(Cell));
	final Expression xy = y.join(x.join(covered));
	// covering relation is symmetric
	Formula symm = xy.product(x.product(y)).in(covered).forAll(d);
	// each pair of cells on the board should be covered
	// by a domino, which also covers ONE of its neighbors
	Expression xNeighbors = (prev(x).union(next(x))).product(y);
	Expression yNeighbors = x.product(prev(y).union(next(y)));
	Formula covering = (xy.one().and(xy.in(xNeighbors.union(yNeighbors)))).forAll(d);
	return symm.and(covering);
}
 
Example #26
Source File: Viktor.java    From kodkod with MIT License 5 votes vote down vote up
/**
 * Returns the equations to be satisfied.
 * @return equations to be satisfied.
 */
public final Formula equations() {
	
	// each b <= cols-1
	Formula f0 = Formula.TRUE;
	final IntConstant colConst = IntConstant.constant(cols-1);
	for(IntExpression bi: b) {
		f0 = f0.and(bi.lte(colConst));
	}
	
	final Variable[] y = new Variable[rows];
	for(int i = 0; i < rows; i++) {
		y[i] = Variable.unary("y"+i);
	}
	
	Decls decls = y[0].oneOf(INTS);
	for(int i = 1; i < rows; i++)
		decls = decls.and(y[i].oneOf(INTS));
	
	Formula f1 = Formula.TRUE;
	final Expression[] combo = new Expression[rows];
	for(int i = 0; i < cols; i++) {
		for(int j = i+1; j < cols; j++) {
			for(int k = j+1; k < cols; k++) {
				Formula f2 = Formula.TRUE;
				for(int m = 0; m < rows; m++) {
					combo[0] = a[m][i];
					combo[1] = a[m][j];
					combo[2] = a[m][k];
					f2 = f2.and(conditionalSum(combo, y, 0, rows-1).eq(b[m]));
				}
				f1 = f1.and(f2.not().forAll(decls));
			}
		}
	}
	return f0.and(f1); 
}
 
Example #27
Source File: OverflowTheoremTest.java    From org.alloytools.alloy with Apache License 2.0 5 votes vote down vote up
/**
 * all a, b: set univ | no a & b && some a => #(a + b) > #b
 */
@Test
public void testCardinality4() {
    Variable a = Variable.unary("a");
    Variable b = Variable.unary("b");
    Decls dcls = a.setOf(Expression.UNIV).and(b.setOf(Expression.UNIV));
    Formula pre = a.some().and(a.intersection(b).no());
    Formula post = a.union(b).count().gt(b.count());
    checkTrue(pre, post, dcls);
}
 
Example #28
Source File: TranslateAlloyToKodkod.java    From org.alloytools.alloy with Apache License 2.0 5 votes vote down vote up
private Decls am(final Expression a, Decls d, int i, Variable v) {
    Expression colType;
    if (a.arity() == 1) {
        assert i == 1;
        colType = a;
    } else {
        // colType = a.project(IntConstant.constant(i - 1))); //UNSOUND
        colType = Expression.UNIV;
    }
    return (d == null) ? v.oneOf(colType) : d.and(v.oneOf(colType));
}
 
Example #29
Source File: BoundsComputer.java    From org.alloytools.alloy with Apache License 2.0 5 votes vote down vote up
/**
 * Helper method that returns the constraint that the sig has exactly "n"
 * elements, or at most "n" elements
 */
private Formula size(Sig sig, int n, boolean exact) {
    Expression a = sol.a2k(sig);
    if (n <= 0)
        return a.no();
    if (n == 1)
        return exact ? a.one() : a.lone();
    Formula f = exact ? Formula.TRUE : null;
    Decls d = null;
    Expression sum = null;
    while (n > 0) {
        n--;
        Variable v = Variable.unary("v" + Integer.toString(TranslateAlloyToKodkod.cnt++));
        kodkod.ast.Decl dd = v.oneOf(a);
        if (d == null)
            d = dd;
        else
            d = dd.and(d);
        if (sum == null)
            sum = v;
        else {
            if (f != null)
                f = v.intersection(sum).no().and(f);
            sum = v.union(sum);
        }
    }
    if (f != null)
        return sum.eq(a).and(f).forSome(d);
    else
        return a.no().or(sum.eq(a).forSome(d));
}
 
Example #30
Source File: OverflowTheoremTest.java    From org.alloytools.alloy with Apache License 2.0 5 votes vote down vote up
/**
 * all a, b: set univ | a in b => #a <= #b
 */
@Test
public void testCardinality3() {
    Variable a = Variable.unary("a");
    Variable b = Variable.unary("b");
    Decls dcls = a.setOf(Expression.UNIV).and(b.setOf(Expression.UNIV));
    Formula pre = a.in(b);
    Formula post = a.count().lte(b.count());
    checkTrue(pre, post, dcls);
}