001package org.clafer.lsp;
002
003import java.util.ArrayList;
004import java.util.List;
005import java.util.Optional;
006import java.util.function.Function;
007import org.clafer.frontend.ClaferParser;
008import org.clafer.frontend.Diagnostic;
009import org.clafer.frontend.ModelFiles;
010import org.clafer.frontend.Names;
011import org.clafer.frontend.SourceSpan;
012import org.clafer.frontend.ToIr;
013import org.eclipse.lsp4j.DiagnosticSeverity;
014import org.eclipse.lsp4j.DocumentSymbol;
015import org.eclipse.lsp4j.Position;
016import org.eclipse.lsp4j.Range;
017
018/**
019 * What the server knows of one version of a document: its tree and its
020 * diagnostics. A document is analyzed again, completely, on every change.
021 *
022 * @param text the text of the document
023 * @param positions the positions in it
024 * @param parsed the tree of the document alone, with its comments and
025 * parse errors; what was read around the errors
026 * @param diagnostics the LSP diagnostics of the model of the document, its
027 * imports included
028 * @param index the names of the model and what they refer to
029 */
030public record Analysis(String text, Positions positions, ClaferParser.Result parsed,
031        List<org.eclipse.lsp4j.Diagnostic> diagnostics, Index index) {
032
033    /**
034     * The name of the server in the diagnostics.
035     */
036    static final String Source = "clafer";
037
038    /**
039     * Analyzes a document.
040     *
041     * @param uri the document's URI
042     * @param path the document's file, absolute, or a name if it has no file
043     * @param text the document's text
044     * @param open the text of the open documents, by the path that a model
045     * names them with; the files that are not open are read from disk
046     * @return the analysis
047     */
048    public static Analysis of(String uri, String path, String text, Function<String, Optional<String>> open) {
049        Positions positions = new Positions(text);
050        ClaferParser.Result parsed = ClaferParser.parse(text);
051        Function<String, Optional<String>> withThis = p -> p.equals(path) ? Optional.of(text) : open.apply(p);
052        ModelFiles files = ModelFiles.read(path, List.of(), withThis);
053        ToIr.Result result;
054        try {
055            result = ToIr.toIr(files);
056        } catch (RuntimeException e) {
057            // a bug of the frontend: shown on the first line rather than lost
058            result = null;
059        }
060        List<org.eclipse.lsp4j.Diagnostic> diagnostics = new ArrayList<>();
061        if (result == null) {
062            diagnostics.add(diagnostic(firstLine(positions), "The Java frontend failed on this model; please report it"));
063        } else {
064            for (Diagnostic d : result.diagnostics()) {
065                diagnostics.add(toLsp(d, files, path, positions));
066            }
067        }
068        Index index = new Index(uri, path, positions, parsed.model(),
069                files.errors().isEmpty() ? Optional.of(files) : Optional.empty(),
070                result == null ? Names.None : result.names());
071        return new Analysis(text, positions, parsed, List.copyOf(diagnostics), index);
072    }
073
074    /**
075     * A diagnostic of the model at its place in this document: where it is
076     * if it is in this document, else on the first line, with its file and
077     * line in the message.
078     */
079    private static org.eclipse.lsp4j.Diagnostic toLsp(Diagnostic d, ModelFiles files, String path,
080            Positions positions) {
081        SourceSpan s = d.span();
082        if (files.files().isEmpty()) {
083            return diagnostic(firstLine(positions), d.message());
084        }
085        ModelFiles.Position start = files.position(s.line());
086        if (!start.path().equals(path)) {
087            return diagnostic(firstLine(positions), "in " + files.format(d));
088        }
089        ModelFiles.Position end = files.position(s.endLine());
090        SourceSpan local = end.path().equals(path) && end.line() >= start.line()
091                ? new SourceSpan(start.line(), s.column(), end.line(),
092                        end.line() == start.line() ? Math.max(s.endColumn(), s.column()) : s.endColumn())
093                : SourceSpan.at(start.line(), s.column());
094        return diagnostic(positions.toVisibleLsp(local), d.message());
095    }
096
097    private static Range firstLine(Positions positions) {
098        return new Range(new Position(0, 0), new Position(0, positions.line(0).length()));
099    }
100
101    private static org.eclipse.lsp4j.Diagnostic diagnostic(Range range, String message) {
102        return new org.eclipse.lsp4j.Diagnostic(range, message, DiagnosticSeverity.Error, Source);
103    }
104
105    /**
106     * @return the outline of the document
107     */
108    public List<DocumentSymbol> outline() {
109        return Outline.of(parsed.model(), positions);
110    }
111}