001package org.clafer.frontend;
002
003import java.io.IOException;
004import java.nio.charset.StandardCharsets;
005import java.nio.file.Files;
006import java.nio.file.Path;
007import java.net.URI;
008import java.net.URISyntaxException;
009import java.util.ArrayList;
010import java.util.List;
011import java.util.Optional;
012import java.util.function.Function;
013
014/**
015 * The files of a model: the model and the files it imports, transitively,
016 * with {@code --import=FILE} in their {@code //# OPTIONS} lines, as the
017 * compiler reads them ({@code Import.readModel}): local files and http or
018 * https URLs ({@link Http}). An import is relative to the folder or the URL of
019 * the importing file; the imported files come before the files that import
020 * them, each once, and the model last. The model is their concatenation, and
021 * a line of it is shown in its file ({@link #position}). The web tools'
022 * restrictions of the imports are {@link ImportOptions}.
023 *
024 * @param files the files, in order, the model last
025 * @param options the options of all the files, combined
026 * @param errors the compiler's errors of reading the files and combining
027 * their options; the files are empty if there is one
028 */
029public record ModelFiles(List<ModelFile> files, ModelOptions options, List<String> errors) {
030
031    /**
032     * @param path the path or URL as the messages show it
033     * @param text the text, which ends with a newline
034     */
035    public record ModelFile(String path, String text) {
036    }
037
038    /**
039     * A model in one file, whose imports are not read: its text and options.
040     *
041     * @param path the path that the messages show, or empty
042     */
043    public static ModelFiles of(String path, String text) {
044        return new ModelFiles(List.of(new ModelFile(path, withNewline(text))), ModelOptions.of(text), List.of());
045    }
046
047    /**
048     * @return the text of the model, the files in order
049     */
050    public String text() {
051        StringBuilder sb = new StringBuilder();
052        for (ModelFile f : files) {
053            sb.append(f.text());
054        }
055        return sb.toString();
056    }
057
058    /**
059     * The restrictions of the imports, which only the command line gives, as
060     * the web tools give them to the compiler:
061     *
062     * @param roots {@code --import-root}: a local import must be inside one
063     * of these folders, after resolving {@code ..} and symbolic links; any
064     * local file without them
065     * @param publicOnly {@code --public-imports}: URLs only from public
066     * addresses, without a proxy
067     * @param base {@code --import-base}: the URL from which the model's text
068     * was read, which its imports are relative to, so they can only be URLs
069     * @param readUrls whether URLs are downloaded; if not, an import of a URL
070     * is an error ({@link #importsUrl}), e.g., in an editor, which analyzes the
071     * model on every change
072     */
073    public record ImportOptions(List<String> roots, boolean publicOnly, Optional<String> base, boolean readUrls) {
074
075        public ImportOptions {
076            roots = List.copyOf(roots);
077        }
078
079        /**
080         * No restrictions; URLs are read.
081         */
082        public static final ImportOptions Default = new ImportOptions(List.of(), false, Optional.empty(), true);
083
084        /**
085         * No restrictions, and only local files.
086         */
087        public static final ImportOptions LocalOnly = new ImportOptions(List.of(), false, Optional.empty(), false);
088    }
089
090    /**
091     * The name of the standard input, as the messages show it.
092     */
093    public static final String Stdin = "<stdin>";
094
095    /**
096     * Reads a model and the files it imports, local files and URLs.
097     *
098     * @param path the model's file or URL, as the messages show it
099     * @param commandLineImports the imports given on the command line,
100     * relative to the working folder, which come first
101     */
102    public static ModelFiles read(String path, List<String> commandLineImports) {
103        return read(path, commandLineImports, p -> Optional.empty(), ImportOptions.Default);
104    }
105
106    /**
107     * Reads a model and the local files it imports, taking the text of a
108     * file from {@code open} where it has one, e.g., a document open in an
109     * editor, and from disk otherwise. An import of a URL is an error
110     * ({@link #importsUrl}).
111     *
112     * @param path the model's file, as the messages show it
113     * @param commandLineImports the imports given on the command line
114     * @param open the text of a file, by its path as the model names it, if
115     * it is not to be read from disk
116     */
117    public static ModelFiles read(String path, List<String> commandLineImports,
118            Function<String, Optional<String>> open) {
119        return read(path, commandLineImports, open, ImportOptions.LocalOnly);
120    }
121
122    /**
123     * Reads a model and the files it imports, as the compiler does
124     * ({@code Import.readModel}). The model is a file, a URL, or the
125     * standard input ({@link #Stdin}, whose text {@code open} gives). The
126     * imports of the command line are relative to the working folder, and
127     * those of a file to its folder or URL, or, for the model, to
128     * {@code --import-base}. A file read from a URL may only import URLs.
129     *
130     * @param path the model's file or URL, as the messages show it
131     * @param commandLineImports the imports given on the command line
132     * @param open the text of a file, by its path, if it is not to be read
133     * @param restrictions the restrictions of the imports
134     */
135    public static ModelFiles read(String path, List<String> commandLineImports,
136            Function<String, Optional<String>> open, ImportOptions restrictions) {
137        Reader reader = new Reader(open, restrictions);
138        try {
139            boolean stdin = path.equals(Stdin);
140            Location rootLocation = location(path);
141            Location base = restrictions.base().map(ModelFiles::location).orElse(rootLocation);
142            String text = withNewline(reader.fetch(false, "", rootLocation));
143            ModelOptions rootOptions = ModelOptions.of(text);
144            List<Location> rootImports = new ArrayList<>();
145            for (String name : rootOptions.imports()) {
146                rootImports.add(importLocation(path, base, name));
147            }
148            // the imports of the command line and of the model, imported by the model
149            List<String> stackKeys = stdin ? List.of() : List.of(key(base));
150            List<String> stackNames = stdin ? List.of() : List.of(path);
151            for (String name : commandLineImports) {
152                reader.visit(stackKeys, stackNames, location(name));
153            }
154            for (Location l : rootImports) {
155                reader.visit(stackKeys, stackNames, l);
156            }
157            List<String> errors = new ArrayList<>();
158            ModelOptions options = ModelOptions.combine(reader.paths, reader.options, path, rootOptions, errors);
159            if (!errors.isEmpty()) {
160                return new ModelFiles(List.of(), rootOptions, errors);
161            }
162            List<ModelFile> files = new ArrayList<>(reader.files);
163            files.add(new ModelFile(stdin ? Stdin : rootLocation.show(), text));
164            return new ModelFiles(List.copyOf(files), options, List.of());
165        } catch (ImportError e) {
166            return new ModelFiles(List.of(), ModelOptions.Defaults, List.of(e.getMessage()));
167        }
168    }
169
170    /**
171     * The name of the model's file for its outputs: its path, or, for a URL,
172     * the last segment of its path ({@code model.cfr} if it has none), in the
173     * working folder.
174     */
175    public static String localName(String path) {
176        Location l = location(path);
177        if (l.url().isEmpty()) {
178            return l.path();
179        }
180        String p = Http.path(l.url().get());
181        String name = p.substring(p.lastIndexOf('/') + 1);
182        return name.isEmpty() ? "model.cfr" : name;
183    }
184
185    /**
186     * Where a file of a model is: a local path, or an http or https URL.
187     */
188    record Location(String path, Optional<URI> url) {
189
190        /**
191         * @return the location as the messages show it
192         */
193        String show() {
194            return url.map(URI::toString).orElse(path);
195        }
196
197        /**
198         * @return the path that must name a .cfr file, unescaped for a URL
199         */
200        String modelPath() {
201            return url.map(Http::path).orElse(path);
202        }
203    }
204
205    /**
206     * The location of a name ({@code Import.location}): an absolute
207     * {@code http} or {@code https} URI without a fragment, otherwise a local
208     * path, a {@code file://} URL being its path.
209     */
210    static Location location(String name) {
211        try {
212            URI uri = new URI(name);
213            String scheme = uri.getScheme();
214            if (uri.isAbsolute() && scheme != null && (scheme.equalsIgnoreCase("http")
215                    || scheme.equalsIgnoreCase("https")) && uri.getRawFragment() == null && !uri.isOpaque()) {
216                return new Location(name, Optional.of(uri));
217            }
218        } catch (URISyntaxException e) {
219            // a local path
220        }
221        if (name.startsWith("file://")) {
222            return new Location(unescape(name.substring("file://".length())), Optional.empty());
223        }
224        return new Location(name, Optional.empty());
225    }
226
227    private static String unescape(String s) {
228        try {
229            return java.net.URLDecoder.decode(s.replace("+", "%2B"), StandardCharsets.UTF_8);
230        } catch (IllegalArgumentException e) {
231            return s;
232        }
233    }
234
235    /**
236     * The location of an import, relative to the importing file
237     * ({@code Import.importLocation}): to its folder, or to its URL, from
238     * which only URLs can be imported.
239     *
240     * @param importerName the importing file, as the messages show it
241     * @param importer its location
242     */
243    static Location importLocation(String importerName, Location importer, String name) {
244        Location l = location(name);
245        if (l.url().isPresent()) {
246            return l;
247        }
248        if (importer.url().isEmpty()) {
249            return new Location(importLocation(importer.path(), l.path()), Optional.empty());
250        }
251        if (name.startsWith("file://") || Path.of(l.path()).isAbsolute()) {
252            throw new ImportError(ModelOptions.inFile(importerName,
253                    "a model read from a URL cannot import the local file " + name));
254        }
255        try {
256            return new Location(name, Optional.of(importer.url().get().resolve(new URI(Http.escape(l.path())))));
257        } catch (URISyntaxException | IllegalArgumentException e) {
258            throw new ImportError(ModelOptions.inFile(importerName,
259                    "the import " + name + " is not a valid relative URL"));
260        }
261    }
262
263    private static final class ImportError extends RuntimeException {
264
265        ImportError(String message) {
266            super(message, null, false, false);
267        }
268    }
269
270    private static final class Reader {
271
272        final List<String> done = new ArrayList<>();
273        final List<ModelFile> files = new ArrayList<>();
274        final List<String> paths = new ArrayList<>();
275        final List<ModelOptions> options = new ArrayList<>();
276        final Function<String, Optional<String>> open;
277        final ImportOptions restrictions;
278        final List<Path> roots = new ArrayList<>();
279
280        Reader(Function<String, Optional<String>> open, ImportOptions restrictions) {
281            this.open = open;
282            this.restrictions = restrictions;
283            for (String r : restrictions.roots()) {
284                roots.add(canonical(r));
285            }
286        }
287
288        /**
289         * Reads an import and its imports, unless it was read; the stack has
290         * the importing files, the last first, and is empty for the imports
291         * of the command line of a model read from the standard input.
292         */
293        void visit(List<String> stackKeys, List<String> stackNames, Location loc) {
294            String importer = stackNames.isEmpty() ? "the command line" : stackNames.get(0);
295            String name = loc.show();
296            if (loc.url().isPresent() && !restrictions.readUrls()) {
297                throw new ImportError(ModelOptions.inFile(importer, "the import " + name + UrlImport));
298            }
299            // before anything is known about the file, e.g., whether it exists
300            if (!isModelPath(loc.modelPath())) {
301                throw new ImportError(ModelOptions.inFile(importer, "the import " + name + " is not a .cfr file"));
302            }
303            if (loc.url().isEmpty() && !roots.isEmpty()) {
304                Path real = canonical(loc.path());
305                if (roots.stream().noneMatch(real::startsWith)) {
306                    throw new ImportError(ModelOptions.inFile(importer, "the import " + loc.path()
307                            + " is outside the folders from which files can be imported"));
308                }
309            }
310            String k = key(loc);
311            int at = stackKeys.indexOf(k);
312            if (at >= 0) {
313                // the importing files from the one that imports this one again
314                List<String> cycle = new ArrayList<>();
315                cycle.add(name);
316                cycle.addAll(stackNames.subList(0, at));
317                cycle.add(name);
318                java.util.Collections.reverse(cycle);
319                throw new ImportError("Import cycle: " + String.join(" imports ", cycle));
320            }
321            if (done.contains(k)) {
322                return;
323            }
324            String text = withNewline(fetch(true, importer, loc));
325            ModelOptions o = ModelOptions.of(text);
326            List<Location> imports = new ArrayList<>();
327            for (String i : o.imports()) {
328                imports.add(importLocation(name, loc, i));
329            }
330            List<String> keys = new ArrayList<>();
331            keys.add(k);
332            keys.addAll(stackKeys);
333            List<String> names = new ArrayList<>();
334            names.add(name);
335            names.addAll(stackNames);
336            for (Location i : imports) {
337                visit(keys, names, i);
338            }
339            done.add(k);
340            files.add(new ModelFile(name, text));
341            paths.add(name);
342            options.add(o);
343        }
344
345        String fetch(boolean isImport, String importer, Location loc) {
346            Optional<String> text = open.apply(loc.show());
347            if (text.isPresent()) {
348                return text.get();
349            }
350            if (loc.url().isPresent()) {
351                try {
352                    return Http.get(loc.url().get(), isImport, restrictions.publicOnly());
353                } catch (Http.Failure e) {
354                    throw new ImportError(ModelOptions.inFile(importer, "cannot read " + loc.show() + ": "
355                            + e.getMessage()));
356                }
357            }
358            String path = loc.path();
359            Path p = Path.of(path);
360            if (!Files.isRegularFile(p)) {
361                throw new ImportError(ModelOptions.inFile(importer, "the file " + path + " does not exist"));
362            }
363            try {
364                return Files.readString(p, StandardCharsets.UTF_8);
365            } catch (IOException e) {
366                throw new ImportError(ModelOptions.inFile(importer, "cannot read " + path + ": " + e.getMessage()));
367            }
368        }
369    }
370
371    /**
372     * {@code System.Directory.canonicalizePath}: the absolute path, with
373     * {@code ..} and the symbolic links of the part that exists resolved.
374     */
375    static Path canonical(String path) {
376        Path p = Path.of(path).toAbsolutePath().normalize();
377        Path existing = p;
378        while (existing != null && !Files.exists(existing)) {
379            existing = existing.getParent();
380        }
381        if (existing == null) {
382            return p;
383        }
384        try {
385            return existing.toRealPath().resolve(existing.relativize(p)).normalize();
386        } catch (IOException e) {
387            return p;
388        }
389    }
390
391    /**
392     * The end of the error of an import of a URL that is not read.
393     */
394    private static final String UrlImport = " is a URL, which is not read here";
395
396    /**
397     * @return whether the model could not be read because it imports a URL,
398     * which was not to be read ({@link ImportOptions#readUrls})
399     */
400    public boolean importsUrl() {
401        return errors.stream().anyMatch(e -> e.endsWith(UrlImport));
402    }
403
404    /**
405     * @return whether an import names a URL
406     */
407    public static boolean isUrl(String name) {
408        return location(name).url().isPresent();
409    }
410
411    /**
412     * Whether a path names a Clafer model: it ends with {@code .cfr}.
413     */
414    static boolean isModelPath(String path) {
415        return path.endsWith(".cfr");
416    }
417
418    /**
419     * The location of an import, relative to the folder of the importing
420     * file: {@code normalise (takeDirectory importer </> path)}.
421     */
422    static String importLocation(String importer, String name) {
423        String path = name;
424        if (Path.of(path).isAbsolute()) {
425            return normalise(path);
426        }
427        int slash = importer.lastIndexOf('/');
428        String dir = slash < 0 ? "." : importer.substring(0, slash == 0 ? 1 : slash);
429        return normalise(dir.equals("/") ? "/" + path : dir + "/" + path);
430    }
431
432    /**
433     * {@code System.FilePath.normalise}: no {@code ./} segments and no
434     * repeated slashes; {@code ..} is kept.
435     */
436    static String normalise(String path) {
437        boolean absolute = path.startsWith("/");
438        List<String> parts = new ArrayList<>();
439        for (String part : path.split("/+")) {
440            if (!part.isEmpty() && !part.equals(".")) {
441                parts.add(part);
442            }
443        }
444        String joined = String.join("/", parts);
445        return absolute ? "/" + joined : joined.isEmpty() ? "." : joined;
446    }
447
448    /**
449     * What identifies a file: its real path, if it exists, or its URL.
450     */
451    private static String key(Location l) {
452        if (l.url().isPresent()) {
453            return l.show();
454        }
455        try {
456            Path p = Path.of(l.path());
457            return Files.exists(p) ? p.toRealPath().toString() : l.path();
458        } catch (IOException | java.nio.file.InvalidPathException e) {
459            return l.path();
460        }
461    }
462
463    private static String withNewline(String s) {
464        return s.isEmpty() || s.endsWith("\n") ? s : s + "\n";
465    }
466
467    /**
468     * @param line a line of the model, from 1
469     * @return the path of its file and its line in it
470     */
471    public Position position(int line) {
472        int start = 1;
473        for (int i = 0; i < files.size(); i++) {
474            ModelFile f = files.get(i);
475            int size = (int) f.text().chars().filter(ch -> ch == '\n').count();
476            if (i == files.size() - 1 || line < start + size) {
477                return new Position(f.path(), line - start + 1);
478            }
479            start += size;
480        }
481        return new Position("", line);
482    }
483
484    /**
485     * A line in a file.
486     */
487    public record Position(String path, int line) {
488    }
489
490    /**
491     * @return the diagnostic at its position in its file, e.g.,
492     * {@code model.cfr:3:5: message}, or without a path if the model has no
493     * name
494     */
495    public String format(Diagnostic d) {
496        Position p = position(d.span().line());
497        String at = p.line() + ":" + d.span().column() + ": " + d.message();
498        return p.path().isEmpty() ? at : p.path() + ":" + at;
499    }
500}