001package org.clafer.cli; 002 003import java.io.BufferedReader; 004import java.io.File; 005import java.io.IOException; 006import java.io.InputStreamReader; 007import java.math.BigDecimal; 008import java.util.ArrayList; 009import java.util.Collections; 010import java.util.List; 011import java.util.function.UnaryOperator; 012import joptsimple.OptionSet; 013import org.clafer.ast.AstClafer; 014import org.clafer.ast.AstModel; 015import static org.clafer.ast.Asts.global; 016import static org.clafer.ast.Asts.sum; 017import org.clafer.compiler.ClaferCompiler; 018import org.clafer.compiler.ClaferOption; 019import org.clafer.compiler.ClaferSearch; 020import org.clafer.compiler.ClaferSearchStrategy; 021import org.clafer.compiler.ClaferUnsat; 022import org.clafer.ig.Backend; 023import org.clafer.ig.ClaferModel; 024import org.clafer.ig.Repl; 025import org.clafer.ig.Solution; 026import org.clafer.instance.InstanceClafer; 027import org.clafer.instance.InstanceModel; 028import org.clafer.javascript.JavascriptFile; 029import org.clafer.objective.Objective; 030import org.clafer.scope.Scope; 031 032/** 033 * clafersg's REPL for a static model: the Choco backend of the one solution 034 * loop ({@link Repl}), with clafersg's commands and messages, and the 035 * instances as chocosolver prints them. 036 */ 037public class REPL { 038 039 public static void runREPL(File inputFile, JavascriptFile javascriptFile, OptionSet options) throws Exception { 040 ChocoBackend backend = new ChocoBackend(inputFile, javascriptFile, options); 041 new Repl(backend, new Repl.Io(new BufferedReader(new InputStreamReader(System.in)), System.out, System.err), 042 false).run(); 043 } 044 045 public static void printHelp() { 046 System.out.print(ChocoBackend.Help); 047 } 048 049 /** 050 * The Choco backend. 051 */ 052 static final class ChocoBackend implements Backend { 053 054 static final String Help = """ 055 'h'elp Print the REPL commands. 056 'n'ext Generate the next instance. 057 <enter> Generate the next instance. 058 'p'rettify Toggle prettify on/off. 059 'r'eload Reload the model from its file: a .cfr file is compiled again. 060 'u'nsatCore Compute the set of contradicting constraints if any. 061 min'U'nsat Compute the minimal UnSAT core and a near-miss example. 062 'S'etGlobalScope <value> Set the global scope to the <value> . 063 's'etScope <claferUID> <value> Set the scope of the given clafer to the <value>. 064 'I'ncGlobalScope <value?> Increase the global scope by <value> or 1 by default. 065 'i'ncScope <claferUID> <value?> Increase the scope of the given clafer by the <value> or 1 by default. 066 sa'v'eScopes Save the currect scopes to a .cfr-scope file. 067 'scope' Print the global scope and the scope of each clafer. 068 'm'axInt <value> Set the largest allowed integer to <value>. 069 ma`x`imize <claferUID> Find a solution where <claferUID>.dref is maximal. 070 minimi'z'e <claferUID> Find a solution where <claferUID>.dref is minimal. 071 sta't's Display statistics about the current search. 072 'O'ptions Display the current solver options. 073 strate'g'y <smaller|larger|random> Set search strategy to prefer smaller, prefer larger, or random. 074 'o'ptimizations Toggle optimizations basic/full. 075 symmetry'B'reaking Toggle symmetry breaking basic/full. 076 'd'iff Show each next instance as its changes from the previous one, or in full. 077 sav'e' Save the instances shown so far to <model file name>.<number>.data. 078 'dot' Save the most recent instance as a Graphviz graph. 079 'f'ind <name> Print the clafer with the given name of the most recent instance. 080 'q'uit Exit the REPL sesssion. 081 """; 082 083 private final File inputFile; 084 private final OptionSet options; 085 private final String scopesFile; 086 private JavascriptFile javascriptFile; 087 private Scope scope; 088 private ClaferOption compilerOption; 089 private AstModel model; 090 private Objective[] objectives; 091 private ClaferSearch solver; 092 private boolean prettify; 093 private final boolean addTypes; 094 private int instanceID = 0; // id of an instance generated previously 095 096 ChocoBackend(File inputFile, JavascriptFile javascriptFile, OptionSet options) throws IOException { 097 this.inputFile = inputFile; 098 this.javascriptFile = javascriptFile; 099 this.options = options; 100 // the model's scope file, e.g., model.cfr-scope for model.js, model.des.cfr-scope for model.des.cfr 101 String path = inputFile.getAbsolutePath(); 102 this.scopesFile = path.substring(0, path.lastIndexOf('.')) + ".cfr-scope"; 103 this.scope = Utils.resolveScopes(inputFile, javascriptFile, options); 104 ClaferOption option = javascriptFile.getOption(); 105 if (options.has("search")) { 106 option = option.setStrategy((ClaferSearchStrategy) options.valueOf("search")); 107 } 108 this.compilerOption = option; 109 this.model = javascriptFile.getModel(); 110 this.objectives = javascriptFile.getObjectives(); 111 this.prettify = options.has("prettify"); 112 this.addTypes = options.has("addtypes"); 113 } 114 115 @Override 116 public boolean isDynamic() { 117 return false; 118 } 119 120 @Override 121 public String prompt() { 122 return "\nClaferChocoIG> "; 123 } 124 125 @Override 126 public String help() { 127 return Help; 128 } 129 130 @Override 131 public void start(Repl.Io io) { 132 solver = objectives.length == 0 133 ? ClaferCompiler.compile(model, scope, compilerOption) 134 : ClaferCompiler.compile(model, scope, objectives, compilerOption); 135 io.out().println("Type 'help' for the list of available REPL commands"); 136 } 137 138 @Override 139 public Shown next(Repl.Io io) throws IOException { 140 if (solver == null) { 141 solver = compileModel(io); 142 } 143 return nextInstance(io); 144 } 145 146 private Shown nextInstance(Repl.Io io) throws IOException { 147 if (solver == null) { 148 io.out().println("Could not start the instantiation"); 149 return null; 150 } 151 if (!solver.find()) { 152 io.out().println("No more instances found. Consider increasing scopes."); 153 return null; 154 } 155 InstanceModel instance = solver.instance(); 156 StringBuilder text = new StringBuilder(); 157 if (prettify) { 158 instance.print(text, addTypes); 159 } else { 160 for (InstanceClafer c : instance.getTopClafers()) { 161 Utils.printClafer(c, text); 162 } 163 } 164 return new Shown(new Solution.Instance(tree(instance), text.toString()), null); 165 } 166 167 @Override 168 public String show(int n, Shown shown) { 169 return "\n=== Instance " + n + " Begin ===\n\n" + ((Solution.Instance) shown.solution()).text() 170 + "\n--- Instance " + n + " End ---\n\n"; 171 } 172 173 @Override 174 public int number(Repl.Context context) { 175 return ++instanceID; 176 } 177 178 @Override 179 public Shown fork(Repl.Io io, int state) { 180 return null; 181 } 182 183 @Override 184 public Shown nextConfiguration(Repl.Io io) { 185 io.out().println("The command 'config' is not available for static models yet."); 186 return null; 187 } 188 189 @Override 190 public void check(Repl.Io io, Integer line, Repl.Displayer display) { 191 io.out().println("The command 'check' is not available for static models yet: run clafersg with -v" 192 + " to check the assertions."); 193 } 194 195 @Override 196 public UnaryOperator<String> names() { 197 return uid -> uid; 198 } 199 200 @Override 201 public String modelFileName() { 202 return inputFile.getName(); 203 } 204 205 @Override 206 public void quit() { 207 } 208 209 @Override 210 public void unknown(Repl.Io io, String input) { 211 io.out().println("Unhandled command: " + input.trim()); 212 } 213 214 private ClaferSearch compileModel(Repl.Io io) { 215 ClaferSearch s; 216 instanceID = 0; // reset instance ID 217 try { 218 s = objectives.length == 0 219 ? ClaferCompiler.compile(model, scope, compilerOption) 220 : ClaferCompiler.compile(model, scope, objectives, compilerOption); 221 } catch (Exception e) { 222 s = null; 223 io.out().println("Message: " + e.getMessage()); 224 e.printStackTrace(io.err()); 225 } 226 return s; 227 } 228 229 // The result of an unsat command is null when removing constraints cannot make the model satisfiable 230 private static void printUnsat(Repl.Io io, Object unsat) { 231 io.out().println(unsat == null 232 ? "No constraints to report: the model is unsatisfiable without them. Check the cardinalities or increase the scopes." 233 : unsat); 234 } 235 236 private void recompiled(Repl.Io io) { 237 solver = compileModel(io); 238 if (solver != null) { 239 io.out().println("Model is ready after the scope change"); 240 } 241 } 242 243 private Integer integer(Repl.Io io, String value) { 244 try { 245 return Integer.parseInt(value); 246 } catch (Exception e) { 247 io.out().println("The scope has to be an integer number. Given '" + value + "'"); 248 return null; 249 } 250 } 251 252 private AstClafer clafer(Repl.Io io, String claferName) { 253 AstClafer clafer = Utils.getModelChildByName(model, claferName); 254 if (clafer == null) { 255 io.out().println("The clafer is not found: '" + claferName + "'"); 256 } 257 return clafer; 258 } 259 260 @Override 261 public boolean command(Repl.Io io, String s, List<String> words, Repl.Context context) throws Exception { 262 s = s.trim(); 263 String[] commandParts = s.split(" "); 264 String command = commandParts[0]; 265 switch (command) { 266 case "n", "next" -> { 267 // clafersg's next ignores the arguments 268 Shown shown = next(io); 269 if (shown != null) { 270 context.display(shown); 271 } 272 } 273 case "p", "prettify" -> { 274 prettify = !prettify; 275 io.out().println("Prettify: " + (prettify ? "On" : "Off")); 276 } 277 case "t", "stats" -> io.out().println(solver.getInternalSolver().getMeasures().toString()); 278 case "O", "Options" -> { 279 String strategy = (compilerOption.getStrategy() == ClaferSearchStrategy.PreferSmallerInstances) 280 ? "smaller" 281 : ((compilerOption.getStrategy() == ClaferSearchStrategy.PreferLargerInstances) 282 ? "larger" : "random"); 283 io.out().println("Options:" 284 + "\n strate'g'y: " + strategy 285 + "\n symmetry'B'reaking: " 286 + (compilerOption.isBasicSymmetryBreaking() ? "basic" : "") 287 + (compilerOption.isFullSymmetryBreaking() ? "full" : "") 288 + "\n 'o'ptimizations: " 289 + (compilerOption.isBasicOptimizations() ? "basic" : "") 290 + (compilerOption.isFullOptimizations() ? "full" : "") 291 + "\n 'm'axInt " + (scope.getIntHigh()) 292 + "\n global'S'cope " + (scope.getDefaultScope())); 293 } 294 case "o", "optimizations" -> { 295 if (compilerOption.isBasicOptimizations()) { 296 compilerOption = compilerOption.fullOptimizations(); 297 io.out().println("Optimizations: full"); 298 } else { 299 compilerOption = compilerOption.basicOptimizations(); 300 io.out().println("Optimizations: basic"); 301 } 302 } 303 case "B", "symmetryBreaking" -> { 304 if (compilerOption.isBasicSymmetryBreaking()) { 305 compilerOption = compilerOption.fullSymmetryBreaking(); 306 io.out().println("Symmetry breaking: full"); 307 } else { 308 compilerOption = compilerOption.basicSymmetryBreaking(); 309 io.out().println("Symmetry breaking: basic"); 310 } 311 } 312 case "U", "minUnsat" -> { 313 io.out().println("Min UNSAT command:"); 314 ClaferUnsat unsat = ClaferCompiler.compileUnsat(model, scope); 315 // Print the Min-Unsat and near-miss example. 316 printUnsat(io, unsat.minUnsat()); 317 } 318 case "u", "unsatCore" -> { 319 io.out().println("UNSAT Core command:"); 320 ClaferUnsat unsat = ClaferCompiler.compileUnsat(model, scope); 321 printUnsat(io, unsat.unsatCore()); 322 } 323 case "r", "reload" -> reload(io); 324 case "S", "SetGlobalScope" -> { 325 io.out().println("Set global scope: " + s); 326 if (commandParts.length != 2) { 327 io.out().println("The format of the command is: 'S <integer>'"); 328 io.out().println("Given: '" + s + "'"); 329 return true; 330 } 331 Integer scopeValue = integer(io, commandParts[1]); 332 if (scopeValue != null) { 333 scope = scope.toBuilder().defaultScope(scopeValue).toScope(); 334 recompiled(io); 335 } 336 } 337 case "I", "IncGlobalScope" -> { 338 io.out().println("Increase global scope: " + s); 339 if (commandParts.length > 2) { 340 io.out().println("The format of the command is: 'I <integer?>'"); 341 io.out().println("Given: '" + s + "'"); 342 return true; 343 } 344 Integer scopeValue = commandParts.length == 2 ? integer(io, commandParts[1]) : Integer.valueOf(1); 345 if (scopeValue != null) { 346 scope = scope.toBuilder().adjustDefaultScope(scopeValue).toScope(); 347 recompiled(io); 348 } 349 } 350 case "m", "maxInt", "maxint" -> { 351 io.out().println("Max Integer: " + s); 352 if (commandParts.length != 2) { 353 io.out().println("The format of the command is: 'm <integer>'"); 354 io.out().println("Given: '" + s + "'"); 355 return true; 356 } 357 int scopeHigh; 358 try { 359 scopeHigh = Integer.parseInt(commandParts[1]); 360 } catch (Exception e) { 361 io.out().println("Expected an integer number. Given '" + commandParts[1] + "'"); 362 return true; 363 } 364 int scopeLow = -(scopeHigh + 1); 365 scope = scope.toBuilder().intLow(scopeLow).intHigh(scopeHigh).toScope(); 366 recompiled(io); 367 } 368 case "x", "maximize", "z", "minimize" -> { 369 boolean maximize = command.equals("x") || command.equals("maximize"); 370 io.out().println((maximize ? "Maximize: " : "Minimize: ") + s); 371 if (commandParts.length != 2) { 372 io.out().println("The format of the command is: '" + (maximize ? "x" : "z") + " <claferUID>'"); 373 io.out().println("Given: '" + s + "'"); 374 return true; 375 } 376 AstClafer clafer = clafer(io, commandParts[1]); 377 if (clafer == null) { 378 return true; 379 } 380 if (!clafer.hasRef()) { 381 io.out().println("Cannot " + (maximize ? "maximize " : "minimize ") + clafer 382 + " because it is not a reference."); 383 return true; 384 } 385 solver = ClaferCompiler.compile(model, scope, maximize 386 ? Objective.maximize(sum(global(clafer))) : Objective.minimize(sum(global(clafer)))); 387 // shown by the loop as the next instance 388 Shown shown = nextInstance(io); 389 if (shown != null) { 390 context.display(shown); 391 } 392 } 393 case "v", "saveScopes" -> { 394 List<ClaferNameScopePair> claferScopePairs = new ArrayList<>(); 395 for (AstClafer curClafer : Utils.getAllModelClafers(model)) { 396 int curScope; 397 try { 398 curScope = scope.getScope(curClafer); 399 } catch (Exception e) { 400 curScope = 0; 401 } 402 claferScopePairs.add(new ClaferNameScopePair(curClafer.getName(), curScope)); 403 } 404 Collections.sort(claferScopePairs); 405 Utils.produceScopeFile(claferScopePairs, scopesFile); 406 } 407 case "scope" -> { 408 io.out().println("Global scope = " + scope.getDefaultScope()); 409 for (AstClafer c : Utils.getAllModelClafers(model)) { 410 int curScope; 411 try { 412 curScope = scope.getScope(c); 413 } catch (Exception e) { 414 curScope = 0; 415 } 416 io.out().println(" " + c.getName() + " scope = " + curScope); 417 } 418 } 419 case "s", "setScope" -> { 420 io.out().println("Set individual scope: " + s); 421 if (commandParts.length != 3) { 422 io.out().println("The format of the command is: 's <claferUID> <integer>'"); 423 io.out().println("Given: '" + s + "'"); 424 return true; 425 } 426 Integer claferScopeValue = integer(io, commandParts[2]); 427 if (claferScopeValue == null) { 428 return true; 429 } 430 AstClafer clafer = clafer(io, commandParts[1]); 431 if (clafer != null) { 432 scope = scope.toBuilder().setScope(clafer, claferScopeValue).toScope(); 433 recompiled(io); 434 } 435 } 436 case "i", "incScope" -> { 437 io.out().println("Increase individual scope: " + s); 438 if (commandParts.length < 2 || commandParts.length > 3) { 439 io.out().println("The format of the command is: 'i <claferUID> <integer?>'"); 440 io.out().println("Given: '" + s + "'"); 441 return true; 442 } 443 Integer claferScopeValue = commandParts.length == 3 ? integer(io, commandParts[2]) 444 : Integer.valueOf(1); 445 if (claferScopeValue == null) { 446 return true; 447 } 448 AstClafer clafer = clafer(io, commandParts[1]); 449 if (clafer != null) { 450 scope = scope.toBuilder().adjustScope(clafer, claferScopeValue).toScope(); 451 recompiled(io); 452 } 453 } 454 case "g", "strategy" -> { 455 if (commandParts.length != 2 || (!"smaller".equals(commandParts[1]) 456 && !"larger".equals(commandParts[1]) && !"random".equals(commandParts[1]))) { 457 io.out().println("The format of the command is: 'g <smaller|larger|random>'"); 458 io.out().println("Given: '" + s + "'"); 459 return true; 460 } 461 switch (commandParts[1]) { 462 case "smaller" -> { 463 compilerOption = compilerOption.setStrategy(ClaferSearchStrategy.PreferSmallerInstances); 464 io.out().println("Search strategy: smaller"); 465 } 466 case "larger" -> { 467 compilerOption = compilerOption.setStrategy(ClaferSearchStrategy.PreferLargerInstances); 468 io.out().println("Search strategy: larger"); 469 } 470 default -> { 471 io.out().println("Search strategy: random"); 472 compilerOption = compilerOption.setStrategy(ClaferSearchStrategy.Random); 473 } 474 } 475 } 476 case "b", "bitwidth", "tl", "a", "alloyModel", "c", "claferModel", "loadScopes", "setUnsatCoreMinimization" -> 477 io.out().println("The command '" + command + "' is for temporal models, which Alloy solves."); 478 default -> { 479 return false; 480 } 481 } 482 return true; 483 } 484 485 private void reload(Repl.Io io) throws IOException { 486 try { 487 javascriptFile = Utils.readModel(inputFile, options); 488 } catch (Frontend.ModelException | IllegalArgumentException e) { 489 // the errors of the model, with their positions 490 io.out().println(e.getMessage()); 491 javascriptFile = null; 492 } catch (Exception e) { 493 io.out().println("Unhandled compilation error occured. Please report this problem."); 494 io.out().println(e.getMessage()); 495 javascriptFile = null; 496 } 497 if (javascriptFile != null) { 498 model = javascriptFile.getModel(); 499 scope = Utils.resolveScopes(inputFile, javascriptFile, options); 500 objectives = javascriptFile.getObjectives(); 501 solver = compileModel(io); 502 io.out().println(solver == null ? "Could not reload" : "Reloaded"); 503 } else { 504 io.out().println("Could not reload"); 505 } 506 } 507 508 /** 509 * The instance as the loop's tree: each clafer named as chocosolver 510 * prints it. 511 */ 512 private static ClaferModel tree(InstanceModel instance) { 513 List<ClaferModel.Clafer> top = new ArrayList<>(); 514 for (InstanceClafer c : instance.getTopClafers()) { 515 top.add(tree(c)); 516 } 517 return new ClaferModel(top); 518 } 519 520 private static String name(InstanceClafer c) { 521 return c.getType().getName() + Utils.countSuffix(c.getId()); 522 } 523 524 private static ClaferModel.Clafer tree(InstanceClafer c) { 525 ClaferModel.Value value = null; 526 if (c.hasRef()) { 527 Object ref = c.getRef(); 528 value = switch (ref) { 529 case InstanceClafer r -> new ClaferModel.AliasValue(new ClaferModel.Id(name(r), 0)); 530 case Integer i -> new ClaferModel.IntValue(i); 531 case BigDecimal d -> new ClaferModel.StringValue(d.toPlainString()); 532 default -> new ClaferModel.StringValue(ref.toString()); 533 }; 534 } 535 List<ClaferModel.Clafer> children = new ArrayList<>(); 536 for (InstanceClafer child : c.getChildren()) { 537 children.add(tree(child)); 538 } 539 return new ClaferModel.Clafer(new ClaferModel.Id(name(c), 0), c.getType().getName(), value, children); 540 } 541 } 542}