use of edu.mit.csail.sdg.alloy4.Pair in project org.alloytools.alloy by AlloyTools.
the class SimInstance method validate.
/**
* Checks whether this instance satisfies every fact defined in the given model.
*
* @param world - this must be the root of the Alloy model
* @return an empty String if yes, nonempty String if no
*/
public String validate(Module world) {
try {
for (Sig s : world.getAllReachableSigs()) if (!s.builtin) {
if (s.isLone != null && !(visit(s).longsize() <= 1))
return "There can be at most one " + s;
if (s.isOne != null && !(visit(s).longsize() == 1))
return "There must be exactly one " + s;
if (s.isSome != null && !(visit(s).longsize() >= 1))
return "There must be at least one " + s;
if (s instanceof SubsetSig) {
SubsetSig p = (SubsetSig) s;
Expr sum = null;
for (Sig par : p.parents) sum = par.plus(sum);
if (p.exact) {
if (!equal(s, sum))
return "Sig " + s + " must be equal to the union of its parents " + p.parents;
} else {
if (!isIn(s, sum))
return "Sig " + s + " must be equal or subset of its parents " + p.parents;
}
} else if (s != Sig.UNIV && s != Sig.NONE) {
PrimSig p = (PrimSig) s;
if (!isIn(s, p.parent))
return "Sig " + s + " must be equal or subset of its parent " + p.parent;
}
if (s.isAbstract != null) {
Expr sum = null;
for (Sig x : ((PrimSig) s).children()) sum = x.plus(sum);
if (sum != null && !equal(s, sum))
return "Abstract sig " + s + " must be equal to the union of its subsigs";
}
for (Decl d : s.getFieldDecls()) for (ExprHasName f : d.names) if (!((Field) f).defined) {
if (!cform(s.decl.get().join(f).in(d.expr).forAll(s.decl))) {
return "Field " + f + " violated its bound: " + visit((Field) f) + "\n" + d.expr;
}
SimTupleset setS = visit(s);
SimTupleset setF = visit((Field) f);
for (SimAtom x : setF.getAllAtoms(0)) if (!setS.has(x))
return "Field " + f + " first column has extra atom: " + setF + " not in " + setS;
}
for (Decl d : s.getFieldDecls()) {
if (d.disjoint != null && d.names.size() > 0) {
if (!cform(ExprList.makeDISJOINT(null, null, d.names)))
return "Fields must be disjoint.";
}
if (d.disjoint2 != null)
for (ExprHasName f : d.names) {
Decl that = s.oneOf("that");
Expr formula = s.decl.get().equal(that.get()).not().implies(s.decl.get().join(f).intersect(that.get().join(f)).no());
if (!cform(formula.forAll(that).forAll(s.decl)))
return "Fields must be disjoint.";
}
}
for (Expr f : s.getFacts()) {
if (!cform(f.forAll(s.decl))) {
f = f.deNOP();
if (f instanceof ExprUnary) {
ExprUnary u = (ExprUnary) f;
f = u.sub.deNOP();
if (f instanceof ExprBinary) {
ExprBinary b = (ExprBinary) f;
if (b.op == ExprBinary.Op.JOIN && b.left.isSame(s.decl.get()) && b.right.deNOP() instanceof Field) {
String n = ((Field) (b.right.deNOP())).label;
if (u.op == ExprUnary.Op.SOME)
return "The " + n + " cannot be empty.";
if (u.op == ExprUnary.Op.LONE)
return "The " + n + " cannot have more than one value.";
if (u.op == ExprUnary.Op.ONE)
return "The " + n + " must have exactly one value.";
if (u.op == ExprUnary.Op.NO)
return "The " + n + " must be empty.";
}
}
}
return "Cannot violate a consistency constraint";
}
}
}
for (Module m : world.getAllReachableModules()) for (Pair<String, Expr> f : m.getAllFacts()) if (!cform(f.b)) {
String err = f.a;
if (err.matches("^fact\\$[0-9][0-9]*"))
err = f.b.toString();
if (err.length() >= 2 && err.startsWith("\"") && err.endsWith("\""))
err = err.substring(1, err.length() - 1);
return "Violation: " + err;
}
return "";
} catch (Err ex) {
return "An internal error has occured:\n" + ex.dump();
}
}
use of edu.mit.csail.sdg.alloy4.Pair in project org.alloytools.alloy by AlloyTools.
the class CompModule method resolveMeta.
// ============================================================================================================================//
private static void resolveMeta(final CompModule root) throws Err {
// Now, add the meta sigs and fields if needed
Map<Sig, PrimSig> sig2meta = new LinkedHashMap<Sig, PrimSig>();
Map<Field, PrimSig> field2meta = new LinkedHashMap<Field, PrimSig>();
boolean hasMetaSig = false, hasMetaField = false;
root.new2old.put(root.metaSig, root.metaSig);
root.sigs.put(base(root.metaSig), root.metaSig);
root.new2old.put(root.metaField, root.metaField);
root.sigs.put(base(root.metaField), root.metaField);
for (CompModule m : root.allModules) for (Sig s : new ArrayList<Sig>(m.sigs.values())) if (m != root || (s != root.metaSig && s != root.metaField)) {
PrimSig ka = new PrimSig(s.label + "$", root.metaSig, Attr.ONE, PRIVATE.makenull(s.isPrivate), Attr.META);
sig2meta.put(s, ka);
ka.addDefinedField(Pos.UNKNOWN, null, Pos.UNKNOWN, "value", s);
m.new2old.put(ka, ka);
m.sigs.put(base(ka), ka);
hasMetaSig = true;
Expr allfields = ExprConstant.EMPTYNESS;
for (Field field : s.getFields()) {
Pos priv = field.isPrivate;
if (priv == null)
priv = s.isPrivate;
PrimSig kb = new PrimSig(s.label + "$" + field.label, root.metaField, Attr.ONE, PRIVATE.makenull(priv), Attr.META);
field2meta.put(field, kb);
m.new2old.put(kb, kb);
m.sigs.put(base(kb), kb);
hasMetaField = true;
kb.addDefinedField(Pos.UNKNOWN, null, Pos.UNKNOWN, "value", field);
if (allfields == ExprConstant.EMPTYNESS)
allfields = kb;
else
allfields = allfields.plus(kb);
}
ka.addDefinedField(Pos.UNKNOWN, null, Pos.UNKNOWN, "fields", allfields);
}
for (Map.Entry<Sig, PrimSig> e : sig2meta.entrySet()) {
Expr expr = null;
if ((e.getKey()) instanceof PrimSig) {
PrimSig a = (PrimSig) (e.getKey());
if (a.parent != null && a.parent != UNIV)
expr = sig2meta.get(a.parent);
}
e.getValue().addDefinedField(Pos.UNKNOWN, null, Pos.UNKNOWN, "parent", (expr == null ? ExprConstant.EMPTYNESS : expr));
}
for (Map.Entry<Sig, PrimSig> e : sig2meta.entrySet()) {
Sig s = e.getKey();
PrimSig s2 = e.getValue();
Expr allfields = ExprConstant.EMPTYNESS;
for (Field f : s.getFields()) {
PrimSig metaF = field2meta.get(f);
if (allfields == ExprConstant.EMPTYNESS)
allfields = metaF;
else
allfields = allfields.plus(metaF);
}
if (s instanceof PrimSig)
for (Sig c : (((PrimSig) s).descendents())) for (Field f : c.getFields()) {
PrimSig metaF = field2meta.get(f);
if (allfields == ExprConstant.EMPTYNESS)
allfields = metaF;
else
allfields = allfields.plus(metaF);
}
s2.addDefinedField(Pos.UNKNOWN, null, Pos.UNKNOWN, "subfields", allfields);
}
if (hasMetaSig == false)
root.facts.add(new Pair<String, Expr>("sig$fact", root.metaSig.no().and(root.metaField.no())));
else if (hasMetaField == false)
root.facts.add(new Pair<String, Expr>("sig$fact", root.metaField.no()));
}
use of edu.mit.csail.sdg.alloy4.Pair in project org.alloytools.alloy by AlloyTools.
the class SimpleGUI method doVisualize.
/**
* This method displays a particular instance or message.
*/
@SuppressWarnings("unchecked")
Runner doVisualize(String arg) {
if (wrap)
return wrapMe(arg);
text.clearShade();
if (arg.startsWith("MSG: ")) {
// MSG: message
OurDialog.showtext("Detailed Message", arg.substring(5));
}
if (arg.startsWith("CORE: ")) {
// CORE: filename
String filename = Util.canon(arg.substring(6));
Pair<Set<Pos>, Set<Pos>> hCore;
// Set<Pos> lCore;
InputStream is = null;
ObjectInputStream ois = null;
try {
is = new FileInputStream(filename);
ois = new ObjectInputStream(is);
hCore = (Pair<Set<Pos>, Set<Pos>>) ois.readObject();
// lCore = (Set<Pos>) ois.readObject();
} catch (Throwable ex) {
log.logRed("Error reading or parsing the core \"" + filename + "\"\n");
return null;
} finally {
Util.close(ois);
Util.close(is);
}
text.clearShade();
text.shade(hCore.b, subCoreColor, false);
text.shade(hCore.a, coreColor, false);
// shade again, because if not all files were open, some shadings
// will have no effect
text.shade(hCore.b, subCoreColor, false);
text.shade(hCore.a, coreColor, false);
}
if (arg.startsWith("POS: ")) {
// POS: x1 y1 x2 y2 filename
Scanner s = new Scanner(arg.substring(5));
int x1 = s.nextInt(), y1 = s.nextInt(), x2 = s.nextInt(), y2 = s.nextInt();
String f = s.nextLine();
if (f.length() > 0 && f.charAt(0) == ' ')
// Get rid of the space after Y2
f = f.substring(1);
Pos p = new Pos(Util.canon(f), x1, y1, x2, y2);
text.shade(p);
}
if (arg.startsWith("CNF: ")) {
// CNF: filename
String filename = Util.canon(arg.substring(5));
try {
String text = Util.readAll(filename);
OurDialog.showtext("Text Viewer", text);
} catch (IOException ex) {
log.logRed("Error reading the file \"" + filename + "\"\n");
}
}
if (arg.startsWith("XML: ")) {
// XML: filename
viz.loadXML(Util.canon(arg.substring(5)), false);
}
return null;
}
use of edu.mit.csail.sdg.alloy4.Pair in project org.alloytools.alloy by AlloyTools.
the class SimpleCLI method main.
public static void main(String[] args) throws Exception {
final boolean sat4j = "yes".equals(System.getProperty("sat4j"));
final boolean minisat = "yes".equals(System.getProperty("minisat"));
SatSolver solver = A4Options.SatSolver.make("mem", "mem", "/zweb/sat/mem");
final SimpleReporter rep = new SimpleReporter();
final StringBuilder sb = rep.sb;
for (String filename : args) {
try {
// Parse+Typecheck
rep.sb.append("\n\nMain file = " + filename + "\n");
if (db)
db("Parsing+Typechecking...");
Module world = CompUtil.parseEverything_fromFile(rep, null, filename);
if (db)
db(" ok\n");
List<Command> cmds = world.getAllCommands();
for (ErrorWarning msg : rep.warnings) rep.sb.append("Relevance Warning:\n" + (msg.toString().trim()) + "\n\n");
rep.warnings.clear();
// Do a detailed dump if we will not be executing the commands
if (args.length != 1) {
for (Module m : world.getAllReachableModules()) {
for (Sig x : m.getAllSigs()) {
sb.append("\nSig ").append(x.label).append(" at position ").append(x.pos).append("\n");
for (Decl d : x.getFieldDecls()) for (ExprHasName f : d.names) {
sb.append("\nField ").append(f.label).append(" with type ").append(f.type()).append("\n");
d.expr.toString(sb, 2);
}
rep.flush();
}
for (Func x : m.getAllFunc()) {
sb.append("\nFun/pred ").append(x.label).append(" at position ").append(x.pos).append("\n");
for (Decl d : x.decls) for (ExprHasName v : d.names) {
v.toString(sb, 2);
d.expr.toString(sb, 4);
}
x.returnDecl.toString(sb, 2);
x.getBody().toString(sb, 4);
rep.flush();
}
for (Pair<String, Expr> x : m.getAllFacts()) {
sb.append("\nFact ").append(x.a).append("\n");
x.b.toString(sb, 4);
rep.flush();
}
for (Pair<String, Expr> x : m.getAllAssertions()) {
sb.append("\nAssertion ").append(x.a).append("\n");
x.b.toString(sb, 4);
rep.flush();
}
if (m == world)
for (Command x : m.getAllCommands()) {
sb.append("\nCommand ").append(x.label).append("\n");
x.formula.toString(sb, 4);
rep.flush();
}
}
continue;
}
// Validate the metamodel generation code
StringWriter metasb = new StringWriter();
PrintWriter meta = new PrintWriter(metasb);
Util.encodeXMLs(meta, "\n<alloy builddate=\"", Version.buildDate(), "\">\n\n");
A4SolutionWriter.writeMetamodel(world.getAllReachableSigs(), filename, meta);
Util.encodeXMLs(meta, "\n</alloy>");
meta.flush();
metasb.flush();
String metaxml = metasb.toString();
A4SolutionReader.read(new ArrayList<Sig>(), new XMLNode(new StringReader(metaxml)));
StaticInstanceReader.parseInstance(new StringReader(metaxml));
// Okay, now solve the commands
A4Options options = new A4Options();
options.originalFilename = filename;
options.solverDirectory = "/zweb/zweb/tmp/alloy4/x86-freebsd";
options.solver = sat4j ? A4Options.SatSolver.SAT4J : (minisat ? A4Options.SatSolver.MiniSatJNI : solver);
for (int i = 0; i < cmds.size(); i++) {
Command c = cmds.get(i);
if (db) {
String cc = c.toString();
if (cc.length() > 60)
cc = cc.substring(0, 55);
db("Executing " + cc + "...\n");
}
rep.sb.append("Executing \"" + c + "\"\n");
options.skolemDepth = 0;
A4Solution s = TranslateAlloyToKodkod.execute_commandFromBook(rep, world.getAllReachableSigs(), c, options);
if (s.satisfiable()) {
validate(s);
if (s.isIncremental()) {
s = s.next();
if (s.satisfiable())
validate(s);
}
}
options.skolemDepth = 2;
s = TranslateAlloyToKodkod.execute_commandFromBook(rep, world.getAllReachableSigs(), c, options);
if (s.satisfiable()) {
validate(s);
if (s.isIncremental()) {
s = s.next();
if (s.satisfiable())
validate(s);
}
}
}
} catch (Throwable ex) {
rep.sb.append("\n\nException: " + ex);
}
if (db) {
if (args.length != 1)
db(" ERROR!\n");
else
db("\n\n");
}
}
rep.close();
}
use of edu.mit.csail.sdg.alloy4.Pair in project org.alloytools.alloy by AlloyTools.
the class VizTree method convertValueToText.
/**
* {@inheritDoc}
*/
@Override
public String convertValueToText(Object val, boolean selected, boolean expanded, boolean leaf, int row, boolean focus) {
String c = ">";
if (onWindows)
c = selected ? " style=\"color:#ffffff;\">" : " style=\"color:#000000;\">";
if (val instanceof A4Solution)
return "<html> <b" + c + encode(title == null ? "" : title) + "</b></html>";
if (val instanceof Sig) {
String label = ((Sig) val).label;
if (label.startsWith("this/"))
label = label.substring(5);
return "<html> <b" + c + "sig " + encode(label) + "</b></html>";
}
if (val instanceof ExprVar)
return "<html> <b" + c + "set " + encode(((ExprVar) val).label) + "</b></html>";
if (val instanceof String)
return "<html> <span" + c + encode((String) val) + "</span></html>";
if (val instanceof Pair)
return "<html> <b" + c + "field " + encode(((ExprHasName) (((Pair<?, ?>) val).b)).label) + "</b></html>";
if (val instanceof A4Tuple) {
StringBuilder sb = new StringBuilder("<html> <span" + c);
A4Tuple tp = (A4Tuple) val;
for (int i = 1; i < tp.arity(); i++) {
if (i > 1)
sb.append(" -> ");
sb.append(encode(tp.atom(i)));
}
sb.append("</span></html>");
return sb.toString();
}
return "";
}
Aggregations