001package org.clafer.alloy.solve;
002
003import java.io.IOException;
004import java.io.StringReader;
005import java.util.ArrayList;
006import java.util.HashMap;
007import java.util.LinkedHashSet;
008import java.util.List;
009import java.util.Map;
010import java.util.TreeMap;
011import java.util.function.UnaryOperator;
012import javax.xml.parsers.DocumentBuilderFactory;
013import javax.xml.parsers.ParserConfigurationException;
014import org.clafer.ig.ClaferModel;
015import org.clafer.ig.ClaferModel.AliasValue;
016import org.clafer.ig.ClaferModel.Clafer;
017import org.clafer.ig.ClaferModel.Id;
018import org.clafer.ig.ClaferModel.IntValue;
019import org.clafer.ig.ClaferModel.StringValue;
020import org.clafer.ig.ClaferModel.Value;
021import org.clafer.ig.Solution;
022import org.w3c.dom.Element;
023import org.w3c.dom.Node;
024import org.xml.sax.InputSource;
025import org.xml.sax.SAXException;
026
027/**
028 * A solution from Alloy's XML, as claferIG reads it: {@code Solution.hs}
029 * (the sigs and fields of each state), {@code ClaferModel.hs} (the tree of
030 * the clafers) and {@code Sugarer.hs} (the names of the instances).
031 */
032public final class AlloyXml {
033
034    /**
035     * What the names of the instances need of a clafer, by its Alloy name.
036     *
037     * @param ident its name
038     * @param superName the Alloy name of its super clafer, or null
039     * @param reference the primitive type of its own reference, e.g.,
040     * {@code string}, or null
041     */
042    public record ClaferInfo(String ident, String superName, String reference) {
043    }
044
045    /**
046     * How the instances are named.
047     *
048     * @param clafers the clafers by their Alloy names
049     * @param toUid the UID of a clafer by its Alloy name
050     * @param useUids the instances are named by the UIDs of their clafers
051     * @param addTypes each instance has the super clafer of its clafer
052     * @param strings the strings by their integers
053     */
054    public record Naming(Map<String, ClaferInfo> clafers, UnaryOperator<String> toUid, boolean useUids,
055            boolean addTypes, Map<Integer, String> strings) {
056    }
057
058    private AlloyXml() {
059    }
060
061    // ----------------------------------------------------------------------
062    // Solution.hs
063    // ----------------------------------------------------------------------
064    private record Sig(String label, int id, List<String> atoms) {
065    }
066
067    private record Field(String label, int toType, List<String[]> tuples) {
068    }
069
070    private record Instance(List<Sig> sigs, List<Field> fields) {
071    }
072
073    private static Element parse(String xml) {
074        try {
075            DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
076            f.setExpandEntityReferences(false);
077            f.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
078            return f.newDocumentBuilder().parse(new InputSource(new StringReader(xml))).getDocumentElement();
079        } catch (ParserConfigurationException | SAXException | IOException e) {
080            throw new IllegalArgumentException("Not Alloy's XML of a solution: " + e.getMessage(), e);
081        }
082    }
083
084    private static List<Element> children(Element e, String tag) {
085        List<Element> out = new ArrayList<>();
086        for (Node n = e.getFirstChild(); n != null; n = n.getNextSibling()) {
087            if (n instanceof Element c && c.getTagName().equals(tag)) {
088                out.add(c);
089            }
090        }
091        return out;
092    }
093
094    private static Instance parseInstance(Element instance) {
095        List<Sig> sigs = new ArrayList<>();
096        for (Element s : children(instance, "sig")) {
097            List<String> atoms = children(s, "atom").stream().map(a -> a.getAttribute("label")).toList();
098            sigs.add(new Sig(s.getAttribute("label"), Integer.parseInt(s.getAttribute("ID")), atoms));
099        }
100        List<Field> fields = new ArrayList<>();
101        for (Element f : children(instance, "field")) {
102            List<Element> types = children(f, "types").stream().flatMap(t -> children(t, "type").stream()).toList();
103            int toType = Integer.parseInt(types.get(1).getAttribute("ID"));
104            List<String[]> tuples = new ArrayList<>();
105            for (Element t : children(f, "tuple")) {
106                List<Element> atoms = children(t, "atom");
107                tuples.add(new String[]{atoms.get(0).getAttribute("label"), atoms.get(1).getAttribute("label")});
108            }
109            fields.add(new Field(f.getAttribute("label"), toType, tuples));
110        }
111        return new Instance(sigs, fields);
112    }
113
114    // ----------------------------------------------------------------------
115    // ClaferModel.hs
116    // ----------------------------------------------------------------------
117    private sealed interface TreeNode {
118
119        Id id();
120    }
121
122    private record ClaferNode(Id id, int type) implements TreeNode {
123    }
124
125    private record ValueNode(Id id, int type) implements TreeNode {
126    }
127
128    private static final class FamilyTree {
129
130        final TreeMap<Id, TreeNode> roots = new TreeMap<>();
131        final Map<Id, List<TreeNode>> descendants = new HashMap<>();
132
133        List<TreeNode> children(Id parent) {
134            return descendants.getOrDefault(parent, List.of());
135        }
136    }
137
138    private static Id labelAsId(String label) {
139        int i = label.indexOf('$');
140        return i < 0 ? new Id(label, 0) : new Id(label.substring(0, i), Integer.parseInt(label.substring(i + 1)));
141    }
142
143    private static FamilyTree buildFamilyTree(Instance solution, List<Field> fields) {
144        FamilyTree tree = new FamilyTree();
145        for (Sig s : solution.sigs()) {
146            for (String a : s.atoms()) {
147                Id id = labelAsId(a);
148                tree.roots.put(id, new ClaferNode(id, s.id()));
149            }
150        }
151        // the fields and their tuples in order: foldr of the prepending addChild
152        for (Field f : fields) {
153            boolean value = f.label().endsWith("_ref");
154            for (String[] t : f.tuples()) {
155                Id from = labelAsId(t[0]);
156                Id to = labelAsId(t[1]);
157                TreeNode child = value ? new ValueNode(to, f.toType()) : new ClaferNode(to, f.toType());
158                if (child instanceof ClaferNode) {
159                    tree.roots.remove(to);
160                }
161                tree.descendants.computeIfAbsent(from, k -> new ArrayList<>()).add(child);
162            }
163        }
164        return tree;
165    }
166
167    /**
168     * The instance in a state of a trace of a dynamic model. The sigs of a
169     * dynamic model are pools of atoms, which exist in every state; the clafers
170     * that exist in the state are those reachable from the root through their
171     * containment relations ({@code r_c0_name}). The parent relations
172     * ({@code p_c0_name}) of the atoms are static, and do not belong to the
173     * tree.
174     */
175    private static ClaferModel buildStateModel(Instance solution) {
176        List<Field> fields = solution.fields().stream()
177                .filter(f -> f.label().startsWith("r_") || f.label().endsWith("_ref")).toList();
178        FamilyTree tree = buildFamilyTree(solution, fields);
179        return buildClafers(solution, tree, tree.children(new Id("root", 0)));
180    }
181
182    private static ClaferModel buildClaferModel(Instance solution) {
183        FamilyTree tree = buildFamilyTree(solution, solution.fields());
184        return buildClafers(solution, tree, new ArrayList<>(tree.roots.values()));
185    }
186
187    private static ClaferModel buildClafers(Instance solution, FamilyTree tree, List<TreeNode> nodes) {
188        int intType = solution.sigs().stream().filter(s -> s.label().equals("Int")).findFirst()
189                .orElseThrow(() -> new IllegalStateException("Missing Int sig")).id();
190        List<Clafer> clafers = new ArrayList<>();
191        for (TreeNode n : nodes) {
192            if (n instanceof ClaferNode c) {
193                clafers.add(buildClafer(c, tree, intType));
194            }
195        }
196        return new ClaferModel(removeDups(clafers));
197    }
198
199    private static Clafer buildClafer(ClaferNode node, FamilyTree tree, int intType) {
200        List<Clafer> claferChildren = new ArrayList<>();
201        LinkedHashSet<Value> values = new LinkedHashSet<>();
202        for (TreeNode child : tree.children(node.id())) {
203            switch (child) {
204                case ClaferNode c -> claferChildren.add(buildClafer(c, tree, intType));
205                case ValueNode v -> values.add(v.type() == intType
206                        ? new IntValue(Integer.parseInt(v.id().name())) : new AliasValue(v.id()));
207            }
208        }
209        if (values.size() > 1) {
210            throw new IllegalStateException("Received more than one value " + values);
211        }
212        return new Clafer(node.id(), node.id().name(), values.isEmpty() ? null : values.iterator().next(),
213                claferChildren);
214    }
215
216    // removeDups: a clafer that appears again later is left out here; the result is reversed, as the
217    // compiler's accumulator gives it
218    private static List<Clafer> removeDups(List<Clafer> ms) {
219        List<Clafer> acc = new ArrayList<>();
220        for (int i = 0; i < ms.size(); i++) {
221            Clafer m = ms.get(i);
222            if (ms.subList(i + 1, ms.size()).contains(m)) {
223                continue;
224            }
225            acc.add(0, new Clafer(m.id(), m.uid(), m.value(), removeDups(m.children())));
226        }
227        return acc;
228    }
229
230    // ----------------------------------------------------------------------
231    // Sugarer.hs
232    // ----------------------------------------------------------------------
233    /**
234     * The simple name of each instance and its number among the instances of
235     * that name, and how many instances each name has.
236     */
237    private static final class Census {
238
239        final Map<Id, Object[]> sample = new HashMap<>();
240        final Map<String, Integer> counts = new HashMap<>();
241
242        void poll(Naming naming, Id id) {
243            String name = claferName(naming, id.name());
244            int ordinal = counts.merge(name, 1, Integer::sum);
245            sample.put(id, new Object[]{ordinal, name});
246        }
247    }
248
249    private static String claferName(Naming naming, String alloyName) {
250        ClaferInfo info = naming.clafers().get(alloyName);
251        return info == null ? alloyName : info.ident();
252    }
253
254    /**
255     * Count the number of each clafer in the states of a trace: an instance
256     * that exists in several states is counted once, so it has the same name
257     * in each of them.
258     */
259    private static Census statesCensus(Naming naming, List<ClaferModel> states) {
260        Census census = new Census();
261        for (ClaferModel state : states) {
262            state.topLevel().forEach(c -> census(naming, c, census));
263        }
264        return census;
265    }
266
267    private static void census(Naming naming, Clafer c, Census census) {
268        c.children().forEach(x -> census(naming, x, census));
269        if (!census.sample.containsKey(c.id())) {
270            census.poll(naming, c.id());
271        }
272    }
273
274    private static ClaferModel sugar(Census census, Naming naming, ClaferModel model) {
275        return new ClaferModel(model.topLevel().stream().map(c -> sugarClafer(census, naming, c)).toList());
276    }
277
278    private static Clafer sugarClafer(Census census, Naming naming, Clafer c) {
279        return new Clafer(sugarId(census, naming, true, c.id()), c.uid(), sugarValue(census, naming, c),
280                c.children().stream().map(x -> sugarClafer(census, naming, x)).toList());
281    }
282
283    private static Value sugarValue(Census census, Naming naming, Clafer c) {
284        if (c.value() instanceof AliasValue a) {
285            return new AliasValue(sugarId(census, naming, false, a.alias()));
286        }
287        if (c.value() == null) {
288            return null;
289        }
290        ClaferInfo info = naming.clafers().get(c.id().name());
291        if (info == null) {
292            throw new IllegalStateException("IClafer not found:" + c.id().name());
293        }
294        if ("string".equals(info.reference()) && c.value() instanceof IntValue i) {
295            String s = naming.strings().get(i.value());
296            return new StringValue(s == null ? "\"<text " + i.value() + ">\"" : s);
297        }
298        return c.value();
299    }
300
301    private static Id sugarId(Census census, Naming naming, boolean addRefDecl, Id id) {
302        Object[] sample = census.sample.get(id);
303        if (sample == null) {
304            // an atom that is in no state of the trace, e.g., the literal of an enumeration
305            return new Id(naming.useUids() ? naming.toUid().apply(id.name()) : claferName(naming, id.name()), 0);
306        }
307        int ordinal = (Integer) sample[0];
308        String simpleName = (String) sample[1];
309        int count = census.counts.get(simpleName);
310        String ordinalDisplay = naming.useUids() || count > 1 ? "$" + ordinal : "";
311        String finalName = naming.useUids() ? naming.toUid().apply(id.name()) : simpleName;
312        String refDecl = "";
313        if (naming.addTypes() && addRefDecl) {
314            ClaferInfo info = naming.clafers().get(id.name());
315            if (info == null) {
316                throw new IllegalStateException("IClafer not found: " + id.name());
317            }
318            if (info.superName() != null) {
319                refDecl = " : " + (naming.useUids() ? naming.toUid().apply(info.superName())
320                        : claferName(naming, info.superName()));
321            }
322        }
323        return new Id(finalName + ordinalDisplay + refDecl, 0);
324    }
325
326    // ----------------------------------------------------------------------
327    // ClaferIG.xmlToSolution
328    // ----------------------------------------------------------------------
329    /**
330     * The instance of a static model, or the trace of a dynamic model.
331     */
332    public static Solution toSolution(String xml, boolean dynamic, Naming naming) {
333        Element alloy = parse(xml);
334        List<Element> instances = children(alloy, "instance");
335        if (!dynamic) {
336            ClaferModel model = buildClaferModel(parseInstance(instances.get(0)));
337            Census census = new Census();
338            model.topLevel().forEach(c -> census(naming, c, census));
339            return new Solution.Instance(sugar(census, naming, model));
340        }
341        // the state to which its last state loops back: Alloy gives the length of the trace and of its loop
342        int loopState = 0;
343        if (!instances.isEmpty() && instances.get(0).hasAttribute("tracelength")
344                && instances.get(0).hasAttribute("looplength")) {
345            loopState = Integer.parseInt(instances.get(0).getAttribute("tracelength"))
346                    - Integer.parseInt(instances.get(0).getAttribute("looplength"));
347        }
348        List<ClaferModel> states = instances.stream().map(i -> buildStateModel(parseInstance(i))).toList();
349        Census census = statesCensus(naming, states);
350        return new Solution.Trace(states.stream().map(s -> sugar(census, naming, s)).toList(), loopState);
351    }
352}