001package org.clafer.cli;
002
003
004import java.io.File;
005import java.io.IOException;
006import java.io.PrintStream;
007import java.util.Optional;
008import java.util.Properties;
009import joptsimple.OptionException;
010import joptsimple.OptionParser;
011import joptsimple.OptionSet;
012import joptsimple.OptionSpec;
013import org.clafer.compiler.ClaferSearchStrategy;
014import org.clafer.frontend.ToIr;
015import org.clafer.javascript.JavascriptFile;
016
017public class Main
018{
019    /**
020     * @return the parser of the command line options
021     */
022    static OptionParser optionParser() {
023        return new OptionParser() {
024            {
025                accepts( "addtypes", "Add the super clafer of each clafer to the prettified output (the default output always has them)." );
026                accepts( "dataFile", "Text file to store time (in seconds) to find each instance.").withRequiredArg()
027                        .ofType( File.class ).describedAs("text file");
028                accepts( "decimal-digits", "Specify the number of fractional digits of decimals (overrides the model's)." )
029                    .withRequiredArg().ofType( Integer.class );
030                accepts( "explicit", "The .cfr model is an explicit model (as 'clafer -m clafer' prints it): read it directly, without the Clafer compiler. A model whose first line is '//# OPTIONS --explicit' is one without this option." );
031                accepts( "haskell-frontend", "Compile the .cfr model with the Haskell compiler (clafer -m choco), as before chocosolver 0.6.0, rather than with the Java frontend. Without it, the Haskell compiler compiles only the models that the Java frontend cannot ([choco| |] escapes) or rejects." );
032                accepts( "import-root", "Allow only local imports inside DIR (repeatable), as clafer's --import-root." )
033                    .withRequiredArg().describedAs( "DIR" );
034                accepts( "public-imports", "Allow only URL imports from public addresses, as clafer's --public-imports." );
035                accepts( "import-base", "The URL from which the model's text was read, as clafer's --import-base." )
036                    .withRequiredArg().describedAs( "URL" );
037                accepts( "file", "Input file in .cfr or .js format" ).withRequiredArg().ofType( File.class )
038                    .describedAs( "Clafer model file (.cfr), explicit or not, or Clafer Javascript file (.js)." );
039                accepts( "help", "Show help.").forHelp();
040                accepts( "import", "Compile the .cfr model together with the given Clafer file or URL, relative to the current directory (repeatable); a model also imports files with --import in its //# OPTIONS directive." )
041                    .withRequiredArg().describedAs( "Clafer file or URL" );
042                accepts( "maxint", "Specify maximum integer value." ).withRequiredArg().ofType( Integer.class );
043                accepts( "minint", "Specify minimum integer value." ).withRequiredArg().ofType( Integer.class );
044                accepts( "moo", "Run in multi-objective optimization mode." );
045                accepts( "n", "Specify the maximum number of instances." ).withRequiredArg().ofType( Integer.class );
046                accepts( "noprint", "Don't print the instances to the console or a file");
047                accepts( "output", "Output instances to the given file." ).withRequiredArg().ofType( File.class ).describedAs( "text file" );
048                accepts( "prettify", "Use simple and pretty output format (not formal)." );
049                accepts( "repl", "Run in REPL (interactive) mode." );
050                accepts( "scope", "Override the default global scope value." ).withRequiredArg().ofType( Integer.class );
051                accepts( "scope-file", "Read the scopes of clafers from the given .cfr-scope file (by default, from the model's .cfr-scope file, e.g., model.cfr-scope, if it exists)." ).withRequiredArg().ofType( File.class ).describedAs( "scope file" );
052                accepts( "search", "PreferSmallerInstances/PreferLargerInstances/Random" ).withRequiredArg().ofType( ClaferSearchStrategy.class );
053                accepts( "time", "Time how long it takes to find all instances (and print if it is turned on");
054                accepts( "v", "Run in validation mode; checks all assertions." );
055                accepts( "version", "Display the tool version" );
056            }
057        };
058    }
059
060    /**
061     * Reports a wrong command line, e.g., an unknown option, without a stack trace, and exits with 1.
062     */
063    private static void usageError(String message) {
064        System.err.println("clafersg: " + message);
065        System.err.println("Run clafersg --help to see the options.");
066        System.exit(1);
067    }
068
069    public static void main(String[] args) throws Exception {
070        OptionParser parser = optionParser();
071        OptionSet options;
072        try {
073            options = parser.parse(args);
074            // jopt-simple converts the values only when they are read, e.g., "-n abc"
075            for (OptionSpec<?> spec : options.specs())
076                options.valuesOf(spec);
077        } catch (OptionException e) { // unknown option, missing or wrong argument
078            usageError(e.getMessage());
079            return;
080        }
081
082        if (options.has("version")) {
083            Properties configFile = new Properties();
084            try {
085                configFile.load(Main.class.getClassLoader().getResourceAsStream("version.properties"));
086                String name = configFile.getProperty("name");
087                String releaseDate = configFile.getProperty("releasedate");
088                String version = configFile.getProperty("version");
089                System.out.println(name + " v" + version + "." + releaseDate);
090            } catch (IOException e) {
091                e.printStackTrace();
092            }
093            return;
094        }
095        if (options.has("help")) {
096            parser.printHelpOn(System.out);
097            return;
098        }
099        if (!options.has( "file" )) {
100            usageError("use --file to provide the input file");
101            return;
102        }
103
104        File inputFile = (File) options.valueOf("file");
105
106        if (!inputFile.exists()) {
107            usageError("the input file does not exist: " + inputFile.getPath());
108            return;
109        }
110
111        String fileName = inputFile.toString();
112        // a .cfr file that is not an explicit model is compiled first, by the Java frontend
113        // or, as its fallback, by the Haskell compiler (see Frontend)
114        boolean explicit = Utils.isExplicitModel(inputFile, options);
115        // a temporal model's solutions are traces, which Alloy finds
116        Optional<ToIr.Result> temporal = options.has("v") ? Optional.empty() : Temporal.read(inputFile, options);
117        // the REPL of a temporal model says it, as claferIG's
118        if (fileName.endsWith(".cfr") && !explicit && !(temporal.isPresent() && options.has("repl")))
119            System.out.println("Compiling the Clafer model...");
120
121        PrintStream outStream = System.out;
122
123        if (options.has("output"))
124        {
125            File outputFile = (File) options.valueOf("output");
126            outStream = new PrintStream(outputFile);
127        }
128
129        if (!inputFile.exists())
130        {
131            throw new Exception("File does not exist: " + inputFile.getPath());
132        }
133
134        if (temporal.isPresent()) {
135            if (options.has("repl"))
136                Temporal.runREPL(inputFile, temporal.get(), options);
137            else
138                Temporal.runNormal(inputFile, temporal.get(), options, outStream);
139            return;
140        }
141
142        // run the different modes
143        JavascriptFile javascriptFile = null;
144        try {
145            if (options.has( "v"))
146                System.out.println("=========== Parsing+Typechecking " + fileName + "  =============");
147            javascriptFile = Utils.readModel(inputFile, options);
148        }
149        catch(Frontend.ModelException e) {
150            // the errors of a .cfr model, with their positions
151            System.out.println(e.getMessage());
152            System.exit(1);
153            return;
154        }
155        catch(IllegalArgumentException e) {
156            if (!explicit)
157                throw e;
158            // the errors of an explicit model, with their positions
159            System.out.println(e.getMessage());
160            System.exit(1);
161            return;
162        }
163        catch(Exception e) {
164            System.out.println("Unhandled compilation error occured. Please report this problem.");
165            System.out.println(e.getMessage());
166            System.exit(1);
167            return;
168        }
169
170        if (options.has("v"))
171            Validate.runValidate(inputFile, javascriptFile, options, outStream);
172        else if (options.has("repl"))
173            REPL.runREPL(inputFile, javascriptFile, options);
174        else
175            Normal.runNormal(inputFile, javascriptFile, options, outStream);
176    }
177}