001package org.clafer.frontend;
002
003import java.io.IOException;
004import java.io.InputStream;
005import java.io.PrintStream;
006import java.nio.charset.StandardCharsets;
007import java.nio.file.Files;
008import java.nio.file.Path;
009import java.util.ArrayList;
010import java.util.HashMap;
011import java.util.HashSet;
012import java.util.LinkedHashSet;
013import java.util.List;
014import java.util.Map;
015import java.util.Optional;
016import java.util.OptionalInt;
017import java.util.OptionalLong;
018import java.util.Set;
019import java.util.TreeMap;
020import java.util.function.Function;
021import org.clafer.alloy.AlloyGenerator;
022
023/**
024 * {@code claferc}: the Clafer compiler's {@code clafer -m clafer} and
025 * {@code clafer -m alloy} in Java. With {@code -m alloy}, the default, it
026 * prints the Alloy 6 model ({@code P.als}) of the port of the compiler's
027 * temporal generator ({@link AlloyGenerator}), for static and temporal models
028 * alike. With {@code -m clafer} it
029 * prints the rich explicit model ({@code P.des.cfr}) or, with {@code --core},
030 * the explicit core model ({@code P.core.cfr}, with {@code --record-provenance}
031 * its provenance comments), and with {@code --meta-data} the explicit model's
032 * scope file and the map of names ({@code P.cfr-map}), with the compiler's
033 * file names, statistics and errors.
034 * <p>
035 * Everything else is forwarded to {@code clafer} on the path, with the same
036 * arguments: a model that the Alloy generator does not translate (e.g., with a
037 * decimal or an {@code [alloy| |]} escape), the other modes ({@code -m choco},
038 * {@code json}, {@code html}, {@code graph}, {@code cvlgraph}), the options
039 * that the Java side does not implement (e.g., {@code -i}, {@code -v},
040 * {@code -c}, {@code --check-afm}, {@code -l}), and any argument that it
041 * does not read, so that
042 * the compiler gives its own message for it. The executable is
043 * {@link ClaferExecutable#find()}: {@code -Dclafer.executable}, or {@code clafer} next to
044 * {@code claferc.jar}, or on the {@code PATH}.
045 */
046public final class ClaferCommand {
047
048    private final InputStream in;
049    private final PrintStream out;
050    private final String executable;
051
052    /**
053     * @param in the standard input, which holds the model if no file is given
054     * @param out the standard output
055     * @param executable the compiler that the other modes are forwarded to
056     */
057    public ClaferCommand(InputStream in, PrintStream out, String executable) {
058        this.in = in;
059        this.out = out;
060        this.executable = executable;
061    }
062
063    public static void main(String[] args) {
064        PrintStream out = new PrintStream(new java.io.FileOutputStream(java.io.FileDescriptor.out), false,
065                StandardCharsets.UTF_8);
066        int code = new ClaferCommand(System.in, out, ClaferExecutable.find())
067                .run(List.of(args));
068        out.flush();
069        System.exit(code);
070    }
071
072    // ------------------------------------------------------------------
073    // The arguments, as the compiler's cmdargs reads them
074    // ------------------------------------------------------------------
075
076    /**
077     * The arguments of a command line or of an {@code //# OPTIONS} line, as
078     * far as the Java side reads them.
079     *
080     * @param forward why the arguments are forwarded to the compiler, if
081     * they are
082     */
083    record Args(List<String> modes, boolean console, boolean skipResolver, boolean explicit, boolean core,
084            boolean provenance, boolean noStats, boolean metaData, boolean noLayout, boolean checks,
085            OptionalInt traceLength, Optional<Boolean> simpleScopes, OptionalLong minInt, OptionalLong maxInt,
086            Optional<Integer> decimalDigits, List<String> imports, List<String> files, boolean help,
087            boolean version, List<String> importRoots, boolean publicImports, Optional<String> importBase,
088            Optional<String> forward) {
089    }
090
091    /**
092     * The flags without a value that the Java side reads, by their long and
093     * short names.
094     */
095    private static final Map<String, String> Flags = Map.ofEntries(
096            Map.entry("--console-output", "o"), Map.entry("-o", "o"),
097            Map.entry("--skip-resolver", "f"), Map.entry("-f", "f"),
098            Map.entry("--explicit", "explicit"), Map.entry("--core", "core"),
099            Map.entry("--record-provenance", "provenance"),
100            Map.entry("--keep-unused", "k"), Map.entry("-k", "k"),
101            Map.entry("--no-stats", "s"), Map.entry("-s", "s"),
102            Map.entry("--meta-data", "meta"), Map.entry("--public-imports", "public"),
103            Map.entry("--no-layout", "l"), Map.entry("-l", "l"),
104            Map.entry("--check-duplicates", "c"), Map.entry("-c", "c"),
105            Map.entry("--check-afm", "afm"), Map.entry("--afm", "afm"),
106            Map.entry("--help", "help"), Map.entry("-?", "help"),
107            Map.entry("--version", "version"), Map.entry("-V", "version"));
108
109    /**
110     * The options with a value that the Java side reads.
111     */
112    private static final Map<String, String> Valued = Map.ofEntries(
113            Map.entry("--mode", "m"), Map.entry("-m", "m"),
114            Map.entry("--tl", "tl"), Map.entry("--trace-len", "tl"),
115            Map.entry("--ss", "ss"), Map.entry("--scope-strategy", "ss"),
116            Map.entry("--minint", "minint"), Map.entry("--maxint", "maxint"),
117            Map.entry("--decimal-digits", "digits"), Map.entry("--import", "import"),
118            Map.entry("--import-root", "root"), Map.entry("--import-base", "base"),
119            Map.entry("--timeout-analysis", "timeout"));
120
121    /**
122     * Reads the arguments. An argument that the Java side does not read
123     * sets {@link Args#forward}.
124     *
125     * @param inFile whether they are the options of a model file, where
126     * {@code -c} and {@code --check-afm} are read, as the frontend checks them
127     */
128    static Args parse(List<String> args, boolean inFile) {
129        List<String> modes = new ArrayList<>();
130        Set<String> flags = new HashSet<>();
131        OptionalInt tl = OptionalInt.empty();
132        Optional<Boolean> simple = Optional.empty();
133        OptionalLong minInt = OptionalLong.empty();
134        OptionalLong maxInt = OptionalLong.empty();
135        Optional<Integer> digits = Optional.empty();
136        List<String> imports = new ArrayList<>();
137        List<String> files = new ArrayList<>();
138        List<String> roots = new ArrayList<>();
139        Optional<String> base = Optional.empty();
140        Optional<String> forward = Optional.empty();
141        boolean onlyFiles = false;
142        for (int i = 0; i < args.size() && forward.isEmpty(); i++) {
143            String arg = args.get(i);
144            if (onlyFiles || !arg.startsWith("-") || arg.equals("-")) {
145                files.add(arg);
146                continue;
147            }
148            if (arg.equals("--")) {
149                onlyFiles = true;
150                continue;
151            }
152            // the flags and options, with their values
153            List<String[]> given = new ArrayList<>();
154            if (arg.startsWith("--")) {
155                int eq = arg.indexOf('=');
156                String name = eq < 0 ? arg : arg.substring(0, eq);
157                if (Flags.containsKey(name) && eq < 0) {
158                    given.add(new String[]{Flags.get(name), null});
159                } else if (Valued.containsKey(name)) {
160                    String value = eq >= 0 ? arg.substring(eq + 1) : i + 1 < args.size() ? args.get(++i) : null;
161                    given.add(new String[]{Valued.get(name), value});
162                } else {
163                    forward = Optional.of("the option " + arg);
164                }
165            } else {
166                // short flags, which may be grouped (-so), and -mclafer or -m clafer
167                for (int j = 1; j < arg.length() && forward.isEmpty(); j++) {
168                    String name = "-" + arg.charAt(j);
169                    if (Valued.containsKey(name)) {
170                        String rest = arg.substring(j + 1);
171                        if (rest.startsWith("=")) {
172                            rest = rest.substring(1);
173                        }
174                        String value = !rest.isEmpty() ? rest : i + 1 < args.size() ? args.get(++i) : null;
175                        given.add(new String[]{Valued.get(name), value});
176                        break;
177                    } else if (Flags.containsKey(name)) {
178                        given.add(new String[]{Flags.get(name), null});
179                    } else {
180                        forward = Optional.of("the option " + arg);
181                    }
182                }
183            }
184            for (String[] g : given) {
185                if (forward.isPresent()) {
186                    break;
187                }
188                String key = g[0];
189                String value = g[1];
190                if (Valued.containsValue(key) && value == null) {
191                    forward = Optional.of("the option " + arg + " without a value");
192                    break;
193                }
194                try {
195                    switch (key) {
196                        case "m" -> {
197                            if (!modes.contains(value)) {
198                                modes.add(value);
199                            }
200                        }
201                        case "tl" -> tl = OptionalInt.of(Integer.parseInt(value));
202                        case "ss" -> {
203                            if (value.equals("none") || value.equals("simple")) {
204                                simple = Optional.of(value.equals("simple"));
205                            } else {
206                                forward = Optional.of("the scope strategy " + value);
207                            }
208                        }
209                        case "minint" -> minInt = OptionalLong.of(Long.parseLong(value));
210                        case "maxint" -> maxInt = OptionalLong.of(Long.parseLong(value));
211                        case "digits" -> digits = Optional.of(Integer.parseInt(value));
212                        case "import" -> {
213                            if (!imports.contains(value)) {
214                                imports.add(value);
215                            }
216                        }
217                        case "timeout" -> Integer.parseInt(value);
218                        case "root" -> roots.add(value);
219                        case "base" -> base = Optional.of(value);
220                        case "c", "afm" -> {
221                            if (inFile) {
222                                flags.add(key);
223                            } else {
224                                forward = Optional.of("the option " + arg);
225                            }
226                        }
227                        default -> flags.add(key);
228                    }
229                } catch (NumberFormatException e) {
230                    forward = Optional.of("the option " + arg + " with the value " + value);
231                }
232            }
233        }
234        if (forward.isEmpty() && files.size() > 1) {
235            forward = Optional.of("several model files");
236        }
237        return new Args(List.copyOf(modes), flags.contains("o"), flags.contains("f"), flags.contains("explicit"),
238                flags.contains("core"), flags.contains("provenance"), flags.contains("s"), flags.contains("meta"),
239                flags.contains("l"), flags.contains("c") || flags.contains("afm"), tl, simple, minInt, maxInt,
240                digits, List.copyOf(imports), List.copyOf(files), flags.contains("help"), flags.contains("version"),
241                List.copyOf(roots), flags.contains("public"), base, forward);
242    }
243
244    /**
245     * @return the arguments of the {@code //# OPTIONS} line of a model file
246     */
247    static Args fileArgs(String text) {
248        String prefix = "//# OPTIONS ";
249        if (!text.startsWith(prefix)) {
250            return parse(List.of(), true);
251        }
252        int end = text.indexOf('\n');
253        String line = (end < 0 ? text : text.substring(0, end)).substring(prefix.length()).replace("\r", "");
254        return parse(ModelOptions.splitArgs(line), true);
255    }
256
257    // ------------------------------------------------------------------
258    // The run
259    // ------------------------------------------------------------------
260
261    /**
262     * Runs the command.
263     *
264     * @return the exit code
265     */
266    public int run(List<String> args) {
267        Args cli = parse(args, false);
268        if (cli.forward().isPresent()) {
269            return forward(args, cli.forward().get());
270        }
271        if (cli.help()) {
272            out.print(Help);
273            return 0;
274        }
275        if (cli.version()) {
276            out.println(version());
277            return 0;
278        }
279        if (!cli.modes().isEmpty() && !isOwnMode(cli.modes())) {
280            return forward(args, "the mode " + String.join(", ", cli.modes()));
281        }
282        String file = cli.files().isEmpty() ? "" : cli.files().get(0);
283        String name = file.isEmpty() ? ModelFiles.Stdin : file;
284        Optional<String> stdin = Optional.empty();
285        if (file.isEmpty()) {
286            try {
287                stdin = Optional.of(new String(in.readAllBytes(), StandardCharsets.UTF_8));
288            } catch (IOException e) {
289                return error("cannot read the standard input: " + e.getMessage());
290            }
291        }
292        Optional<String> stdinText = stdin;
293        ModelFiles files = ModelFiles.read(name, cli.imports(),
294                p -> file.isEmpty() && p.equals(name) ? stdinText : Optional.empty(),
295                new ModelFiles.ImportOptions(cli.importRoots(), cli.publicImports(), cli.importBase(), true));
296        if (!files.errors().isEmpty()) {
297            return error(files.errors().get(0));
298        }
299        // the options of the files, which the command line's override
300        List<String> modes = new ArrayList<>(cli.modes());
301        boolean console = cli.console() || file.isEmpty();
302        boolean core = cli.core();
303        boolean provenance = cli.provenance();
304        boolean noStats = cli.noStats();
305        boolean metaData = cli.metaData();
306        boolean explicit = cli.explicit();
307        boolean noLayout = cli.noLayout();
308        ModelFiles.ModelFile root = files.files().get(files.files().size() - 1);
309        List<String> fileModes = new ArrayList<>();
310        for (ModelFiles.ModelFile f : files.files()) {
311            Args a = fileArgs(f.text());
312            if (a.forward().isPresent()) {
313                return forward(args, a.forward().get() + " in " + f.path());
314            }
315            if (!a.files().isEmpty() || a.help() || a.version()) {
316                return forward(args, "the options of " + f.path());
317            }
318            a.modes().stream().filter(m -> !fileModes.contains(m)).forEach(fileModes::add);
319            noLayout |= a.noLayout() && !a.explicit();
320            if (f == root) {
321                console |= a.console();
322                core |= a.core();
323                provenance |= a.provenance();
324                noStats |= a.noStats();
325                metaData |= a.metaData();
326            }
327        }
328        if (modes.isEmpty()) {
329            modes = fileModes.isEmpty() ? List.of("alloy") : fileModes;
330        }
331        if (!isOwnMode(modes)) {
332            return forward(args, "the mode " + String.join(", ", modes));
333        }
334        boolean alloy = modes.equals(List.of("alloy"));
335        if (alloy && ClaferLexer.lex(files.text()).others().stream()
336                .anyMatch(t -> t.kind() == TokenKind.ESCAPE && t.text().startsWith("[alloy|"))) {
337            return forward(args, "an [alloy| |] escape");
338        }
339        if (alloy && metaData) {
340            return forward(args, "--meta-data with -m alloy");
341        }
342        if (noLayout && !explicit) {
343            return forward(args, "-l");
344        }
345        ModelOptions o = files.options();
346        Set<String> others = new LinkedHashSet<>(o.others());
347        boolean simple = o.simpleScopes();
348        if (cli.simpleScopes().isPresent() && !cli.simpleScopes().get()) {
349            simple = false;
350        }
351        if (cli.skipResolver()) {
352            others.add("-f");
353        }
354        if (explicit) {
355            others.add("--explicit");
356            others.add("-f");
357            others.add("-l");
358            simple = false;
359        }
360        OptionalInt tl = cli.traceLength().isPresent() && cli.traceLength().getAsInt() != 10
361                ? cli.traceLength() : o.traceLength();
362        ModelOptions options = new ModelOptions(core || o.core(), tl,
363                cli.minInt().isPresent() ? cli.minInt() : o.minInt(),
364                cli.maxInt().isPresent() ? cli.maxInt() : o.maxInt(),
365                cli.decimalDigits().isPresent() ? cli.decimalDigits() : o.decimalDigits(),
366                simple, o.imports(), Set.copyOf(others));
367        files = new ModelFiles(files.files(), options, files.errors());
368        ToIr.Result result = ToIr.toIr(files);
369        if (!result.errors().isEmpty()) {
370            // a ClaferErr of the compiler, after a blank line, unlike the errors of reading the files
371            return error("\n" + result.errors().get(0));
372        }
373        if (!result.diagnostics().isEmpty()) {
374            Diagnostic d = result.diagnostics().get(0);
375            boolean parse = !ClaferParser.parse(files.text()).diagnostics().isEmpty();
376            ModelFiles.Position p = files.position(d.span().line());
377            String at = p.path() + ":" + p.line() + ":" + d.span().column();
378            out.print("\n" + (parse ? "Parse failed at " : "Compile error at ") + at + "...\n");
379            out.print(d.message() + "\n");
380            return 1;
381        }
382        Ir.Model model = result.model();
383        if (alloy) {
384            return alloy(args, result, files, options, console, noStats, file);
385        }
386        ModelFiles theFiles = files;
387        String code;
388        if (options.core()) {
389            Function<SourceSpan, Ir.Position> position = span -> {
390                ModelFiles.Position p = theFiles.position(span.line());
391                return new Ir.Position(Path.of(p.path()).getFileName().toString(), p.line(), span.column());
392            };
393            Ir.Model lowered = ToCore.toCore(model, position, clocklessValues(files.text()));
394            code = ExplicitPrinter.print(lowered, provenance);
395        } else {
396            code = ExplicitPrinter.print(model, false);
397        }
398        if (!noStats) {
399            Syntax.Model source = ClaferParser.parse(files.text()).model();
400            out.print(Statistics.of(result) + Warnings.of(result, source, options.skipResolver()) + "\n");
401        }
402        String base = dropExtension(file.isEmpty() ? "" : ModelFiles.localName(file));
403        String extension = options.core() ? "core.cfr" : "des.cfr";
404        try {
405            if (console) {
406                out.print(code + "\n");
407            } else {
408                write(base + "." + extension, code);
409            }
410            if (metaData) {
411                write(base + ".cfr-map", nameMap(result.names()));
412                write(base + "." + extension + "-scope", result.scopes().orElseThrow().scopeFile());
413            }
414        } catch (IOException e) {
415            return error(e.getMessage());
416        }
417        out.flush();
418        return 0;
419    }
420
421    private static boolean isOwnMode(List<String> modes) {
422        return modes.equals(List.of("clafer")) || modes.equals(List.of("alloy"));
423    }
424
425    /**
426     * {@code -m alloy}: the Alloy 6 code of the port of the compiler's
427     * {@code AlloyLtl.hs}, for every model, static or temporal, with the
428     * statistics as a comment; a model with a construct that the port does
429     * not translate is forwarded to {@code clafer}.
430     */
431    private int alloy(List<String> args, ToIr.Result result, ModelFiles files, ModelOptions options,
432            boolean console, boolean noStats, String file) {
433        boolean keepUnused = options.others().contains("-k") || options.others().contains("--keep-unused")
434                || args.contains("-k") || args.contains("--keep-unused");
435        String code;
436        try {
437            code = AlloyGenerator.generate(result.model(), result.scopes().orElseThrow().clafers(),
438                    options.traceLength().orElse(10), keepUnused, false);
439        } catch (AlloyGenerator.UnsupportedModel e) {
440            return forward(args, e.getMessage() + ", which the Alloy generator does not translate");
441        }
442        String stats = "";
443        if (!noStats) {
444            Syntax.Model source = ClaferParser.parse(files.text()).model();
445            stats = Statistics.of(result) + largeScopes(result, files)
446                    + Warnings.of(result, source, options.skipResolver());
447            out.print(stats + "\n");
448            code = "/*\n" + stats + "*/\n" + code;
449        }
450        String base = dropExtension(file.isEmpty() ? "" : ModelFiles.localName(file));
451        try {
452            if (console) {
453                out.print(code + "\n");
454            } else {
455                write(base + ".als", code);
456            }
457        } catch (IOException e) {
458            return error(e.getMessage());
459        }
460        out.flush();
461        return 0;
462    }
463
464    /**
465     * The warnings of the compiler about the large scopes of references in
466     * the Alloy output ({@code showLargeScopes} of
467     * {@code largeReferenceScopes}): a reference with an unbounded
468     * multiplicity to a clafer, whose scope is above 100.
469     */
470    static String largeScopes(ToIr.Result result, ModelFiles files) {
471        Map<String, Long> scopes = result.scopes().orElseThrow().clafers();
472        Map<String, String> names = new HashMap<>();
473        for (Symbols.ClaferSymbol c : result.names().clafers()) {
474            names.put(c.uid(), c.name());
475        }
476        StringBuilder out = new StringBuilder();
477        largeScopes(result.model().elements(), scopes, names, files, out);
478        return out.toString();
479    }
480
481    private static void largeScopes(List<Ir.Element> elements, Map<String, Long> scopes, Map<String, String> names,
482            ModelFiles files, StringBuilder out) {
483        for (Ir.Element e : elements) {
484            if (!(e instanceof Ir.ClaferDecl c)) {
485                continue;
486            }
487            String uid = c.name().text();
488            long scope = scopes.getOrDefault(uid, 1L);
489            if (c.card().isUnbounded() && c.ref().isPresent() && names.containsKey(c.ref().get().target().text())
490                    && scope > 100) {
491                String target = c.ref().get().target().text();
492                String name = names.getOrDefault(uid, uid);
493                String refText = name + " -> " + names.get(target);
494                ModelFiles.Position p = files.position(c.span().line());
495                out.append("Warning: ").append(p.path()).append(':').append(p.line()).append(':')
496                        .append(c.span().column()).append(": the scope of ").append(refText).append(' ')
497                        .append(c.card()).append(" is ").append(scope).append(", since ").append(name)
498                        .append(" may point to all ").append(scopes.getOrDefault(target, 1L)).append(' ')
499                        .append(names.get(target)).append(" in each of its parents. If fewer suffice, give it an")
500                        .append(" upper bound, e.g., ").append(refText).append(' ').append(c.card().low())
501                        .append("..10, to make the instance generation faster.\n");
502            }
503            largeScopes(c.elements(), scopes, names, files, out);
504        }
505    }
506
507    private static void write(String path, String text) throws IOException {
508        Files.writeString(Path.of(path), text, StandardCharsets.UTF_8);
509    }
510
511    private int error(String message) {
512        out.print("\nError...\n" + message + "\n");
513        out.flush();
514        return 1;
515    }
516
517    /**
518     * {@code System.FilePath.dropExtension}: the path without the extension
519     * of its file name.
520     */
521    static String dropExtension(String path) {
522        int slash = path.lastIndexOf('/');
523        int dot = path.lastIndexOf('.');
524        return dot > slash ? path.substring(0, dot) : path;
525    }
526
527    /**
528     * The spans of the values of the {@code :=} written without a clock.
529     */
530    private static Set<SourceSpan> clocklessValues(String text) {
531        Set<SourceSpan> spans = new HashSet<>();
532        ClaferParser.Result parsed = ClaferParser.parse(text);
533        for (Syntax.Declaration d : parsed.model().declarations()) {
534            if (d instanceof Syntax.Element e) {
535                clocklessValues(e, spans);
536            }
537        }
538        return spans;
539    }
540
541    private static void clocklessValues(Syntax.Element e, Set<SourceSpan> spans) {
542        Optional<Syntax.Elements> elements = Optional.empty();
543        if (e instanceof Syntax.Clafer c) {
544            c.init().filter(i -> i.how() == Syntax.InitHow.Default).ifPresent(i -> spans.add(i.exp().span()));
545            elements = c.elements();
546        } else if (e instanceof Syntax.ClaferUse u) {
547            elements = u.elements();
548        }
549        elements.ifPresent(es -> es.elements().forEach(x -> clocklessValues(x, spans)));
550    }
551
552    /**
553     * The map of names, {@code P.cfr-map}, as {@code generateJSONnameUIDMap}
554     * writes it: each clafer's fully qualified name, its least-partially
555     * qualified name and its UID, sorted by the first.
556     */
557    static String nameMap(Names names) {
558        TreeMap<String, String> byFqName = new TreeMap<>();
559        for (Symbols.ClaferSymbol c : names.clafers()) {
560            StringBuilder fq = new StringBuilder(c.name());
561            for (Optional<Symbols.ClaferSymbol> p = c.parent(); p.isPresent(); p = p.get().parent()) {
562                fq.insert(0, p.get().name() + "__");
563            }
564            byFqName.put("root__" + fq, c.uid());
565        }
566        StringBuilder sb = new StringBuilder("[");
567        boolean first = true;
568        for (Map.Entry<String, String> e : byFqName.entrySet()) {
569            sb.append(first ? "" : ",");
570            first = false;
571            sb.append("{\"fqName\":").append(json(e.getKey())).append(",\"lpqName\":").append(json(e.getValue()))
572                    .append(",\"uid\":").append(json(e.getValue())).append('}');
573        }
574        sb.append(']');
575        // prettyPrintJSON: a newline after [, { and , and before ] and }
576        StringBuilder pretty = new StringBuilder();
577        for (char ch : sb.toString().toCharArray()) {
578            switch (ch) {
579                case '[', '{', ',' -> pretty.append(ch).append('\n');
580                case ']', '}' -> pretty.append('\n').append(ch);
581                default -> pretty.append(ch);
582            }
583        }
584        return pretty.toString();
585    }
586
587    private static String json(String s) {
588        StringBuilder sb = new StringBuilder("\"");
589        for (char ch : s.toCharArray()) {
590            switch (ch) {
591                case '"' -> sb.append("\\\"");
592                case '\\' -> sb.append("\\\\");
593                default -> sb.append(ch);
594            }
595        }
596        return sb.append('"').toString();
597    }
598
599    // ------------------------------------------------------------------
600    // Forwarding
601    // ------------------------------------------------------------------
602
603    /**
604     * Runs the compiler with the arguments, its output on this one's.
605     */
606    private int forward(List<String> args, String why) {
607        List<String> command = new ArrayList<>();
608        command.add(executable);
609        command.addAll(args);
610        try {
611            Process p = new ProcessBuilder(command).redirectInput(ProcessBuilder.Redirect.INHERIT)
612                    .redirectError(ProcessBuilder.Redirect.INHERIT).start();
613            p.getInputStream().transferTo(out);
614            out.flush();
615            return p.waitFor();
616        } catch (IOException e) {
617            out.print("\nError...\nThe Java frontend does not implement " + why + ", which needs the compiler "
618                    + executable + ", but it cannot be run: " + e.getMessage() + "\n");
619            out.flush();
620            return 1;
621        } catch (InterruptedException e) {
622            Thread.currentThread().interrupt();
623            return 1;
624        }
625    }
626
627    /**
628     * @return the name, the version and the build date, as the other Clafer
629     * tools print them: {@code claferc v0.6.0.2026-11-26}
630     */
631    static String version() {
632        java.util.Properties p = new java.util.Properties();
633        try (java.io.InputStream in = ClaferCommand.class.getResourceAsStream("version.properties")) {
634            p.load(in);
635        } catch (java.io.IOException | NullPointerException e) {
636            return "claferc vunknown";
637        }
638        return "claferc v" + p.getProperty("version") + "." + p.getProperty("releasedate");
639    }
640
641    private static final String Help = """
642            claferc [OPTIONS] [FILE]
643
644            The Clafer compiler's 'clafer -m clafer' and 'clafer -m alloy' in Java.
645
646              -m alloy                The Alloy 6 model, static or temporal, written to FILE.als (the
647                                      default mode; a model with a construct that it does not translate
648                                      and the other modes are forwarded to clafer).
649              -m clafer               The explicit model, written to FILE.des.cfr.
650                 --core               The explicit core model, written to FILE.core.cfr.
651                 --record-provenance  With --core, the provenance comments of the lowered constructs.
652                 --meta-data          The explicit model's scope file (FILE.des.cfr-scope or
653                                      FILE.core.cfr-scope) and the map of names (FILE.cfr-map).
654              -o --console-output     Print the output instead of writing it.
655              -s --no-stats           Don't print the statistics.
656              -f --skip-resolver      The names are the UIDs.
657                 --explicit           The model is an explicit model: -f -l --ss=none.
658                 --ss=none|simple     The scope strategy.
659                 --tl=INT             The trace length.
660                 --minint=INT, --maxint=INT, --decimal-digits=INT
661                                      The ranges of the scope file.
662                 --import=FILE        Compile the model with the model in FILE (a path or an http/https
663                                      URL). Can be repeated. FILE may also be a URL.
664                 --import-root=DIR    Allow only local imports inside DIR. Can be repeated.
665                 --public-imports     Allow only URL imports from public addresses.
666                 --import-base=URL    The URL from which the model's text was read.
667              -k --keep-unused        Keep the abstract clafers that nothing needs in the Alloy model.
668                 --timeout-analysis=INT
669                                      Accepted; it changes nothing.
670
671            Any other mode or option is forwarded to clafer on the path, with the same arguments.
672            """;
673}