001package org.clafer.scope;
002
003import java.math.BigDecimal;
004import java.util.ArrayList;
005import java.util.Comparator;
006import java.util.LinkedHashMap;
007import java.util.List;
008import java.util.Map;
009import java.util.stream.Collectors;
010import org.clafer.ast.AstClafer;
011import org.clafer.ast.AstConcreteClafer;
012import org.clafer.ast.AstModel;
013import org.clafer.ast.AstUtil;
014
015/**
016 * A {@code .cfr-scope} file: the scopes of a model, kept apart from the model.
017 * It is a JSON array of entries, each an object of one kind:
018 * <ul>
019 * <li>{@code {"lpqName": name, "scope": n}}: the scope of the clafers named
020 * {@code name}, a UID ({@code c0_Cfeatures}) or a (partially) qualified name
021 * ({@code Cfeatures}, {@code Component::Cfeatures},
022 * {@code ::Component::Cfeatures}) that names all the clafers whose containment
023 * paths end with it. The empty name is the root, whose scope is always 1. This
024 * is the entry {@code clafer --meta-data}, claferIG and the REPL write.</li>
025 * <li>{@code {"defaultScope": n}}: the scope of the clafers without their own.
026 * It also matters when every clafer has its own: the scope analysis of a
027 * recursive structure uses it.</li>
028 * <li>{@code {"int": [low, high]}}: the integers.</li>
029 * <li>{@code {"mul": [low, high]}}: the products of multiplications.</li>
030 * <li>{@code {"stringLength": n}}: the longest string.</li>
031 * <li>{@code {"chars": [low, high]}}: the characters of strings, as code
032 * points.</li>
033 * <li>{@code {"decimalDigits": n}}: the fractional digits of decimals.</li>
034 * <li>{@code {"decimal": [low, high]}}: the decimals, e.g.,
035 * {@code [-21474.83648, 21474.83647]}.</li>
036 * </ul>
037 * Anything not in the file keeps the scope it had.
038 */
039public final class ScopeFile {
040
041    private final String fileName;
042    // name -> scope, in the order of the file
043    private final List<Map.Entry<String, Integer>> claferScopes;
044    private final Map<String, Object> ranges;
045
046    private ScopeFile(String fileName, List<Map.Entry<String, Integer>> claferScopes, Map<String, Object> ranges) {
047        this.fileName = fileName;
048        this.claferScopes = claferScopes;
049        this.ranges = ranges;
050    }
051
052    /**
053     * Prints every scope of a model: the scope of every clafer by its UID,
054     * sorted, whether it was given or is the default, then the default scope
055     * and every range.
056     *
057     * @param model the model
058     * @param scope its scope
059     * @return the contents of the model's {@code .cfr-scope} file
060     */
061    public static String print(AstModel model, Scope scope) {
062        List<AstClafer> clafers = AstUtil.getClafers(model).stream()
063                .filter(c -> c != model.getAbstractRoot() && c != model.getRoot() && c != model.getTypeRoot())
064                .sorted(Comparator.comparing(AstClafer::getName))
065                .collect(Collectors.toList());
066        List<String> entries = new ArrayList<>();
067        for (AstClafer clafer : clafers) {
068            entries.add("{\"lpqName\": " + quote(clafer.getName()) + ", \"scope\": " + scope.getScope(clafer) + "}");
069        }
070        entries.add("{\"defaultScope\": " + scope.getDefaultScope() + "}");
071        entries.add("{\"int\": [" + scope.getIntLow() + ", " + scope.getIntHigh() + "]}");
072        entries.add("{\"mul\": [" + scope.getMulLow() + ", " + scope.getMulHigh() + "]}");
073        entries.add("{\"stringLength\": " + scope.getStringLength() + "}");
074        entries.add("{\"chars\": [" + (int) scope.getCharLow() + ", " + (int) scope.getCharHigh() + "]}");
075        entries.add("{\"decimalDigits\": " + scope.getDecimalScale() + "}");
076        entries.add("{\"decimal\": [" + scope.unscaleDecimal(scope.getDecimalLow()).toPlainString()
077                + ", " + scope.unscaleDecimal(scope.getDecimalHigh()).toPlainString() + "]}");
078        return "[\n" + String.join(",\n", entries) + "\n]\n";
079    }
080
081    /**
082     * Reads a scope file.
083     *
084     * @param json the contents
085     * @param fileName the file's name, for errors
086     * @return the scope file
087     * @throws IllegalArgumentException if the file is malformed
088     */
089    public static ScopeFile parse(String json, String fileName) {
090        Reader reader = new Reader(json, fileName);
091        List<Map.Entry<String, Integer>> claferScopes = new ArrayList<>();
092        Map<String, Object> ranges = new LinkedHashMap<>();
093        for (Map<String, Object> entry : reader.readFile()) {
094            if (entry.containsKey("lpqName")) {
095                if (!(entry.get("lpqName") instanceof String name)
096                        || !(entry.get("scope") instanceof BigDecimal scope) || entry.size() != 2) {
097                    throw reader.error("expected {\"lpqName\": name, \"scope\": n} but found " + entry);
098                }
099                claferScopes.add(Map.entry(name, reader.natural(scope)));
100            } else if (entry.size() == 1) {
101                Map.Entry<String, Object> range = entry.entrySet().iterator().next();
102                ranges.put(range.getKey(), reader.range(range.getKey(), range.getValue()));
103            } else {
104                throw reader.error("expected one range per entry but found " + entry);
105            }
106        }
107        return new ScopeFile(fileName, claferScopes, ranges);
108    }
109
110    /**
111     * @return whether the file gives the integers
112     */
113    public boolean hasIntRange() {
114        return ranges.containsKey("int");
115    }
116
117    /**
118     * Applies the file to a scope.
119     *
120     * @param scope the scope
121     * @param model the model, whose clafers the file names
122     * @return the scope with the file's scopes and ranges
123     * @throws IllegalArgumentException if a name is not of a clafer in the
124     * model
125     */
126    public Scope applyTo(Scope scope, AstModel model) {
127        List<AstClafer> clafers = new ArrayList<>(AstUtil.getClafers(model));
128        clafers.remove(model.getAbstractRoot());
129        clafers.remove(model.getRoot());
130        ScopeBuilder builder = scope.toBuilder();
131        for (Map.Entry<String, Integer> entry : claferScopes) {
132            // the REPL saves the root clafer #clafer# with an empty name
133            if (entry.getKey().isEmpty()) {
134                continue;
135            }
136            List<AstClafer> named = claferNamed(clafers, entry.getKey());
137            if (named.isEmpty()) {
138                throw new IllegalArgumentException(fileName + ": the model has no clafer " + entry.getKey());
139            }
140            for (AstClafer clafer : named) {
141                builder.setScope(clafer, entry.getValue());
142            }
143        }
144        for (Map.Entry<String, Object> range : ranges.entrySet()) {
145            Object value = range.getValue();
146            switch (range.getKey()) {
147                case "defaultScope" -> builder.defaultScope((Integer) value);
148                case "int" -> builder.intLow(((int[]) value)[0]).intHigh(((int[]) value)[1]);
149                case "mul" -> builder.mulLow(((int[]) value)[0]).mulHigh(((int[]) value)[1]);
150                case "stringLength" -> builder.stringLength((Integer) value);
151                case "chars" -> builder.charLow((char) ((int[]) value)[0]).charHigh((char) ((int[]) value)[1]);
152                case "decimalDigits" -> builder.decimalScale((Integer) value);
153                case "decimal" -> builder.decimalLow(((BigDecimal[]) value)[0]).decimalHigh(((BigDecimal[]) value)[1]);
154                default -> throw new IllegalStateException(range.getKey());
155            }
156        }
157        try {
158            return builder.toScope();
159        } catch (IllegalArgumentException e) {
160            throw new IllegalArgumentException(fileName + ": " + e.getMessage(), e);
161        }
162    }
163
164    /**
165     * The clafer with the given UID, otherwise the clafers with the given
166     * (partially) qualified name. A UID is the clafer's least-partially-qualified
167     * name, with {@code __} between the names, e.g., {@code size}, {@code x__size}
168     * or {@code root__size} (a top-level {@code size} when another one exists).
169     * A qualified name names the clafers whose paths of names end with it:
170     * {@code size} names every clafer named {@code size}, {@code x__size} every
171     * {@code size} in an {@code x}, and {@code root__x__size} only the one in a
172     * top-level {@code x}. The older form with {@code ::} is read too:
173     * {@code x::size} is {@code x__size}, and {@code ::x::size} is
174     * {@code root__x__size}. An apostrophe is {@code _prime}, as in the UIDs.
175     * <p>
176     * The names are matched from the end, a UID at a time: the clafer's UID
177     * ends with the names, e.g., {@code x__size} with {@code size}, or is the
178     * last names, e.g., {@code size} of {@code x__size}, and the names before
179     * them are its parent's, and so on.
180     *
181     * @param clafers the clafers to look in
182     * @param qName a UID or a (partially) qualified name
183     * @return the clafers it names
184     */
185    public static List<AstClafer> claferNamed(List<AstClafer> clafers, String qName) {
186        List<AstClafer> result = new ArrayList<>();
187        for (AstClafer clafer : clafers) {
188            if (clafer.getName().equals(qName)) {
189                result.add(clafer);
190            }
191        }
192        if (!result.isEmpty()) {
193            return result;
194        }
195        String name = (qName.startsWith("::") ? "root__" + qName.substring(2) : qName)
196                .replace("::", "__").replace("'", "_prime");
197        List<String> names = List.of(name.split("__", -1));
198        boolean fromRoot = names.size() > 1 && names.get(0).equals("root");
199        for (AstClafer clafer : clafers) {
200            if (endsWith(clafer, names, fromRoot)) {
201                result.add(clafer);
202            }
203        }
204        return result;
205    }
206
207    /**
208     * Whether the path of names of a clafer ends with the given names, or is
209     * them, from the root.
210     */
211    private static boolean endsWith(AstClafer clafer, List<String> names, boolean fromRoot) {
212        // the clafer and its ancestors, from the top level
213        List<AstClafer> chain = new ArrayList<>();
214        for (AstClafer c = clafer; c != null; c = parentOf(c)) {
215            chain.add(0, c);
216        }
217        return endsWith(chain, chain.size() - 1, names, fromRoot);
218    }
219
220    /**
221     * Whether the names end the path of the clafers up to chain[i]. A UID is
222     * the last names of a clafer's path, its own and its ancestors', e.g.,
223     * Device__Cfeatures, or root__size for a top-level size: it covers that
224     * many places, the root's at -1.
225     */
226    private static boolean endsWith(List<AstClafer> chain, int i, List<String> names, boolean fromRoot) {
227        String uid = chain.get(i).getName();
228        // the names end within the UID, e.g., size in x__size
229        if (!fromRoot && uid.endsWith("__" + String.join("__", names))) {
230            return true;
231        }
232        for (int k = 1; k <= names.size(); k++) {
233            if (String.join("__", names.subList(names.size() - k, names.size())).equals(uid)) {
234                List<String> rest = names.subList(0, names.size() - k);
235                int next = i - k;
236                if (rest.isEmpty() ? !fromRoot || next == -2
237                        : next == -1 ? fromRoot && rest.equals(List.of("root"))
238                        : next >= 0 && endsWith(chain, next, rest, fromRoot)) {
239                    return true;
240                }
241            }
242        }
243        return false;
244    }
245
246    /**
247     * The parent of a clafer in the model's text, or null for a top-level one:
248     * its parent is the model's root, or #root# or #clafer# for an abstract one;
249     * an abstract clafer can be nested, also under a concrete clafer.
250     */
251    private static AstClafer parentOf(AstClafer clafer) {
252        AstClafer parent = clafer.getParent();
253        return parent == null || parent.getName().startsWith("#")
254                || (parent instanceof AstConcreteClafer && !parent.hasParent()) ? null : parent;
255    }
256
257    private static String quote(String s) {
258        return "\"" + s.replace("\\", "\\\\").replace("\"", "\\\"") + "\"";
259    }
260
261    /**
262     * Reads the JSON of a scope file: an array of objects whose values are
263     * strings, numbers or arrays of numbers.
264     */
265    private static final class Reader {
266
267        private final String json;
268        private final String fileName;
269        private int pos = 0;
270
271        Reader(String json, String fileName) {
272            this.json = json;
273            this.fileName = fileName;
274        }
275
276        IllegalArgumentException error(String message) {
277            return new IllegalArgumentException(fileName + ": " + message);
278        }
279
280        List<Map<String, Object>> readFile() {
281            List<Map<String, Object>> entries = new ArrayList<>();
282            expect('[');
283            if (!consume(']')) {
284                do {
285                    entries.add(readObject());
286                } while (consume(','));
287                expect(']');
288            }
289            skipSpace();
290            if (pos < json.length()) {
291                throw error("unexpected text after the list at offset " + pos);
292            }
293            return entries;
294        }
295
296        private Map<String, Object> readObject() {
297            Map<String, Object> object = new LinkedHashMap<>();
298            expect('{');
299            if (!consume('}')) {
300                do {
301                    String key = readString();
302                    expect(':');
303                    if (object.put(key, readValue()) != null) {
304                        throw error("\"" + key + "\" twice in one entry");
305                    }
306                } while (consume(','));
307                expect('}');
308            }
309            return object;
310        }
311
312        private Object readValue() {
313            skipSpace();
314            if (pos < json.length() && json.charAt(pos) == '"') {
315                return readString();
316            }
317            if (consume('[')) {
318                List<BigDecimal> numbers = new ArrayList<>();
319                if (!consume(']')) {
320                    do {
321                        numbers.add(readNumber());
322                    } while (consume(','));
323                    expect(']');
324                }
325                return numbers;
326            }
327            return readNumber();
328        }
329
330        private String readString() {
331            expect('"');
332            StringBuilder out = new StringBuilder();
333            while (pos < json.length() && json.charAt(pos) != '"') {
334                char c = json.charAt(pos++);
335                if (c == '\\' && pos < json.length()) {
336                    char e = json.charAt(pos++);
337                    switch (e) {
338                        case 'n' -> out.append('\n');
339                        case 't' -> out.append('\t');
340                        case 'u' -> {
341                            if (pos + 4 > json.length()) {
342                                throw error("a bad escape at offset " + pos);
343                            }
344                            out.append((char) Integer.parseInt(json.substring(pos, pos + 4), 16));
345                            pos += 4;
346                        }
347                        default -> out.append(e);
348                    }
349                } else {
350                    out.append(c);
351                }
352            }
353            expect('"');
354            return out.toString();
355        }
356
357        private BigDecimal readNumber() {
358            skipSpace();
359            int start = pos;
360            while (pos < json.length() && "+-0123456789.eE".indexOf(json.charAt(pos)) >= 0) {
361                pos++;
362            }
363            try {
364                return new BigDecimal(json.substring(start, pos));
365            } catch (NumberFormatException e) {
366                throw error("expected a number at offset " + start);
367            }
368        }
369
370        int natural(BigDecimal n) {
371            try {
372                int value = n.intValueExact();
373                if (value >= 0) {
374                    return value;
375                }
376            } catch (ArithmeticException e) {
377                // below
378            }
379            throw error("expected a natural number but found " + n);
380        }
381
382        private int integer(BigDecimal n) {
383            try {
384                return n.intValueExact();
385            } catch (ArithmeticException e) {
386                throw error("expected an integer but found " + n);
387            }
388        }
389
390        Object range(String key, Object value) {
391            switch (key) {
392                case "int", "mul", "chars", "decimal" -> {
393                    if (!(value instanceof List<?> list) || list.size() != 2) {
394                        throw error("expected {\"" + key + "\": [low, high]} but found " + value);
395                    }
396                    BigDecimal low = (BigDecimal) list.get(0);
397                    BigDecimal high = (BigDecimal) list.get(1);
398                    if (low.compareTo(high) > 0) {
399                        throw error("the range " + key + " " + low + ".." + high + " is empty");
400                    }
401                    return key.equals("decimal")
402                            ? new BigDecimal[]{low, high}
403                            : new int[]{integer(low), integer(high)};
404                }
405                case "defaultScope", "stringLength", "decimalDigits" -> {
406                    if (!(value instanceof BigDecimal n)) {
407                        throw error("expected {\"" + key + "\": n} but found " + value);
408                    }
409                    return natural(n);
410                }
411                default -> throw error("unknown entry \"" + key + "\"");
412            }
413        }
414
415        private void skipSpace() {
416            while (pos < json.length() && Character.isWhitespace(json.charAt(pos))) {
417                pos++;
418            }
419        }
420
421        private boolean consume(char c) {
422            skipSpace();
423            if (pos < json.length() && json.charAt(pos) == c) {
424                pos++;
425                return true;
426            }
427            return false;
428        }
429
430        private void expect(char c) {
431            if (!consume(c)) {
432                throw error("expected '" + c + "' at offset " + pos
433                        + (pos < json.length() ? " but found '" + json.charAt(pos) + "'" : " but found the end"));
434            }
435        }
436    }
437}