001package org.clafer.cli;
002
003import java.io.BufferedReader;
004import java.io.File;
005import java.io.FileNotFoundException;
006import java.io.IOException;
007import java.io.PrintWriter;
008import java.math.BigDecimal;
009import java.nio.file.Files;
010import java.util.ArrayList;
011import java.util.Arrays;
012import java.util.List;
013import java.util.stream.Collectors;
014import joptsimple.OptionSet;
015import org.clafer.ast.AstClafer;
016import org.clafer.ast.AstModel;
017import org.clafer.ast.AstPrinter;
018import org.clafer.compiler.ClaferOption;
019import org.clafer.ast.ToAst;
020import org.clafer.ast.AstUtil;
021import org.clafer.instance.InstanceClafer;
022import org.clafer.javascript.Javascript;
023import org.clafer.javascript.JavascriptFile;
024import org.clafer.scope.Scope;
025import org.clafer.scope.ScopeFile;
026
027
028public class Utils {
029    /**
030     * Whether a model file is an explicit model, to be read by
031     * {@link ToAst} rather than compiled by clafer: given with
032     * --explicit, or a .cfr file whose first line is
033     * {@link AstPrinter#ExplicitHeader} (or another {@code //# OPTIONS} line
034     * with --explicit).
035     */
036    public static boolean isExplicitModel(File file, OptionSet options) throws IOException {
037        if (options.has("explicit"))
038            return true;
039        if (!file.getName().endsWith(".cfr"))
040            return false;
041        try (BufferedReader reader = Files.newBufferedReader(file.toPath())) {
042            String firstLine = reader.readLine();
043            return firstLine != null && firstLine.startsWith("//# OPTIONS ")
044                    && Arrays.asList(firstLine.substring(12).trim().split("\\s+")).contains("--explicit");
045        }
046    }
047
048    /**
049     * Reads a model: an explicit model with {@link ToAst}, another .cfr
050     * model with {@link Frontend}, otherwise a .js file. An explicit model
051     * starts from the default scope (its scopes are in its scope file, see
052     * {@link #resolveScopes(File, JavascriptFile, OptionSet)}).
053     *
054     * @throws IllegalArgumentException with the diagnostics, if the explicit
055     * model has errors
056     * @throws Frontend.ModelException with the errors, if the .cfr model has
057     * errors
058     */
059    public static JavascriptFile readModel(File file, OptionSet options) throws Exception {
060        if (!isExplicitModel(file, options))
061            return file.getName().endsWith(".cfr")
062                    ? Frontend.read(file, options, System.out)
063                    : Javascript.readModel(file);
064        ToAst.Result parsed = ToAst.parse(Files.readString(file.toPath()));
065        if (!parsed.diagnostics().isEmpty())
066            throw new IllegalArgumentException(parsed.diagnostics().stream()
067                    .map(d -> file.getPath() + ":" + d).collect(Collectors.joining("\n")));
068        return new JavascriptFile(parsed.model(), Scope.builder().toScope(), ClaferOption.Default,
069                parsed.objectives(), parsed.assertions());
070    }
071
072    /**
073     * All the clafers of the model, including the nested abstract ones and the
074     * type root #clafer#, except the roots of the model.
075     */
076    public static List<AstClafer> getAllModelClafers(AstModel model) {
077        List<AstClafer> result = new ArrayList<AstClafer>(AstUtil.getClafers(model));
078        result.remove(model.getAbstractRoot());
079        result.remove(model.getRoot());
080        return result;
081    }
082
083    public static void produceScopeFile(
084            List<ClaferNameScopePair> claferScopePairs, String scopesFile) throws FileNotFoundException {
085// could be done with JSON serializer, but this way I do not refer to any libraries
086
087        PrintWriter writer = new PrintWriter(scopesFile);
088        writer.println("[");
089
090        for (int i = 0; i < claferScopePairs.size(); i++)
091        {
092            ClaferNameScopePair pair = claferScopePairs.get(i);
093
094            if (pair.name.equals("#clafer#"))
095                pair.name = "";
096
097            writer.print("{\"lpqName\": \"" + pair.name + "\", \"scope\": " + pair.scope + "}");
098
099            if (i != claferScopePairs.size() - 1)
100            {
101                writer.println(",");
102            }
103
104        }
105
106        writer.println("]");
107        writer.close();
108
109    }
110
111public static InstanceClafer getInstanceValueByName(InstanceClafer[] topClafers, String name) {
112
113        for (int i = 0; i < topClafers.length; i++)
114        {
115            if (topClafers[i].getType().getName().equals(name))
116            {
117                return topClafers[i];
118            }
119        }
120
121        for (int i = 0; i < topClafers.length; i++)
122        {
123            if (topClafers[i].hasChildren())
124            {
125                InstanceClafer result = getInstanceValueByName(topClafers[i].getChildren(), name);
126                if (result != null)
127                    return result;
128            }
129        }
130
131        return null;
132    }
133
134    public static AstClafer getModelChildByName(AstModel model, String name) {
135        for (AstClafer clafer : getAllModelClafers(model))
136            if (clafer.getName().equals(name))
137                return clafer;
138        return null;
139    }
140
141    public static void printClafer(InstanceClafer clafer, Appendable out) throws IOException {
142        printClafer(clafer, "", out);
143    }
144
145    private static void printClafer(InstanceClafer clafer, String indent, Appendable out) throws IOException {
146        out.append(indent).append(clafer.getType().getName()).append(countSuffix(clafer.getId()));
147
148        if (clafer.getType().getSuperClafer() != null) {
149            String name = clafer.getType().getSuperClafer().getName();
150            // do not print the default super type "clafer"
151            if (! name.equals("#clafer#"))
152                out.append(" : ").append(name);
153        }
154
155        if(clafer.hasRef()) {
156            out.append(" -> " + AstUtil.getInheritedRef(clafer.getType()).getTargetType().getName() + " = ");
157            if (clafer.getRef() instanceof InstanceClafer) {
158                InstanceClafer refClafer = (InstanceClafer) clafer.getRef();
159                out.append(refClafer.getType().getName()).append(countSuffix(refClafer.getId()));
160            } else if (clafer.getRef() instanceof BigDecimal)
161                // Never scientific notation, e.g. 0.0000001 rather than 1E-7.
162                out.append(((BigDecimal) clafer.getRef()).toPlainString());
163            else
164                out.append(clafer.getRef().toString());
165        }
166
167        out.append(" \n");
168        for (InstanceClafer child : clafer.getChildren()) {
169            printClafer(child, indent + "  ", out);
170        }
171    }
172
173    public static String countSuffix(int count) {
174        return count == 0 ? "" : "$" + Integer.toString(count);
175    }
176
177    public static Scope resolveScopes(JavascriptFile javascriptFile, OptionSet options) {
178        return resolveScopes(javascriptFile.getScope(), javascriptFile.hasIntRange(), options);
179    }
180
181    /**
182     * The scope with the command line's scopes and ranges, which override the given ones.
183     *
184     * @param hasIntRange whether the scope's integers were given, by the model or its scope file;
185     * otherwise they are -128..127
186     */
187    private static Scope resolveScopes(Scope scope, boolean hasIntRange, OptionSet options) {
188        if (options.has("scope"))
189            scope = scope.toBuilder().defaultScope((int) options.valueOf("scope")).toScope();
190
191        /* overrides the model's decimalScale; a decimal literal with more digits is an error */
192        if (options.has("decimal-digits"))
193            scope = scope.toBuilder().decimalScale((int) options.valueOf("decimal-digits")).toScope();
194
195        if (options.has("maxint")) {
196            int scopeHigh = (int)options.valueOf("maxint");
197            int scopeLow = options.has("minint") ? (int)options.valueOf("minint") : -(scopeHigh + 1);
198
199            scope = scope.toBuilder().intLow(scopeLow).intHigh(scopeHigh).toScope();
200        }
201        else if (hasIntRange) {
202            /* the integer range of the model, e.g., from clafer's --minint and --maxint, or of its scope file */
203            if (options.has("minint")) {
204                scope = scope.toBuilder().intLow((int)options.valueOf("minint")).toScope();
205            }
206        }
207        else {
208            /* setting the default int range */
209            int scopeHighDef = 127;
210            int scopeLowDef = -(scopeHighDef + 1);
211            scope = scope.toBuilder().intLow(scopeLowDef).intHigh(scopeHighDef).toScope();
212        }
213        return scope;
214    }
215
216    /**
217     * The scopes of the model: the model's, then its scope file's, if it has one, then the command line's.
218     */
219    public static Scope resolveScopes(File inputFile, JavascriptFile javascriptFile, OptionSet options) throws IOException {
220        File scopeFile = scopeFile(inputFile, options);
221        if (scopeFile == null)
222            return resolveScopes(javascriptFile, options);
223        if (!scopeFile.exists())
224            throw new FileNotFoundException("The scope file does not exist: " + scopeFile.getPath());
225        System.out.println("Using the scopes from " + scopeFile.getPath());
226        ScopeFile file = ScopeFile.parse(Files.readString(scopeFile.toPath()), scopeFile.getPath());
227        return resolveScopes(file.applyTo(javascriptFile.getScope(), javascriptFile.getModel()),
228                javascriptFile.hasIntRange() || file.hasIntRange(), options);
229    }
230
231    /**
232     * The scope file given by --scope-file, otherwise the model's .cfr-scope file (model.cfr-scope next to
233     * model.cfr or model.js) if it exists, otherwise null.
234     */
235    public static File scopeFile(File inputFile, OptionSet options) {
236        if (options.has("scope-file"))
237            return (File) options.valueOf("scope-file");
238        String path = inputFile.getPath();
239        int dot = path.lastIndexOf('.');
240        if (dot > path.lastIndexOf(File.separatorChar))
241            path = path.substring(0, dot);
242        File file = new File(path + ".cfr-scope");
243        return file.exists() ? file : null;
244    }
245
246    /**
247     * Applies a .cfr-scope file (see {@link ScopeFile}) to a scope.
248     *
249     * @throws IllegalArgumentException if the file is malformed or a name is not of a clafer in the model
250     */
251    public static Scope applyScopeFile(Scope scope, AstModel model, String json, String fileName) {
252        return ScopeFile.parse(json, fileName).applyTo(scope, model);
253    }
254
255    /**
256     * The clafers with the given UID, otherwise with the given (partially) qualified name.
257     */
258    static List<AstClafer> claferNamed(List<AstClafer> clafers, String qName) {
259        return ScopeFile.claferNamed(clafers, qName);
260    }
261}
262
263class ClaferNameScopePair implements Comparable<ClaferNameScopePair> {
264    int scope;
265    String name;
266
267    public ClaferNameScopePair(String name, int scope) {
268        this.name = name;
269        this.scope = scope;
270    }
271
272    @Override
273    public int compareTo(ClaferNameScopePair o) {
274        return name.compareTo(o.name);
275    }
276}