001package org.clafer.frontend; 002 003import java.util.ArrayDeque; 004import java.util.ArrayList; 005import java.util.Collections; 006import java.util.Deque; 007import java.util.HashMap; 008import java.util.HashSet; 009import java.util.IdentityHashMap; 010import java.util.LinkedHashSet; 011import java.util.List; 012import java.util.Map; 013import java.util.Optional; 014import java.util.Set; 015import java.util.stream.Collectors; 016import org.clafer.frontend.Ir.InitKind; 017import org.clafer.frontend.Syntax.Binary; 018import org.clafer.frontend.Syntax.BinaryOp; 019import org.clafer.frontend.Syntax.CardNum; 020import org.clafer.frontend.Syntax.CardSymbol; 021import org.clafer.frontend.Syntax.Clafer; 022import org.clafer.frontend.Syntax.ClaferId; 023import org.clafer.frontend.Syntax.ClaferUse; 024import org.clafer.frontend.Syntax.Declaration; 025import org.clafer.frontend.Syntax.Element; 026import org.clafer.frontend.Syntax.EnumDecl; 027import org.clafer.frontend.Syntax.Exp; 028import org.clafer.frontend.Syntax.GroupKeyword; 029import org.clafer.frontend.Syntax.Ident; 030import org.clafer.frontend.Syntax.Literal; 031import org.clafer.frontend.Syntax.Model; 032import org.clafer.frontend.Syntax.NCard; 033import org.clafer.frontend.Syntax.Node; 034import org.clafer.frontend.Syntax.TempModifier; 035import org.clafer.frontend.Syntax.TempModifierKind; 036import org.clafer.frontend.Syntax.Unary; 037import org.clafer.frontend.Syntax.UnaryOp; 038 039/** 040 * The symbols of a model, the first pass after the parser: a symbol per 041 * clafer, with its UID, its parent, its super clafer, the type of its 042 * reference, its card and group card with the defaults applied, its temporal 043 * modifiers and the clock of its initializer. An enumeration declares a 044 * symbol for itself and one for each literal. The tree is not changed: the 045 * symbols are found by their declarations. 046 * 047 * <p> 048 * The rules are those of the Clafer compiler, in the order it applies them: 049 * the desugarer ({@code Desugarer.hs}: enumerations, clafer uses, a primitive 050 * super, a reference to a constant), the UIDs ({@code UIDs.hs}), the supers 051 * ({@code ResolverInheritance.resolveNModule}, with the relocation of a 052 * top-level abstract clafer that extends a nested one, gsdlab/clafer#67), 053 * the references ({@code resolveOModule}), and the defaults of the cards 054 * ({@code analyzeModule}). A reference's target is resolved as the compiler 055 * resolves it: by a name, a path of names, or a set expression whose type is 056 * the primitive of its values or the nearest common super of its clafers. 057 * The names inside constraints are the next pass. 058 */ 059public final class Symbols { 060 061 private Symbols() { 062 } 063 064 /** 065 * An interval of a card or a group card. 066 * 067 * @param low the lower bound 068 * @param high the upper bound, {@link #Unbounded} for {@code *} 069 */ 070 public record Interval(int low, int high) { 071 072 public static final int Unbounded = -1; 073 public static final Interval Any = new Interval(0, Unbounded); 074 public static final Interval One = new Interval(1, 1); 075 public static final Interval Lone = new Interval(0, 1); 076 077 @Override 078 public String toString() { 079 return low + ".." + (high == Unbounded ? "*" : Integer.toString(high)); 080 } 081 } 082 083 /** 084 * A group card. 085 * 086 * @param keyword whether it was written as {@code xor}, {@code or}, 087 * {@code mux} or {@code opt}: a child under {@code opt} is optional, 088 * under a written {@code 0..*} mandatory 089 * @param interval its interval 090 */ 091 public record GroupCard(boolean keyword, Interval interval) { 092 093 /** 094 * The group card of a clafer that has none and inherits none. 095 */ 096 public static final GroupCard Default = new GroupCard(false, Interval.Any); 097 } 098 099 /** 100 * The modifiers of a reference: {@code finalref}, {@code finaltarget}, 101 * and {@code final}, which is both. 102 */ 103 public enum RefModifier { 104 FinalRef("finalref"), FinalTarget("finaltarget"), FinalRefTarget("final"); 105 106 private final String keyword; 107 108 RefModifier(String keyword) { 109 this.keyword = keyword; 110 } 111 112 public String keyword() { 113 return keyword; 114 } 115 } 116 117 /** 118 * The reference of a clafer. 119 * 120 * @param span the target as written, or the constant of {@code -> 1} 121 * @param isSet whether it is {@code ->}, rather than {@code ->>} 122 * @param target the target as written; for {@code -> 1}, the constant 123 * @param clafer the clafer it refers to, if its type is a clafer 124 * @param primitive the primitive it refers to, as written 125 * ({@code integer} or {@code int}), if its type is a primitive 126 */ 127 public record Reference(SourceSpan span, boolean isSet, Exp target, Optional<ClaferSymbol> clafer, 128 Optional<String> primitive) { 129 130 /** 131 * @return whether the reference has one type, a clafer or a 132 * primitive; a union of unrelated clafers has none 133 */ 134 public boolean hasType() { 135 return clafer.isPresent() || primitive.isPresent(); 136 } 137 138 /** 139 * @return the type as the explicit form writes it: a UID, or a 140 * primitive with {@code integer} as {@code int} 141 */ 142 public String typeName() { 143 if (clafer.isPresent()) { 144 return clafer.get().uid(); 145 } 146 String p = primitive.orElseThrow(); 147 return p.equals("integer") ? "int" : p; 148 } 149 } 150 151 /** 152 * A clafer, or an enumeration or one of its literals. 153 */ 154 public static final class ClaferSymbol { 155 156 private final Node declaration; 157 private final Ident name; 158 private final ClaferSymbol lexicalParent; 159 private final boolean isAbstract; 160 private final boolean isEnum; 161 private final boolean initial; 162 private final boolean isFinal; 163 private final List<RefModifier> refModifiers; 164 private final Optional<GroupCard> writtenGroupCard; 165 private final Optional<Interval> writtenCard; 166 private final Optional<Exp> superExp; 167 private final Optional<Syntax.Reference> writtenReference; 168 private final Optional<InitKind> initializer; 169 final List<ClaferSymbol> lexicalChildren = new ArrayList<>(); 170 // what the pass finds 171 String uid; 172 ClaferSymbol parent; 173 final List<ClaferSymbol> children = new ArrayList<>(); 174 ClaferSymbol superClafer; 175 boolean superResolved; 176 boolean inheritsInitial; 177 boolean inheritsFinal; 178 Reference reference; 179 // the types of the values of the reference, as the compiler's getRefIds 180 List<String> referenceIds = List.of(); 181 Interval card; 182 GroupCard groupCard; 183 184 ClaferSymbol(Node declaration, Ident name, ClaferSymbol lexicalParent, boolean isAbstract, boolean isEnum, 185 boolean initial, boolean isFinal, List<RefModifier> refModifiers, 186 Optional<GroupCard> writtenGroupCard, Optional<Interval> writtenCard, Optional<Exp> superExp, 187 Optional<Syntax.Reference> writtenReference, Optional<InitKind> initializer) { 188 this.declaration = declaration; 189 this.name = name; 190 this.lexicalParent = lexicalParent; 191 this.isAbstract = isAbstract; 192 this.isEnum = isEnum; 193 this.initial = initial; 194 this.isFinal = isFinal; 195 this.refModifiers = List.copyOf(refModifiers); 196 this.writtenGroupCard = writtenGroupCard; 197 this.writtenCard = writtenCard; 198 this.superExp = superExp; 199 this.writtenReference = writtenReference; 200 this.initializer = initializer; 201 } 202 203 /** 204 * @return the {@link Clafer}, {@link ClaferUse} or {@link EnumDecl} 205 * that declares it, or the {@link Ident} of an enumeration's literal 206 */ 207 public Node declaration() { 208 return declaration; 209 } 210 211 public String name() { 212 return name.text(); 213 } 214 215 public SourceSpan nameSpan() { 216 return name.span(); 217 } 218 219 public String uid() { 220 return uid; 221 } 222 223 /** 224 * @return its parent, empty at the top level; a top-level abstract 225 * clafer that extends a nested one is a sibling of its super 226 * (gsdlab/clafer#67) 227 */ 228 public Optional<ClaferSymbol> parent() { 229 return Optional.ofNullable(parent); 230 } 231 232 /** 233 * @return the clafer whose block declares it, empty at the top level 234 */ 235 public Optional<ClaferSymbol> lexicalParent() { 236 return Optional.ofNullable(lexicalParent); 237 } 238 239 /** 240 * @return its subclafers, in the order of the model, with the clafers 241 * relocated under it last 242 */ 243 public List<ClaferSymbol> children() { 244 return Collections.unmodifiableList(children); 245 } 246 247 public boolean isAbstract() { 248 return isAbstract; 249 } 250 251 /** 252 * @return whether it is an enumeration or one of its literals 253 */ 254 public boolean isEnum() { 255 return isEnum; 256 } 257 258 /** 259 * @return whether its parent is the root, as the compiler's 260 * {@code isTopLevel} 261 */ 262 public boolean isTopLevel() { 263 return parent == null; 264 } 265 266 /** 267 * @return the super as written, if it is a clafer: not a primitive 268 * super, which is a reference, nor {@code : clafer} 269 */ 270 Optional<Exp> superExp() { 271 return superExp; 272 } 273 274 public Optional<ClaferSymbol> superClafer() { 275 return Optional.ofNullable(superClafer); 276 } 277 278 public Optional<Reference> reference() { 279 return Optional.ofNullable(reference); 280 } 281 282 /** 283 * @return its card, as written or by default 284 */ 285 public Interval card() { 286 return card; 287 } 288 289 /** 290 * @return its group card: as written, or else that of its nearest 291 * super with one, or else {@link GroupCard#Default} 292 */ 293 public GroupCard groupCard() { 294 return groupCard; 295 } 296 297 public Optional<Interval> writtenCard() { 298 return writtenCard; 299 } 300 301 public Optional<GroupCard> writtenGroupCard() { 302 return writtenGroupCard; 303 } 304 305 /** 306 * @return whether it is initial, as written or as its super is 307 * written 308 */ 309 public boolean isInitial() { 310 return initial || inheritsInitial; 311 } 312 313 /** 314 * @return whether it is final, as written or as its super is written 315 */ 316 public boolean isFinal() { 317 return isFinal || inheritsFinal; 318 } 319 320 /** 321 * @return the modifiers of its reference, of its own or of the one it 322 * inherits ({@code finalref motor : engine}), as written 323 */ 324 public List<RefModifier> refModifiers() { 325 return refModifiers; 326 } 327 328 /** 329 * @return the clock of its initializer, if it has one: {@code =}, 330 * {@code := each} or {@code := together}, written or derived from the 331 * written card 332 */ 333 public Optional<InitKind> initializer() { 334 return initializer; 335 } 336 337 @Override 338 public String toString() { 339 return uid != null ? uid : name.text(); 340 } 341 } 342 343 /** 344 * The symbols of a model. 345 * 346 * @param topLevel the top-level symbols, in the order of the model, 347 * enumerations followed by their literals 348 * @param all all symbols, in pre-order of the declarations 349 * @param byDeclaration the symbol of each declaration, by identity 350 * @param diagnostics the errors 351 */ 352 public record Result(List<ClaferSymbol> topLevel, List<ClaferSymbol> all, 353 Map<Node, ClaferSymbol> byDeclaration, List<Diagnostic> diagnostics) { 354 355 /** 356 * @param declaration a clafer, a clafer use, an enumeration or the 357 * name of a literal 358 * @return its symbol 359 */ 360 public Optional<ClaferSymbol> of(Node declaration) { 361 return Optional.ofNullable(byDeclaration.get(declaration)); 362 } 363 } 364 365 static final Set<String> Primitives = Set.of("string", "int", "integer", "decimal", "double", "real"); 366 private static final Set<String> Specials = Set.of("this", "parent", "dref", "root", "children", "noclafer"); 367 368 /** 369 * @param model a parsed model 370 * @return its symbols 371 */ 372 public static Result analyze(Model model) { 373 return new Analysis().run(model); 374 } 375 376 private static final class Analysis { 377 378 private final List<ClaferSymbol> topLevel = new ArrayList<>(); 379 private final List<ClaferSymbol> all = new ArrayList<>(); 380 private final Map<Node, ClaferSymbol> byDeclaration = new IdentityHashMap<>(); 381 private final List<Diagnostic> diagnostics = new ArrayList<>(); 382 private final Set<ClaferSymbol> resolving = Collections.newSetFromMap(new IdentityHashMap<>()); 383 384 Result run(Model model) { 385 for (Declaration d : model.declarations()) { 386 declare(d); 387 } 388 assignUids(); 389 for (ClaferSymbol c : all) { 390 resolveSuper(c); 391 } 392 checkCycles(); 393 relocate(); 394 for (ClaferSymbol c : all) { 395 resolveReference(c); 396 } 397 for (ClaferSymbol c : roots()) { 398 analyzeCards(c, null); 399 } 400 checkDuplicateSiblings(roots()); 401 for (ClaferSymbol c : all) { 402 checkRedefinition(c); 403 checkGroup(c); 404 } 405 diagnostics.sort((a, b) -> a.span().line() != b.span().line() 406 ? Integer.compare(a.span().line(), b.span().line()) 407 : Integer.compare(a.span().column(), b.span().column())); 408 return new Result(List.copyOf(roots()), List.copyOf(all), Collections.unmodifiableMap(byDeclaration), 409 List.copyOf(diagnostics)); 410 } 411 412 private List<ClaferSymbol> roots() { 413 return topLevel; 414 } 415 416 private void error(SourceSpan span, String message) { 417 diagnostics.add(new Diagnostic(span, message)); 418 } 419 420 // -------------------------------------------------------------- 421 // Declarations, as the desugarer makes them 422 // -------------------------------------------------------------- 423 private void declare(Declaration d) { 424 switch (d) { 425 case EnumDecl e -> { 426 // an abstract clafer, and a clafer extending it for each literal 427 ClaferSymbol en = add(new ClaferSymbol(e, e.name(), null, true, true, false, false, List.of(), 428 Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty()), 429 null, e); 430 for (Ident literal : e.literals()) { 431 ClaferSymbol l = add(new ClaferSymbol(literal, literal, null, false, true, false, false, 432 List.of(), Optional.empty(), Optional.of(Interval.One), Optional.empty(), 433 Optional.empty(), Optional.empty()), null, literal); 434 l.superClafer = en; 435 l.superResolved = true; 436 } 437 } 438 case Element e -> declare(e, null); 439 } 440 } 441 442 private void declare(Element e, ClaferSymbol parent) { 443 switch (e) { 444 case Clafer c -> declareClafer(c, parent); 445 case ClaferUse u -> { 446 Ident name = u.name().path().get(u.name().path().size() - 1); 447 ClaferSymbol s = add(new ClaferSymbol(u, name, parent, false, false, false, false, List.of(), 448 Optional.empty(), u.card().flatMap(this::card), Optional.of(new ClaferId(u.name().span(), u.name())), 449 Optional.empty(), Optional.empty()), parent, u); 450 u.elements().ifPresent(es -> es.elements().forEach(x -> declare(x, s))); 451 } 452 default -> { 453 } 454 } 455 } 456 457 private void declareClafer(Clafer c, ClaferSymbol parent) { 458 Optional<Interval> writtenCard = c.card().flatMap(this::card); 459 Optional<Syntax.Reference> reference = c.reference(); 460 Optional<Exp> superExp = c.superClafer().map(Syntax.Super::exp); 461 Optional<InitKind> init = c.init().map(i -> switch (i.how()) { 462 case Constant -> InitKind.FIXED; 463 case Each -> InitKind.EACH; 464 case Together -> InitKind.TOGETHER; 465 // more than one instance under a parent: together; by the written card 466 case Default -> writtenCard.map(w -> w.high() != 0 && w.high() != 1).orElse(false) 467 ? InitKind.TOGETHER : InitKind.EACH; 468 }); 469 // a reference to a constant, `-> 1`, is a reference to its type with the value `= 1` 470 if (c.init().isEmpty() && reference.isPresent() && constantType(reference.get().exp()).isPresent()) { 471 init = Optional.of(InitKind.FIXED); 472 } 473 // a primitive super, `: integer`, is a reference 474 if (superExp.isPresent() && superName(superExp.get()).filter(Primitives::contains).isPresent()) { 475 if (reference.isPresent()) { 476 error(superExp.get().span(), "A clafer with a reference cannot have a primitive type as its super: " 477 + superName(superExp.get()).get()); 478 } else { 479 reference = Optional.of(new Syntax.Reference(c.superClafer().get().span(), false, superExp.get())); 480 } 481 superExp = Optional.empty(); 482 } 483 // `: clafer` is no super 484 if (superExp.isPresent() && superExp.get() instanceof ClaferId id && id.name().path().size() == 1 485 && id.name().path().get(0).text().equals("clafer")) { 486 superExp = Optional.empty(); 487 } 488 boolean initial = false; 489 boolean isFinal = false; 490 List<RefModifier> refModifiers = new ArrayList<>(); 491 for (TempModifier m : c.modifiers()) { 492 switch (m.kind()) { 493 case Initial -> initial = true; 494 case Final -> { 495 isFinal = true; 496 if (c.reference().isPresent()) { 497 addOnce(refModifiers, RefModifier.FinalRefTarget); 498 } 499 } 500 case FinalRef -> addOnce(refModifiers, RefModifier.FinalRef); 501 case FinalTarget -> addOnce(refModifiers, RefModifier.FinalTarget); 502 } 503 } 504 ClaferSymbol s = add(new ClaferSymbol(c, c.name(), parent, c.isAbstract(), false, initial, isFinal, 505 refModifiers, c.groupCard().flatMap(this::groupCard), writtenCard, superExp, reference, init), 506 parent, c); 507 c.elements().ifPresent(es -> es.elements().forEach(x -> declare(x, s))); 508 } 509 510 private static <T> void addOnce(List<T> list, T t) { 511 if (!list.contains(t)) { 512 list.add(t); 513 } 514 } 515 516 private ClaferSymbol add(ClaferSymbol s, ClaferSymbol parent, Node declaration) { 517 all.add(s); 518 byDeclaration.put(declaration, s); 519 if (parent == null) { 520 topLevel.add(s); 521 } else { 522 parent.lexicalChildren.add(s); 523 parent.children.add(s); 524 } 525 s.parent = parent; 526 return s; 527 } 528 529 private Optional<Interval> card(Syntax.Card card) { 530 return switch (card) { 531 case CardSymbol s -> Optional.of(switch (s.symbol()) { 532 case "?" -> Interval.Lone; 533 case "+" -> new Interval(1, Interval.Unbounded); 534 default -> Interval.Any; 535 }); 536 case CardNum n -> number(n.span(), n.number()).map(k -> new Interval(k, k)); 537 case NCard n -> interval(n); 538 }; 539 } 540 541 private Optional<GroupCard> groupCard(Syntax.GCard card) { 542 return switch (card) { 543 case GroupKeyword k -> Optional.of(new GroupCard(true, switch (k.keyword()) { 544 case "xor" -> Interval.One; 545 case "or" -> new Interval(1, Interval.Unbounded); 546 case "mux" -> Interval.Lone; 547 default -> Interval.Any; 548 })); 549 case NCard n -> interval(n).map(i -> new GroupCard(false, i)); 550 }; 551 } 552 553 private Optional<Interval> interval(NCard n) { 554 Optional<Integer> low = number(n.span(), n.low()); 555 Optional<Integer> high = n.high().isEmpty() ? Optional.of(Interval.Unbounded) : number(n.span(), n.high().get()); 556 return low.isPresent() && high.isPresent() ? Optional.of(new Interval(low.get(), high.get())) : Optional.empty(); 557 } 558 559 private Optional<Integer> number(SourceSpan span, String text) { 560 try { 561 return Optional.of(Integer.parseInt(text)); 562 } catch (NumberFormatException e) { 563 error(span, "The bound " + text + " is too large"); 564 return Optional.empty(); 565 } 566 } 567 568 /** 569 * The type of a constant as a reference's target, as the desugarer's 570 * {@code constantType}: a real literal, {@code 3.14}, is a decimal. 571 */ 572 private static Optional<String> constantType(Exp exp) { 573 Exp e = exp instanceof Unary u && u.op() == UnaryOp.Minus ? u.exp() : exp; 574 if (e instanceof Literal l) { 575 return Optional.of(switch (l.kind()) { 576 case Int -> "integer"; 577 case Double -> "double"; 578 case Real -> "decimal"; 579 case Str -> "string"; 580 }); 581 } 582 return Optional.empty(); 583 } 584 585 /** 586 * The last name of a name or a path, as the desugarer's 587 * {@code getPExpClaferIdent}. 588 */ 589 private static Optional<String> superName(Exp exp) { 590 return switch (exp) { 591 case ClaferId id -> Optional.of(last(id)); 592 case Binary b when b.op() == BinaryOp.Join -> superName(b.right()); 593 default -> Optional.empty(); 594 }; 595 } 596 597 private static String last(ClaferId id) { 598 return id.name().path().get(id.name().path().size() - 1).text(); 599 } 600 601 // -------------------------------------------------------------- 602 // UIDs, as UIDs.assignUIDs 603 // -------------------------------------------------------------- 604 private void assignUids() { 605 List<List<String>> reversed = new ArrayList<>(); 606 for (ClaferSymbol s : all) { 607 List<String> path = new ArrayList<>(); 608 for (ClaferSymbol c = s; c != null; c = c.lexicalParent) { 609 path.add(c.name()); 610 } 611 reversed.add(path); 612 } 613 Map<List<String>, Integer> suffixCounts = new HashMap<>(); 614 for (List<String> rp : reversed) { 615 Set<List<String>> suffixes = new HashSet<>(); 616 for (int k = 1; k <= rp.size(); k++) { 617 suffixes.add(rp.subList(0, k)); 618 } 619 for (List<String> s : suffixes) { 620 suffixCounts.merge(s, 1, Integer::sum); 621 } 622 } 623 Set<String> used = new HashSet<>(); 624 for (int i = 0; i < all.size(); i++) { 625 List<String> rp = reversed.get(i); 626 List<String> chosen = null; 627 for (int k = 1; k <= rp.size() && chosen == null; k++) { 628 if (suffixCounts.get(rp.subList(0, k)) == 1) { 629 chosen = rp.subList(0, k); 630 } 631 } 632 if (chosen == null) { 633 chosen = new ArrayList<>(rp); 634 chosen.add("root"); 635 } 636 List<String> names = new ArrayList<>(chosen); 637 Collections.reverse(names); 638 String uid = names.stream().map(n -> n.replace("'", "_prime")).collect(Collectors.joining("__")); 639 String fresh = uid; 640 for (int n = 2; used.contains(fresh); n++) { 641 fresh = uid + "__" + n; 642 } 643 used.add(fresh); 644 all.get(i).uid = fresh; 645 } 646 } 647 648 // -------------------------------------------------------------- 649 // Supers, as ResolverInheritance.resolveNSuper 650 // -------------------------------------------------------------- 651 private List<ClaferSymbol> abstractClafers() { 652 return all.stream().filter(c -> c.isAbstract).toList(); 653 } 654 655 /** 656 * The supers of the clafer, nearest first, without a cycle. 657 */ 658 private List<ClaferSymbol> superChain(ClaferSymbol c) { 659 List<ClaferSymbol> chain = new ArrayList<>(); 660 Set<ClaferSymbol> visited = Collections.newSetFromMap(new IdentityHashMap<>()); 661 visited.add(c); 662 for (ClaferSymbol s = resolveSuper(c); s != null && visited.add(s); s = resolveSuper(s)) { 663 chain.add(s); 664 } 665 return chain; 666 } 667 668 private ClaferSymbol resolveSuper(ClaferSymbol c) { 669 if (c.superResolved || c.superExp.isEmpty()) { 670 return c.superClafer; 671 } 672 if (!resolving.add(c)) { 673 // a cycle, which checkCycles reports 674 return null; 675 } 676 try { 677 Exp exp = c.superExp.get(); 678 c.superClafer = switch (exp) { 679 case ClaferId id -> superByName(c, id); 680 case Binary b when b.op() == BinaryOp.Join -> superByPath(c, b); 681 default -> { 682 error(exp.span(), "A super must be the name of an abstract clafer or a path to it, e.g., Person.Head"); 683 yield null; 684 } 685 }; 686 c.superResolved = true; 687 if (c.superClafer != null) { 688 c.inheritsInitial = c.superClafer.initial; 689 c.inheritsFinal = c.superClafer.isFinal; 690 } 691 return c.superClafer; 692 } finally { 693 resolving.remove(c); 694 } 695 } 696 697 private ClaferSymbol superByName(ClaferSymbol c, ClaferId id) { 698 String name = last(id); 699 if (Primitives.contains(name)) { 700 error(id.span(), "Primitive types are not allowed as super types: " + name); 701 return null; 702 } 703 List<ClaferSymbol> abstracts = abstractClafers().stream().filter(a -> a != c).toList(); 704 // a clafer cannot extend itself, unless it redefines another clafer with its name 705 if (c.isAbstract && name.equals(c.name()) && abstracts.stream().noneMatch(a -> a.name().equals(name))) { 706 error(c.declaration.span(), "clafer " + c.uid + " inherits from itself"); 707 return null; 708 } 709 // the nearest abstract clafer with the name among the children of the parent and 710 // those the parent inherits 711 if (c.lexicalParent != null) { 712 List<ClaferSymbol> scopes = new ArrayList<>(); 713 scopes.add(c.lexicalParent); 714 scopes.addAll(superChain(c.lexicalParent)); 715 for (ClaferSymbol s : scopes) { 716 for (ClaferSymbol child : s.lexicalChildren) { 717 if (child.isAbstract && child != c && child.name().equals(name)) { 718 return child; 719 } 720 } 721 } 722 } 723 List<ClaferSymbol> candidates = abstracts.stream().filter(a -> a.name().equals(name)).toList(); 724 if (candidates.isEmpty()) { 725 error(id.span(), "No superclafer found: " + name); 726 return null; 727 } 728 if (candidates.size() > 1) { 729 error(id.span(), "clafer \"" + name + "\" is not unique. Available paths: " 730 + candidates.stream().map(Analysis::path).collect(Collectors.joining(", "))); 731 return null; 732 } 733 return candidates.get(0); 734 } 735 736 private ClaferSymbol superByPath(ClaferSymbol c, Binary path) { 737 List<ClaferId> names = new ArrayList<>(); 738 if (!pathNames(path, names)) { 739 error(path.span(), "A super must be the name of an abstract clafer or a path to it, e.g., Person.Head"); 740 return null; 741 } 742 String text = names.stream().map(Analysis::last).collect(Collectors.joining(".")); 743 String first = last(names.get(0)); 744 ClaferSymbol s = null; 745 for (ClaferSymbol a = c.lexicalParent; a != null && s == null; a = a.lexicalParent) { 746 if (a.name().equals(first)) { 747 s = a; 748 } 749 } 750 if (s == null) { 751 List<ClaferSymbol> named = all.stream().filter(x -> x.name().equals(first)).toList(); 752 List<ClaferSymbol> top = named.stream().filter(x -> x.lexicalParent == null).toList(); 753 if (named.isEmpty()) { 754 error(path.span(), "No superclafer found: no clafer " + first + " for " + text); 755 return null; 756 } else if (named.size() == 1) { 757 s = named.get(0); 758 } else if (top.size() == 1) { 759 s = top.get(0); 760 } else { 761 error(path.span(), "No superclafer found: the clafer " + first + " in " + text + " is not unique"); 762 return null; 763 } 764 } 765 for (ClaferId id : names.subList(1, names.size())) { 766 String n = last(id); 767 ClaferSymbol child = null; 768 List<ClaferSymbol> scopes = new ArrayList<>(); 769 scopes.add(s); 770 scopes.addAll(superChain(s)); 771 for (ClaferSymbol scope : scopes) { 772 for (ClaferSymbol x : scope.lexicalChildren) { 773 if (child == null && x.name().equals(n)) { 774 child = x; 775 } 776 } 777 } 778 if (child == null) { 779 error(id.span(), "No superclafer found: " + s.name() + " has no child " + n 780 + ", neither its own nor an inherited one, for " + text); 781 return null; 782 } 783 s = child; 784 } 785 if (s == c) { 786 error(path.span(), "clafer " + c.uid + " inherits from itself"); 787 return null; 788 } 789 if (!s.isAbstract) { 790 error(path.span(), "No superclafer found: " + text + " is not abstract, and only abstract clafers can be supers"); 791 return null; 792 } 793 return s; 794 } 795 796 private static boolean pathNames(Exp exp, List<ClaferId> names) { 797 return switch (exp) { 798 case ClaferId id -> names.add(id); 799 case Binary b when b.op() == BinaryOp.Join -> pathNames(b.left(), names) && pathNames(b.right(), names); 800 default -> false; 801 }; 802 } 803 804 private static String path(ClaferSymbol c) { 805 List<String> names = new ArrayList<>(); 806 for (ClaferSymbol a = c; a != null; a = a.lexicalParent) { 807 names.add(0, a.name()); 808 } 809 return String.join(".", names); 810 } 811 812 private void checkCycles() { 813 for (ClaferSymbol c : all) { 814 Set<ClaferSymbol> visited = Collections.newSetFromMap(new IdentityHashMap<>()); 815 for (ClaferSymbol s = c.superClafer; s != null && visited.add(s); s = s.superClafer) { 816 if (s == c) { 817 error(c.declaration.span(), "clafer " + c.uid + " inherits from itself"); 818 break; 819 } 820 } 821 } 822 } 823 824 /** 825 * A top-level abstract clafer that extends a nested abstract clafer 826 * becomes a sibling of its super (gsdlab/clafer#67): it goes after 827 * the children of its super's parent. 828 */ 829 private void relocate() { 830 List<ClaferSymbol> moved = new ArrayList<>(); 831 for (ClaferSymbol c : topLevel) { 832 if (c.isAbstract && c.superClafer != null && c.superClafer.lexicalParent != null) { 833 moved.add(c); 834 } 835 } 836 for (ClaferSymbol c : moved) { 837 topLevel.remove(c); 838 c.parent = c.superClafer.lexicalParent; 839 c.parent.children.add(c); 840 } 841 } 842 843 // -------------------------------------------------------------- 844 // References, as ResolverInheritance.resolveOReference 845 // -------------------------------------------------------------- 846 private void resolveReference(ClaferSymbol c) { 847 if (c.writtenReference.isEmpty()) { 848 return; 849 } 850 Syntax.Reference r = c.writtenReference.get(); 851 Exp target = r.exp(); 852 boolean isSet = !r.bag(); 853 Optional<String> constant = constantType(target); 854 if (constant.isPresent()) { 855 c.reference = new Reference(target.span(), isSet, target, Optional.empty(), constant); 856 c.referenceIds = List.of(constant.get()); 857 return; 858 } 859 List<Type> leaves = new ArrayList<>(); 860 boolean setExp = target instanceof Binary b && isSetOp(b.op()); 861 if (!typesOf(c, target, leaves)) { 862 c.reference = new Reference(target.span(), isSet, target, Optional.empty(), Optional.empty()); 863 return; 864 } 865 c.referenceIds = leaves.stream().map(t -> t.clafer().map(ClaferSymbol::uid).orElseGet(() -> t.primitive().get())) 866 .toList(); 867 Optional<Type> type = setExp ? setExpType(leaves) : leaves.size() == 1 ? Optional.of(leaves.get(0)) : Optional.empty(); 868 c.reference = new Reference(target.span(), isSet, target, 869 type.flatMap(Type::clafer), type.flatMap(Type::primitive)); 870 } 871 872 private record Type(Optional<ClaferSymbol> clafer, Optional<String> primitive) { 873 874 static Type of(ClaferSymbol c) { 875 return new Type(Optional.of(c), Optional.empty()); 876 } 877 878 static Type of(String primitive) { 879 return new Type(Optional.empty(), Optional.of(primitive)); 880 } 881 } 882 883 private static boolean isSetOp(BinaryOp op) { 884 return op == BinaryOp.Union || op == BinaryOp.UnionCom || op == BinaryOp.Difference 885 || op == BinaryOp.Intersection || op == BinaryOp.IntersectionDeprecated; 886 } 887 888 /** 889 * The types of the values of a target, as the compiler's 890 * {@code getRefIds}: of each operand of a set operator, and of the 891 * last name of a path. 892 */ 893 private boolean typesOf(ClaferSymbol c, Exp exp, List<Type> types) { 894 Optional<String> constant = constantType(exp); 895 if (constant.isPresent()) { 896 types.add(Type.of(constant.get())); 897 return true; 898 } 899 switch (exp) { 900 case Binary b when isSetOp(b.op()) -> { 901 return typesOf(c, b.left(), types) && typesOf(c, b.right(), types); 902 } 903 case Binary b when b.op() == BinaryOp.Join -> { 904 List<ClaferId> names = new ArrayList<>(); 905 if (!pathNames(b, names)) { 906 error(exp.span(), "A reference's target must be a name, a path or a set expression"); 907 return false; 908 } 909 Optional<Type> t = resolveFirst(c, names.get(0)); 910 for (ClaferId id : names.subList(1, names.size())) { 911 if (t.isEmpty() || t.get().clafer().isEmpty()) { 912 if (t.isPresent()) { 913 error(id.span(), "Name resolver: '" + last(id) + "' not found"); 914 } 915 return false; 916 } 917 t = resolveChild(t.get().clafer().get(), id); 918 } 919 t.ifPresent(types::add); 920 return t.isPresent(); 921 } 922 case ClaferId id -> { 923 Optional<Type> t = resolveFirst(c, id); 924 t.ifPresent(types::add); 925 return t.isPresent(); 926 } 927 default -> { 928 error(exp.span(), "A reference's target must be a name, a path or a set expression"); 929 return false; 930 } 931 } 932 } 933 934 /** 935 * The first name of a target: a primitive, or the unique clafer with 936 * the name in the trees of the top-level abstract clafers, or else of 937 * the concrete ones, inherited children included, as the compiler's 938 * {@code resolveTopLevel}. 939 */ 940 private Optional<Type> resolveFirst(ClaferSymbol c, ClaferId id) { 941 String name = last(id); 942 if (Primitives.contains(name)) { 943 return Optional.of(Type.of(name)); 944 } 945 if (Specials.contains(name)) { 946 error(id.span(), "A reference's target cannot be '" + name + "'"); 947 return Optional.empty(); 948 } 949 for (boolean abstractTrees : new boolean[]{true, false}) { 950 List<List<ClaferSymbol>> found = new ArrayList<>(); 951 for (List<ClaferSymbol> p : bfs(abstractTrees)) { 952 if (p.get(0).name().equals(name)) { 953 found.add(p); 954 } 955 } 956 if (found.size() == 1) { 957 return Optional.of(Type.of(found.get(0).get(0))); 958 } 959 if (found.size() > 1) { 960 error(id.span(), "clafer \"" + name + "\" is not unique. Available paths: " 961 + found.stream().map(Analysis::showPath).distinct().collect(Collectors.joining(", "))); 962 return Optional.empty(); 963 } 964 } 965 error(id.span(), "Name resolver: '" + name + "' not found"); 966 return Optional.empty(); 967 } 968 969 private static String showPath(List<ClaferSymbol> path) { 970 List<String> uids = path.stream().map(ClaferSymbol::uid).collect(Collectors.toList()); 971 Collections.reverse(uids); 972 return String.join(".", uids); 973 } 974 975 /** 976 * The paths, nearest clafer first, of the clafers in the trees of the 977 * top-level abstract or concrete clafers, breadth first, through the 978 * children and the inherited children; a path stops at a clafer that 979 * it reaches a second time. 980 */ 981 private List<List<ClaferSymbol>> bfs(boolean abstractTrees) { 982 List<List<ClaferSymbol>> out = new ArrayList<>(); 983 Deque<List<ClaferSymbol>> queue = new ArrayDeque<>(); 984 for (ClaferSymbol t : topLevel) { 985 if (t.isAbstract == abstractTrees) { 986 queue.add(List.of(t)); 987 } 988 } 989 Set<List<ClaferSymbol>> seen = new HashSet<>(); 990 while (!queue.isEmpty()) { 991 List<ClaferSymbol> p = queue.poll(); 992 if (seen.add(p)) { 993 out.add(p); 994 } 995 ClaferSymbol c = p.get(0); 996 if (Collections.frequency(p, c) > 1) { 997 continue; 998 } 999 for (ClaferSymbol child : inheritedChildren(c)) { 1000 List<ClaferSymbol> q = new ArrayList<>(); 1001 q.add(child); 1002 q.addAll(p); 1003 queue.add(q); 1004 } 1005 } 1006 return out; 1007 } 1008 1009 /** 1010 * The children of the clafer and of its supers. 1011 */ 1012 private List<ClaferSymbol> inheritedChildren(ClaferSymbol c) { 1013 List<ClaferSymbol> out = new ArrayList<>(c.children); 1014 for (ClaferSymbol s : superChain(c)) { 1015 out.addAll(s.children); 1016 } 1017 return out; 1018 } 1019 1020 /** 1021 * The next name of a path: a child of the clafer, its own or an 1022 * inherited one, or else a child of its reference's target. 1023 */ 1024 private Optional<Type> resolveChild(ClaferSymbol c, ClaferId id) { 1025 String name = last(id); 1026 Set<ClaferSymbol> own = new LinkedHashSet<>(); 1027 for (ClaferSymbol x : inheritedChildren(c)) { 1028 if (x.name().equals(name)) { 1029 own.add(x); 1030 } 1031 } 1032 if (own.isEmpty()) { 1033 Set<ClaferSymbol> visited = Collections.newSetFromMap(new IdentityHashMap<>()); 1034 for (ClaferSymbol t = c; t != null && visited.add(t); ) { 1035 if (t.writtenReference.isPresent() && t.reference == null && t != c) { 1036 resolveReference(t); 1037 } 1038 ClaferSymbol target = null; 1039 for (ClaferSymbol s : withSupers(t)) { 1040 if (s.reference != null && s.reference.clafer().isPresent()) { 1041 target = s.reference.clafer().get(); 1042 break; 1043 } 1044 } 1045 t = target; 1046 if (t != null) { 1047 for (ClaferSymbol x : inheritedChildren(t)) { 1048 if (x.name().equals(name)) { 1049 own.add(x); 1050 } 1051 } 1052 } 1053 } 1054 } 1055 if (own.size() == 1) { 1056 return Optional.of(Type.of(own.iterator().next())); 1057 } 1058 error(id.span(), own.isEmpty() 1059 ? "Name resolver: '" + name + "' not found within " + c.uid 1060 : "clafer \"" + name + "\" is not unique in " + c.uid); 1061 return Optional.empty(); 1062 } 1063 1064 private List<ClaferSymbol> withSupers(ClaferSymbol c) { 1065 List<ClaferSymbol> out = new ArrayList<>(); 1066 out.add(c); 1067 out.addAll(superChain(c)); 1068 return out; 1069 } 1070 1071 /** 1072 * The type of a set expression, as the compiler's 1073 * {@code setExpType}: the primitive of its values, with integers 1074 * among decimals as decimals, or the nearest common super of its 1075 * clafers. 1076 */ 1077 private Optional<Type> setExpType(List<Type> leaves) { 1078 if (leaves.stream().allMatch(t -> t.primitive().isPresent())) { 1079 Set<String> types = new java.util.TreeSet<>(); 1080 for (Type t : leaves) { 1081 types.add(t.primitive().get().equals("int") ? "integer" : t.primitive().get()); 1082 } 1083 if (types.size() == 1) { 1084 return Optional.of(Type.of(types.iterator().next())); 1085 } 1086 if (types.equals(Set.of("decimal", "integer"))) { 1087 return Optional.of(Type.of("decimal")); 1088 } 1089 return Optional.empty(); 1090 } 1091 if (leaves.stream().allMatch(t -> t.clafer().isPresent())) { 1092 List<List<ClaferSymbol>> supers = leaves.stream().map(t -> withSupers(t.clafer().get())).toList(); 1093 for (ClaferSymbol u : supers.get(0)) { 1094 if (supers.stream().allMatch(s -> s.contains(u))) { 1095 return Optional.of(Type.of(u)); 1096 } 1097 } 1098 } 1099 return Optional.empty(); 1100 } 1101 1102 // -------------------------------------------------------------- 1103 // Cards, as ResolverInheritance.analyzeModule 1104 // -------------------------------------------------------------- 1105 private void analyzeCards(ClaferSymbol c, ClaferSymbol parent) { 1106 c.groupCard = c.writtenGroupCard.orElse(null); 1107 if (c.groupCard == null && c.superClafer != null) { 1108 for (ClaferSymbol s : superChain(c)) { 1109 if (s.writtenGroupCard.isPresent()) { 1110 c.groupCard = s.writtenGroupCard.get(); 1111 break; 1112 } 1113 } 1114 } 1115 if (c.groupCard == null) { 1116 c.groupCard = GroupCard.Default; 1117 } 1118 if (c.writtenCard.isPresent()) { 1119 c.card = c.writtenCard.get(); 1120 } else if (c.isAbstract) { 1121 c.card = Interval.Any; 1122 } else if (parent == null || parent.groupCard.equals(GroupCard.Default)) { 1123 // mandatory at the top level and under the default group; optional under a 1124 // keyword group (opt included) or a numeric one 1125 c.card = Interval.One; 1126 } else { 1127 c.card = Interval.Lone; 1128 } 1129 for (ClaferSymbol child : c.children) { 1130 analyzeCards(child, c); 1131 } 1132 } 1133 1134 /** 1135 * The UID of the parent as the compiler's {@code _parentUID}: the 1136 * root of a top-level clafer is {@code root}, and that of a 1137 * top-level abstract one {@code clafer}. 1138 */ 1139 private static String parentUid(ClaferSymbol c) { 1140 return c.parent != null ? c.parent.uid : c.isAbstract ? "clafer" : "root"; 1141 } 1142 1143 /** 1144 * A primitive and the primitives it converts to, as the compiler's 1145 * hierarchy of primitives: an integer is a decimal, a decimal and a 1146 * double are reals. 1147 */ 1148 private static List<String> primitiveSupers(String p) { 1149 return switch (p) { 1150 case "integer", "int" -> List.of(p, "decimal", "real"); 1151 case "decimal", "double" -> List.of(p, "real"); 1152 default -> List.of(p); 1153 }; 1154 } 1155 1156 private List<String> supersOfId(String id) { 1157 if (Primitives.contains(id)) { 1158 return primitiveSupers(id); 1159 } 1160 return all.stream().filter(s -> s.uid.equals(id)).findFirst() 1161 .map(s -> withSupers(s).stream().map(x -> x.uid).toList()).orElse(List.of(id)); 1162 } 1163 1164 /** 1165 * The nesting and the redefinition of a clafer with a super, as the 1166 * compiler's {@code resolveRedefinition}: a super that is nested 1167 * belongs to the parent, or to a super of the parent's super; a 1168 * concrete super's card is narrowed; a set reference stays a set; the 1169 * target is a subtype of the super's target. 1170 */ 1171 private void checkRedefinition(ClaferSymbol c) { 1172 ClaferSymbol s = c.superClafer; 1173 if (s == null || c.isEnum) { 1174 return; 1175 } 1176 String superParent = parentUid(s); 1177 boolean properNesting = (s.parent == null && s.isAbstract) 1178 || parentUid(c).equals(superParent) 1179 || (c.parent != null && c.parent.superClafer != null 1180 && withSupers(c.parent.superClafer).stream().anyMatch(x -> x.uid.equals(superParent))); 1181 String problem = null; 1182 if (!properNesting) { 1183 problem = "Improperly nested clafer"; 1184 } else if (!s.isAbstract && !(c.card.low() >= s.card.low() 1185 && (c.card.high() <= s.card.high() || s.card.high() == Interval.Unbounded))) { 1186 problem = "Improper cardinality refinement for clafer"; 1187 } else if (c.reference != null && s.reference != null && s.reference.isSet() && !c.reference.isSet()) { 1188 problem = "Improper bag to set refinement for clafer"; 1189 } else if (c.referenceIds.size() == 1 && s.referenceIds.size() == 1) { 1190 String target = c.referenceIds.get(0); 1191 String superTarget = s.referenceIds.get(0); 1192 if (!supersOfId(target).contains(superTarget) 1193 && !((target.equals("integer") || target.equals("int")) && superTarget.equals("double"))) { 1194 problem = "Improper target subtyping for clafer"; 1195 } 1196 } 1197 if (problem != null) { 1198 error(c.declaration.span(), problem + " '" + c.name() + "'"); 1199 } 1200 } 1201 1202 /** 1203 * A concrete clafer's group card can be satisfied: its children, the 1204 * inherited ones included, can have as many instances as its lower 1205 * bound, as the compiler's {@code unsatisfiableGroups}, e.g., 1206 * {@code xor} over no children. 1207 */ 1208 private void checkGroup(ClaferSymbol c) { 1209 int low = c.groupCard.interval().low(); 1210 if (c.isAbstract || low <= 0) { 1211 return; 1212 } 1213 long most = 0; 1214 for (ClaferSymbol child : inheritedChildren(c)) { 1215 if (child.card.high() == Interval.Unbounded) { 1216 return; 1217 } 1218 most += child.card.high(); 1219 } 1220 if (most < low) { 1221 error(c.declaration.span(), "The group cardinality " + c.groupCard.interval() + " of " + c.name() 1222 + " cannot be satisfied: its children, including the inherited ones, can have at most " 1223 + most + " instances"); 1224 } 1225 } 1226 1227 private void checkDuplicateSiblings(List<ClaferSymbol> siblings) { 1228 // at the first clafer with the name, as the compiler reports it 1229 Map<String, ClaferSymbol> seen = new HashMap<>(); 1230 Set<ClaferSymbol> reported = Collections.newSetFromMap(new IdentityHashMap<>()); 1231 for (ClaferSymbol s : siblings) { 1232 ClaferSymbol first = seen.putIfAbsent(s.name(), s); 1233 if (first != null && reported.add(first)) { 1234 error(first.declaration.span(), "Duplicate name: " + s.name()); 1235 } 1236 checkDuplicateSiblings(s.children); 1237 } 1238 } 1239 } 1240 1241 // ------------------------------------------------------------------ 1242 // The outline 1243 // ------------------------------------------------------------------ 1244 /** 1245 * The clafers as the explicit form declares them, without their 1246 * constraints and the values of their initializers: one line per clafer, 1247 * {@code [abstract] [modifiers] gcard uid [: super] [-> type] card [init]}, 1248 * its subclafers indented under it, and an enumeration as 1249 * {@code enum E = a | b}. It is what the symbols say about a model, and 1250 * {@link #outline(Ir.Model)} gives the same for an explicit model. 1251 * 1252 * @param symbols the symbols of a model 1253 * @return its outline 1254 */ 1255 public static String outline(Result symbols) { 1256 StringBuilder out = new StringBuilder(); 1257 for (ClaferSymbol c : symbols.topLevel()) { 1258 if (c.isEnum()) { 1259 if (c.isAbstract()) { 1260 out.append("enum ").append(c.uid()).append(" = ").append(symbols.topLevel().stream() 1261 .filter(l -> l.isEnum() && l.superClafer().orElse(null) == c) 1262 .map(ClaferSymbol::uid).collect(Collectors.joining(" | "))).append('\n'); 1263 } 1264 } else { 1265 outline(c, "", out); 1266 } 1267 } 1268 return out.toString(); 1269 } 1270 1271 private static void outline(ClaferSymbol c, String indent, StringBuilder out) { 1272 out.append(indent); 1273 if (c.isAbstract()) { 1274 out.append("abstract "); 1275 } 1276 if (c.isInitial()) { 1277 out.append("initial "); 1278 } 1279 if (c.isFinal()) { 1280 out.append("final "); 1281 } else { 1282 for (RefModifier m : c.refModifiers()) { 1283 out.append(m.keyword()).append(' '); 1284 } 1285 } 1286 out.append(printedGroupCard(c)).append(' ').append(c.uid()); 1287 c.superClafer().ifPresent(s -> out.append(" : ").append(s.uid())); 1288 c.reference().filter(Reference::hasType) 1289 .ifPresent(r -> out.append(r.isSet() ? " -> " : " ->> ").append(r.typeName())); 1290 out.append(' ').append(c.card()); 1291 c.initializer().ifPresent(i -> out.append(' ').append(i.syntax())); 1292 out.append('\n'); 1293 for (ClaferSymbol child : c.children()) { 1294 outline(child, indent + " ", out); 1295 } 1296 } 1297 1298 /** 1299 * The group card as the explicit form prints it: the clafer's, unless it 1300 * is {@code 0..*}, and then its super's. 1301 */ 1302 static Interval printedGroupCard(ClaferSymbol c) { 1303 Set<ClaferSymbol> visited = Collections.newSetFromMap(new IdentityHashMap<>()); 1304 for (ClaferSymbol s = c; s != null && visited.add(s); s = s.superClafer().orElse(null)) { 1305 if (!s.groupCard().interval().equals(Interval.Any)) { 1306 return s.groupCard().interval(); 1307 } 1308 } 1309 return Interval.Any; 1310 } 1311 1312 /** 1313 * @param model an explicit model 1314 * @return its outline, as {@link #outline(Result)} 1315 */ 1316 public static String outline(Ir.Model model) { 1317 StringBuilder out = new StringBuilder(); 1318 for (Ir.Element e : model.elements()) { 1319 switch (e) { 1320 case Ir.EnumDecl en -> out.append("enum ").append(en.name().text()).append(" = ") 1321 .append(en.literals().stream().map(Ir.Name::text).collect(Collectors.joining(" | "))) 1322 .append('\n'); 1323 case Ir.ClaferDecl c -> outline(c, "", out); 1324 default -> { 1325 } 1326 } 1327 } 1328 return out.toString(); 1329 } 1330 1331 private static void outline(Ir.ClaferDecl c, String indent, StringBuilder out) { 1332 out.append(indent); 1333 if (c.isAbstract()) { 1334 out.append("abstract "); 1335 } 1336 for (Ir.Modifier m : c.modifiers()) { 1337 out.append(m.kind().keyword()).append(' '); 1338 } 1339 out.append(c.groupCard()).append(' ').append(c.name().text()); 1340 c.superName().ifPresent(s -> out.append(" : ").append(s.text())); 1341 c.ref().ifPresent(r -> out.append(r.isSet() ? " -> " : " ->> ").append(r.target().text())); 1342 out.append(' ').append(c.abstractMultiplicity().map(Ir.AbstractMultiplicity::card).orElse(c.card())); 1343 c.initializer().ifPresent(i -> out.append(' ').append(i.kind().syntax())); 1344 out.append('\n'); 1345 for (Ir.Element e : c.elements()) { 1346 if (e instanceof Ir.ClaferDecl child) { 1347 outline(child, indent + " ", out); 1348 } 1349 } 1350 } 1351}