001package org.clafer.alloy.solve; 002 003import edu.mit.csail.sdg.alloy4.Err; 004import java.io.IOException; 005import java.nio.charset.StandardCharsets; 006import java.nio.file.Files; 007import java.nio.file.Path; 008import java.util.ArrayList; 009import java.util.HashMap; 010import java.util.HashSet; 011import java.util.LinkedHashMap; 012import java.util.List; 013import java.util.Map; 014import java.util.Optional; 015import java.util.Set; 016import java.util.TreeMap; 017import java.util.function.Supplier; 018import java.util.function.UnaryOperator; 019import org.clafer.alloy.AlloyGenerator; 020import org.clafer.alloy.solve.Constraints.ClaferInfo; 021import org.clafer.alloy.solve.Constraints.Constraint; 022import org.clafer.alloy.solve.Constraints.ConstraintInfo; 023import org.clafer.alloy.solve.Constraints.ExactCardinalityConstraint; 024import org.clafer.alloy.solve.Constraints.LowerCardinalityConstraint; 025import org.clafer.alloy.solve.Constraints.Range; 026import org.clafer.alloy.solve.Constraints.UpperCardinalityConstraint; 027import org.clafer.alloy.solve.Constraints.UserConstraint; 028import org.clafer.frontend.Symbols.ClaferSymbol; 029import org.clafer.frontend.ToIr; 030import org.clafer.ig.Backend; 031import org.clafer.ig.Repl; 032import org.clafer.ig.Solution; 033import org.clafer.ig.SolutionView; 034 035/** 036 * The Alloy backend of the solution loop, for a temporal model: claferIG's 037 * {@code ClaferIG.hs}, and its commands of {@code CommandLine.hs}, on an 038 * {@link AlloySession} in this JVM. The model is translated by the 039 * frontend's port of the compiler's AlloyLtl generator, with {@code -k}, as 040 * claferIG has the compiler translate it; the code is given to Alloy in 041 * memory. 042 */ 043public final class AlloyBackend implements Backend { 044 045 /** 046 * What claferIG takes from its command line. 047 * 048 * @param bitwidth {@code --bitwidth}, 4 by default 049 * @param useUids {@code --useuids} 050 * @param addTypes {@code --addtypes} 051 */ 052 public record Options(int bitwidth, boolean useUids, boolean addTypes) { 053 054 public static final Options Default = new Options(4, false, false); 055 } 056 057 /** 058 * Reads the model again ({@code r}), with the errors of the model as the 059 * messages of an exception. 060 */ 061 @FunctionalInterface 062 public interface Loader { 063 064 ToIr.Result load() throws Exception; 065 } 066 067 private final Loader loader; 068 private final Options options; 069 private final String modelFileName; 070 private final AlloySession session = new AlloySession(); 071 // the environment of the model, ClaferIGEnv 072 private ToIr.Result ir; 073 private AlloyGenerator.Translation translation; 074 private List<Constraint> constraints; 075 private AlloyXml.Naming naming; 076 private Map<String, String> alloyNames; 077 private Map<String, String> uids; 078 private Map<String, ClaferInfo> claferInfos; 079 private Set<String> emptySigs; 080 private Map<String, List<String>> paths; 081 private int bitwidth; 082 private boolean dynamic; 083 // AlloyIGInterface's AlloyIGEnv 084 private final Map<String, AlloySession.SigInfo> sigMap = new TreeMap<>(); 085 private final Map<String, Integer> scopes = new TreeMap<>(); 086 private int globalScope; 087 088 /** 089 * Loads the model, as claferIG's {@code load} does. 090 * 091 * @param modelFileName the name of the model's file, which names the 092 * saved files 093 */ 094 public AlloyBackend(Loader loader, String modelFileName, Options options) throws Exception { 095 this.loader = loader; 096 this.modelFileName = modelFileName; 097 this.options = options; 098 this.bitwidth = options.bitwidth(); 099 load(); 100 } 101 102 private void load() throws Exception { 103 ir = loader.load(); 104 translation = AlloyGenerator.translate(ir.model(), ir.scopes().orElseThrow().clafers(), 105 ir.model().options().traceLength().orElse(10)); 106 // the integer range of the options (--maxint, --minint) raises the bitwidth 107 int bw = bitwidth; 108 var o = ir.files().options(); 109 if (o.maxInt().isPresent()) { 110 bw = Math.max(bw, requiredBitwidth(o.maxInt().getAsLong())); 111 } 112 if (o.minInt().isPresent()) { 113 bw = Math.max(bw, requiredBitwidth(-o.minInt().getAsLong() - 1)); 114 } 115 alloyNames = new HashMap<>(translation.alloyNames()); 116 uids = new HashMap<>(); 117 alloyNames.forEach((u, a) -> uids.put(a, u)); 118 claferInfos = new HashMap<>(); 119 Map<String, AlloyXml.ClaferInfo> namingInfos = new HashMap<>(); 120 paths = new LinkedHashMap<>(); 121 for (ClaferSymbol c : ir.names().clafers()) { 122 String a = alloyName(c.uid()); 123 var card = c.card(); 124 claferInfos.put(a, new ClaferInfo(c.name(), new Constraints.Cardinality(card.low(), card.high()))); 125 String reference = c.reference().flatMap(r -> r.primitive()).orElse(null); 126 namingInfos.put(a, new AlloyXml.ClaferInfo(c.name(), 127 c.superClafer().map(s -> alloyName(s.uid())).orElse(null), reference)); 128 List<String> path = new ArrayList<>(); 129 for (Optional<ClaferSymbol> p = Optional.of(c); p.isPresent(); p = p.get().parent()) { 130 path.add(0, p.get().name()); 131 } 132 paths.put(c.uid(), path); 133 } 134 naming = new AlloyXml.Naming(namingInfos, this::toUid, options.useUids(), options.addTypes(), 135 translation.strings()); 136 constraints = Constraints.parseConstraints(ir.files(), claferInfos, translation.mapping()); 137 emptySigs = new HashSet<>(); 138 ir.scopes().orElseThrow().clafers().forEach((u, s) -> { 139 if (s == 0) { 140 emptySigs.add("this/" + alloyName(u)); 141 } 142 }); 143 AlloySession.Loaded loaded = session.load(translation.code()); 144 dynamic = session.isDynamic(); 145 sigMap.clear(); 146 scopes.clear(); 147 loaded.sigs().forEach(s -> sigMap.put(s.label(), s)); 148 globalScope = loaded.globalScope(); 149 for (AlloySession.SigInfo s : sigMap.values()) { 150 setScopeCommand(s.label(), s.startingScope().orElse(1)); 151 } 152 setBitwidth(bw); 153 } 154 155 private String alloyName(String uid) { 156 return alloyNames.getOrDefault(uid, uid); 157 } 158 159 private String toUid(String alloyName) { 160 return uids.getOrDefault(alloyName, alloyName); 161 } 162 163 // ---------------------------------------------------------------------- 164 // AlloyIGInterface 165 // ---------------------------------------------------------------------- 166 private static boolean withinRange(int scope, String multiplicity) { 167 return switch (multiplicity) { 168 case "One" -> scope == 1; 169 case "Lone" -> scope == 0 || scope == 1; 170 case "Some" -> scope >= 1; 171 default -> true; 172 }; 173 } 174 175 // sendSetScopeCommand: the subset sig, if it is one, whose scope is not set 176 private Optional<String> setScopeCommand(String sig, int scope) throws Err { 177 AlloySession.SigInfo info = sigMap.get(sig); 178 if (!info.subset().isEmpty()) { 179 return Optional.of(info.subset()); 180 } 181 if (withinRange(scope, info.multiplicity())) { 182 session.setScope(sig, scope); 183 } 184 scopes.put(sig, scope); 185 return Optional.empty(); 186 } 187 188 private int valueOfScope(String sig) { 189 return scopes.getOrDefault(sig, globalScope); 190 } 191 192 private void setGlobalScope(int scope) { 193 session.setGlobalScope(scope); 194 globalScope = scope; 195 } 196 197 private void setBitwidth(int bw) { 198 bitwidth = bw; 199 session.setBitwidth(bw); 200 } 201 202 // ---------------------------------------------------------------------- 203 // ClaferIG 204 // ---------------------------------------------------------------------- 205 private boolean hasNoInstances(String sig) { 206 return emptySigs.contains(sig); 207 } 208 209 // setAlloyScope: the clafer's name of the subset sig, if it is one 210 private Optional<String> setAlloyScope(int value, String sig) throws Err { 211 return setScopeCommand(sig, hasNoInstances(sig) ? 0 : value).map(this::claferNameOfSig); 212 } 213 214 private String claferNameOfSig(String sig) { 215 String name = sig.startsWith("this/") ? sig.substring(5) : sig; 216 AlloyXml.ClaferInfo info = naming.clafers().get(name); 217 return info == null ? name : info.ident(); 218 } 219 220 private String sigOfUID(String uid) { 221 return "this/" + alloyName(uid); 222 } 223 224 private String uidOfSig(String sig) { 225 return toUid(sig.startsWith("this/") ? sig.substring(5) : sig); 226 } 227 228 /** 229 * {@code getUIDs}: the clafers that a name names. 230 */ 231 private List<String> getUIDs(String qName) { 232 if (paths.containsKey(qName)) { 233 return List.of(qName); 234 } 235 boolean fromRoot; 236 List<String> names; 237 if (qName.startsWith("::")) { 238 fromRoot = true; 239 names = List.of(qName.substring(2).split("::", -1)); 240 } else if (qName.contains("::")) { 241 fromRoot = false; 242 names = List.of(qName.split("::", -1)); 243 } else { 244 List<String> parts = List.of(qName.split("__", -1)); 245 if (parts.size() > 1 && parts.get(0).equals("root")) { 246 fromRoot = true; 247 names = parts.subList(1, parts.size()); 248 } else { 249 fromRoot = false; 250 names = parts; 251 } 252 } 253 if (names.isEmpty() || qName.isEmpty()) { 254 return List.of(); 255 } 256 List<String> out = new ArrayList<>(); 257 paths.forEach((uid, path) -> { 258 if (fromRoot ? path.equals(names) 259 : path.size() >= names.size() && path.subList(path.size() - names.size(), path.size()).equals(names)) { 260 out.add(uid); 261 } 262 }); 263 return out; 264 } 265 266 private Solution toSolution(String xml) { 267 return AlloyXml.toSolution(xml, dynamic, naming); 268 } 269 270 private Shown shown(Optional<String> xml) { 271 return xml.map(x -> new Shown(toSolution(x), x)).orElse(null); 272 } 273 274 private List<Optional<Constraint>> findRemovable(List<int[]> core) { 275 Set<String> absIDs = new HashSet<>(); 276 for (ClaferSymbol c : ir.names().clafers()) { 277 if (c.isAbstract()) { 278 absIDs.add(c.name()); 279 } 280 } 281 List<Optional<Constraint>> out = new ArrayList<>(); 282 for (int[] c : core) { 283 Range r = new Range(c[0], c[1], c[2], c[3]); 284 Optional<Constraint> found = constraints.stream().filter(k -> k.range().equals(r)).findFirst(); 285 if (found.isPresent() && found.get() instanceof UpperCardinalityConstraint u 286 && u.claferInfo().cardinality().lower() == 0 && u.claferInfo().cardinality().upper() == 0 287 && absIDs.contains(u.claferInfo().uniqueId())) { 288 continue; 289 } 290 out.add(found); 291 } 292 return out; 293 } 294 295 private static Optional<Constraint> first(List<Optional<Constraint>> cs) { 296 return cs.stream().filter(Optional::isPresent).map(Optional::get).findFirst(); 297 } 298 299 private static List<Constraint> present(List<Optional<Constraint>> cs) { 300 return cs.stream().filter(Optional::isPresent).map(Optional::get).toList(); 301 } 302 303 /** 304 * {@code next}: the next solution, or the unsat core of the model with a 305 * near-miss, or none. 306 */ 307 @Override 308 public Shown next(Repl.Io io) throws Exception { 309 Optional<String> xml = session.next(); 310 if (xml.isPresent()) { 311 return shown(xml); 312 } 313 session.saveState(); 314 // Generating counterexample modifies the state. If we ever want to 315 // rerun the original model, we need to restore the state. 316 List<int[]> core = session.unsatCore(); 317 List<Constraint> removed = new ArrayList<>(); 318 List<Constraint> unsatCore = null; 319 Shown nearMiss = null; 320 while (true) { 321 Optional<Constraint> remove = first(findRemovable(core)); 322 if (remove.isEmpty()) { 323 // It is possible that none of the constraints are removable 324 break; 325 } 326 Range r = remove.get().range(); 327 session.removeConstraint((int) r.line(), (int) r.column(), (int) r.endLine(), (int) r.endColumn()); 328 session.resolve(); 329 Optional<String> near = session.next(); 330 removed.add(remove.get()); 331 if (near.isPresent()) { 332 unsatCore = present(findRemovable(core)); 333 nearMiss = shown(near); 334 break; 335 } 336 core = session.unsatCore(); 337 } 338 session.restoreState(); 339 if (unsatCore == null) { 340 io.err().println(dynamic 341 ? "No more traces found. Try increasing the scopes or the maximum trace length ('tl') to get more traces (type 'h' for help)." 342 : "No more instances found. Try increasing the scopes to get more instances (type 'h' for help)."); 343 return null; 344 } 345 io.err().println("No instances found."); 346 io.err().println("The following set of constraints cannot be satisfied in the current scope."); 347 io.err().println("Consider removing one of the constraints from the model."); 348 io.err().println("Use the setUnsatCoreMinimization command to minimize the set of constraints below."); 349 io.err().println("Try increasing the scopes to get an instance (type 'h' for help)."); 350 int i = 1; 351 for (Constraint c : unsatCore) { 352 io.err().println(" " + i++ + ") " + printConstraint(c)); 353 } 354 io.err().println("Altering the following constraints produced the following near-miss example:"); 355 printTransformations(io, removed); 356 io.err().flush(); 357 io.out().println(SolutionView.solutionText(nearMiss.solution())); 358 return null; 359 } 360 361 private static String printConstraint(Constraint c) { 362 return switch (c) { 363 case UserConstraint u -> u.constraintInfo().toString(); 364 case ExactCardinalityConstraint e -> e.claferInfo().toString(); 365 case LowerCardinalityConstraint l -> l.claferInfo().toString(); 366 case UpperCardinalityConstraint u -> u.claferInfo().toString(); 367 }; 368 } 369 370 private static ClaferInfo withCard(ClaferInfo info, long lower, long upper) { 371 return new ClaferInfo(info.uniqueId(), new Constraints.Cardinality(lower, upper)); 372 } 373 374 private void printTransformations(Repl.Io io, List<Constraint> cs) { 375 List<Constraint> rest = new ArrayList<>(cs); 376 int i = 1; 377 while (!rest.isEmpty()) { 378 Constraint c = rest.remove(0); 379 String text = switch (c) { 380 case UserConstraint u -> "removed " + u.constraintInfo().syntax(); 381 case ExactCardinalityConstraint e -> e.claferInfo() + " changed to " + withCard(e.claferInfo(), 0, -1); 382 case LowerCardinalityConstraint l -> { 383 ClaferInfo info = l.claferInfo(); 384 // Deleted the lower and upper constraint, or only the lower one 385 yield deleteOther(rest, info, UpperCardinalityConstraint.class) 386 ? info + " changed to " + withCard(info, 0, -1) 387 : info + " changed to " + withCard(info, 0, info.cardinality().upper()); 388 } 389 case UpperCardinalityConstraint u -> { 390 ClaferInfo info = u.claferInfo(); 391 yield deleteOther(rest, info, LowerCardinalityConstraint.class) 392 ? info + " changed to " + withCard(info, 0, -1) 393 : info + " changed to " + withCard(info, info.cardinality().lower(), -1); 394 } 395 }; 396 io.err().println(" " + i++ + ") " + text); 397 } 398 } 399 400 // findAndDelete in the cardinality constraints of the other kind: the rest without the first one of the 401 // same clafer, if any (the rest keeps only that kind, as the compiler's filter gives it) 402 private static boolean deleteOther(List<Constraint> rest, ClaferInfo info, Class<?> kind) { 403 List<Constraint> ofKind = rest.stream().filter(kind::isInstance).toList(); 404 for (int i = 0; i < ofKind.size(); i++) { 405 ClaferInfo other = ofKind.get(i) instanceof LowerCardinalityConstraint l ? l.claferInfo() 406 : ((UpperCardinalityConstraint) ofKind.get(i)).claferInfo(); 407 if (other.uniqueId().equals(info.uniqueId())) { 408 List<Constraint> left = new ArrayList<>(ofKind); 409 left.remove(i); 410 rest.clear(); 411 rest.addAll(left); 412 return true; 413 } 414 } 415 return false; 416 } 417 418 @Override 419 public Shown fork(Repl.Io io, int state) throws Exception { 420 Shown s = shown(session.fork(state)); 421 if (s == null) { 422 io.out().println("No other trace has the states of the last trace before state " + state + "."); 423 } 424 return s; 425 } 426 427 @Override 428 public Shown nextConfiguration(Repl.Io io) throws Exception { 429 Shown s = shown(session.nextConfiguration()); 430 if (s == null) { 431 io.out().println("No solution has another configuration."); 432 } 433 return s; 434 } 435 436 @Override 437 public void check(Repl.Io io, Integer line, Repl.Displayer display) throws Exception { 438 List<String[]> assertions = new ArrayList<>(); 439 List<ConstraintInfo> infos = new ArrayList<>(); 440 List<String> text = Constraints.text(ir.files()); 441 for (AlloyGenerator.Assertion a : translation.assertions()) { 442 ConstraintInfo info = Constraints.constraintInfoOf(ir.files(), text, a.span()); 443 if (line == null || info.isOnLine(line)) { 444 assertions.add(new String[]{a.name()}); 445 infos.add(info); 446 } 447 } 448 if (assertions.isEmpty()) { 449 io.out().println(line == null ? "The model has no assertions." 450 : "The model has no assertion on line " + line + "."); 451 return; 452 } 453 int failed = 0; 454 for (int i = 0; i < assertions.size(); i++) { 455 Optional<String> xml = session.check(assertions.get(i)[0]); 456 if (xml.isEmpty()) { 457 io.out().println("No counterexample: " + infos.get(i)); 458 } else { 459 io.out().println("Counterexample of: " + infos.get(i)); 460 display.display(new Shown(toSolution(xml.get()), xml.get())); 461 failed++; 462 } 463 } 464 String bounds = dynamic ? "the scopes and the maximum trace length" : "the scopes"; 465 io.out().println(assertions.size() + " assertion(s) checked within " + bounds + ": " + failed 466 + " with a counterexample."); 467 } 468 469 // ---------------------------------------------------------------------- 470 // the commands of CommandLine.hs 471 // ---------------------------------------------------------------------- 472 /** 473 * The bitwidth required to store the given integer. 474 */ 475 static int requiredBitwidth(long n) { 476 return (int) Math.ceil(Math.log(2.0 * n + 1) / Math.log(2)); 477 } 478 479 /** 480 * The largest integer allowed by the given bitwidth. 481 */ 482 static long allowedMaxInt(int bw) { 483 return (1L << (bw - 1)) - 1; 484 } 485 486 private static long allowedMinInt(int bw) { 487 return -(allowedMaxInt(bw) + 1); 488 } 489 490 private void printBitwidthIntRange(Repl.Io io, int bw) { 491 io.out().println("Integer range = " + allowedMinInt(bw) + ".." + allowedMaxInt(bw) + " (bitwidth = " + bw 492 + ")"); 493 } 494 495 private void printBitwidthWarning(Repl.Io io, int bw) { 496 if (bw > 9) { 497 io.out().println("Warning! This is a very large bitwidth for Alloy, which may cause slow down."); 498 } 499 } 500 501 /** 502 * {@code findNecessaryBitwidth}. 503 */ 504 private int findNecessaryBitwidth(int oldBw, List<Integer> scopeValues) { 505 long max = Math.max(scopeValues.stream().mapToLong(Integer::longValue).max().orElse(0), translation.maxInt()); 506 int newBw = (int) Math.ceil(Math.log(2.0 * max + 1) / Math.log(2)); 507 return Math.max(newBw, oldBw); 508 } 509 510 private void solve() throws Err { 511 session.resolve(); 512 } 513 514 @Override 515 public void start(Repl.Io io) throws Exception { 516 io.out().println("Compiling the Clafer model..."); 517 prepare(); 518 io.out().println("Type 'h' for the list of available REPL commands\n"); 519 } 520 521 /** 522 * Sets the bitwidth that the scopes need and solves the model, as 523 * {@link #start} does without its messages: before the first 524 * {@link #next}. 525 */ 526 public void prepare() throws Exception { 527 setBitwidth(findNecessaryBitwidth(bitwidth, new ArrayList<>(scopes.values()))); 528 solve(); 529 } 530 531 @Override 532 public boolean isDynamic() { 533 return dynamic; 534 } 535 536 @Override 537 public String prompt() { 538 return "claferIG> "; 539 } 540 541 @Override 542 public int number(Repl.Context context) { 543 return 1 + context.unsavedCount(); 544 } 545 546 @Override 547 public String show(int n, Shown shown) { 548 return SolutionView.showSolution(n, shown.solution()) + "\n"; 549 } 550 551 @Override 552 public UnaryOperator<String> names() { 553 // the least-partially-qualified name is the UID, with dots for the compiler's :: 554 return uid -> uid; 555 } 556 557 @Override 558 public String modelFileName() { 559 return modelFileName; 560 } 561 562 @Override 563 public void quit() { 564 } 565 566 @Override 567 public void unknown(Repl.Io io, String input) { 568 io.out().println("Unhandled command: " + input.trim()); 569 } 570 571 private static Integer integer(String s) { 572 try { 573 return Integer.valueOf(s); 574 } catch (NumberFormatException e) { 575 return null; 576 } 577 } 578 579 private static Integer natural(String s) { 580 Integer n = integer(s); 581 return n != null && n >= 0 && !s.startsWith("+") && !s.startsWith("-") ? n : null; 582 } 583 584 @Override 585 public boolean command(Repl.Io io, String input, List<String> words, Repl.Context context) throws Exception { 586 String name = words.isEmpty() ? "" : words.get(0); 587 int arity = words.size() - 1; 588 switch (name) { 589 case "S", "SetGlobalScope" -> { 590 Integer n = arity == 1 ? natural(words.get(1)) : null; 591 if (n == null) { 592 io.out().println("The format of the command is: 'S <integer>'"); 593 return true; 594 } 595 setGlobalScopeCommand(io, n); 596 } 597 case "I", "IncGlobalScope" -> { 598 Integer n = arity == 0 ? Integer.valueOf(1) : arity == 1 ? integer(words.get(1)) : null; 599 if (n == null) { 600 io.out().println("The format of the command is: 'I <integer?>'"); 601 return true; 602 } 603 increaseGlobalScope(io, n); 604 } 605 case "s", "setScope" -> { 606 Integer n = arity == 2 ? natural(words.get(2)) : null; 607 if (n == null) { 608 io.out().println("The format of the command is: 's <claferUID> <integer>'"); 609 return true; 610 } 611 setScopes(io, words.get(1), sig -> n); 612 } 613 case "i", "incScope" -> { 614 Integer n = arity == 1 ? Integer.valueOf(1) : arity == 2 ? integer(words.get(2)) : null; 615 if (n == null) { 616 io.out().println("The format of the command is: 'i <claferUID> <integer?>'"); 617 return true; 618 } 619 setScopes(io, words.get(1), sig -> Math.max(1, valueOfScope(sig) + n)); 620 } 621 case "b", "bitwidth" -> { 622 Integer n = arity == 1 ? natural(words.get(1)) : null; 623 if (n == null) { 624 io.out().println("The format of the command is: 'b <integer>'"); 625 return true; 626 } 627 if (n >= 4) { 628 setBitwidth(n); 629 printBitwidthWarning(io, n); 630 solve(); 631 printBitwidthIntRange(io, n); 632 } 633 } 634 case "m", "maxInt", "maxint" -> { 635 Integer n = arity == 1 ? natural(words.get(1)) : null; 636 if (n == null) { 637 io.out().println("The format of the command is: 'm <integer>'"); 638 return true; 639 } 640 if (n >= 7) { 641 int bw = requiredBitwidth(n); 642 setBitwidth(bw); 643 printBitwidthWarning(io, bw); 644 solve(); 645 printBitwidthIntRange(io, bw); 646 } 647 } 648 case "tl" -> { 649 Integer n = arity == 1 ? natural(words.get(1)) : null; 650 if (n == null) { 651 io.out().println("The format of the command is: 'tl <integer>'"); 652 return true; 653 } 654 if (!dynamic) { 655 io.out().println("The model is static: its instances are not traces."); 656 } else if (n < 1) { 657 io.out().println("The trace length must be at least 1."); 658 } else { 659 session.setMaxTraceLength(n); 660 solve(); 661 io.out().println("The maximum trace length is " + n + "."); 662 } 663 } 664 case "r", "reload" -> reload(io); 665 case "scope" -> showScopes(io); 666 case "v", "saveScopes" -> { 667 saveScopes(); 668 io.out().println("Scopes saved to the `.cfr-scope` file."); 669 } 670 case "loadScopes" -> loadScopes(io); 671 case "a", "alloyModel" -> io.out().println(editAlloyModel()); 672 case "c", "claferModel" -> showClaferModel(io); 673 case "setUnsatCoreMinimization" -> { 674 Integer level = arity != 1 ? null : switch (words.get(1)) { 675 case "fastest" -> 2; 676 case "medium" -> 1; 677 case "best" -> 0; 678 default -> null; 679 }; 680 if (level == null) { 681 io.out().println("The format of the command is: 'setUnsatCoreMinimization <fastest|medium|best>'"); 682 return true; 683 } 684 session.setUnsatCoreMinimization(level); 685 solve(); 686 } 687 case "u", "unsatCore" -> { 688 // clafersg's header, with the constraints of claferIG's unsat core, as 'n' lists them 689 io.out().println("UNSAT Core command:"); 690 List<Constraint> core = present(findRemovable(session.unsatCore())); 691 if (core.isEmpty()) { 692 io.out().println("No unsat core: the model has a solution within " + (dynamic 693 ? "the scopes and the maximum trace length." : "the scopes.")); 694 } 695 int i = 1; 696 for (Constraint c : core) { 697 io.out().println(" " + i++ + ") " + printConstraint(c)); 698 } 699 } 700 case "U", "minUnsat", "p", "prettify", "x", "maximize", "z", "minimize", "t", "stats", 701 "O", "Options", "g", "strategy", "o", "optimizations", "B", "symmetryBreaking" -> 702 io.out().println("The command '" + name + "' is for static models, which Choco solves."); 703 default -> { 704 return false; 705 } 706 } 707 return true; 708 } 709 710 private void setGlobalScopeCommand(Repl.Io io, int value) throws Err { 711 int newGlobalScope = Math.max(1, value); 712 setGlobalScope(newGlobalScope); 713 if (newGlobalScope > allowedMaxInt(bitwidth)) { 714 io.out().println("Warning! Requested global scope is larger than maximum allowed by bitwidth ... increasing bitwidth"); 715 setBitwidth(requiredBitwidth(newGlobalScope)); 716 printBitwidthWarning(io, bitwidth); 717 } 718 solve(); 719 io.out().println("Global scope set to " + newGlobalScope); 720 } 721 722 private void increaseGlobalScope(Repl.Io io, int inc) throws Err { 723 int bw = bitwidth; 724 int newGlobalScope = Math.max(1, globalScope + inc); 725 setGlobalScope(newGlobalScope); 726 if (newGlobalScope > allowedMaxInt(bw)) { 727 io.out().println("Warning! Requested global scope is larger than maximum allowed by bitwidth ... increasing bitwidth"); 728 setBitwidth(requiredBitwidth(newGlobalScope)); 729 printBitwidthWarning(io, bitwidth); 730 } 731 // the clafers without instances keep their scopes, 0 732 for (Map.Entry<String, Integer> s : new ArrayList<>(scopes.entrySet())) { 733 if (!hasNoInstances(s.getKey())) { 734 setAlloyScopeAndBitwidth(io, bw, Math.max(1, s.getValue() + inc), claferNameOfSig(s.getKey()), 735 s.getKey()); 736 } 737 } 738 solve(); 739 io.out().println("Global scope changed to " + newGlobalScope); 740 } 741 742 @FunctionalInterface 743 private interface ScopeOf { 744 745 int of(String sig); 746 } 747 748 private void setScopes(Repl.Io io, String qName, ScopeOf value) throws Err { 749 int bw = bitwidth; 750 for (String uid : getUIDs(qName)) { 751 String sig = sigOfUID(uid); 752 if (!sigMap.containsKey(sig)) { 753 continue; 754 } 755 // the compiler's setAlloyScopeAndBitwidth ignores a subset sig, whose scope is not set 756 setAlloyScopeAndBitwidth(io, bw, value.of(sig), qName, sig); 757 } 758 solve(); 759 } 760 761 private Optional<String> setAlloyScopeAndBitwidth(Repl.Io io, int bw, int newValue, String fqName, String sig) 762 throws Err { 763 if (hasNoInstances(sig)) { 764 io.out().println("Scope of " + fqName + " (" + sig.substring(5) + ") stays 0: it has no instances, since no" 765 + " concrete clafer inherits from it or from the abstract clafer it is in"); 766 return Optional.empty(); 767 } 768 if (newValue > allowedMaxInt(bw)) { 769 setBitwidth(requiredBitwidth(newValue)); 770 io.out().println("Warning! Requested scope for " + fqName + " is larger than maximum allowed by bitwidth" 771 + " ... increasing bitwidth"); 772 printBitwidthWarning(io, bitwidth); 773 } 774 Optional<String> subset = setAlloyScope(newValue, sig); 775 io.out().println("Scope of " + fqName + " (" + sig.substring(5) + ") changed to " + newValue); 776 return subset; 777 } 778 779 private void showScopes(Repl.Io io) { 780 io.out().println("Global scope = " + globalScope); 781 scopes.forEach((sig, value) -> io.out().println(" " + uidOfSig(sig) + " scope = " + value)); 782 } 783 784 private Path scopeFile() { 785 return Path.of(modelFileName + "-scope"); 786 } 787 788 private void saveScopes() throws IOException { 789 StringBuilder sb = new StringBuilder("[\n"); 790 List<String> entries = new ArrayList<>(); 791 entries.add("{\"lpqName\": \"\", \"scope\": " + globalScope + "}"); 792 scopes.forEach((sig, value) -> entries.add("{\"lpqName\": \"" + uidOfSig(sig) + "\", \"scope\": " + value 793 + "}")); 794 sb.append(String.join(",\n", entries)).append("\n]\n"); 795 Files.writeString(scopeFile(), sb.toString(), StandardCharsets.UTF_8); 796 } 797 798 private void loadScopes(Repl.Io io) throws Exception { 799 if (!Files.isRegularFile(scopeFile())) { 800 io.out().println("The `.cfr-scope` file does not exist. Use the command `saveScopes` to create one."); 801 return; 802 } 803 Map<String, Integer> read = readScopeFile(Files.readString(scopeFile(), StandardCharsets.UTF_8)); 804 Integer global = null; 805 for (Map.Entry<String, Integer> e : read.entrySet()) { 806 if (e.getKey().isEmpty()) { 807 global = global == null ? e.getValue() : Math.max(global, e.getValue()); 808 } 809 } 810 // a file may list only some clafers, without the global scope; then it stays 811 if (global != null) { 812 setGlobalScope(global); 813 } 814 for (Map.Entry<String, Integer> e : read.entrySet()) { 815 if (!e.getKey().isEmpty()) { 816 for (String uid : getUIDs(e.getKey())) { 817 String sig = sigOfUID(uid); 818 if (sigMap.containsKey(sig)) { 819 setAlloyScope(e.getValue(), sig); 820 } 821 } 822 } 823 } 824 io.out().println("Scopes loaded from the `.cfr-scope` file."); 825 showScopes(io); 826 } 827 828 // the {"lpqName": ..., "scope": ...} entries of a .cfr-scope file 829 private static Map<String, Integer> readScopeFile(String text) { 830 Map<String, Integer> out = new LinkedHashMap<>(); 831 java.util.regex.Matcher m = java.util.regex.Pattern 832 .compile("\\{\\s*\"lpqName\"\\s*:\\s*\"([^\"]*)\"\\s*,\\s*\"scope\"\\s*:\\s*(-?\\d+)\\s*\\}") 833 .matcher(text); 834 while (m.find()) { 835 out.put(m.group(1), Integer.parseInt(m.group(2))); 836 } 837 return out; 838 } 839 840 private void reload(Repl.Io io) throws Exception { 841 Map<String, Integer> oldScopes = new TreeMap<>(scopes); 842 int oldBw = bitwidth; 843 int oldGlobal = globalScope; 844 try { 845 load(); 846 setGlobalScope(oldGlobal); 847 } catch (Exception e) { 848 io.err().println(e.getMessage()); 849 } 850 // mergeScopes: the larger of the old and the new scope of each clafer 851 for (Map.Entry<String, Integer> s : new ArrayList<>(scopes.entrySet())) { 852 int old = oldScopes.getOrDefault(s.getKey(), s.getValue()); 853 setAlloyScope(Math.max(s.getValue(), old), s.getKey()); 854 } 855 setBitwidth(findNecessaryBitwidth(oldBw, new ArrayList<>(scopes.values()))); 856 printBitwidthWarning(io, bitwidth); 857 solve(); 858 } 859 860 /** 861 * {@code c}: the Clafer model, each line with its number in its file, 862 * the lines of the unsat core marked, and the scope of the clafer 863 * declared on the line, as claferIG's {@code ShowClaferModel}. 864 */ 865 private void showClaferModel(Repl.Io io) { 866 printBitwidthIntRange(io, bitwidth); 867 io.out().println("Global scope = " + globalScope + "\n"); 868 // the constraints of the unsat core: a constraint on the line where it starts, a cardinality by its text 869 List<Integer> unsatLines = new ArrayList<>(); 870 List<String> unsatTexts = new ArrayList<>(); 871 for (Constraint c : present(findRemovable(session.unsatCore()))) { 872 switch (c) { 873 case UserConstraint u -> unsatLines.add(u.constraintInfo().pos().line()); 874 case ExactCardinalityConstraint e -> unsatTexts.add(e.claferInfo().toString()); 875 case LowerCardinalityConstraint l -> unsatTexts.add(l.claferInfo().toString()); 876 case UpperCardinalityConstraint u -> unsatTexts.add(u.claferInfo().toString()); 877 } 878 } 879 String text = ir.files().text(); 880 // the lines of the comments 881 Set<Integer> commentLines = new HashSet<>(); 882 for (org.clafer.frontend.Token t : org.clafer.frontend.ClaferLexer.lex(text).others()) { 883 if (t.kind() == org.clafer.frontend.TokenKind.COMMENT) { 884 for (int l = t.span().line(); l <= t.span().endLine(); l++) { 885 commentLines.add(l); 886 } 887 } 888 } 889 // the clafer declared on each line, by its Alloy name: of two on a line, the smaller UID 890 Map<Integer, String> lineNumMap = new HashMap<>(); 891 Map<Integer, String> lineUids = new HashMap<>(); 892 for (ClaferSymbol c : ir.names().clafers()) { 893 int line = c.declaration().span().line(); 894 String other = lineUids.get(line); 895 if (other == null || c.uid().compareTo(other) < 0) { 896 lineUids.put(line, c.uid()); 897 lineNumMap.put(line, alloyName(c.uid())); 898 } 899 } 900 List<String> claferLines = lines(removeCommentsAndUnify(text)); 901 int maxLineLength = claferLines.stream().mapToInt(String::length).max().orElse(0); 902 int digits = Integer.toString(claferLines.size()).length(); 903 StringBuilder sb = new StringBuilder(); 904 String previousPath = null; 905 for (int num = 1; num <= claferLines.size(); num++) { 906 String l = claferLines.get(num - 1); 907 if (commentLines.contains(num) && isEmptyLine(l)) { 908 continue; 909 } 910 var position = ir.files().position(num); 911 if (!position.path().equals(previousPath)) { 912 sb.append("--- ").append(position.path()).append('\n'); 913 previousPath = position.path(); 914 } 915 boolean unsat = isUnsat(unsatLines, unsatTexts, l, num); 916 String fileNum = Integer.toString(position.line()); 917 sb.append(fileNum).append('.').append(" ".repeat(Math.max(0, 1 + digits - fileNum.length()))) 918 .append(unsat ? "> " : "| ").append(l).append(" ".repeat(3 + maxLineLength - l.length())) 919 .append(unsat ? "<UnSAT " : "| "); 920 String clafer = lineNumMap.get(num); 921 if (clafer != null) { 922 Integer scope = scopes.get("this/" + clafer); 923 sb.append("scope = ").append(scope == null ? "Nothing" : scope); 924 } 925 sb.append('\n'); 926 } 927 io.out().println(sb); 928 } 929 930 // a constraint is on the line where it starts; a cardinality is on the line with the clafer's name and 931 // cardinality 932 private static boolean isUnsat(List<Integer> unsatLines, List<String> unsatTexts, String l, int num) { 933 if (unsatLines.contains(num)) { 934 return true; 935 } 936 List<String> lw = words(l); 937 for (String u : unsatTexts) { 938 List<String> uw = words(u); 939 String uFirst = uw.isEmpty() ? "" : uw.get(0); 940 String lFirst = lw.isEmpty() ? "" : lw.get(0); 941 String uLast = uw.isEmpty() ? "" : uw.get(uw.size() - 1); 942 String lLast = lw.isEmpty() ? "" : lw.get(lw.size() - 1); 943 if ((uFirst.equals(lFirst) && uLast.equals(lLast)) || l.contains(u)) { 944 return true; 945 } 946 } 947 return false; 948 } 949 950 private static List<String> words(String s) { 951 String t = s.strip(); 952 return t.isEmpty() ? List.of() : List.of(t.split("\\s+")); 953 } 954 955 private String editAlloyModel() { 956 String model = translation.code(); 957 List<String> alloyLines = lines(removeCommentsAndUnify(model)); 958 int splitNum = 1; 959 while (splitNum - 1 < alloyLines.size() && !isEmptyLine(alloyLines.get(splitNum - 1))) { 960 splitNum++; 961 } 962 List<String> info = alloyLines.subList(0, Math.min(splitNum, alloyLines.size())); 963 List<String> rest = alloyLines.subList(Math.min(splitNum, alloyLines.size()), alloyLines.size()); 964 int m = rest.stream().mapToInt(String::length).max().orElse(0); 965 int digits = Integer.toString(alloyLines.size()).length(); 966 StringBuilder sb = new StringBuilder("global scope = " + globalScope + "\n\n"); 967 info.forEach(l -> sb.append(l).append('\n')); 968 int num = 1 + splitNum; 969 for (String l : rest) { 970 String withScope; 971 String pad = " ".repeat(3 + m - l.length()); 972 if (!List.of(l.trim().split("\\s+")).contains("sig")) { 973 withScope = l + pad + " |"; 974 } else { 975 int us = l.indexOf('_'); 976 String key = us < 0 ? "" : l.substring(us + 1).split("[ \t\n]", 2)[0]; 977 Integer val = scopes.get(key); 978 withScope = l + pad + " | scope = " + (val == null ? "Nothing" : val); 979 } 980 sb.append(num).append('.').append(" ".repeat(1 + digits - Integer.toString(num).length())).append("| ") 981 .append(withScope).append('\n'); 982 num++; 983 } 984 return sb.toString(); 985 } 986 987 private static List<String> lines(String s) { 988 List<String> out = new ArrayList<>(); 989 int start = 0; 990 while (start < s.length()) { 991 int end = s.indexOf('\n', start); 992 if (end < 0) { 993 out.add(s.substring(start)); 994 break; 995 } 996 out.add(s.substring(start, end)); 997 start = end + 1; 998 } 999 return out; 1000 } 1001 1002 private static boolean isEmptyLine(String l) { 1003 return l.chars().allMatch(c -> c == ' ' || c == '\n' || c == '\t' || c == '\r'); 1004 } 1005 1006 // only remove the contents while preserving the empty lines 1007 private static String removeCommentsAndUnify(String model) { 1008 StringBuilder sb = new StringBuilder(); 1009 int i = 0; 1010 int n = model.length(); 1011 while (i < n) { 1012 if (i == n - 1) { 1013 sb.append(model.charAt(i)); 1014 break; 1015 } 1016 char c = model.charAt(i); 1017 if (c == '\t') { 1018 sb.append(" "); 1019 i++; 1020 } else if (c == '/' && model.charAt(i + 1) == '/') { 1021 while (i < n && model.charAt(i) != '\n') { 1022 i++; 1023 } 1024 } else if (c == '/' && model.charAt(i + 1) == '*') { 1025 i += 2; 1026 while (i < n) { 1027 if (i == n - 1) { 1028 i = n; 1029 break; 1030 } 1031 if (model.charAt(i) == '\n') { 1032 sb.append('\n'); 1033 i++; 1034 } else if (model.charAt(i) == '*' && model.charAt(i + 1) == '/') { 1035 i += 2; 1036 break; 1037 } else { 1038 i++; 1039 } 1040 } 1041 } else { 1042 sb.append(c); 1043 i++; 1044 } 1045 } 1046 return sb.toString(); 1047 } 1048 1049 @Override 1050 public String help() { 1051 return """ 1052 You can invoke the following commands as indicated by single quotes: 1053 'n'ext, [enter] - to produce the next solution if available, an instance of a static model or a trace 1054 of a dynamic model, or to output a message that no more solutions exist within 1055 the given scope 1056 'S'etGlobalScope <n> - to set the global scope to <n> 1057 'I'ncGlobalScope <n?> - to increase the global scope by <n>, 1 by default 1058 's'etScope <name> <n> - to set the scope of the clafer <name> to <n> 1059 'i'ncScope <name> <n?> - to increase the scope of the clafer <name> by <n>, 1 by default 1060 'm'axInt, 'maxint' <n> - to set the bitwidth by providing the largest integer 1061 'b'itwidth <n> - to set the bitwidth 1062 'tl' <n> - to set the maximum length of the traces of a dynamic model 1063 'd'iff - to show each next instance or state as its changes from the previous one, or in full 1064 (+ appears, - disappears, ~ changes its value) 1065 'fork' <n> - to produce another trace with the states of the last trace before state <n> 1066 'config' - to produce a trace of a dynamic model whose clafers that do not change over time 1067 differ from those of the traces so far 1068 'check' <n?> - to check the assertions of the model within the scopes and the maximum trace 1069 length, and to give a counterexample of each one that fails; with <n>, only 1070 the assertions on line <n> 1071 sav'e' - to save all solutions displayed so far to files named 1072 <model file name>.<solution number>.data, one solution per file 1073 'dot' - to save the most recent solution as a Graphviz graph, for a trace its states 1074 and transitions, to <model file name>.<solution number>.dot 1075 'q'uit - to quit the interactive session 1076 'r'eload - to reload your clafer model 1077 'h'elp - to display this menu options summary 1078 'scope' - to print out the values of the global scope and individual Clafer scopes 1079 sa'v'eScopes - to generate a '<model>.cfr-scope' file with the current scopes 1080 'loadScopes' - to load scopes from a '<model>.cfr-scope' file 1081 'setUnsatCoreMinimization' <fastest|medium|best> - to choose the UnSAT core minimization strategy. Default: fastest 1082 'u'nsatCore - to print out the constraints of the unsat core of the model, if it has no solution 1083 'c', 'claferModel' - to print out the Clafer model verbatim, with the scopes and the unsat core 1084 'a', 'alloyModel' - to print out the Alloy model 1085 'alloyInstance' - to print out the Alloy xml document of the most recent solution 1086 'f'ind <name> - to print a Clafer with given name found in the most recent solution 1087 """; 1088 } 1089}