001package org.clafer.ast; 002 003import java.util.ArrayDeque; 004import java.util.ArrayList; 005import java.util.Arrays; 006import java.util.Deque; 007import java.util.HashMap; 008import java.util.List; 009import java.util.Map; 010import java.util.stream.Collectors; 011import org.clafer.assertion.Assertion; 012import org.clafer.objective.Objective; 013 014/** 015 * Prints a model in a Clafer-like syntax with nothing left implicit: the 016 * clafers by their names (the compiler's UIDs), every card and group card, 017 * every {@code this}, {@code parent} and {@code dref}. The output is a Clafer 018 * model, which the Clafer compiler reads with {@code -f} (the names are already 019 * UIDs) and {@code -l} (no layout). Two models print the same when they have 020 * the same clafers, constraints, objectives and assertions, so the output can 021 * be compared, e.g., between two compilers of the same Clafer model. The 022 * scopes, all of them, go to the model's {@code .cfr-scope} file 023 * ({@link org.clafer.scope.ScopeFile}). The solver options (e.g., branching 024 * priorities) are not printed. 025 * <p> 026 * The clafers, their children and their constraints are printed in the order 027 * they were added, which is the order of the source and of the instances, 028 * abstract and concrete clafers interleaved (see {@link #sourceOrder}). 029 * Source spans are not printed. 030 * <p> 031 * Nesting is in braces, as in Clafer without layout: every clafer has its 032 * block, {@code {}} if it is empty. The indentation is only for reading; 033 * whitespace and line breaks carry no meaning. 034 * <p> 035 * Values are printed as they apply, declarations where they are declared. A 036 * group card and a multiplicity are values: a clafer without its own group 037 * card has its super clafer's, as chocosolver solves it, and {@code 0..*} if 038 * no super clafer has one; an abstract clafer's multiplicity is {@code 0..*}. 039 * Children, constraints and references are declarations: they stay under the 040 * clafer that declares them. A reference is printed only where it is declared 041 * or redefined, since in Clafer a reference written on a sub clafer redefines 042 * the inherited one, even with the same target. 043 * <p> 044 * Expressions are fully parenthesized, except for navigation ({@code .}), 045 * which binds tightest. {@code sum} and {@code product} take a set of clafers 046 * and add (multiply) the {@code dref} of each instance, so two instances with 047 * the same value count twice; this is printed as in Clafer, e.g., 048 * {@code sum c0_Phone.c0_cost.dref}. An explicit dereference inside would 049 * print as {@code .dref.dref}. 050 */ 051public class AstPrinter { 052 053 private static final String Indent = " "; 054 055 private AstPrinter() { 056 } 057 058 /** 059 * The first line of an explicit model, which declares it to the Clafer 060 * compiler (its options -f -k -l --ss=none) and to chocosolver (read with 061 * {@link org.clafer.ast.ToAst}, not compiled by clafer). 062 */ 063 public static final String ExplicitHeader = "//# OPTIONS --explicit"; 064 065 /** 066 * Prints a model with its objectives and assertions, as an explicit model: 067 * {@link #ExplicitHeader}, then the model. Its scopes go to a separate 068 * file, see {@link org.clafer.scope.ScopeFile#print}. 069 * 070 * @param model the model 071 * @param objectives the objectives 072 * @param assertions the assertions 073 * @return the model as text, one line per clafer, constraint, objective 074 * and assertion 075 */ 076 public static String print(AstModel model, Objective[] objectives, Assertion[] assertions) { 077 StringBuilder out = new StringBuilder(); 078 out.append(ExplicitHeader).append('\n'); 079 out.append(print(model)); 080 if (objectives.length > 0 || assertions.length > 0) { 081 out.append('\n'); 082 } 083 for (Objective objective : objectives) { 084 out.append("<< ").append(objective.isMaximize() ? "max " : "min ") 085 .append(print(objective.getExpr())).append(" >>\n"); 086 } 087 for (Assertion assertion : assertions) { 088 out.append("assert [").append(print(assertion.getExpr())).append("]\n"); 089 } 090 return out.toString(); 091 } 092 093 /** 094 * Prints the clafers and constraints of a model. 095 * 096 * @param model the model 097 * @return the model as text 098 */ 099 public static String print(AstModel model) { 100 StringBuilder out = new StringBuilder(); 101 AstAbstractClafer top = model.getAbstractRoot(); 102 for (AstConstraint constraint : top.getConstraints()) { 103 printConstraint(constraint, "", out); 104 } 105 List<AstAbstractClafer> abstracts = top.getAbstractChildren().stream() 106 .filter(c -> c != model.getTypeRoot()).collect(Collectors.toList()); 107 for (AstClafer clafer : sourceOrder(abstracts, top.getChildren())) { 108 printClafer(clafer, model, "", out); 109 } 110 // Constraints directly under root, as opposed to the top level, are 111 // possible in the Java API. 112 if (model.getRoot().hasConstraints()) { 113 out.append("root {\n"); 114 for (AstConstraint constraint : model.getRoot().getConstraints()) { 115 printConstraint(constraint, Indent, out); 116 } 117 out.append("}\n"); 118 } 119 return out.toString(); 120 } 121 122 private static void printClafer(AstClafer clafer, AstModel model, String indent, StringBuilder out) { 123 out.append(indent); 124 if (clafer instanceof AstAbstractClafer) { 125 out.append("abstract "); 126 } 127 Card groupCard = AstUtil.getInheritedGroupCard(clafer); 128 out.append(groupCard == null ? "0..*" : card(groupCard)).append(' '); 129 out.append(clafer.getName()); 130 if (clafer.hasSuperClafer() && clafer.getSuperClafer() != model.getTypeRoot()) { 131 out.append(" : ").append(clafer.getSuperClafer().getName()); 132 } 133 // Only the clafer's own reference: an inherited one written here would redefine it. 134 AstRef ref = clafer.getRef(); 135 if (ref != null) { 136 out.append(ref.isUnique() ? " -> " : " ->> ").append(ref.getTargetType().getName()); 137 } 138 // An abstract clafer has no card of its own: its instances are those 139 // of the clafers that extend it. 140 out.append(' ').append(clafer instanceof AstConcreteClafer concrete ? card(concrete.getCard()) : "0..*"); 141 if (!clafer.hasConstraints() && !clafer.hasAbstractChildren() && !clafer.hasChildren()) { 142 out.append(" {}\n"); 143 return; 144 } 145 out.append(" {\n"); 146 String inner = indent + Indent; 147 for (AstConstraint constraint : clafer.getConstraints()) { 148 printConstraint(constraint, inner, out); 149 } 150 for (AstClafer child : sourceOrder(clafer.getAbstractChildren(), clafer.getChildren())) { 151 printClafer(child, model, inner, out); 152 } 153 out.append(indent).append("}\n"); 154 } 155 156 /** 157 * The abstract and concrete children of a clafer, which the model keeps 158 * apart, merged in the order of the source model. The order matters to 159 * the solver: a sub clafer's place among the subs of its super clafer 160 * numbers its instances. The model built from the source adds the subs in 161 * the order of the source, and a clafer without a super clafer stays among 162 * the subs of {@code #clafer#} in the order of creation; so a list of subs 163 * that holds clafers from the subtrees of two children tells which child 164 * came first. Without one, the order is not seen by the solver, and the 165 * abstract child comes first. 166 */ 167 private static List<AstClafer> sourceOrder(List<AstAbstractClafer> abstracts, List<AstConcreteClafer> concretes) { 168 if (abstracts.isEmpty() || concretes.isEmpty()) { 169 List<AstClafer> one = new ArrayList<>(abstracts); 170 one.addAll(concretes); 171 return one; 172 } 173 // A topological sort of the siblings: each list keeps its order, and 174 // a list of subs orders an abstract and a concrete child. Without an 175 // order between two, the abstract child comes first. 176 List<AstClafer> siblings = new ArrayList<>(abstracts); 177 siblings.addAll(concretes); 178 int n = siblings.size(); 179 List<List<Integer>> after = new ArrayList<>(); 180 int[] before = new int[n]; 181 for (int k = 0; k < n; k++) { 182 after.add(new ArrayList<>()); 183 } 184 int a = abstracts.size(); 185 for (int k = 0; k + 1 < n; k++) { 186 if (k + 1 != a) { 187 after.get(k).add(k + 1); 188 before[k + 1]++; 189 } 190 } 191 for (int i = 0; i < a; i++) { 192 for (int j = a; j < n; j++) { 193 Boolean abstractFirst = before(siblings.get(i), siblings.get(j)); 194 if (abstractFirst != null) { 195 int from = abstractFirst ? i : j, to = abstractFirst ? j : i; 196 after.get(from).add(to); 197 before[to]++; 198 } 199 } 200 } 201 List<AstClafer> sorted = new ArrayList<>(n); 202 boolean[] placed = new boolean[n]; 203 while (sorted.size() < n) { 204 // The first sibling, in the default order, that nothing must 205 // precede; if the orders contradict each other, the first left. 206 int next = -1; 207 for (int k = 0; k < n && next < 0; k++) { 208 if (!placed[k] && before[k] == 0) { 209 next = k; 210 } 211 } 212 for (int k = 0; k < n && next < 0; k++) { 213 if (!placed[k]) { 214 next = k; 215 } 216 } 217 placed[next] = true; 218 sorted.add(siblings.get(next)); 219 for (int k : after.get(next)) { 220 before[k]--; 221 } 222 } 223 return sorted; 224 } 225 226 /** 227 * @return whether the subtree of a comes before the subtree of b in a list 228 * of subs that has clafers of both, or null if no list has 229 */ 230 private static Boolean before(AstClafer a, AstClafer b) { 231 Map<AstClafer, Integer> firstOfB = new HashMap<>(); 232 for (AstClafer y : subtree(b)) { 233 if (y.hasSuperClafer()) { 234 firstOfB.merge(y.getSuperClafer(), y.getSuperClafer().getSubs().indexOf(y), Math::min); 235 } 236 } 237 for (AstClafer x : subtree(a)) { 238 if (x.hasSuperClafer()) { 239 Integer other = firstOfB.get(x.getSuperClafer()); 240 if (other != null) { 241 return x.getSuperClafer().getSubs().indexOf(x) < other; 242 } 243 } 244 } 245 return null; 246 } 247 248 private static List<AstClafer> subtree(AstClafer clafer) { 249 List<AstClafer> subtree = new ArrayList<>(); 250 Deque<AstClafer> todo = new ArrayDeque<>(); 251 todo.push(clafer); 252 while (!todo.isEmpty()) { 253 AstClafer c = todo.pop(); 254 subtree.add(c); 255 c.getAbstractChildren().forEach(todo::push); 256 c.getChildren().forEach(todo::push); 257 } 258 return subtree; 259 } 260 261 private static void printConstraint(AstConstraint constraint, String indent, StringBuilder out) { 262 String expr = print(constraint.getExpr()); 263 out.append(indent).append(constraint.isHard() ? "[" + expr + "]" : "(" + expr + ")").append('\n'); 264 } 265 266 private static String card(Card card) { 267 return card.getLow() + ".." + (card.hasHigh() ? Integer.toString(card.getHigh()) : "*"); 268 } 269 270 /** 271 * Prints an expression. 272 * 273 * @param expr the expression 274 * @return the expression as text 275 */ 276 public static String print(AstExpr expr) { 277 return switch (expr) { 278 case AstThis e -> "this"; 279 case AstGlobal e -> e.type().getName(); 280 case AstLocal e -> e.getName(); 281 case AstChildRelation e -> e.childType().getName(); 282 case AstParentRelation e -> "parent(" + e.parentRelation().getName() + ")"; 283 case AstRefRelation e -> "dref(" + e.ref().getSourceType().getName() + ")"; 284 case AstConstant e -> constant(e); 285 case AstDecimalConstant e -> e.value().toPlainString(); 286 case AstStringConstant e -> string(e.value()); 287 case AstJoin e -> operand(e.left()) + "." + step(e.right()); 288 case AstJoinParent e -> operand(e.children()) + ".parent"; 289 case AstJoinRef e -> operand(e.deref()) + ".dref"; 290 case AstNot e -> "!" + operand(e.expr()); 291 // -1 is a constant, so the negation of a number is -(1), and of 292 // -1 is -(-1) rather than --1, which reads as the difference --. 293 case AstMinus e -> "-" + (e.expr() instanceof AstConstant || e.expr() instanceof AstDecimalConstant 294 ? "(" + print(e.expr()) + ")" : operand(e.expr())); 295 case AstCard e -> "#" + operand(e.set()); 296 case AstSum e -> "sum " + operand(e.set()) + ".dref"; 297 case AstProduct e -> "product " + operand(e.set()) + ".dref"; 298 case AstMax e -> "max " + operand(e.set()); 299 case AstMin e -> "min " + operand(e.set()); 300 case AstLength e -> "length " + operand(e.string()); 301 case AstInverse e -> "~" + operand(e.relation()); 302 case AstTransitiveClosure e -> (e.reflexive() ? "*" : "^") + operand(e.relation()); 303 case AstCompare e -> binary(e.left(), e.op().getSyntax(), e.right()); 304 case AstSetTest e -> binary(e.left(), e.op().getSyntax(), e.right()); 305 case AstMembership e -> binary(e.member(), e.op().getSyntax(), e.set()); 306 case AstMod e -> binary(e.dividend(), "%", e.divisor()); 307 case AstUnion e -> binary(e.left(), "++", e.right()); 308 case AstDifference e -> binary(e.left(), "--", e.right()); 309 case AstIntersection e -> binary(e.left(), "**", e.right()); 310 case AstDomainRestriction e -> binary(e.domain(), "<:", e.relation()); 311 case AstRangeRestriction e -> binary(e.relation(), ":>", e.range()); 312 case AstArithm e -> nary(e.operands(), e.op() == AstArithm.Op.DecimalMul ? "*." 313 : e.op() == AstArithm.Op.DecimalDiv ? "/." : e.op().getSyntax()); 314 case AstBoolArithm e -> nary(e.operands(), e.op().getSyntax()); 315 case AstConcat e -> "concat(" + print(e.left()) + ", " + print(e.right()) + ")"; 316 case AstPrefix e -> "prefix(" + print(e.prefix()) + ", " + print(e.word()) + ")"; 317 case AstSuffix e -> "suffix(" + print(e.suffix()) + ", " + print(e.word()) + ")"; 318 case AstConnected e -> "connected(" + print(e.nodes()) + ", " + print(e.relation()) 319 + (e.directed() ? ", directed)" : ", undirected)"); 320 case AstUpcast e -> "upcast(" + print(e.base()) + ", " + e.target() + ")"; 321 case AstDowncast e -> "downcast(" + print(e.base()) + ", " + e.target() + ")"; 322 case AstTernary e -> "if " + operand(e.antecedent()) + " then " + operand(e.consequent()) 323 + " else " + operand(e.alternative()); 324 case AstIfThenElse e -> "if " + operand(e.antecedent()) + " then " + operand(e.consequent()) 325 + " else " + operand(e.alternative()); 326 case AstQuantify e -> e.quantifier().getSyntax() + " " 327 + Arrays.stream(e.decls()).map(AstPrinter::decl).collect(Collectors.joining(", ")) 328 + " | " + print(e.body()); 329 }; 330 } 331 332 private static String decl(AstDecl decl) { 333 return (decl.isDisjoint() ? "disj " : "") 334 + Arrays.stream(decl.getLocals()).map(AstLocal::getName).collect(Collectors.joining("; ")) 335 + " : " + print(decl.getBody()); 336 } 337 338 private static boolean isAtom(AstExpr expr) { 339 return switch (expr) { 340 case AstThis e -> true; 341 case AstGlobal e -> true; 342 case AstLocal e -> true; 343 case AstChildRelation e -> true; 344 case AstParentRelation e -> true; 345 case AstRefRelation e -> true; 346 case AstConstant e -> true; 347 case AstDecimalConstant e -> true; 348 case AstStringConstant e -> true; 349 case AstConcat e -> true; 350 case AstPrefix e -> true; 351 case AstSuffix e -> true; 352 case AstConnected e -> true; 353 case AstUpcast e -> true; 354 case AstDowncast e -> true; 355 default -> false; 356 }; 357 } 358 359 private static boolean isNavigation(AstExpr expr) { 360 return expr instanceof AstJoin || expr instanceof AstJoinParent || expr instanceof AstJoinRef; 361 } 362 363 /** 364 * An operand of an operator: navigation binds tighter than any operator, 365 * so only the other compound expressions are parenthesized. 366 */ 367 private static String operand(AstExpr expr) { 368 return isAtom(expr) || isNavigation(expr) ? print(expr) : "(" + print(expr) + ")"; 369 } 370 371 /** 372 * The right of a navigation, parenthesized unless it is an atom. 373 */ 374 private static String step(AstExpr expr) { 375 return isAtom(expr) ? print(expr) : "(" + print(expr) + ")"; 376 } 377 378 private static String binary(AstExpr left, String op, AstExpr right) { 379 return operand(left) + " " + op + " " + operand(right); 380 } 381 382 private static String nary(AstExpr[] operands, String op) { 383 return Arrays.stream(operands).map(AstPrinter::operand).collect(Collectors.joining(" " + op + " ")); 384 } 385 386 private static String constant(AstConstant constant) { 387 int[][] value = constant.value(); 388 // The empty set, of any type, is Clafer's noclafer. 389 if (Arrays.stream(value).allMatch(column -> column.length == 0)) { 390 return "noclafer"; 391 } 392 if (constant.type().isInt() && value.length == 1 && value[0].length == 1) { 393 return Integer.toString(value[0][0]); 394 } 395 String tuples = Arrays.stream(value).map(Arrays::toString).collect(Collectors.joining(", ")); 396 return "{" + tuples + "} :: " + constant.type(); 397 } 398 399 /** 400 * A string from Clafer is its literal, quotes and escapes included, e.g., 401 * {@code "John"}, and chocosolver solves and prints it so; it is printed 402 * as it is. Other strings, from the Java API, are quoted and escaped. 403 */ 404 private static String string(String value) { 405 if (value.length() >= 2 && value.startsWith("\"") && value.endsWith("\"")) { 406 return value; 407 } 408 StringBuilder out = new StringBuilder("\""); 409 for (char c : value.toCharArray()) { 410 switch (c) { 411 case '"' -> out.append("\\\""); 412 case '\\' -> out.append("\\\\"); 413 case '\n' -> out.append("\\n"); 414 case '\t' -> out.append("\\t"); 415 default -> { 416 if (c < ' ' || c > '~') { 417 out.append(String.format("\\u%04x", (int) c)); 418 } else { 419 out.append(c); 420 } 421 } 422 } 423 } 424 return out.append('"').toString(); 425 } 426}