001package org.clafer.alloy;
002
003import java.util.ArrayList;
004import java.util.Comparator;
005import java.util.IdentityHashMap;
006import java.util.LinkedHashMap;
007import java.util.List;
008import java.util.Map;
009import org.clafer.alloy.Concat.ExactCard;
010import org.clafer.alloy.Concat.IrPExp;
011import org.clafer.alloy.Concat.LowerCard;
012import org.clafer.alloy.Concat.UpperCard;
013import org.clafer.alloy.Mirror.IClafer;
014import org.clafer.alloy.Mirror.IConstraint;
015import org.clafer.alloy.Mirror.IDeclPExp;
016import org.clafer.alloy.Mirror.IElement;
017import org.clafer.alloy.Mirror.IFunExp;
018import org.clafer.alloy.Mirror.PExp;
019import org.clafer.frontend.Ir;
020import org.clafer.frontend.SourceSpan;
021
022/**
023 * The Alloy 6 code of a temporal model, as {@code clafer -m alloy} writes it
024 * ({@code P.als}): the port of the compiler's {@code Generator/AlloyLtl.hs}
025 * ({@link AlloyLtl}) on the input the compiler builds for it
026 * ({@link AlloyInput}). Static models are solved with Choco, and have no
027 * Alloy code here.
028 */
029public final class AlloyGenerator {
030
031    private AlloyGenerator() {
032    }
033
034    /**
035     * A model that the port does not translate.
036     */
037    public static final class UnsupportedModel extends Exception {
038
039        UnsupportedModel(String message) {
040            super(message);
041        }
042    }
043
044    /**
045     * @param rich the rich explicit IR of a temporal model, as {@code ToIr}
046     * gives it
047     * @param scopes its scopes, by UID, in the order of the UIDs
048     * @param traceLength the trace length ({@code --tl})
049     * @param keepUnused {@code -k}: keep the abstract clafers that nothing
050     * needs
051     * @param validate {@code -v}: without the {@code run} command
052     * @return the Alloy code, without the statistics comment
053     */
054    public static String generate(Ir.Model rich, Map<String, Long> scopes, int traceLength, boolean keepUnused,
055            boolean validate)
056            throws UnsupportedModel {
057        try {
058            AlloyInput.Input in = AlloyInput.input(rich, scopes, traceLength, keepUnused);
059            return AlloyLtl.genAlloyLtlModule(in.statics(), in.staticRefs(), in.literals(), validate, in.root(),
060                    in.scopes(), in.traceLength()).code();
061        } catch (AlloyInput.Unsupported e) {
062            throw new UnsupportedModel(e.getMessage());
063        }
064    }
065
066    /**
067     * What the code of a region of the Alloy code is: a constraint of the
068     * model, or a cardinality of a clafer (not a group cardinality).
069     */
070    public enum Kind {
071        CONSTRAINT, LOWER_CARD, UPPER_CARD, EXACT_CARD
072    }
073
074    /**
075     * A region of the Alloy code (1-based lines and columns, as
076     * {@code mapLineCol} gives them) and what it is the code of.
077     *
078     * @param clafer for a cardinality, the clafer's Alloy name
079     * @param span for a constraint, its span in the model's text
080     */
081    public record Mapped(long line, long column, long endLine, long endColumn, Kind kind, String clafer,
082            SourceSpan span) {
083    }
084
085    /**
086     * An assertion of the model, with its name in the Alloy code.
087     */
088    public record Assertion(String name, SourceSpan span) {
089    }
090
091    /**
092     * The Alloy code of a model for solving it, as claferIG has the compiler
093     * write it, and what claferIG reads from the compiler with it.
094     *
095     * @param code the Alloy code, with the {@code run} command
096     * @param mapping the regions of the code that are constraints and
097     * cardinalities, for the unsat cores
098     * @param strings each string literal by its integer
099     * @param alloyNames the Alloy name of each clafer whose UID is not one,
100     * by UID
101     * @param assertions the assertions, in the order of the model
102     * @param maxInt the largest integer of the model, for the bitwidth
103     */
104    public record Translation(String code, List<Mapped> mapping, Map<Integer, String> strings,
105            Map<String, String> alloyNames, List<Assertion> assertions, long maxInt) {
106    }
107
108    /**
109     * The Alloy code of a temporal model for solving it, as claferIG has the
110     * compiler write it: with {@code -k}, so that no abstract clafer is
111     * removed.
112     *
113     * @param rich the rich explicit IR of a temporal model
114     * @param scopes its scopes, by UID, in the order of the UIDs
115     * @param traceLength the trace length ({@code --tl})
116     */
117    public static Translation translate(Ir.Model rich, Map<String, Long> scopes, int traceLength)
118            throws UnsupportedModel {
119        AlloyInput.Input in;
120        AlloyLtl.Result result;
121        try {
122            in = AlloyInput.input(rich, scopes, traceLength, true);
123            result = AlloyLtl.genAlloyLtlModule(in.statics(), in.staticRefs(), in.literals(), false, in.root(),
124                    in.scopes(), in.traceLength());
125        } catch (AlloyInput.Unsupported e) {
126            throw new UnsupportedModel(e.getMessage());
127        }
128        Map<Object, SourceSpan> spans = new IdentityHashMap<>();
129        List<Assertion> assertions = new ArrayList<>();
130        positions(in.root(), spans, assertions);
131        assertions.sort(Comparator.comparing(Assertion::span,
132                Comparator.comparingInt(SourceSpan::line).thenComparingInt(SourceSpan::column)));
133        List<Mapped> mapping = new ArrayList<>();
134        for (Map.Entry<AlloyLtl.Span, Concat.IrTrace> e : result.mapping()) {
135            AlloyLtl.Span at = e.getKey();
136            Mapped m = switch (e.getValue()) {
137                case IrPExp p -> spans.containsKey(p.pUid())
138                        ? new Mapped(at.startLine(), at.startColumn(), at.endLine(), at.endColumn(), Kind.CONSTRAINT,
139                                null, spans.get(p.pUid())) : null;
140                case LowerCard c when !c.isGroup() -> new Mapped(at.startLine(), at.startColumn(), at.endLine(),
141                        at.endColumn(), Kind.LOWER_CARD, c.pUid(), null);
142                case UpperCard c when !c.isGroup() -> new Mapped(at.startLine(), at.startColumn(), at.endLine(),
143                        at.endColumn(), Kind.UPPER_CARD, c.pUid(), null);
144                case ExactCard c when !c.isGroup() -> new Mapped(at.startLine(), at.startColumn(), at.endLine(),
145                        at.endColumn(), Kind.EXACT_CARD, c.pUid(), null);
146                default -> null;
147            };
148            if (m != null) {
149                mapping.add(m);
150            }
151        }
152        Map<Integer, String> strings = new LinkedHashMap<>();
153        in.strings().forEach((text, i) -> strings.put(i, text));
154        return new Translation(result.code(), List.copyOf(mapping), strings, Map.copyOf(in.names()),
155                List.copyOf(assertions), AlloyInput.maxInModel(rich));
156    }
157
158    /**
159     * The spans of the expressions of the constraints, by their ids, and the
160     * assertions ({@code parseConstraints}, {@code parseAssertions}).
161     */
162    private static void positions(IClafer c, Map<Object, SourceSpan> spans, List<Assertion> assertions) {
163        for (IElement e : c.elements) {
164            switch (e) {
165                case IClafer sub -> positions(sub, spans, assertions);
166                case IConstraint k -> {
167                    subexpressions(k.pexp(), spans);
168                    if (!k.isHard()) {
169                        assertions.add(new Assertion(AlloyLtl.assertionName(k.pexp()), k.pexp().inPos()));
170                    }
171                }
172                default -> {
173                }
174            }
175        }
176    }
177
178    private static void subexpressions(PExp p, Map<Object, SourceSpan> spans) {
179        spans.putIfAbsent(p.pid(), p.inPos());
180        switch (p.exp()) {
181            case IDeclPExp d -> {
182                d.oDecls().forEach(x -> subexpressions(x.body(), spans));
183                subexpressions(d.bpexp(), spans);
184            }
185            case IFunExp f -> f.exps().forEach(x -> subexpressions(x, spans));
186            default -> {
187            }
188        }
189    }
190}