001package org.clafer.cli;
002
003import java.io.File;
004import java.io.IOException;
005import java.io.PrintStream;
006import java.nio.file.Files;
007import java.util.ArrayList;
008import java.util.List;
009import java.util.Optional;
010import joptsimple.OptionSet;
011import org.clafer.ast.ToAst;
012import org.clafer.compiler.ClaferOption;
013import org.clafer.frontend.ClaferExecutable;
014import org.clafer.frontend.ModelFiles;
015import org.clafer.frontend.ToIr;
016import org.clafer.javascript.Javascript;
017import org.clafer.javascript.JavascriptFile;
018import org.clafer.scope.Scope;
019import org.clafer.scope.ScopeFile;
020
021/**
022 * Reads a {@code .cfr} model that is not an explicit model: with the Java
023 * frontend ({@link ToIr}, then {@link ToAst}) in this JVM, or, when the Java
024 * frontend cannot take the model, with the Haskell compiler
025 * ({@code clafer -k -m choco}), whose {@code .js} file is read with Rhino. The compiler is
026 * {@link ClaferExecutable#find()}: {@code clafer} next to {@code clafersg.jar}, as in Clafer
027 * Tools, or on the {@code PATH}.
028 * <p>
029 * The Haskell compiler reads the model when:
030 * <ul>
031 * <li>{@code --haskell-frontend} is given;</li>
032 * <li>the model has a {@code [choco| |]} escape, which is JavaScript;</li>
033 * <li>the Java frontend reports errors or fails: if the compiler compiles the
034 * model, chocosolver solves its output and says that the Java frontend
035 * rejected the model; otherwise the Java frontend's errors are the
036 * model's.</li>
037 * </ul>
038 * The imports are read as the compiler reads them, URLs included, with the
039 * restrictions of {@code --import-root}, {@code --public-imports} and
040 * {@code --import-base} ({@link ModelFiles.ImportOptions}).
041 * <p>
042 * The model's scopes are those of its explicit model's scope file
043 * ({@link org.clafer.frontend.Scopes}), as the compiler writes them with
044 * {@code -m clafer --meta-data}.
045 */
046public final class Frontend {
047
048    private Frontend() {
049    }
050
051    /**
052     * A model that cannot be read.
053     */
054    public static class ModelException extends Exception {
055
056        private static final long serialVersionUID = 1L;
057
058        public ModelException(String message) {
059            super(message);
060        }
061    }
062
063    /**
064     * Reads a {@code .cfr} model with the Java frontend, without a fallback.
065     *
066     * @param file the model
067     * @param imports the imports of the command line
068     * @return the model, with the scopes of its explicit model's scope file
069     * @throws ModelException with the errors of the model, each at its
070     * position in its file
071     */
072    public static JavascriptFile readWithJava(File file, List<String> imports) throws ModelException {
073        return readWithJava(file, imports, ModelFiles.ImportOptions.Default);
074    }
075
076    /**
077     * Reads a {@code .cfr} model with the Java frontend, without a fallback.
078     *
079     * @param file the model
080     * @param imports the imports of the command line
081     * @param restrictions the restrictions of the imports
082     * @return the model, with the scopes of its explicit model's scope file
083     * @throws ModelException with the errors of the model, each at its
084     * position in its file
085     */
086    public static JavascriptFile readWithJava(File file, List<String> imports, ModelFiles.ImportOptions restrictions)
087            throws ModelException {
088        ModelFiles files = ModelFiles.read(file.getPath(), imports, p -> Optional.empty(), restrictions);
089        ToIr.Result ir = ToIr.toIr(files);
090        List<String> errors = ir.messages();
091        if (errors.isEmpty()) {
092            ToAst.Result built = ToAst.toAst(ir.model());
093            // a construct that ToAst refuses can be reached twice, e.g., in a set expression
094            errors = built.diagnostics().stream().map(ir.files()::format).distinct().toList();
095            if (errors.isEmpty()) {
096                Scope scope = ScopeFile.parse(ir.scopes().orElseThrow().scopeFile(), file.getPath() + "-scope")
097                        .applyTo(Scope.builder().toScope(), built.model());
098                return new JavascriptFile(built.model(), scope, ClaferOption.Default, built.objectives(),
099                        built.assertions(), true);
100            }
101        }
102        throw new ModelException(String.join("\n", errors));
103    }
104
105    /**
106     * Reads a {@code .cfr} model.
107     *
108     * @param file the model
109     * @param options the command line
110     * @param out where the fallback to the Haskell compiler is reported
111     * @return the model, its scopes, objectives and assertions
112     * @throws ModelException with the errors of the model
113     */
114    public static JavascriptFile read(File file, OptionSet options, PrintStream out)
115            throws ModelException, IOException {
116        List<String> imports = new ArrayList<>();
117        for (Object i : options.valuesOf("import")) {
118            imports.add(i.toString());
119        }
120        if (options.has("haskell-frontend")) {
121            return haskell(file, options);
122        }
123        Optional<String> unsupported = unsupported(file);
124        if (unsupported.isPresent()) {
125            out.println("The model " + unsupported.get() + ": compiling it with the Haskell compiler (clafer)");
126            return haskell(file, options);
127        }
128        List<String> errors;
129        try {
130            return readWithJava(file, imports, restrictions(options));
131        } catch (ModelException e) {
132            errors = List.of(e.getMessage());
133        } catch (RuntimeException e) {
134            errors = List.of("The Java frontend failed on the model: " + e);
135        }
136        // the compiler is the reference: a model that it compiles is a model
137        JavascriptFile compiled;
138        try {
139            compiled = haskell(file, options);
140        } catch (ModelException | IOException e) {
141            throw new ModelException(String.join("\n", errors) + "\nClafer compilation failed. Aborting...");
142        }
143        out.println("The Java frontend rejected the model, which the Haskell compiler (clafer) compiles;"
144                + " please report this problem at https://github.com/gsdlab/chocosolver/issues:");
145        for (String error : errors) {
146            out.println(error);
147        }
148        out.println("Solving the Haskell compiler's output.");
149        return compiled;
150    }
151
152    /**
153     * Why the Java frontend cannot read the model, if it cannot.
154     */
155    private static Optional<String> unsupported(File file) throws IOException {
156        String text = Files.readString(file.toPath());
157        if (text.contains("[choco|")) {
158            return Optional.of("has a [choco| |] escape, whose JavaScript the Java frontend does not run");
159        }
160        return Optional.empty();
161    }
162
163    /**
164     * The restrictions of the imports of the command line.
165     */
166    static ModelFiles.ImportOptions restrictions(OptionSet options) {
167        List<String> roots = new ArrayList<>();
168        for (Object root : options.valuesOf("import-root")) {
169            roots.add(root.toString());
170        }
171        Optional<String> base = options.has("import-base")
172                ? Optional.of(options.valueOf("import-base").toString()) : Optional.empty();
173        return new ModelFiles.ImportOptions(roots, options.has("public-imports"), base, true);
174    }
175
176    /**
177     * Compiles the model with the Haskell compiler and reads its {@code .js}
178     * file, next to the model.
179     *
180     * @throws ModelException with the compiler's output, if it does not
181     * compile the model or cannot be run
182     */
183    private static JavascriptFile haskell(File file, OptionSet options) throws ModelException, IOException {
184        String fileName = file.getPath();
185        File jsFile = new File(fileName.substring(0, fileName.lastIndexOf('.')) + ".js");
186        jsFile.delete();
187        List<String> command = new ArrayList<>(List.of(ClaferExecutable.find(), "-k", "-m", "choco"));
188        for (Object i : options.valuesOf("import")) {
189            command.add("--import=" + i);
190        }
191        for (Object root : options.valuesOf("import-root")) {
192            command.add("--import-root=" + root);
193        }
194        if (options.has("public-imports")) {
195            command.add("--public-imports");
196        }
197        if (options.has("import-base")) {
198            command.add("--import-base=" + options.valueOf("import-base"));
199        }
200        command.add(fileName);
201        String output;
202        int exitValue;
203        try {
204            Process compiler = new ProcessBuilder(command).redirectErrorStream(true).start();
205            output = new String(compiler.getInputStream().readAllBytes());
206            exitValue = compiler.waitFor();
207        } catch (IOException e) {
208            throw new ModelException("Could not run the Clafer compiler (clafer): " + e.getMessage());
209        } catch (InterruptedException e) {
210            Thread.currentThread().interrupt();
211            throw new ModelException("The Clafer compiler (clafer) was interrupted");
212        }
213        // clafer exits with 0 also when the model has no Choco output (e.g., temporal operators)
214        if (exitValue != 0 || !jsFile.exists()) {
215            throw new ModelException(output.strip() + "\nClafer compilation failed. Aborting...");
216        }
217        try {
218            return Javascript.readModel(jsFile);
219        } catch (IOException e) {
220            throw e;
221        } catch (Exception e) {
222            throw new ModelException("Unhandled compilation error occured. Please report this problem.\n"
223                    + e.getMessage());
224        }
225    }
226}