001package org.clafer.frontend;
002
003import java.util.ArrayList;
004import java.util.LinkedHashSet;
005import java.util.List;
006import java.util.Optional;
007import java.util.OptionalInt;
008import java.util.OptionalLong;
009import java.util.Set;
010
011/**
012 * The options of a model file that the frontend uses, from its first line,
013 * {@code //# OPTIONS ...}, as the compiler reads them
014 * ({@code Import.fileOptions}): {@code --core}, {@code --tl},
015 * {@code --minint}, {@code --maxint}, {@code --decimal-digits},
016 * {@code --ss} and {@code --import}. An option is {@code --name=value} or
017 * {@code --name value}; the other options are kept by name only, the short
018 * name if it has one, e.g., {@code -c} for {@code --check-duplicates}, for
019 * the checks of the model and of {@link #combine}. As in the compiler,
020 * {@code --explicit} implies {@code -f}, {@code -l} and {@code --ss=none}.
021 *
022 * @param core {@code --core}
023 * @param traceLength {@code --tl}
024 * @param minInt {@code --minint}
025 * @param maxInt {@code --maxint}
026 * @param decimalDigits {@code --decimal-digits}
027 * @param simpleScopes {@code --ss=simple}, the default, rather than
028 * {@code --ss=none}
029 * @param imports the files of {@code --import}, as written
030 * @param others the names of the other options given, e.g., {@code -k}
031 */
032public record ModelOptions(boolean core, OptionalInt traceLength, OptionalLong minInt, OptionalLong maxInt,
033        Optional<Integer> decimalDigits, boolean simpleScopes, List<String> imports, Set<String> others) {
034
035    /**
036     * The options of a model without a {@code //# OPTIONS} line.
037     */
038    public static final ModelOptions Defaults = new ModelOptions(false, OptionalInt.empty(), OptionalLong.empty(),
039            OptionalLong.empty(), Optional.empty(), true, List.of(), Set.of());
040
041    private static final String Prefix = "//# OPTIONS ";
042
043    /**
044     * @param text the text of a model file
045     * @return the options of its first line
046     */
047    public static ModelOptions of(String text) {
048        if (!text.startsWith(Prefix)) {
049            return Defaults;
050        }
051        int end = text.indexOf('\n');
052        String line = (end < 0 ? text : text.substring(0, end)).substring(Prefix.length()).replace("\r", "");
053        List<String> args = splitArgs(line);
054        boolean core = false;
055        OptionalInt tl = OptionalInt.empty();
056        OptionalLong minInt = OptionalLong.empty();
057        OptionalLong maxInt = OptionalLong.empty();
058        Optional<Integer> digits = Optional.empty();
059        boolean simple = true;
060        List<String> imports = new ArrayList<>();
061        Set<String> others = new LinkedHashSet<>();
062        for (int i = 0; i < args.size(); i++) {
063            String arg = args.get(i);
064            String name = arg;
065            String value = null;
066            int eq = arg.indexOf('=');
067            if (arg.startsWith("--") && eq > 0) {
068                name = arg.substring(0, eq);
069                value = arg.substring(eq + 1);
070            }
071            boolean takesValue = Set.of("--tl", "--minint", "--maxint", "--decimal-digits", "--ss", "--import")
072                    .contains(name);
073            if (takesValue && value == null && i + 1 < args.size()) {
074                value = args.get(++i);
075            }
076            try {
077                switch (name) {
078                    case "--core" -> core = true;
079                    case "--tl" -> tl = OptionalInt.of(Integer.parseInt(value));
080                    case "--minint" -> minInt = OptionalLong.of(Long.parseLong(value));
081                    case "--maxint" -> maxInt = OptionalLong.of(Long.parseLong(value));
082                    case "--decimal-digits" -> digits = Optional.of(Integer.parseInt(value));
083                    case "--ss" -> simple = !"none".equalsIgnoreCase(value);
084                    case "--import" -> imports.add(value);
085                    default -> others.add(Aliases.getOrDefault(name, name));
086                }
087            } catch (NumberFormatException | NullPointerException e) {
088                others.add(name);
089            }
090        }
091        if (others.contains("--explicit")) {
092            // the names are the UIDs, there is no layout and no scope analysis (ClaferArgs.withExplicit)
093            others.add("-f");
094            others.add("-l");
095            simple = false;
096        }
097        return new ModelOptions(core, tl, minInt, maxInt, digits, simple, List.copyOf(imports), Set.copyOf(others));
098    }
099
100    /**
101     * The options that the frontend reads by their short names.
102     */
103    private static final java.util.Map<String, String> Aliases = java.util.Map.of("--check-duplicates", "-c",
104            "--skip-resolver", "-f", "--no-layout", "-l", "--new-layout", "--nl", "--afm", "--check-afm");
105
106    /**
107     * @return {@code --explicit}: the model is an explicit model, whose
108     * names are the UIDs, without layout and without scope analysis
109     */
110    public boolean explicit() {
111        return others.contains("--explicit");
112    }
113
114    /**
115     * @return {@code -f}, also of {@code --explicit}: the names are the
116     * UIDs
117     */
118    public boolean skipResolver() {
119        return others.contains("-f");
120    }
121
122    /**
123     * @return {@code --check-duplicates}: no two clafers have the same name
124     */
125    public boolean checkDuplicates() {
126        return others.contains("-c");
127    }
128
129    /**
130     * @return {@code --check-afm}: no concrete clafer has more than one
131     * instance
132     */
133    public boolean checkAfm() {
134        return others.contains("--check-afm");
135    }
136
137    /**
138     * The arguments of the line, split at spaces outside double quotes
139     * ({@code SplitJoin.splitArgs}).
140     */
141    static List<String> splitArgs(String line) {
142        List<String> out = new ArrayList<>();
143        StringBuilder current = new StringBuilder();
144        boolean quoted = false;
145        boolean any = false;
146        for (int i = 0; i < line.length(); i++) {
147            char ch = line.charAt(i);
148            if (ch == '"') {
149                quoted = !quoted;
150                any = true;
151            } else if (ch == '\\' && i + 1 < line.length() && line.charAt(i + 1) == '"') {
152                current.append('"');
153                i++;
154            } else if (Character.isWhitespace(ch) && !quoted) {
155                if (any || current.length() > 0) {
156                    out.add(current.toString());
157                }
158                current.setLength(0);
159                any = false;
160            } else {
161                current.append(ch);
162            }
163        }
164        if (any || current.length() > 0) {
165            out.add(current.toString());
166        }
167        return out;
168    }
169
170    /**
171     * The options that only the command line can give.
172     */
173    private static final List<String> CommandLineOptions = List.of("-v", "--tooldir", "--import-root",
174            "--public-imports", "--import-base");
175
176    /**
177     * The options of the compilation, which only the compiled model can give.
178     */
179    private static final List<String> RunOptions = List.of("-o", "-s", "-a", "--self-contained", "--add-graph",
180            "--sr", "--add-comments", "--meta-data", "--ecore2clafer");
181
182    /**
183     * Combines the options of the imported files and of the model as the
184     * compiler does ({@code Import.combineOptions}): the largest
185     * {@code --maxint}, {@code --decimal-digits} and {@code --tl} (10 for a
186     * file without it), the smallest {@code --minint}, all the imports, and
187     * {@code --ss} the same in all files.
188     *
189     * @param imported the paths and options of the imported files, in order
190     * @param root the path of the model
191     * @param rootOptions its options
192     * @param errors the compiler's errors of the options
193     * @return the options of the whole model
194     */
195    static ModelOptions combine(List<String> importedPaths, List<ModelOptions> imported, String root,
196            ModelOptions rootOptions, List<String> errors) {
197        List<String> paths = new ArrayList<>();
198        List<ModelOptions> all = new ArrayList<>();
199        paths.add(root);
200        all.add(rootOptions);
201        paths.addAll(importedPaths);
202        all.addAll(imported);
203        for (int i = 0; i < all.size(); i++) {
204            List<String> names = CommandLineOptions.stream().filter(all.get(i).others()::contains).toList();
205            if (!names.isEmpty()) {
206                errors.add(inFile(paths.get(i), theOptions(names) + " can only be given on the command line, not in"
207                        + " //# OPTIONS"));
208                return rootOptions;
209            }
210        }
211        for (int i = 0; i < imported.size(); i++) {
212            List<String> names = RunOptions.stream().filter(imported.get(i).others()::contains).toList();
213            if (!names.isEmpty()) {
214                errors.add(inFile(importedPaths.get(i), theOptions(names) + " can only be given in the compiled model"
215                        + " or on the command line, not in an imported file"));
216                return rootOptions;
217            }
218        }
219        for (String option : List.of("-l", "--nl")) {
220            List<String> differ = new ArrayList<>();
221            for (int i = 0; i < imported.size(); i++) {
222                if (imported.get(i).others().contains(option) != rootOptions.others().contains(option)) {
223                    differ.add(importedPaths.get(i));
224                }
225            }
226            if (!differ.isEmpty()) {
227                errors.add(differs(option, differ, root));
228                return rootOptions;
229            }
230        }
231        List<String> differ = new ArrayList<>();
232        for (int i = 0; i < imported.size(); i++) {
233            if (imported.get(i).simpleScopes() != rootOptions.simpleScopes()) {
234                differ.add(importedPaths.get(i));
235            }
236        }
237        if (!differ.isEmpty()) {
238            errors.add(differs("--ss", differ, root));
239            return rootOptions;
240        }
241        if (imported.isEmpty()) {
242            return rootOptions;
243        }
244        OptionalInt tl = OptionalInt.of(all.stream().mapToInt(o -> o.traceLength().orElse(10)).max().getAsInt());
245        OptionalLong maxInt = all.stream().filter(o -> o.maxInt().isPresent()).mapToLong(o -> o.maxInt().getAsLong())
246                .max();
247        OptionalLong minInt = all.stream().filter(o -> o.minInt().isPresent()).mapToLong(o -> o.minInt().getAsLong())
248                .min();
249        Optional<Integer> digits = all.stream().flatMap(o -> o.decimalDigits().stream()).max(Integer::compare);
250        LinkedHashSet<String> imports = new LinkedHashSet<>();
251        Set<String> others = new LinkedHashSet<>();
252        for (ModelOptions o : all) {
253            imports.addAll(o.imports());
254            others.addAll(o.others());
255        }
256        // the model is explicit if its file is, and the names are the UIDs if they are in all files
257        if (!rootOptions.explicit()) {
258            others.remove("--explicit");
259        }
260        if (!all.stream().allMatch(ModelOptions::skipResolver)) {
261            others.remove("-f");
262        }
263        return new ModelOptions(rootOptions.core(), tl, minInt, maxInt, digits, rootOptions.simpleScopes(),
264                List.copyOf(imports), Set.copyOf(others));
265    }
266
267    private static String differs(String option, List<String> paths, String root) {
268        return "The option " + option + " must be the same in all files of the model: it differs in "
269                + String.join(", ", paths) + " from " + root;
270    }
271
272    private static String theOptions(List<String> names) {
273        return names.size() == 1 ? "the option " + names.get(0) : "the options " + String.join(", ", names);
274    }
275
276    static String inFile(String path, String message) {
277        return (path.isEmpty() ? "" : path + ": ") + message;
278    }
279}