001package org.clafer.frontend;
002
003import java.util.ArrayList;
004import java.util.EnumSet;
005import java.util.HashMap;
006import java.util.HashSet;
007import java.util.List;
008import java.util.Map;
009import java.util.Optional;
010import java.util.Set;
011import java.util.function.Function;
012import org.clafer.frontend.Ir.*;
013
014/**
015 * The lowering of the rich explicit model to the explicit core model: the
016 * port of the Clafer compiler's {@code lowerAbstractBounds TopLevelBounds .
017 * lowerToCore} ({@code Intermediate/Core.hs}, {@code Initializers.hs},
018 * {@code Finality.hs}, {@code AbstractMultiplicity.hs}), pass by pass and in
019 * the same order, so that {@code ExplicitPrinter.print(toCore(m))} is the
020 * compiler's {@code --core} output for the model of {@code m}.
021 * <ol>
022 * <li>The initializers become constraints: of the parent, right after the
023 * clafer, or, for the per-instance {@code :=} of a temporal model whose value
024 * has no temporal operator, of the clafer, at the end of its elements.</li>
025 * <li>A constraint or assertion with a pattern or a transition gets the
026 * origin of the first one.</li>
027 * <li>The patterns become the LTL formulas of Dwyer et al.'s catalogue, and the
028 * transitions implications.</li>
029 * <li>An enumeration becomes an abstract clafer and a clafer for each literal;
030 * in a temporal model, they are final.</li>
031 * <li>The finality modifiers become constraints of their clafers, at the end
032 * of their elements.</li>
033 * <li>{@code initial x} becomes {@code [ initially (some this.x) ]} at the end
034 * of the parent's elements.</li>
035 * <li>The anchors become guards on the birth and the death of the context
036 * instance, {@code this}, or the root at the top level.</li>
037 * <li>The multiplicity of a top-level abstract clafer becomes a constraint
038 * right after it.</li>
039 * </ol>
040 * A model is temporal if it has a trace length, {@code --tl=N}: then
041 * {@code :=} gives the value at the start of each lifetime; in a static model,
042 * it is {@code =}.
043 * <p>
044 * The core is a fixpoint: {@code toCore} of a core model is the model.
045 * <p>
046 * The provenance of the lowered clafers and constraints names the rich
047 * construct and its position, in the rich model or in the files of the source. The
048 * rich model writes the clock of every {@code :=}, so the origin of a lowered
049 * {@code :=} is {@code := each} or {@code := together}, where the compiler,
050 * from the source, writes {@code :=} for one without a written clock.
051 */
052public final class ToCore {
053
054    private final boolean temporal;
055    private final Function<SourceSpan, Position> position;
056    private final Set<SourceSpan> clocklessValues;
057
058    private ToCore(boolean temporal, Function<SourceSpan, Position> position, Set<SourceSpan> clocklessValues) {
059        this.temporal = temporal;
060        this.position = position;
061        this.clocklessValues = clocklessValues;
062    }
063
064    /**
065     * @param model a rich explicit model
066     * @param file the name of its file, for the provenance
067     * @return its explicit core model
068     */
069    public static Model toCore(Model model, String file) {
070        return toCore(model, span -> new Position(file, span.line(), span.column()), Set.of());
071    }
072
073    /**
074     * The lowering of a model compiled from its source, whose provenance
075     * names the positions in the source's files, as {@code clafer -m clafer
076     * --core --record-provenance P.cfr} does.
077     *
078     * @param model a rich explicit model
079     * @param position the position of a span in its file, for the provenance
080     * @param clocklessValues the spans of the values of the {@code :=}
081     * written without a clock, whose provenance is {@code :=}, as the
082     * compiler writes it
083     * @return its explicit core model
084     */
085    public static Model toCore(Model model, Function<SourceSpan, Position> position,
086            Set<SourceSpan> clocklessValues) {
087        ToCore lowering = new ToCore(model.options().traceLength().isPresent(), position, clocklessValues);
088        Model m = model;
089        Set<String> taken = taken(m);
090        m = lowering.lowerInitializers(m, taken);
091        m = lowering.markRich(m);
092        m = lowering.lowerPatternsAndTransitions(m);
093        m = lowering.lowerEnums(m);
094        m = lowering.lowerFinality(m);
095        m = lowering.lowerInitial(m);
096        m = lowering.lowerAnchors(m);
097        m = lowering.lowerTopLevelBounds(m);
098        return new Model(m.span(), new Options(true, m.options().traceLength()), m.elements(), m.objectives(),
099                m.assertions());
100    }
101
102    /**
103     * @param model a rich explicit model
104     * @return its explicit core model, its provenance positions in
105     * {@code model.des.cfr}
106     */
107    public static Model toCore(Model model) {
108        return toCore(model, "model.des.cfr");
109    }
110
111    // ------------------------------------------------------------------
112    // Expressions
113    // ------------------------------------------------------------------
114    private static Exp some(Exp set) {
115        return new QuantifiedSet(set.span(), Quantifier.SOME, set);
116    }
117
118    private static Exp no(Exp set) {
119        return new QuantifiedSet(set.span(), Quantifier.NO, set);
120    }
121
122    /**
123     * @return the set of {@code some set}, if the formula is one
124     */
125    private static Optional<Exp> someOf(Exp p) {
126        return p instanceof QuantifiedSet q && q.quantifier() == Quantifier.SOME ? Optional.of(q.set()) : Optional.empty();
127    }
128
129    /**
130     * {@code !p}, and {@code no x} for {@code some x}, as the compiler
131     * writes it.
132     */
133    private static Exp not(Exp p) {
134        Optional<Exp> set = someOf(p);
135        return set.isPresent() ? no(set.get()) : new Unary(p.span(), UnaryOp.NOT, p);
136    }
137
138    private static Exp bin(SourceSpan span, BinaryOp op, Exp a, Exp b) {
139        return new Binary(span, op, List.of(a, b));
140    }
141
142    private static Exp tmp(SourceSpan span, TemporalOp op, Exp... args) {
143        return new Temporal(span, op, List.of(args));
144    }
145
146    private static Exp join(Exp left, String name) {
147        return new Join(left.span(), left, new NameExp(left.span(), name));
148    }
149
150    private static Exp local(SourceSpan span, String name) {
151        return new NameExp(span, name);
152    }
153
154    private static Exp all(SourceSpan span, String v, Exp set, Exp body) {
155        return new Quantified(span, Quantifier.ALL, List.of(new Decl(span, false, List.of(new Name(span, v)), set)), body);
156    }
157
158    /**
159     * Rewrites the expression bottom-up.
160     */
161    private static Exp transform(Exp e, Function<Exp, Exp> f) {
162        return f.apply(mapChildren(e, x -> transform(x, f)));
163    }
164
165    /**
166     * The expression with the function applied to each of its immediate
167     * subexpressions.
168     */
169    static Exp mapChildren(Exp e, Function<Exp, Exp> t) {
170        return switch (e) {
171            case Join x -> new Join(x.span(), t.apply(x.left()), t.apply(x.right()));
172            case Dref x -> new Dref(x.span(), t.apply(x.left()));
173            case ParentOf x -> new ParentOf(x.span(), t.apply(x.left()));
174            case Unary x -> new Unary(x.span(), x.op(), t.apply(x.arg()));
175            case Binary x -> new Binary(x.span(), x.op(), x.operands().stream().map(t).toList());
176            case IfThenElse x -> new IfThenElse(x.span(), t.apply(x.condition()), t.apply(x.then()), t.apply(x.otherwise()));
177            case Quantified x -> new Quantified(x.span(), x.quantifier(), x.decls().stream()
178                    .map(d -> new Decl(d.span(), d.disjoint(), d.locals(), t.apply(d.set()))).toList(), t.apply(x.body()));
179            case QuantifiedSet x -> new QuantifiedSet(x.span(), x.quantifier(), t.apply(x.set()));
180            case Call x -> new Call(x.span(), x.function(), x.args().stream().map(t).toList());
181            case Cast x -> new Cast(x.span(), x.up(), t.apply(x.base()), x.type());
182            case Connected x -> new Connected(x.span(), t.apply(x.nodes()), t.apply(x.relation()), x.directed());
183            case Temporal x -> new Temporal(x.span(), x.op(), x.args().stream().map(t).toList());
184            case Anchor x -> new Anchor(x.span(), x.initially(), t.apply(x.body()));
185            case Pattern x -> new Pattern(x.span(), x.kind(), x.scope(), x.args().stream().map(t).toList());
186            case Transition x -> new Transition(x.span(), x.sync(), t.apply(x.from()), x.guard().map(t), t.apply(x.to()));
187            default -> e;
188        };
189    }
190
191    private static boolean hasTemporal(Exp e) {
192        return Core.firstTemporal(e).isPresent();
193    }
194
195    private Optional<Origin> origin(String construct, SourceSpan span) {
196        return Optional.of(new Origin(construct, Optional.of(position.apply(span))));
197    }
198
199    // ------------------------------------------------------------------
200    // Names
201    // ------------------------------------------------------------------
202    /**
203     * The name of a clafer as written in the source, the last part of its
204     * UID, which is qualified with {@code __} where the name is not unique.
205     */
206    private static String ident(String uid) {
207        int i = uid.lastIndexOf("__");
208        return i < 0 || i + 2 >= uid.length() ? uid : uid.substring(i + 2);
209    }
210
211    /**
212     * The names that a local variable must not shadow: the UIDs and the
213     * names of the clafers, and the variables of the quantifiers.
214     */
215    private static Set<String> taken(Model model) {
216        Set<String> taken = new HashSet<>();
217        collectTaken(model, taken);
218        return taken;
219    }
220
221    private static void collectTaken(Node node, Set<String> taken) {
222        switch (node) {
223            case ClaferDecl c -> {
224                taken.add(c.name().text());
225                taken.add(ident(c.name().text()));
226            }
227            case EnumDecl e -> {
228                taken.add(e.name().text());
229                e.literals().forEach(l -> taken.add(l.text()));
230            }
231            case Decl d -> d.locals().forEach(l -> taken.add(l.text()));
232            default -> {
233            }
234        }
235        for (Node child : Core.children(node)) {
236            collectTaken(child, taken);
237        }
238    }
239
240    /**
241     * {@code base_k} for the first k from 1 that no name has.
242     */
243    private static String fresh(Set<String> taken, String base) {
244        for (int k = 1;; k++) {
245            String name = base + "_" + k;
246            if (!taken.contains(name)) {
247                return name;
248            }
249        }
250    }
251
252    private static ClaferDecl withElements(ClaferDecl c, List<Element> elements) {
253        return new ClaferDecl(c.span(), c.isAbstract(), c.modifiers(), c.groupCard(), c.name(), c.superName(), c.ref(),
254                c.card(), c.abstractMultiplicity(), c.initializer(), elements, c.origin());
255    }
256
257    private static Model withElements(Model m, List<Element> elements) {
258        return new Model(m.span(), m.options(), elements, m.objectives(), m.assertions());
259    }
260
261    // ------------------------------------------------------------------
262    // 1. Initializers
263    // ------------------------------------------------------------------
264    private Model lowerInitializers(Model m, Set<String> taken) {
265        return withElements(m, lowerInitializers(m.elements(), true, taken));
266    }
267
268    private List<Element> lowerInitializers(List<Element> elements, boolean topLevel, Set<String> taken) {
269        List<Element> out = new ArrayList<>();
270        for (Element e : elements) {
271            if (!(e instanceof ClaferDecl c)) {
272                out.add(e);
273                continue;
274            }
275            List<Element> children = new ArrayList<>(lowerInitializers(c.elements(), false, taken));
276            List<Element> parentConstraints = new ArrayList<>();
277            if (c.initializer().isPresent()) {
278                Initializer init = c.initializer().get();
279                String construct = switch (init.kind()) {
280                    case FIXED -> "=";
281                    case EACH -> clocklessValues.contains(init.span()) ? ":=" : ":= each";
282                    case TOGETHER -> clocklessValues.contains(init.span()) ? ":=" : ":= together";
283                };
284                Optional<Origin> origin = origin(construct, c.span());
285                boolean lowered = !temporal || init.kind() != InitKind.EACH || hasTemporal(init.value());
286                if (lowered) {
287                    parentConstraints.add(new Constraint(init.span(), asConstraint(c, init, topLevel, taken), origin));
288                } else {
289                    children.add(new Constraint(init.span(), initialValue(init, topLevel), origin));
290                }
291            }
292            out.add(new ClaferDecl(c.span(), c.isAbstract(), c.modifiers(), c.groupCard(), c.name(), c.superName(),
293                    c.ref(), c.card(), c.abstractMultiplicity(), Optional.empty(), children, c.origin()));
294            out.addAll(parentConstraints);
295        }
296        return out;
297    }
298
299    /**
300     * The instances of the initialized clafer in the context of its parent:
301     * {@code this.x}, or {@code x} at the top level.
302     */
303    private static Exp initialized(ClaferDecl x, boolean topLevel) {
304        SourceSpan span = x.name().span();
305        return topLevel ? new NameExp(span, x.name().text()) : join(new This(span), x.name().text());
306    }
307
308    private Exp asConstraint(ClaferDecl x, Initializer init, boolean topLevel, Set<String> taken) {
309        SourceSpan span = init.span();
310        Exp xs = initialized(x, topLevel);
311        Exp value = init.value();
312        Exp implied = bin(span, BinaryOp.IMPLIES, some(xs), bin(span, BinaryOp.EQ, new Dref(span, xs), value));
313        boolean fixed = init.kind() == InitKind.FIXED;
314        boolean together = init.kind() == InitKind.TOGETHER;
315        if (temporal && !fixed && together) {
316            return new Anchor(span, true, implied);
317        }
318        String v = ident(x.name().text());
319        if (temporal && !fixed) {
320            // each instance that appears has the value
321            String c = taken.contains(v) ? fresh(taken, v) : v;
322            Exp local = local(span, c);
323            return all(span, c, xs, bin(span, BinaryOp.IMPLIES,
324                    new Unary(span, UnaryOp.NOT, tmp(span, TemporalOp.PREVIOUS, bin(span, BinaryOp.IN, local, xs))),
325                    bin(span, BinaryOp.EQ, new Dref(span, local), value)));
326        }
327        if (!fixed && !together && plural(x)) {
328            String c = taken.contains(v) ? fresh(taken, v) : v;
329            return all(span, c, xs, bin(span, BinaryOp.EQ, new Dref(span, local(span, c)), value));
330        }
331        return implied;
332    }
333
334    /**
335     * A concrete clafer with more than one instance under a parent.
336     */
337    private static boolean plural(ClaferDecl x) {
338        return !x.isAbstract() && x.card().high() != 0 && x.card().high() != 1;
339    }
340
341    /**
342     * The per-instance initial value in the context of the clafer:
343     * {@code initially (this.dref = e')}, where {@code e'} has
344     * {@code this.parent}, or the root at the top level, for {@code this},
345     * the parent instance.
346     */
347    private static Exp initialValue(Initializer init, boolean topLevel) {
348        SourceSpan span = init.span();
349        Exp value = transform(init.value(), e -> e instanceof This t
350                ? (topLevel ? new NameExp(t.span(), "root") : new ParentOf(t.span(), t)) : e);
351        return new Anchor(span, true, bin(span, BinaryOp.EQ, new Dref(span, new This(span)), value));
352    }
353
354    // ------------------------------------------------------------------
355    // 2. The origins of the patterns and transitions
356    // ------------------------------------------------------------------
357    private Model markRich(Model m) {
358        List<Assertion> assertions = m.assertions().stream()
359                .map(a -> new Assertion(a.span(), a.exp(), a.origin().isPresent() ? a.origin() : richOrigin(a.exp())))
360                .toList();
361        return new Model(m.span(), m.options(), mapConstraints(m.elements(),
362                c -> new Constraint(c.span(), c.exp(), c.origin().isPresent() ? c.origin() : richOrigin(c.exp()))),
363                m.objectives(), assertions);
364    }
365
366    /**
367     * The origin of the first pattern or transition of an expression.
368     */
369    private Optional<Origin> richOrigin(Exp e) {
370        Optional<Node> first = firstRichOperator(e);
371        return first.flatMap(n -> origin(switch (n) {
372            case Pattern p -> patternOp(p);
373            case Transition t -> t.guard().isPresent()
374                    ? (t.sync() ? "-[]->>" : "-[]->")
375                    : (t.sync() ? "-->>" : "-->");
376            default -> throw new IllegalStateException("not a pattern or a transition: " + n);
377        }, position(n)));
378    }
379
380    /**
381     * The position of a pattern or a transition, as the compiler gives it:
382     * an infix expression is at its first operand, inside its parentheses,
383     * and so on down.
384     */
385    static SourceSpan position(Node n) {
386        return switch (n) {
387            case Pattern p when p.kind().arity() == 2 -> position(p.args().get(0));
388            case Transition t -> position(t.from());
389            case Binary b -> position(b.operands().get(0));
390            case Join j -> position(j.left());
391            case Dref d -> position(d.left());
392            case ParentOf p -> position(p.left());
393            case Temporal t when t.op().arity() == 2 -> position(t.args().get(0));
394            default -> n.span();
395        };
396    }
397
398    private static Optional<Node> firstRichOperator(Node node) {
399        if (node instanceof Pattern || node instanceof Transition) {
400            return Optional.of(node);
401        }
402        for (Node child : Core.children(node)) {
403            Optional<Node> found = firstRichOperator(child);
404            if (found.isPresent()) {
405                return found;
406            }
407        }
408        return Optional.empty();
409    }
410
411    /**
412     * The keywords of a pattern as written, e.g., {@code must precede between and} for
413     * {@code s must precede p between q and r}.
414     */
415    static String patternOp(Pattern p) {
416        String kind = p.kind().arity() == 2 ? "must " + p.kind().keyword() : p.kind().keyword();
417        return kind + switch (p.scope()) {
418            case GLOBALLY -> "";
419            case BEFORE -> " before";
420            case AFTER -> " after";
421            case BETWEEN -> " between and";
422            case AFTER_UNTIL -> " after until";
423        };
424    }
425
426    /**
427     * The elements with each constraint mapped, at every depth.
428     */
429    private static List<Element> mapConstraints(List<Element> elements, Function<Constraint, Constraint> f) {
430        List<Element> out = new ArrayList<>();
431        for (Element e : elements) {
432            out.add(switch (e) {
433                case Constraint c -> f.apply(c);
434                case ClaferDecl c -> withElements(c, mapConstraints(c.elements(), f));
435                case RootBlock r -> new RootBlock(r.span(), r.constraints().stream().map(f).toList());
436                default -> e;
437            });
438        }
439        return out;
440    }
441
442    // ------------------------------------------------------------------
443    // 3. Patterns and transitions
444    // ------------------------------------------------------------------
445    private Model lowerPatternsAndTransitions(Model m) {
446        return new Model(m.span(), m.options(),
447                mapConstraints(m.elements(), c -> new Constraint(c.span(), lowerExp(c.exp()), c.origin())),
448                m.objectives().stream().map(o -> new Objective(o.span(), o.maximize(), lowerExp(o.exp()))).toList(),
449                m.assertions().stream().map(a -> new Assertion(a.span(), lowerExp(a.exp()), a.origin())).toList());
450    }
451
452    /**
453     * The expression with its patterns and transitions in LTL.
454     */
455    private static Exp lowerExp(Exp e) {
456        return switch (e) {
457            case Transition t -> {
458                Exp[] parts = transitionParts(t);
459                yield bin(t.span(), BinaryOp.IMPLIES, parts[0], parts[1]);
460            }
461            case Pattern p -> pattern(p, p.args().stream().map(ToCore::lowerExp).toList());
462            default -> shallow(e, ToCore::lowerExp);
463        };
464    }
465
466    /**
467     * The expression with the function applied to its direct subexpressions.
468     */
469    private static Exp shallow(Exp e, Function<Exp, Exp> t) {
470        return switch (e) {
471            case Join x -> new Join(x.span(), t.apply(x.left()), t.apply(x.right()));
472            case Dref x -> new Dref(x.span(), t.apply(x.left()));
473            case ParentOf x -> new ParentOf(x.span(), t.apply(x.left()));
474            case Unary x -> new Unary(x.span(), x.op(), t.apply(x.arg()));
475            case Binary x -> new Binary(x.span(), x.op(), x.operands().stream().map(t).toList());
476            case IfThenElse x -> new IfThenElse(x.span(), t.apply(x.condition()), t.apply(x.then()), t.apply(x.otherwise()));
477            case Quantified x -> new Quantified(x.span(), x.quantifier(), x.decls().stream()
478                    .map(d -> new Decl(d.span(), d.disjoint(), d.locals(), t.apply(d.set()))).toList(), t.apply(x.body()));
479            case QuantifiedSet x -> new QuantifiedSet(x.span(), x.quantifier(), t.apply(x.set()));
480            case Call x -> new Call(x.span(), x.function(), x.args().stream().map(t).toList());
481            case Cast x -> new Cast(x.span(), x.up(), t.apply(x.base()), x.type());
482            case Connected x -> new Connected(x.span(), t.apply(x.nodes()), t.apply(x.relation()), x.directed());
483            case Temporal x -> new Temporal(x.span(), x.op(), x.args().stream().map(t).toList());
484            case Anchor x -> new Anchor(x.span(), x.initially(), t.apply(x.body()));
485            case Pattern x -> new Pattern(x.span(), x.kind(), x.scope(), x.args().stream().map(t).toList());
486            case Transition x -> new Transition(x.span(), x.sync(), t.apply(x.from()), x.guard().map(t), t.apply(x.to()));
487            default -> e;
488        };
489    }
490
491    /**
492     * The precondition and the step of a transition, whose target is a
493     * sequence. The context instance of {@code -->>} lasts with the
494     * precondition, unless the precondition is the presence of the context,
495     * {@code some this}, as the compiler writes the transition of a clafer.
496     */
497    private static Exp[] transitionParts(Transition t) {
498        SourceSpan span = t.span();
499        Exp a = lowerExp(t.from());
500        Exp pre = t.guard().isPresent() ? bin(span, BinaryOp.AND, a, lowerExp(t.guard().get())) : a;
501        Exp next = sequence(t.to());
502        if (!t.sync()) {
503            return new Exp[]{pre, tmp(span, TemporalOp.X, next)};
504        }
505        boolean ofThis = someOf(t.from()).map(s -> s instanceof This).orElse(false);
506        Exp lasting = ofThis ? a : bin(span, BinaryOp.AND, some(new This(span)), a);
507        return new Exp[]{pre, tmp(span, TemporalOp.U, lasting, next)};
508    }
509
510    /**
511     * The target of a transition: in a chain, the states follow each other.
512     */
513    private static Exp sequence(Exp e) {
514        if (e instanceof Transition t) {
515            Exp[] parts = transitionParts(t);
516            return bin(t.span(), BinaryOp.AND, parts[0], parts[1]);
517        }
518        return lowerExp(e);
519    }
520
521    /**
522     * A pattern in a scope, with its arguments in LTL: the formulas of Dwyer et
523     * al.'s catalogue, as {@code Core.pattern} writes them.
524     */
525    private static Exp pattern(Pattern pe, List<Exp> args) {
526        SourceSpan s = pe.span();
527        Function<Exp, Exp> f = a -> tmp(s, TemporalOp.F, a);
528        Function<Exp, Exp> g = a -> tmp(s, TemporalOp.G, a);
529        java.util.function.BinaryOperator<Exp> u = (a, b) -> tmp(s, TemporalOp.U, a, b);
530        java.util.function.BinaryOperator<Exp> w = (a, b) -> tmp(s, TemporalOp.W, a, b);
531        java.util.function.BinaryOperator<Exp> impl = (a, b) -> bin(s, BinaryOp.IMPLIES, a, b);
532        java.util.function.BinaryOperator<Exp> and = (a, b) -> bin(s, BinaryOp.AND, a, b);
533        java.util.function.BinaryOperator<Exp> or = (a, b) -> bin(s, BinaryOp.OR, a, b);
534        int own = pe.kind().arity();
535        Exp p = args.get(own - 1);
536        Exp sArg = own == 2 ? args.get(0) : null;
537        List<Exp> scope = args.subList(own, args.size());
538        Exp q = null, r = null;
539        switch (pe.scope()) {
540            case BEFORE -> r = scope.get(0);
541            case AFTER -> q = scope.get(0);
542            case BETWEEN, AFTER_UNTIL -> {
543                q = scope.get(0);
544                r = scope.get(1);
545            }
546            default -> {
547            }
548        }
549        return switch (pe.kind()) {
550            case NEVER -> switch (pe.scope()) {
551                case GLOBALLY -> g.apply(not(p));
552                case BEFORE -> impl.apply(f.apply(r), u.apply(not(p), r));
553                case AFTER -> g.apply(impl.apply(q, g.apply(not(p))));
554                case BETWEEN -> g.apply(impl.apply(and.apply(and.apply(q, not(r)), f.apply(r)), u.apply(not(p), r)));
555                case AFTER_UNTIL -> g.apply(impl.apply(and.apply(q, not(r)), w.apply(not(p), r)));
556            };
557            case SOMETIME -> switch (pe.scope()) {
558                case GLOBALLY -> f.apply(p);
559                case BEFORE -> w.apply(not(r), and.apply(p, not(r)));
560                case AFTER -> or.apply(g.apply(not(q)), f.apply(and.apply(q, f.apply(p))));
561                case BETWEEN -> g.apply(impl.apply(and.apply(q, not(r)), w.apply(not(r), and.apply(p, not(r)))));
562                case AFTER_UNTIL -> g.apply(impl.apply(and.apply(q, not(r)), u.apply(not(r), and.apply(p, not(r)))));
563            };
564            case LONCE -> switch (pe.scope()) {
565                case GLOBALLY -> w.apply(not(p), w.apply(p, g.apply(not(p))));
566                case BEFORE -> impl.apply(f.apply(r), u.apply(and.apply(not(p), not(r)),
567                        or.apply(r, u.apply(and.apply(p, not(r)), or.apply(r, u.apply(not(p), r))))));
568                case AFTER -> impl.apply(f.apply(q), u.apply(not(q),
569                        and.apply(q, w.apply(not(p), w.apply(p, g.apply(not(p)))))));
570                case BETWEEN -> g.apply(impl.apply(and.apply(q, f.apply(r)), u.apply(and.apply(not(p), not(r)),
571                        or.apply(r, u.apply(and.apply(p, not(r)), or.apply(r, u.apply(not(p), r)))))));
572                case AFTER_UNTIL -> g.apply(impl.apply(q, u.apply(and.apply(not(p), not(r)),
573                        or.apply(r, u.apply(and.apply(p, not(r)),
574                                or.apply(or.apply(r, w.apply(not(p), r)), g.apply(p)))))));
575            };
576            case ALWAYS -> switch (pe.scope()) {
577                case GLOBALLY -> g.apply(p);
578                case BEFORE -> impl.apply(f.apply(r), u.apply(p, r));
579                case AFTER -> g.apply(impl.apply(q, g.apply(p)));
580                case BETWEEN -> g.apply(impl.apply(and.apply(and.apply(q, not(r)), f.apply(r)), u.apply(p, r)));
581                case AFTER_UNTIL -> g.apply(impl.apply(and.apply(q, not(r)), w.apply(p, r)));
582            };
583            case PRECEDE -> switch (pe.scope()) {
584                case GLOBALLY -> w.apply(not(p), sArg);
585                case BEFORE -> impl.apply(f.apply(r), u.apply(not(p), or.apply(sArg, r)));
586                case AFTER -> impl.apply(f.apply(q), u.apply(not(q), and.apply(q, w.apply(not(p), sArg))));
587                case BETWEEN -> g.apply(impl.apply(and.apply(and.apply(q, not(r)), f.apply(r)),
588                        u.apply(not(p), or.apply(sArg, r))));
589                case AFTER_UNTIL -> g.apply(impl.apply(and.apply(q, not(r)), w.apply(not(p), or.apply(sArg, r))));
590            };
591            case FOLLOW -> switch (pe.scope()) {
592                case GLOBALLY -> g.apply(impl.apply(p, f.apply(sArg)));
593                case BEFORE -> impl.apply(f.apply(r), u.apply(impl.apply(p, u.apply(not(r), and.apply(sArg, not(r)))), r));
594                case AFTER -> g.apply(impl.apply(q, g.apply(impl.apply(p, f.apply(sArg)))));
595                case BETWEEN -> g.apply(impl.apply(and.apply(and.apply(q, not(r)), f.apply(r)),
596                        u.apply(impl.apply(p, u.apply(not(r), and.apply(sArg, not(r)))), r)));
597                case AFTER_UNTIL -> g.apply(impl.apply(and.apply(q, not(r)),
598                        w.apply(impl.apply(p, u.apply(not(r), and.apply(sArg, not(r)))), r)));
599            };
600        };
601    }
602
603    // ------------------------------------------------------------------
604    // 4. Enumerations
605    // ------------------------------------------------------------------
606    private Model lowerEnums(Model m) {
607        List<Element> out = new ArrayList<>();
608        for (Element e : m.elements()) {
609            if (!(e instanceof EnumDecl en)) {
610                out.add(e);
611                continue;
612            }
613            // in a temporal model, the enumeration is final, and so are its literals
614            List<Modifier> fin = temporal ? List.of(new Modifier(en.span(), ModifierKind.FINAL)) : List.of();
615            SourceSpan span = en.span();
616            out.add(new ClaferDecl(span, true, fin, new Card(span, 0, Card.Unbounded), en.name(), Optional.empty(),
617                    Optional.empty(), new Card(span, 0, Card.Unbounded), Optional.empty(), Optional.empty(), List.of(),
618                    origin("enum", span)));
619            for (Name literal : en.literals()) {
620                List<Modifier> literalFin = temporal ? List.of(new Modifier(literal.span(), ModifierKind.FINAL)) : List.of();
621                out.add(new ClaferDecl(literal.span(), false, literalFin, new Card(literal.span(), 0, Card.Unbounded),
622                        literal, Optional.of(en.name()), Optional.empty(), new Card(literal.span(), 1, 1), Optional.empty(),
623                        Optional.empty(), List.of(), origin("enum", literal.span())));
624            }
625        }
626        return withElements(m, out);
627    }
628
629    // ------------------------------------------------------------------
630    // 5. Finality
631    // ------------------------------------------------------------------
632    /**
633     * The modifiers of a reference, as the desugarer gives them.
634     */
635    private enum RefModifier {
636        FINAL_REF_TARGET, FINAL_REF, FINAL_TARGET
637    }
638
639    private static Set<ModifierKind> kinds(ClaferDecl c) {
640        Set<ModifierKind> kinds = EnumSet.noneOf(ModifierKind.class);
641        c.modifiers().forEach(m -> kinds.add(m.kind()));
642        return kinds;
643    }
644
645    /**
646     * The modifiers of the clafer's own reference: {@code final} fixes it
647     * whole, {@code finalref} and {@code finaltarget} their parts.
648     */
649    private static Set<RefModifier> refModifiers(ClaferDecl c) {
650        Set<RefModifier> mods = EnumSet.noneOf(RefModifier.class);
651        if (c.ref().isPresent()) {
652            Set<ModifierKind> kinds = kinds(c);
653            if (kinds.contains(ModifierKind.FINAL)) {
654                mods.add(RefModifier.FINAL_REF_TARGET);
655            }
656            if (kinds.contains(ModifierKind.FINALREF)) {
657                mods.add(RefModifier.FINAL_REF);
658            }
659            if (kinds.contains(ModifierKind.FINALTARGET)) {
660                mods.add(RefModifier.FINAL_TARGET);
661            }
662        }
663        return mods;
664    }
665
666    private Model lowerFinality(Model m) {
667        Map<String, ClaferDecl> clafers = new HashMap<>();
668        collectClafers(m.elements(), clafers);
669        Set<String> taken = taken(m);
670        return withElements(m, lowerFinality(m.elements(), true, clafers, taken));
671    }
672
673    private static void collectClafers(List<Element> elements, Map<String, ClaferDecl> clafers) {
674        for (Element e : elements) {
675            if (e instanceof ClaferDecl c) {
676                clafers.put(c.name().text(), c);
677                collectClafers(c.elements(), clafers);
678            }
679        }
680    }
681
682    private List<Element> lowerFinality(List<Element> elements, boolean topLevel, Map<String, ClaferDecl> clafers,
683            Set<String> taken) {
684        List<Element> out = new ArrayList<>();
685        for (Element e : elements) {
686            if (!(e instanceof ClaferDecl c)) {
687                out.add(e);
688                continue;
689            }
690            List<Element> children = new ArrayList<>(lowerFinality(c.elements(), false, clafers, taken));
691            children.addAll(finality(c, topLevel, clafers, taken));
692            List<Modifier> kept = c.modifiers().stream().filter(mod -> mod.kind() == ModifierKind.INITIAL).toList();
693            out.add(new ClaferDecl(c.span(), c.isAbstract(), kept, c.groupCard(), c.name(), c.superName(), c.ref(),
694                    c.card(), c.abstractMultiplicity(), c.initializer(), children, c.origin()));
695        }
696        return out;
697    }
698
699    /**
700     * The constraints of the finality modifiers of a clafer, in its context.
701     */
702    private List<Constraint> finality(ClaferDecl x, boolean topLevel, Map<String, ClaferDecl> clafers, Set<String> taken) {
703        Set<ModifierKind> kinds = kinds(x);
704        boolean isFinal = kinds.contains(ModifierKind.FINAL);
705        // the reference that x inherits: the first super clafer's with one
706        ClaferDecl inheritedFrom = null;
707        Set<String> seen = new HashSet<>();
708        for (ClaferDecl s = superOf(x, clafers); s != null && seen.add(s.name().text()); s = superOf(s, clafers)) {
709            if (s.ref().isPresent()) {
710                inheritedFrom = s;
711                break;
712            }
713        }
714        boolean hasRef = x.ref().isPresent() || inheritedFrom != null;
715        Set<RefModifier> own = refModifiers(x);
716        boolean inheritedFixed = inheritedFrom != null && (refModifiers(inheritedFrom).contains(RefModifier.FINAL_REF_TARGET)
717                || refModifiers(inheritedFrom).contains(RefModifier.FINAL_REF));
718        boolean fixesEach;
719        boolean fixesTargets;
720        if (x.ref().isPresent()) {
721            fixesEach = isFinal || own.contains(RefModifier.FINAL_REF_TARGET) || own.contains(RefModifier.FINAL_REF);
722            fixesTargets = own.contains(RefModifier.FINAL_TARGET);
723        } else {
724            fixesEach = (isFinal || kinds.contains(ModifierKind.FINALREF)) && !inheritedFixed;
725            fixesTargets = kinds.contains(ModifierKind.FINALTARGET);
726        }
727        String uid = x.name().text();
728        SourceSpan span = x.span();
729        String vc = fresh(taken, ident(uid));
730        Set<String> takenVc = new HashSet<>(taken);
731        takenVc.add(vc);
732        String vt = fresh(takenVc, ident(uid));
733
734        Exp thisX = new This(span);
735        Exp parentOfThis = topLevel ? new NameExp(span, "root") : new ParentOf(span, new This(span));
736        Exp siblings = topLevel ? new NameExp(span, uid) : join(parentOfThis, uid);
737        Exp c = local(span, vc);
738        Exp tv = local(span, vt);
739        Function<Exp, Exp> since = a -> bin(span, BinaryOp.IMPLIES, tmp(span, TemporalOp.PREVIOUS, some(parentOfThis)),
740                tmp(span, TemporalOp.PREVIOUS, a));
741
742        List<Constraint> out = new ArrayList<>();
743        if (isFinal && !x.isAbstract()) {
744            Optional<Origin> o = origin("final", span);
745            out.add(new Constraint(span, all(span, vc, thisX, tmp(span, TemporalOp.X, bin(span, BinaryOp.IN, c, siblings))), o));
746            out.add(new Constraint(span, all(span, vc, thisX, since.apply(bin(span, BinaryOp.IN, c, siblings))), o));
747        }
748        if (fixesEach && hasRef) {
749            Optional<Origin> o = origin(isFinal ? "final" : "finalref", span);
750            Exp drefC = new Dref(span, c);
751            out.add(new Constraint(span, all(span, vc, thisX, all(span, vt, drefC, tmp(span, TemporalOp.X,
752                    bin(span, BinaryOp.IMPLIES, some(drefC), bin(span, BinaryOp.IN, tv, drefC))))), o));
753        }
754        if (fixesTargets && hasRef) {
755            Optional<Origin> o = origin("finaltarget", span);
756            Exp drefThis = new Dref(span, thisX);
757            Exp drefSiblings = new Dref(span, siblings);
758            out.add(new Constraint(span, all(span, vt, drefThis, tmp(span, TemporalOp.X,
759                    bin(span, BinaryOp.IN, tv, drefSiblings))), o));
760            out.add(new Constraint(span, all(span, vt, drefThis, since.apply(bin(span, BinaryOp.IN, tv, drefSiblings))), o));
761        }
762        return out;
763    }
764
765    private static ClaferDecl superOf(ClaferDecl c, Map<String, ClaferDecl> clafers) {
766        return c.superName().map(s -> clafers.get(s.text())).orElse(null);
767    }
768
769    // ------------------------------------------------------------------
770    // 6. initial
771    // ------------------------------------------------------------------
772    private Model lowerInitial(Model m) {
773        return withElements(m, lowerInitial(m.elements(), true));
774    }
775
776    private List<Element> lowerInitial(List<Element> elements, boolean topLevel) {
777        List<Element> out = new ArrayList<>();
778        List<Element> initials = new ArrayList<>();
779        for (Element e : elements) {
780            if (!(e instanceof ClaferDecl c)) {
781                out.add(e);
782                continue;
783            }
784            boolean initial = c.modifiers().stream().anyMatch(mod -> mod.kind() == ModifierKind.INITIAL);
785            out.add(new ClaferDecl(c.span(), c.isAbstract(), List.of(), c.groupCard(), c.name(), c.superName(), c.ref(),
786                    c.card(), c.abstractMultiplicity(), c.initializer(), lowerInitial(c.elements(), false), c.origin()));
787            // a top-level abstract clafer has no instances of its own
788            if (initial && !(c.isAbstract() && topLevel)) {
789                SourceSpan span = c.span();
790                Exp instances = topLevel ? new NameExp(span, c.name().text()) : join(new This(span), c.name().text());
791                initials.add(new Constraint(span, new Anchor(span, true, some(instances)), origin("initial", span)));
792            }
793        }
794        out.addAll(initials);
795        return out;
796    }
797
798    // ------------------------------------------------------------------
799    // 7. Anchors
800    // ------------------------------------------------------------------
801    private Model lowerAnchors(Model m) {
802        return new Model(m.span(), m.options(), lowerAnchors(m.elements(), true),
803                m.objectives().stream().map(o -> new Objective(o.span(), o.maximize(), anchors(o.exp(), true))).toList(),
804                m.assertions().stream().map(a -> new Assertion(a.span(), anchors(a.exp(), true), a.origin())).toList());
805    }
806
807    private List<Element> lowerAnchors(List<Element> elements, boolean topLevel) {
808        List<Element> out = new ArrayList<>();
809        for (Element e : elements) {
810            out.add(switch (e) {
811                case Constraint c -> new Constraint(c.span(), anchors(c.exp(), topLevel), c.origin());
812                case ClaferDecl c -> withElements(c, lowerAnchors(c.elements(), false));
813                case RootBlock r -> new RootBlock(r.span(), r.constraints().stream()
814                        .map(c -> new Constraint(c.span(), anchors(c.exp(), true), c.origin())).toList());
815                default -> e;
816            });
817        }
818        return out;
819    }
820
821    /**
822     * The anchors of a constraint as guards on the birth or the death of the
823     * context instance, as the source semantics reads them
824     * (kbak/clafer-semantics#200, {@code Formula.denote}).
825     */
826    private static Exp anchors(Exp exp, boolean topLevel) {
827        return signed(exp, true, topLevel);
828    }
829
830    /**
831     * The anchors of an expression in a position of the given sign: a
832     * negation goes into the anchor, so that {@code !(initially p)} is
833     * {@code initially !p}, which holds wherever the context is not born. A
834     * positive anchor is {@code birth => p}, a negative one
835     * {@code birth && p}, whose negation is {@code birth => !p}. The sign
836     * changes under {@code !}, on the left of {@code =>} and in the body of
837     * {@code no x : X |}; the operands of {@code <=>}, {@code xor} and
838     * {@code if then else} have both signs, so these are written out with
839     * {@code =>}, {@code &&} and {@code ||} when they have an anchor. The
840     * bodies of {@code one} and {@code lone} count their witnesses
841     * classically, and an {@code if then else} that is a value, not a
842     * formula, is a term: their anchors are positive guards, under classical
843     * negation.
844     */
845    private static Exp signed(Exp e, boolean positive, boolean topLevel) {
846        switch (e) {
847            case Anchor a -> {
848                Exp guard = a.initially() ? birth(a.span(), topLevel) : death(a.span(), topLevel);
849                return bin(a.span(), positive ? BinaryOp.IMPLIES : BinaryOp.AND, guard, signed(a.body(), positive, topLevel));
850            }
851            case Unary u when u.op() == UnaryOp.NOT ->
852                    { return new Unary(u.span(), u.op(), signed(u.arg(), !positive, topLevel)); }
853            case Binary b when b.op() == BinaryOp.IMPLIES && b.operands().size() == 2 ->
854                    { return bin(b.span(), b.op(), signed(b.operands().get(0), !positive, topLevel),
855                            signed(b.operands().get(1), positive, topLevel)); }
856            case Binary b when (b.op() == BinaryOp.IFF || b.op() == BinaryOp.XOR) && b.operands().size() == 2 && anchored(b) -> {
857                SourceSpan span = b.span();
858                Exp x = b.operands().get(0);
859                Exp y = b.operands().get(1);
860                return signed(b.op() == BinaryOp.IFF
861                        ? bin(span, BinaryOp.AND, bin(span, BinaryOp.IMPLIES, x, y), bin(span, BinaryOp.IMPLIES, y, x))
862                        : bin(span, BinaryOp.OR, bin(span, BinaryOp.AND, x, neg(span, y)), bin(span, BinaryOp.AND, neg(span, x), y)),
863                        positive, topLevel);
864            }
865            case IfThenElse i when !formula(i) -> {
866                return classical(i, topLevel);
867            }
868            case IfThenElse i when anchored(i) -> {
869                SourceSpan span = i.span();
870                return signed(bin(span, BinaryOp.AND, bin(span, BinaryOp.IMPLIES, i.condition(), i.then()),
871                        bin(span, BinaryOp.IMPLIES, neg(span, i.condition()), i.otherwise())), positive, topLevel);
872            }
873            case Quantified q when q.quantifier() == Quantifier.NO ->
874                    { return new Quantified(q.span(), q.quantifier(), q.decls(), signed(q.body(), !positive, topLevel)); }
875            case Quantified q when q.quantifier() == Quantifier.ONE || q.quantifier() == Quantifier.LONE ->
876                    { return new Quantified(q.span(), q.quantifier(), q.decls(), classical(q.body(), topLevel)); }
877            default -> {
878                return mapChildren(e, x -> signed(x, positive, topLevel));
879            }
880        }
881    }
882
883    /**
884     * The anchors as positive guards, under classical negation: in the body
885     * of {@code one} and {@code lone}.
886     */
887    private static Exp classical(Exp exp, boolean topLevel) {
888        return transform(exp, e -> e instanceof Anchor a
889                ? bin(a.span(), BinaryOp.IMPLIES, a.initially() ? birth(a.span(), topLevel) : death(a.span(), topLevel), a.body())
890                : e);
891    }
892
893    /**
894     * The birth of the context instance: it exists now, and not in the
895     * previous state of its lifetime; the root, which exists in every state,
896     * is born at time zero.
897     */
898    private static Exp birth(SourceSpan span, boolean topLevel) {
899        Exp notPrevious = neg(span, tmp(span, TemporalOp.PREVIOUS, some(self(span, topLevel))));
900        return topLevel ? notPrevious : bin(span, BinaryOp.AND, some(self(span, topLevel)), notPrevious);
901    }
902
903    /**
904     * The death of the context instance: it exists now, and not in the next
905     * state.
906     */
907    private static Exp death(SourceSpan span, boolean topLevel) {
908        return bin(span, BinaryOp.AND, some(self(span, topLevel)), tmp(span, TemporalOp.X, no(self(span, topLevel))));
909    }
910
911    private static Exp self(SourceSpan span, boolean topLevel) {
912        return topLevel ? new NameExp(span, "root") : new This(span);
913    }
914
915    // !(some x) is no x, as the compiler writes it, so that the core compiles to itself
916    private static Exp neg(SourceSpan span, Exp e) {
917        Optional<Exp> set = someOf(e);
918        return set.isPresent() ? no(set.get()) : new Unary(span, UnaryOp.NOT, e);
919    }
920
921    /**
922     * Whether the expression is a formula, not a value: the rich model has no
923     * types, so this follows its form, as an {@code if then else} is a formula
924     * when its branches are.
925     */
926    private static boolean formula(Exp e) {
927        return switch (e) {
928            case Anchor a -> true;
929            case Temporal t -> true;
930            case Pattern p -> true;
931            case Transition t -> true;
932            case Quantified q -> true;
933            case QuantifiedSet q -> true;
934            case Connected c -> true;
935            case Unary u -> u.op() == UnaryOp.NOT;
936            case Binary b -> switch (b.op()) {
937                case AND, OR, IMPLIES, IFF, XOR, LT, LE, GT, GE, EQ, NE, IN, NOT_IN -> true;
938                default -> false;
939            };
940            case IfThenElse i -> formula(i.then()) || formula(i.otherwise());
941            default -> false;
942        };
943    }
944
945    private static boolean anchored(Exp e) {
946        boolean[] found = {false};
947        transform(e, x -> {
948            found[0] |= x instanceof Anchor;
949            return x;
950        });
951        return found[0];
952    }
953
954    // ------------------------------------------------------------------
955    // 8. The multiplicities of the top-level abstract clafers
956    // ------------------------------------------------------------------
957    private Model lowerTopLevelBounds(Model m) {
958        List<Element> out = new ArrayList<>();
959        for (Element e : m.elements()) {
960            if (!(e instanceof ClaferDecl c) || c.abstractMultiplicity().isEmpty()) {
961                out.add(e);
962                continue;
963            }
964            Card bound = c.abstractMultiplicity().get().card();
965            SourceSpan span = c.span();
966            out.add(new ClaferDecl(c.span(), c.isAbstract(), c.modifiers(), c.groupCard(), c.name(), c.superName(),
967                    c.ref(), new Card(bound.span(), 0, Card.Unbounded), Optional.empty(), c.initializer(), c.elements(),
968                    c.origin()));
969            Exp count = new Unary(span, UnaryOp.CARD, new NameExp(span, c.name().text()));
970            List<Exp> comparisons = new ArrayList<>();
971            if (bound.low() == bound.high()) {
972                comparisons.add(bin(span, BinaryOp.EQ, count, new IntLit(span, bound.low())));
973            } else {
974                if (bound.low() > 0) {
975                    comparisons.add(bin(span, BinaryOp.GE, count, new IntLit(span, bound.low())));
976                }
977                if (!bound.isUnbounded()) {
978                    comparisons.add(bin(span, BinaryOp.LE, count, new IntLit(span, bound.high())));
979                }
980            }
981            if (!comparisons.isEmpty()) {
982                Exp p = comparisons.get(comparisons.size() - 1);
983                for (int i = comparisons.size() - 2; i >= 0; i--) {
984                    p = bin(span, BinaryOp.AND, comparisons.get(i), p);
985                }
986                out.add(new Constraint(span, p, origin("abstract " + bound, span)));
987            }
988        }
989        return withElements(m, out);
990    }
991}