001package org.clafer.frontend;
002
003import java.util.ArrayList;
004import java.util.HashMap;
005import java.util.HashSet;
006import java.util.List;
007import java.util.Map;
008import java.util.Optional;
009import java.util.OptionalInt;
010import java.util.Set;
011import org.clafer.frontend.Symbols.ClaferSymbol;
012import org.clafer.frontend.Symbols.Interval;
013import org.clafer.frontend.Symbols.RefModifier;
014import org.clafer.frontend.Syntax.Binary;
015import org.clafer.frontend.Syntax.ClaferId;
016import org.clafer.frontend.Syntax.Exp;
017import org.clafer.frontend.Syntax.Ident;
018import org.clafer.frontend.Syntax.Literal;
019
020/**
021 * The explicit IR of a model in the full syntax, as the compiler gives it
022 * ({@code clafer -m clafer}), and its scopes. The clafers are the
023 * {@link Symbols}: their UIDs, supers, references, cards, group cards,
024 * modifiers and initializers, with the layout, the braces and the defaults
025 * gone. The constraints, objectives, assertions, initial values and
026 * transitions are resolved by the {@link Resolver}, and the scopes are the
027 * compiler's ({@link ScopeAnalysis}). As in the compiler, the constraints of
028 * a reference to a set expression come first in its clafer, a nested
029 * assertion is quantified over the instances of its clafer
030 * ({@code all this_ : A.b |}), and the objectives and assertions are
031 * collected in pre-order.
032 * <p>
033 * Every rich explicit model is such a model, so it gives its own IR back.
034 */
035public final class ToIr {
036
037    private ToIr() {
038    }
039
040    /**
041     * @param model the explicit IR, or an empty model if the model has
042     * errors before this pass
043     * @param diagnostics the errors of the files, the parser, the checks, the
044     * symbols and this pass; an error without a position is at 1:1
045     * @param errors the errors without a position, as the compiler gives
046     * them: of reading the files, and of the checks of the whole model
047     * ({@link ModelChecks}), e.g., clafers named after keywords
048     * @param scopes the scopes of the explicit model's scope file, if it has
049     * no errors
050     * @param files the files of the model, whose lines the diagnostics are in
051     * @param names what the names refer to, for the language server, or
052     * {@link Names#None} if the model has errors before the resolver
053     */
054    public record Result(Ir.Model model, List<Diagnostic> diagnostics, List<String> errors, Optional<Scopes> scopes,
055            ModelFiles files, Names names) {
056
057        /**
058         * @return the errors without a position if there are any, else the
059         * diagnostics, each at its position in its file
060         */
061        public List<String> messages() {
062            return errors.isEmpty() ? diagnostics.stream().map(files::format).toList() : errors;
063        }
064    }
065
066    private static Result failed(List<Diagnostic> diagnostics, ModelFiles files) {
067        return new Result(empty(), List.copyOf(diagnostics), List.of(), Optional.empty(), files, Names.None);
068    }
069
070    /**
071     * The result of an error without a position.
072     */
073    private static Result failed(String error, ModelFiles files) {
074        return new Result(empty(), List.of(new Diagnostic(SourceSpan.at(1, 1), error)), List.of(error),
075                Optional.empty(), files, Names.None);
076    }
077
078    /**
079     * Parses a model in one file, without reading its imports, finds its
080     * symbols, and builds its explicit IR.
081     *
082     * @param source the text of a model
083     * @return its IR and the errors
084     */
085    public static Result toIr(String source) {
086        return toIr(ModelFiles.of("", source));
087    }
088
089    /**
090     * Reads a model and its imports, and builds its explicit IR.
091     *
092     * @param path the model's file
093     */
094    public static Result read(String path) {
095        return toIr(ModelFiles.read(path, List.of()));
096    }
097
098    /**
099     * Builds the explicit IR of the files of a model: their concatenation,
100     * with their options combined.
101     */
102    public static Result toIr(ModelFiles files) {
103        if (!files.errors().isEmpty()) {
104            return new Result(empty(), files.errors().stream().map(e -> new Diagnostic(SourceSpan.at(1, 1), e))
105                    .toList(), files.errors(), Optional.empty(), files, Names.None);
106        }
107        String source = files.text();
108        ClaferParser.Result parsed = ClaferParser.parse(source);
109        if (!parsed.diagnostics().isEmpty()) {
110            return failed(parsed.diagnostics(), files);
111        }
112        // the compiler's checks before the names are resolved, in its order
113        ModelOptions o = files.options();
114        Syntax.Model model = parsed.model();
115        Optional<String> keywords = ModelChecks.keywordNames(model);
116        if (keywords.isPresent()) {
117            return failed(keywords.get(), files);
118        }
119        List<Diagnostic> clockless = o.explicit() ? ModelChecks.clocklessInitializers(model) : List.of();
120        if (!clockless.isEmpty()) {
121            return failed(clockless, files);
122        }
123        List<Diagnostic> bounds = ModelChecks.initializerBounds(model);
124        if (!bounds.isEmpty()) {
125            return failed(bounds, files);
126        }
127        Optional<String> duplicates = o.checkDuplicates() ? ModelChecks.duplicateNames(model) : Optional.empty();
128        if (duplicates.isPresent()) {
129            return failed(duplicates.get(), files);
130        }
131        Optional<Diagnostic> nonUid = o.skipResolver() ? ModelChecks.nonUidName(model) : Optional.empty();
132        if (nonUid.isPresent()) {
133            return failed(List.of(nonUid.get()), files);
134        }
135        Symbols.Result symbols = Symbols.analyze(model);
136        if (!symbols.diagnostics().isEmpty()) {
137            return failed(symbols.diagnostics(), files);
138        }
139        return toIr(model, symbols, o, files);
140    }
141
142    private static Ir.Model empty() {
143        SourceSpan span = new SourceSpan(1, 1, 1, 1);
144        return new Ir.Model(span, Ir.Options.Rich, List.of(), List.of(), List.of());
145    }
146
147    /**
148     * The options of the first {@code //# OPTIONS} line that the explicit
149     * form keeps: {@code --core} and the trace length.
150     */
151    static Ir.Options options(String source) {
152        ModelOptions o = ModelOptions.of(source);
153        return new Ir.Options(o.core(), o.traceLength());
154    }
155
156    /**
157     * @param model a parsed model without errors
158     * @param symbols its symbols, without errors
159     * @param options the options of the explicit model
160     * @return its IR and the errors of this pass
161     */
162    public static Result toIr(Syntax.Model model, Symbols.Result symbols, Ir.Options options) {
163        return toIr(model, symbols, options, Optional.empty());
164    }
165
166    /**
167     * @param decimalDigits the decimal scale of {@code --decimal-digits},
168     * if given
169     */
170    public static Result toIr(Syntax.Model model, Symbols.Result symbols, Ir.Options options,
171            Optional<Integer> decimalDigits) {
172        ModelOptions o = new ModelOptions(options.core(), options.traceLength(), java.util.OptionalLong.empty(),
173                java.util.OptionalLong.empty(), decimalDigits, true, List.of(), Set.of());
174        return toIr(model, symbols, o, ModelFiles.of("", ""));
175    }
176
177    private static Result toIr(Syntax.Model model, Symbols.Result symbols, ModelOptions o, ModelFiles files) {
178        Resolver resolver = new Resolver(symbols, model, o.decimalDigits());
179        // a temporal model has a trace length, 10 unless given, as in the compiler; a static one has none
180        Ir.Options options = new Ir.Options(o.core(), resolver.isDynamic()
181                ? OptionalInt.of(o.traceLength().orElse(10)) : OptionalInt.empty());
182        Builder builder = new Builder(symbols, resolver);
183        List<Ir.Element> elements = new ArrayList<>();
184        for (Syntax.Declaration d : model.declarations()) {
185            switch (d) {
186                case Syntax.EnumDecl e -> {
187                    ClaferSymbol en = symbols.of(e).orElseThrow();
188                    List<Ir.Name> literals = new ArrayList<>();
189                    for (Ident literal : e.literals()) {
190                        literals.add(new Ir.Name(literal.span(), symbols.of(literal).orElseThrow().uid()));
191                    }
192                    elements.add(new Ir.EnumDecl(e.span(), new Ir.Name(e.name().span(), en.uid()), literals));
193                }
194                case Syntax.Element e -> builder.element(e, null, elements);
195            }
196        }
197        List<Diagnostic> diagnostics = new ArrayList<>(builder.diagnostics);
198        diagnostics.addAll(builder.resolver.diagnostics);
199        // the compiler's checks after the names are resolved, in its order
200        if (diagnostics.isEmpty()) {
201            diagnostics.addAll(resolver.initialValueErrors);
202        }
203        Ir.Model ir = new Ir.Model(model.span(), options, elements, builder.objectives, builder.assertions);
204        if (diagnostics.isEmpty() && o.explicit() && o.core()) {
205            diagnostics.addAll(Core.richInCore(ir));
206        }
207        List<String> errors = List.of();
208        if (diagnostics.isEmpty() && o.checkAfm()) {
209            Optional<String> afm = ModelChecks.notAttributedFeatureModel(model, symbols);
210            if (afm.isPresent()) {
211                errors = List.of(afm.get());
212                diagnostics.add(new Diagnostic(SourceSpan.at(1, 1), afm.get()));
213            }
214        }
215        Optional<Scopes> scopes = Optional.empty();
216        if (diagnostics.isEmpty()) {
217            try {
218                scopes = Optional.of(scopes(model, resolver, elements, o));
219            } catch (ScopeAnalysis.Failure e) {
220                diagnostics.add(new Diagnostic(model.span(), e.getMessage()));
221            }
222        }
223        diagnostics.sort((a, b) -> a.span().line() != b.span().line()
224                ? Integer.compare(a.span().line(), b.span().line())
225                : Integer.compare(a.span().column(), b.span().column()));
226        return new Result(ir, List.copyOf(diagnostics), errors, scopes, files, Names.of(symbols, resolver.nameUses));
227    }
228
229    /**
230     * The scopes of the scope file: every clafer's, 1 unless the analysis
231     * gives another, and the ranges ({@code ChocoModel.chocoModel}).
232     */
233    private static Scopes scopes(Syntax.Model model, Resolver resolver, List<Ir.Element> elements, ModelOptions o) {
234        Map<String, Long> analysis = ScopeAnalysis.scopes(resolver, elements, o.simpleScopes());
235        Map<String, Long> clafers = new java.util.TreeMap<>();
236        for (String uid : uids(elements, new ArrayList<>())) {
237            clafers.put(uid, analysis.getOrDefault(uid, 1L));
238        }
239        long intLow = -128;
240        long intHigh = 127;
241        if (o.minInt().isPresent() || o.maxInt().isPresent()) {
242            intLow = o.minInt().orElse(-128);
243            intHigh = o.maxInt().orElse(127);
244        }
245        int stringLength = 16;
246        boolean[] decimals = {false};
247        int[] longest = {16};
248        Resolver.forEachExp(model, e -> {
249            if (e instanceof Literal l && l.kind() == Syntax.LiteralKind.Str) {
250                longest[0] = Math.max(longest[0], l.text().codePointCount(0, l.text().length()));
251            }
252            if (e instanceof Literal l && l.kind() == Syntax.LiteralKind.Real) {
253                decimals[0] = true;
254            }
255        });
256        stringLength = longest[0];
257        boolean usesDecimals = decimals[0] || resolver.refersToDecimal();
258        long decimalDigits = usesDecimals || o.decimalDigits().isPresent() ? resolver.decimalScale() : 0;
259        return new Scopes(java.util.Collections.unmodifiableMap(clafers), intLow, intHigh, stringLength, decimalDigits);
260    }
261
262    private static List<String> uids(List<Ir.Element> elements, List<String> out) {
263        for (Ir.Element e : elements) {
264            switch (e) {
265                case Ir.EnumDecl en -> {
266                    out.add(en.name().text());
267                    en.literals().forEach(l -> out.add(l.text()));
268                }
269                case Ir.ClaferDecl c -> {
270                    out.add(c.name().text());
271                    uids(c.elements(), out);
272                }
273                default -> {
274                }
275            }
276        }
277        return out;
278    }
279
280    private static final class Builder {
281
282        private final Symbols.Result symbols;
283        final Resolver resolver;
284        final List<Diagnostic> diagnostics = new ArrayList<>();
285        final List<Ir.Objective> objectives = new ArrayList<>();
286        final List<Ir.Assertion> assertions = new ArrayList<>();
287
288        Builder(Symbols.Result symbols, Resolver resolver) {
289            this.symbols = symbols;
290            this.resolver = resolver;
291        }
292
293        /**
294         * An element of a clafer, or of the model if the clafer is null.
295         */
296        void element(Syntax.Element e, ClaferSymbol parent, List<Ir.Element> out) {
297            switch (e) {
298                case Syntax.Clafer c -> clafer(c, parent, out);
299                case Syntax.ClaferUse u -> clafer(u, parent, out);
300                case Syntax.Constraint c -> {
301                    SourceSpan span = c.exps().get(0).span();
302                    resolver.constraint(c.exps(), parent, false)
303                            .ifPresent(x -> out.add(new Ir.Constraint(span, x, Optional.empty())));
304                }
305                case Syntax.Assertion a -> {
306                    SourceSpan span = a.exps().get(0).span();
307                    resolver.constraint(a.exps(), parent, true).ifPresent(x -> assertions.add(new Ir.Assertion(span,
308                            parent == null ? x : quantified(parent, x, span), Optional.empty())));
309                }
310                case Syntax.Goal g -> {
311                    boolean maximize = g.kind() == Syntax.GoalKind.Maximize || g.kind() == Syntax.GoalKind.MaxDeprecated;
312                    resolver.goal(g, parent).ifPresent(x -> objectives.add(new Ir.Objective(g.span(), maximize, x)));
313                }
314            }
315        }
316
317        /**
318         * A nested assertion holds for each instance of its clafer:
319         * {@code all this_ : A.b | ...}, with {@code this} as {@code this_}.
320         */
321        private Ir.Exp quantified(ClaferSymbol clafer, Ir.Exp body, SourceSpan span) {
322            Ir.Name local = new Ir.Name(span, "this_");
323            Ir.Decl decl = new Ir.Decl(span, false, List.of(local), instancesOf(clafer, span));
324            return new Ir.Quantified(span, Ir.Quantifier.ALL, List.of(decl), thisToLocal(body));
325        }
326
327        private static Ir.Exp instancesOf(ClaferSymbol c, SourceSpan span) {
328            Ir.NameExp name = new Ir.NameExp(span, c.uid());
329            return c.parent().isEmpty() ? name : new Ir.Join(span, instancesOf(c.parent().get(), span), name);
330        }
331
332        /**
333         * Replaces {@code this} with {@code this_}, in the expressions that an
334         * explicit model's constraint can hold.
335         */
336        private static Ir.Exp thisToLocal(Ir.Exp e) {
337            return switch (e) {
338                case Ir.This t -> new Ir.NameExp(t.span(), "this_");
339                case Ir.Join j -> new Ir.Join(j.span(), thisToLocal(j.left()), thisToLocal(j.right()));
340                case Ir.Dref d -> new Ir.Dref(d.span(), thisToLocal(d.left()));
341                case Ir.ParentOf p -> new Ir.ParentOf(p.span(), thisToLocal(p.left()));
342                case Ir.Unary u -> new Ir.Unary(u.span(), u.op(), thisToLocal(u.arg()));
343                case Ir.Binary b -> new Ir.Binary(b.span(), b.op(), b.operands().stream().map(Builder::thisToLocal).toList());
344                case Ir.IfThenElse i -> new Ir.IfThenElse(i.span(), thisToLocal(i.condition()), thisToLocal(i.then()),
345                        thisToLocal(i.otherwise()));
346                case Ir.Quantified q -> new Ir.Quantified(q.span(), q.quantifier(), q.decls().stream()
347                        .map(d -> new Ir.Decl(d.span(), d.disjoint(), d.locals(), thisToLocal(d.set()))).toList(),
348                        thisToLocal(q.body()));
349                case Ir.QuantifiedSet q -> new Ir.QuantifiedSet(q.span(), q.quantifier(), thisToLocal(q.set()));
350                case Ir.Temporal t -> new Ir.Temporal(t.span(), t.op(), t.args().stream().map(Builder::thisToLocal).toList());
351                case Ir.Anchor a -> new Ir.Anchor(a.span(), a.initially(), thisToLocal(a.body()));
352                case Ir.Pattern p -> new Ir.Pattern(p.span(), p.kind(), p.scope(),
353                        p.args().stream().map(Builder::thisToLocal).toList());
354                case Ir.Transition t -> new Ir.Transition(t.span(), t.sync(), thisToLocal(t.from()),
355                        t.guard().map(Builder::thisToLocal), thisToLocal(t.to()));
356                default -> e;
357            };
358        }
359
360        private void clafer(Syntax.Element declaration, ClaferSymbol parent, List<Ir.Element> out) {
361            ClaferSymbol c = symbols.of(declaration).orElseThrow();
362            // a clafer relocated under another (gsdlab/clafer#67) is built there
363            if (c.parent().orElse(null) != parent) {
364                return;
365            }
366            out.add(clafer(c));
367        }
368
369        private Ir.ClaferDecl clafer(ClaferSymbol c) {
370            SourceSpan span = c.declaration().span();
371            List<Ir.Modifier> modifiers = new ArrayList<>();
372            if (c.isInitial()) {
373                modifiers.add(new Ir.Modifier(span, Ir.ModifierKind.INITIAL));
374            }
375            if (c.isFinal()) {
376                modifiers.add(new Ir.Modifier(span, Ir.ModifierKind.FINAL));
377            } else {
378                for (RefModifier m : c.refModifiers()) {
379                    modifiers.add(new Ir.Modifier(span, switch (m) {
380                        case FinalRef -> Ir.ModifierKind.FINALREF;
381                        case FinalTarget -> Ir.ModifierKind.FINALTARGET;
382                        case FinalRefTarget -> Ir.ModifierKind.FINAL;
383                    }));
384                }
385            }
386            Ir.Card groupCard = card(span, Symbols.printedGroupCard(c));
387            Optional<Ir.Name> superName = c.superClafer().map(s -> new Ir.Name(span, s.uid()));
388            Optional<Symbols.Reference> reference = c.reference().filter(Symbols.Reference::hasType);
389            Optional<Ir.RefDecl> ref = reference.map(r -> new Ir.RefDecl(r.span(), r.isSet(),
390                    new Ir.Name(r.span(), r.typeName())));
391            Ir.Card card = card(span, c.card());
392            Optional<Ir.AbstractMultiplicity> abstractMultiplicity = Optional.empty();
393            if (c.isAbstract() && c.isTopLevel() && !c.card().equals(Interval.Any)) {
394                abstractMultiplicity = Optional.of(new Ir.AbstractMultiplicity(span, card));
395                card = card(span, Interval.Any);
396            }
397            Optional<Ir.Initializer> initializer = Optional.empty();
398            if (c.initializer().isPresent()) {
399                // the value as written, or the constant of -> 1
400                Optional<Exp> value = c.declaration() instanceof Syntax.Clafer d && d.init().isPresent()
401                        ? Optional.of(d.init().get().exp())
402                        : c.reference().map(Symbols.Reference::target);
403                if (value.isPresent()) {
404                    SourceSpan initSpan = c.declaration() instanceof Syntax.Clafer d && d.init().isPresent()
405                            ? d.init().get().span() : value.get().span();
406                    Optional<Ir.Exp> v = resolver.initializer(c, value.get(), initSpan);
407                    if (v.isPresent()) {
408                        initializer = Optional.of(new Ir.Initializer(value.get().span(), c.initializer().get(), v.get()));
409                    }
410                }
411            }
412            List<Ir.Element> elements = new ArrayList<>();
413            if (reference.isPresent() && isSetExp(reference.get().target())) {
414                for (Ir.Exp x : resolver.referenceConstraints(c)) {
415                    elements.add(new Ir.Constraint(reference.get().span(), x, Optional.empty()));
416                }
417            }
418            Optional<Syntax.Elements> block = switch (c.declaration()) {
419                case Syntax.Clafer d -> d.elements();
420                case Syntax.ClaferUse u -> u.elements();
421                default -> Optional.empty();
422            };
423            Set<ClaferSymbol> built = new HashSet<>();
424            for (Syntax.Element e : block.map(Syntax.Elements::elements).orElse(List.of())) {
425                element(e, c, elements);
426                if (e instanceof Syntax.Clafer || e instanceof Syntax.ClaferUse) {
427                    built.add(symbols.of(e).orElseThrow());
428                }
429            }
430            // the transition of the clafer, a constraint after its elements
431            if (c.declaration() instanceof Syntax.Clafer d && d.transition().isPresent()) {
432                resolver.transition(c, d.transition().get())
433                        .ifPresent(x -> elements.add(new Ir.Constraint(d.transition().get().span(), x, Optional.empty())));
434            }
435            // the clafers relocated under it, last
436            for (ClaferSymbol child : c.children()) {
437                if (!built.contains(child)) {
438                    elements.add(clafer(child));
439                }
440            }
441            return new Ir.ClaferDecl(span, c.isAbstract(), modifiers, groupCard, new Ir.Name(c.nameSpan(), c.uid()),
442                    superName, ref, card, abstractMultiplicity, initializer, elements, Optional.empty());
443        }
444
445        private static Ir.Card card(SourceSpan span, Interval i) {
446            return new Ir.Card(span, i.low(), i.high() == Interval.Unbounded ? Ir.Card.Unbounded : i.high());
447        }
448
449        private static boolean isSetExp(Exp e) {
450            return e instanceof Binary b && switch (b.op()) {
451                case Union, UnionCom, Intersection, IntersectionDeprecated, Difference -> true;
452                default -> false;
453            };
454        }
455    }
456}