001package org.clafer.ast;
002
003import java.math.BigDecimal;
004import java.util.ArrayDeque;
005import java.util.ArrayList;
006import java.util.Collections;
007import java.util.Deque;
008import java.util.HashMap;
009import java.util.HashSet;
010import java.util.IdentityHashMap;
011import java.util.LinkedHashMap;
012import java.util.List;
013import java.util.Map;
014import java.util.Set;
015import org.clafer.assertion.Assertion;
016import org.clafer.frontend.Core;
017import org.clafer.frontend.Diagnostic;
018import org.clafer.frontend.ExplicitParser;
019import org.clafer.frontend.ToCore;
020import org.clafer.frontend.Ir;
021import org.clafer.frontend.Ir.BinaryOp;
022import org.clafer.frontend.Ir.ClaferDecl;
023import org.clafer.frontend.Ir.Element;
024import org.clafer.frontend.Ir.Exp;
025import org.clafer.frontend.Ir.Node;
026import org.clafer.frontend.SourceSpan;
027import org.clafer.objective.Objective;
028
029/**
030 * Builds chocosolver's {@link AstModel} from a static explicit model of the
031 * {@link Ir explicit IR}: the core explicit model that {@code clafer -m clafer
032 * --core} prints, a static rich one, which it lowers to the core with
033 * {@link ToCore}, or what
034 * {@link AstPrinter} prints. It resolves the names: the clafers, which may be
035 * used before they are declared, and the variables of the quantifiers.
036 * <p>
037 * The clafers are created in the order of the source, so that the instances
038 * are numbered as the compiler numbers them, then given their super clafers,
039 * and then their references and group cards, after their super clafers'.
040 * What the printer writes because it applies, this sets only where it is not
041 * inherited: a group card equal to the super clafer's is the super clafer's.
042 * A written reference is the clafer's own.
043 * <p>
044 * A nested abstract clafer's multiplicity counts the instances of its
045 * subclafers in each parent, so it becomes a constraint of the parent on
046 * {@code #this.A}, as the compiler gives it to chocosolver. A temporal
047 * model has a diagnostic on each line with a temporal construct, since
048 * chocosolver solves only static models. {@code real} and {@code double} have
049 * no solver.
050 * <p>
051 * Clafers, constraints, objectives and assertions get the spans of their
052 * source, so chocosolver's errors name their positions. Errors do not stop
053 * the build: it reports a diagnostic and goes on with the next declaration or
054 * constraint.
055 */
056public final class ToAst {
057
058    /**
059     * A model built from an explicit model.
060     *
061     * @param model the model
062     * @param objectives the objectives
063     * @param assertions the assertions
064     * @param diagnostics the errors, empty if the model is complete
065     */
066    public record Result(AstModel model, Objective[] objectives, Assertion[] assertions,
067            List<Diagnostic> diagnostics) {
068    }
069
070    /**
071     * An error at a node, unwinding to the constraint that contains it.
072     */
073    private static final class BuildError extends RuntimeException {
074
075        private final Diagnostic diagnostic;
076
077        BuildError(SourceSpan span, String message) {
078            super(message, null, false, false);
079            this.diagnostic = new Diagnostic(span, message);
080        }
081    }
082
083    private static final Map<BinaryOp, AstArithm.Op> ArithmOps = Map.of(
084            BinaryOp.ADD, AstArithm.Op.Add, BinaryOp.SUB, AstArithm.Op.Sub, BinaryOp.MUL, AstArithm.Op.Mul,
085            BinaryOp.DIV, AstArithm.Op.Div, BinaryOp.DECIMAL_MUL, AstArithm.Op.DecimalMul,
086            BinaryOp.DECIMAL_DIV, AstArithm.Op.DecimalDiv);
087    private static final Map<BinaryOp, AstBoolArithm.Op> BoolOps = Map.of(
088            BinaryOp.AND, AstBoolArithm.Op.And, BinaryOp.OR, AstBoolArithm.Op.Or,
089            BinaryOp.IMPLIES, AstBoolArithm.Op.Implies, BinaryOp.IFF, AstBoolArithm.Op.IfOnlyIf,
090            BinaryOp.XOR, AstBoolArithm.Op.Xor);
091    private static final Map<BinaryOp, AstCompare.Op> CompareOps = Map.of(
092            BinaryOp.LT, AstCompare.Op.LessThan, BinaryOp.LE, AstCompare.Op.LessThanEqual,
093            BinaryOp.GT, AstCompare.Op.GreaterThan, BinaryOp.GE, AstCompare.Op.GreaterThanEqual);
094    private static final Set<String> Unsolved = Set.of("real", "double");
095
096    private final List<Diagnostic> diagnostics = new ArrayList<>();
097    private final AstModel model = Asts.newModel();
098    private final Map<String, AstClafer> clafers = new LinkedHashMap<>();
099    // In the order of declaration, which is the order in which sub clafers
100    // extend their super clafer, as in the compiler's output.
101    private final Map<AstClafer, ClaferDecl> declOf = new LinkedHashMap<>();
102    private final Deque<Map<String, AstLocal>> locals = new ArrayDeque<>();
103    private final List<Objective> objectives = new ArrayList<>();
104    private final List<Assertion> assertions = new ArrayList<>();
105
106    private ToAst() {
107        clafers.put("int", Asts.IntType);
108        clafers.put("integer", Asts.IntType);
109        clafers.put("string", Asts.StringType);
110        clafers.put("decimal", Asts.DecimalType);
111        clafers.put("bool", Asts.BoolType);
112    }
113
114    /**
115     * Parses an explicit model and builds its {@link AstModel}.
116     *
117     * @param source the text
118     * @return the model, its objectives and assertions, and the errors of the
119     * parser and the build, by position
120     */
121    public static Result parse(String source) {
122        ExplicitParser.Result parsed = ExplicitParser.parse(source);
123        return toAst(parsed.model(), parsed.diagnostics());
124    }
125
126    /**
127     * Builds the {@link AstModel} of an explicit model.
128     *
129     * @param tree the explicit model
130     * @return the model, its objectives and assertions, and the errors
131     */
132    public static Result toAst(Ir.Model tree) {
133        return toAst(tree, List.of());
134    }
135
136    private static Result toAst(Ir.Model tree, List<Diagnostic> parseErrors) {
137        ToAst builder = new ToAst();
138        // a model that declares itself the core but has rich constructs is not an explicit
139        // core model, temporal or not: those are its errors
140        List<Diagnostic> refused = Core.richInCore(tree);
141        if (refused.isEmpty()) {
142            refused = temporal(tree);
143        }
144        if (refused.isEmpty()) {
145            // the rich constructs of a static model: its enumerations,
146            // initializers and top-level abstract multiplicities
147            tree = ToCore.toCore(tree);
148            // := in a model with a trace length gives an initial value
149            refused = temporal(tree);
150        }
151        if (!refused.isEmpty()) {
152            // the other errors of a temporal model follow from its temporal constructs
153            builder.diagnostics.addAll(refused);
154        } else {
155            // what could be read, so that its errors are reported too
156            builder.diagnostics.addAll(parseErrors);
157            builder.build(tree);
158        }
159        List<Diagnostic> diagnostics = new ArrayList<>(builder.diagnostics);
160        diagnostics.sort((a, b) -> a.span().line() != b.span().line()
161                ? Integer.compare(a.span().line(), b.span().line())
162                : Integer.compare(a.span().column(), b.span().column()));
163        return new Result(builder.model,
164                builder.objectives.toArray(new Objective[0]),
165                builder.assertions.toArray(new Assertion[0]),
166                Collections.unmodifiableList(diagnostics));
167    }
168
169    /**
170     * The temporal constructs of a model, the first on each line.
171     */
172    private static List<Diagnostic> temporal(Ir.Model tree) {
173        List<Diagnostic> temporal = new ArrayList<>();
174        collectTemporal(tree, temporal);
175        temporal.sort((a, b) -> a.span().line() != b.span().line()
176                ? Integer.compare(a.span().line(), b.span().line())
177                : Integer.compare(a.span().column(), b.span().column()));
178        List<Diagnostic> first = new ArrayList<>();
179        int line = -1;
180        for (Diagnostic d : temporal) {
181            if (d.span().line() != line) {
182                first.add(d);
183                line = d.span().line();
184            }
185        }
186        return first;
187    }
188
189    private static void collectTemporal(Node node, List<Diagnostic> temporal) {
190        String what = switch (node) {
191            case Ir.Modifier m -> m.kind().keyword() + " is a temporal modifier";
192            case Ir.Temporal t -> t.op().keyword() + " is a temporal operator";
193            case Ir.Anchor a -> (a.initially() ? "initially" : "finally") + " is a temporal operator";
194            case Ir.Pattern p -> p.kind().keyword() + " is a behavioral pattern";
195            case Ir.Transition t -> "a transition is temporal";
196            default -> null;
197        };
198        if (what != null) {
199            temporal.add(new Diagnostic(node.span(), "Chocosolver does not solve temporal models: " + what
200                    + "; Alloy solves them (claferIG)"));
201        }
202        for (Node child : Core.children(node)) {
203            collectTemporal(child, temporal);
204        }
205    }
206
207    // ------------------------------------------------------------------
208    // The clafers
209    // ------------------------------------------------------------------
210    private void build(Ir.Model tree) {
211        // The clafers, so that every name can be found.
212        for (Element element : tree.elements()) {
213            if (element instanceof ClaferDecl decl) {
214                declare(decl, null);
215            }
216        }
217        // Supers, then references and group cards, which depend on the
218        // super clafers' ones.
219        for (Map.Entry<AstClafer, ClaferDecl> entry : declOf.entrySet()) {
220            setSuper(entry.getKey(), entry.getValue());
221        }
222        Set<AstClafer> done = new HashSet<>();
223        for (AstClafer clafer : new ArrayList<>(declOf.keySet())) {
224            setInherited(clafer, done, new HashSet<>());
225        }
226        // The expressions.
227        for (Element element : tree.elements()) {
228            switch (element) {
229                case Ir.Constraint c -> addConstraint(model.getAbstractRoot(), c);
230                case Ir.RootBlock r -> r.constraints().forEach(c -> addConstraint(model.getRoot(), c));
231                default -> {
232                }
233            }
234        }
235        for (Map.Entry<AstClafer, ClaferDecl> entry : declOf.entrySet()) {
236            for (Element element : entry.getValue().elements()) {
237                if (element instanceof Ir.Constraint c) {
238                    addConstraint(entry.getKey(), c);
239                }
240            }
241        }
242        for (Ir.Objective objective : tree.objectives()) {
243            AstExpr expr = convertTop(objective.exp());
244            if (expr instanceof AstSetExpr set) {
245                objectives.add(objective.maximize()
246                        ? Objective.maximize(set, objective.span())
247                        : Objective.minimize(set, objective.span()));
248            } else if (expr != null) {
249                diagnostics.add(new Diagnostic(objective.span(), "An objective must be a number, not a constraint"));
250            }
251        }
252        for (Ir.Assertion assertion : tree.assertions()) {
253            AstExpr expr = convertTop(assertion.exp());
254            if (expr instanceof AstBoolExpr bool) {
255                assertions.add(new Assertion(bool, assertion.span()));
256            } else if (expr != null) {
257                diagnostics.add(new Diagnostic(assertion.span(), "An assertion must be a constraint"));
258            }
259        }
260    }
261
262    private void declare(ClaferDecl decl, AstClafer parent) {
263        String name = decl.name().text();
264        if (clafers.containsKey(name)) {
265            diagnostics.add(new Diagnostic(decl.name().span(), "A clafer named " + name + " is already declared"));
266            return;
267        }
268        AstClafer clafer;
269        if (decl.isAbstract()) {
270            clafer = parent == null ? model.addAbstract(name) : parent.addAbstractChild(name);
271            Ir.Card card = decl.card();
272            if (!card.isAny()) {
273                if (parent == null) {
274                    diagnostics.add(new Diagnostic(card.span(),
275                            "The multiplicity of the top-level abstract clafer " + name + " is rich"));
276                } else {
277                    // the number of the instances of its subclafers in each
278                    // parent, a constraint of the parent
279                    AstSetExpr own = Asts.card(Asts.join(Asts.$this(), clafer));
280                    if (card.low() > 0) {
281                        parent.addConstraint(Asts.greaterThanEqual(own, Asts.constant(card.low())), card.span());
282                    }
283                    if (!card.isUnbounded()) {
284                        parent.addConstraint(Asts.lessThanEqual(own, Asts.constant(card.high())), card.span());
285                    }
286                }
287            }
288        } else {
289            AstConcreteClafer concrete = parent == null ? model.addChild(name) : parent.addChild(name);
290            concrete.withCard(card(decl.card()));
291            clafer = concrete;
292        }
293        clafer.at(decl.name().span());
294        clafers.put(name, clafer);
295        declOf.put(clafer, decl);
296        for (Element element : decl.elements()) {
297            if (element instanceof ClaferDecl child) {
298                declare(child, clafer);
299            }
300        }
301    }
302
303    private static Card card(Ir.Card card) {
304        return card.isUnbounded() ? new Card(card.low()) : new Card(card.low(), card.high());
305    }
306
307    private void setSuper(AstClafer clafer, ClaferDecl decl) {
308        if (decl.superName().isEmpty()) {
309            return;
310        }
311        Ir.Name superName = decl.superName().get();
312        AstClafer sup = clafers.get(superName.text());
313        if (sup == null) {
314            diagnostics.add(new Diagnostic(superName.span(), "No clafer named " + superName.text()));
315        } else if (!(sup instanceof AstAbstractClafer abstractSuper) || sup.isPrimitive()) {
316            diagnostics.add(new Diagnostic(superName.span(), superName.text() + " is not an abstract clafer"));
317        } else {
318            clafer.extending(abstractSuper);
319        }
320    }
321
322    /**
323     * Sets the reference of a clafer, if it has one written, and its group
324     * card where it differs from what it inherits, after its super clafer's.
325     */
326    private void setInherited(AstClafer clafer, Set<AstClafer> done, Set<AstClafer> visiting) {
327        if (done.contains(clafer) || !declOf.containsKey(clafer)) {
328            return;
329        }
330        if (!visiting.add(clafer)) {
331            diagnostics.add(new Diagnostic(declOf.get(clafer).name().span(), clafer.getName() + " extends itself"));
332            return;
333        }
334        AstClafer sup = clafer.hasSuperClafer() ? clafer.getSuperClafer() : null;
335        if (sup != null) {
336            setInherited(sup, done, visiting);
337        }
338        ClaferDecl decl = declOf.get(clafer);
339        // A written reference is the clafer's own, as in Clafer: on a sub
340        // clafer it redefines the inherited one, even with the same target.
341        if (decl.ref().isPresent()) {
342            Ir.RefDecl ref = decl.ref().get();
343            Ir.Name targetName = ref.target();
344            AstClafer target = clafers.get(targetName.text());
345            if (target == null) {
346                diagnostics.add(new Diagnostic(targetName.span(), Unsolved.contains(targetName.text())
347                        ? "Chocosolver does not solve " + targetName.text() + ", nor does any backend"
348                        : "No clafer named " + targetName.text()));
349            } else if (ref.isSet()) {
350                clafer.refToUnique(target);
351            } else {
352                clafer.refTo(target);
353            }
354        }
355        Card inheritedGroupCard = sup == null ? null : AstUtil.getInheritedGroupCard(sup);
356        Card groupCard = card(decl.groupCard());
357        boolean asInherited = inheritedGroupCard == null
358                ? groupCard.getLow() == 0 && !groupCard.hasHigh()
359                : inheritedGroupCard.equals(groupCard);
360        if (!asInherited) {
361            clafer.withGroupCard(groupCard);
362        }
363        visiting.remove(clafer);
364        done.add(clafer);
365    }
366
367    private void addConstraint(AstClafer context, Ir.Constraint constraint) {
368        AstExpr expr = convertTop(constraint.exp());
369        if (expr instanceof AstBoolExpr bool) {
370            context.addConstraint(bool, constraint.span());
371        } else if (expr != null) {
372            diagnostics.add(new Diagnostic(constraint.span(), "A constraint must be true or false, not a set or a number"));
373        }
374    }
375
376    // ------------------------------------------------------------------
377    // Expressions
378    // ------------------------------------------------------------------
379    /**
380     * Converts an expression, or reports why not and returns null.
381     */
382    private AstExpr convertTop(Exp exp) {
383        try {
384            return convert(exp, false);
385        } catch (BuildError e) {
386            diagnostics.add(e.diagnostic);
387            return null;
388        } finally {
389            locals.clear();
390        }
391    }
392
393    private static BuildError error(Node at, String message) {
394        return new BuildError(at.span(), message);
395    }
396
397    /**
398     * @param relation whether names are child relations, as on the right of
399     * a navigation
400     */
401    private AstExpr convert(Exp exp, boolean relation) {
402        return switch (exp) {
403            case Ir.This e -> new AstThis();
404            case Ir.NameExp e -> name(e, relation);
405            case Ir.IntLit e -> {
406                if (e.value() < Integer.MIN_VALUE || e.value() > Integer.MAX_VALUE) {
407                    throw error(e, "The number " + e.value() + " is too large");
408                }
409                yield Asts.constant((int) e.value());
410            }
411            case Ir.DecimalLit e -> new AstDecimalConstant(new BigDecimal(e.text()));
412            case Ir.DoubleLit e -> throw error(e, "Chocosolver does not solve double, nor does any backend");
413            // As from Clafer's JavaScript: the literal, with its quotes.
414            case Ir.StringLit e -> new AstStringConstant(e.text());
415            case Ir.NoClafer e -> noClafer(null);
416            case Ir.Join e -> {
417                AstSetExpr left = set(e, convert(e.left(), relation));
418                if (e.right() instanceof Ir.NameExp n) {
419                    yield new AstJoin(left, new AstChildRelation(clafer(n.span(), n.name())));
420                }
421                yield new AstJoin(left, set(e, convert(e.right(), true)));
422            }
423            case Ir.Dref e -> new AstJoinRef(set(e, convert(e.left(), relation)));
424            case Ir.ParentOf e -> new AstJoinParent(set(e, convert(e.left(), relation)));
425            case Ir.Unary e -> unary(e, relation);
426            case Ir.Binary e -> binary(e, relation);
427            case Ir.IfThenElse e -> {
428                AstBoolExpr antecedent = bool(e, convert(e.condition(), relation));
429                AstExpr consequent = convert(e.then(), relation);
430                AstExpr alternative = convert(e.otherwise(), relation);
431                if (consequent instanceof AstBoolExpr c && alternative instanceof AstBoolExpr a) {
432                    yield new AstIfThenElse(antecedent, c, a);
433                }
434                AstSetExpr c = set(e, consequent);
435                AstSetExpr a = set(e, alternative);
436                yield new AstTernary(antecedent, typedBeside(c, a), typedBeside(a, c));
437            }
438            case Ir.Quantified e -> quantified(e);
439            case Ir.QuantifiedSet e -> {
440                AstSetExpr set = set(e, convert(e.set(), false));
441                yield switch (e.quantifier()) {
442                    case SOME -> Asts.some(set);
443                    case NO -> Asts.none(set);
444                    case LONE -> Asts.lone(set);
445                    case ONE -> Asts.one(set);
446                    case ALL -> throw error(e, "Chocosolver has no 'all' without variables");
447                };
448            }
449            case Ir.Call e -> {
450                AstSetExpr first = set(e, convert(e.args().get(0), false));
451                AstSetExpr second = set(e, convert(e.args().get(1), false));
452                yield switch (e.function()) {
453                    case "concat" -> new AstConcat(first, second);
454                    case "prefix" -> new AstPrefix(first, second);
455                    default -> new AstSuffix(first, second);
456                };
457            }
458            case Ir.RelationOf e -> {
459                AstClafer source = clafer(e.clafer().span(), e.clafer().text());
460                if (e.isDref()) {
461                    if (!source.hasRef()) {
462                        throw error(e.clafer(), e.clafer().text() + " has no reference of its own");
463                    }
464                    yield new AstRefRelation(source.getRef());
465                }
466                if (!(source instanceof AstConcreteClafer concrete)) {
467                    throw error(e.clafer(), e.clafer().text() + " is not a concrete clafer");
468                }
469                yield new AstParentRelation(concrete);
470            }
471            case Ir.Cast e -> {
472                AstSetExpr base = set(e, convert(e.base(), false));
473                ProductType type = type(e.type());
474                yield e.up() ? new AstUpcast(base, type) : new AstDowncast(base, type);
475            }
476            case Ir.Connected e -> new AstConnected(set(e, convert(e.nodes(), false)),
477                    set(e, convert(e.relation(), false)), e.directed());
478            case Ir.ConstantSet e -> {
479                ProductType type = type(e.type());
480                if (type.arity() != e.rows().size()) {
481                    throw error(e, "The constant has " + e.rows().size() + " columns but its type " + type
482                            + " has " + type.arity());
483                }
484                int[][] rows = e.rows().stream().map(r -> r.stream().mapToInt(Integer::intValue).toArray())
485                        .toArray(int[][]::new);
486                yield new AstConstant(type, rows);
487            }
488            case Ir.Temporal e -> throw error(e, "Chocosolver does not solve temporal models");
489            case Ir.Anchor e -> throw error(e, "Chocosolver does not solve temporal models");
490            case Ir.Pattern e -> throw error(e, "Chocosolver does not solve temporal models");
491            case Ir.Transition e -> throw error(e, "Chocosolver does not solve temporal models");
492        };
493    }
494
495    private AstExpr name(Ir.NameExp e, boolean relation) {
496        for (Map<String, AstLocal> scope : locals) {
497            AstLocal local = scope.get(e.name());
498            if (local != null) {
499                return local;
500            }
501        }
502        AstClafer clafer = clafer(e.span(), e.name());
503        return relation ? new AstChildRelation(clafer) : new AstGlobal(clafer);
504    }
505
506    private AstExpr unary(Ir.Unary e, boolean relation) {
507        AstExpr arg = convert(e.arg(), relation);
508        return switch (e.op()) {
509            case NOT -> new AstNot(bool(e, arg));
510            case MINUS -> new AstMinus(set(e, arg));
511            case CARD -> new AstCard(set(e, arg));
512            case SUM -> new AstSum(set(e, arg));
513            case PRODUCT -> new AstProduct(set(e, arg));
514            case MAX -> new AstMax(set(e, arg));
515            case MIN -> new AstMin(set(e, arg));
516            case LENGTH -> new AstLength(set(e, arg));
517            case INVERSE -> new AstInverse(set(e, arg));
518            case CLOSURE -> new AstTransitiveClosure(set(e, arg), false);
519            case REFLEXIVE_CLOSURE -> new AstTransitiveClosure(set(e, arg), true);
520        };
521    }
522
523    private AstExpr binary(Ir.Binary e, boolean relation) {
524        List<AstExpr> operands = e.operands().stream().map(o -> convert(o, relation)).toList();
525        BinaryOp op = e.op();
526        if (ArithmOps.containsKey(op)) {
527            return new AstArithm(ArithmOps.get(op), operands.stream().map(o -> set(e, o)).toArray(AstSetExpr[]::new));
528        }
529        if (BoolOps.containsKey(op)) {
530            return new AstBoolArithm(BoolOps.get(op), operands.stream().map(o -> bool(e, o)).toArray(AstBoolExpr[]::new));
531        }
532        if (operands.size() > 2) {
533            throw error(e, "Parenthesize: '" + op.syntax() + "' takes two operands");
534        }
535        AstSetExpr left0 = set(e, operands.get(0));
536        AstSetExpr right0 = set(e, operands.get(1));
537        AstSetExpr left = typedBeside(left0, right0);
538        AstSetExpr right = typedBeside(right0, left0);
539        return switch (op) {
540            case LT, LE, GT, GE -> new AstCompare(left, CompareOps.get(op), right);
541            case EQ -> new AstSetTest(left, AstSetTest.Op.Equal, right);
542            case NE -> new AstSetTest(left, AstSetTest.Op.NotEqual, right);
543            case IN -> new AstMembership(left, AstMembership.Op.In, right);
544            case NOT_IN -> new AstMembership(left, AstMembership.Op.NotIn, right);
545            case MOD -> new AstMod(left, right);
546            case UNION -> new AstUnion(left, right);
547            case DIFF -> new AstDifference(left, right);
548            case INTER -> new AstIntersection(left, right);
549            case DOMAIN -> new AstDomainRestriction(left, right);
550            case RANGE -> new AstRangeRestriction(left, right);
551            default -> throw error(e, "Unknown operator " + op.syntax());
552        };
553    }
554
555    private AstExpr quantified(Ir.Quantified e) {
556        AstQuantify.Quantifier quantifier = switch (e.quantifier()) {
557            case ALL -> AstQuantify.Quantifier.All;
558            case SOME -> AstQuantify.Quantifier.Some;
559            case NO -> AstQuantify.Quantifier.None;
560            case LONE -> AstQuantify.Quantifier.Lone;
561            case ONE -> AstQuantify.Quantifier.One;
562        };
563        Map<String, AstLocal> scope = new HashMap<>();
564        List<AstDecl> decls = new ArrayList<>();
565        for (Ir.Decl decl : e.decls()) {
566            List<AstLocal> names = decl.locals().stream().map(n -> Asts.local(n.text())).toList();
567            // The body of a declaration sees the variables declared before it.
568            locals.push(scope);
569            AstSetExpr body;
570            try {
571                body = set(decl, convert(decl.set(), false));
572            } finally {
573                locals.pop();
574            }
575            decls.add(new AstDecl(decl.disjoint(), names.toArray(new AstLocal[0]), body));
576            for (AstLocal local : names) {
577                scope.put(local.getName(), local);
578            }
579        }
580        locals.push(scope);
581        try {
582            return new AstQuantify(quantifier, decls.toArray(new AstDecl[0]), bool(e, convert(e.body(), false)));
583        } finally {
584            locals.pop();
585        }
586    }
587
588    private ProductType type(List<Ir.Name> names) {
589        return new ProductType(names.stream().map(n -> clafer(n.span(), n.text())).toArray(AstClafer[]::new));
590    }
591
592    private AstClafer clafer(SourceSpan span, String name) {
593        AstClafer clafer = clafers.get(name);
594        if (clafer == null) {
595            throw new BuildError(span, Unsolved.contains(name)
596                    ? "Chocosolver does not solve " + name + ", nor does any backend"
597                    : "No clafer named " + name);
598        }
599        return clafer;
600    }
601
602    private static AstSetExpr set(Node at, AstExpr expr) {
603        if (expr instanceof AstSetExpr set) {
604            return set;
605        }
606        throw error(at, "Expected a set or a number, not a constraint");
607    }
608
609    private static AstBoolExpr bool(Node at, AstExpr expr) {
610        if (expr instanceof AstBoolExpr bool) {
611            return bool;
612        }
613        throw error(at, "Expected a constraint, not a set or a number");
614    }
615
616    // ------------------------------------------------------------------
617    // noclafer, the empty set
618    // ------------------------------------------------------------------
619    /**
620     * The noclafers built, by identity: each is an empty set of the model's
621     * first clafer until a set beside it gives it its type.
622     */
623    private final Set<AstConstant> noClafers = Collections.newSetFromMap(new IdentityHashMap<>());
624
625    /**
626     * Clafer's {@code noclafer}: an empty set of the given clafer, as the
627     * Clafer compiler writes it ({@code constant(c0_a)}), or, without one, of
628     * the model's first clafer, as for {@code #noclafer}.
629     */
630    private AstConstant noClafer(AstClafer type) {
631        AstClafer t = type != null ? type
632                : declOf.keySet().stream().findFirst().orElse(Asts.IntType);
633        AstConstant empty = Asts.constant(t);
634        noClafers.add(empty);
635        return empty;
636    }
637
638    /**
639     * A noclafer beside another set, e.g., in {@code a ++ noclafer} or
640     * {@code if c then a else noclafer}, is an empty set of that set's clafer.
641     */
642    private AstSetExpr typedBeside(AstSetExpr expr, AstSetExpr other) {
643        if (expr instanceof AstConstant c && noClafers.contains(c) && !noClafers.contains(other)) {
644            AstClafer type = claferOf(other);
645            if (type != null) {
646                return noClafer(type);
647            }
648        }
649        return expr;
650    }
651
652    /**
653     * The clafer whose instances a set is of, as far as the expression shows
654     * it, or null.
655     */
656    private static AstClafer claferOf(AstSetExpr expr) {
657        return switch (expr) {
658            case AstGlobal e -> e.type();
659            case AstJoin e when e.right() instanceof AstChildRelation r -> r.childType();
660            case AstJoinRef e -> {
661                AstClafer c = claferOf(e.deref());
662                AstRef ref = c == null ? null : AstUtil.getInheritedRef(c);
663                yield ref == null ? null : ref.getTargetType();
664            }
665            case AstJoinParent e -> {
666                AstClafer c = claferOf(e.children());
667                yield c == null || !c.hasParent() ? null : c.getParent();
668            }
669            case AstConstant e -> e.type().arity() == 1 ? e.type().get(0) : null;
670            case AstUnion e -> firstNonNull(claferOf(e.left()), claferOf(e.right()));
671            case AstIntersection e -> firstNonNull(claferOf(e.right()), claferOf(e.left()));
672            case AstDifference e -> claferOf(e.left());
673            case AstTernary e -> firstNonNull(claferOf(e.consequent()), claferOf(e.alternative()));
674            default -> null;
675        };
676    }
677
678    private static AstClafer firstNonNull(AstClafer a, AstClafer b) {
679        return a != null ? a : b;
680    }
681}