001package org.clafer.lsp;
002
003import java.net.URI;
004import java.nio.file.Path;
005import java.util.ArrayList;
006import java.util.LinkedHashMap;
007import java.util.List;
008import java.util.Map;
009import java.util.Optional;
010import java.util.concurrent.CompletableFuture;
011import java.util.function.IntConsumer;
012import org.clafer.frontend.Names;
013import org.eclipse.lsp4j.CompletionItem;
014import org.eclipse.lsp4j.CompletionList;
015import org.eclipse.lsp4j.CompletionOptions;
016import org.eclipse.lsp4j.CompletionParams;
017import org.eclipse.lsp4j.DefinitionParams;
018import org.eclipse.lsp4j.Position;
019import org.eclipse.lsp4j.PrepareRenameDefaultBehavior;
020import org.eclipse.lsp4j.PrepareRenameParams;
021import org.eclipse.lsp4j.PrepareRenameResult;
022import org.eclipse.lsp4j.Range;
023import org.eclipse.lsp4j.RenameOptions;
024import org.eclipse.lsp4j.RenameParams;
025import org.eclipse.lsp4j.TextEdit;
026import org.eclipse.lsp4j.WorkspaceEdit;
027import org.eclipse.lsp4j.jsonrpc.ResponseErrorException;
028import org.eclipse.lsp4j.jsonrpc.messages.Either3;
029import org.eclipse.lsp4j.jsonrpc.messages.ResponseError;
030import org.eclipse.lsp4j.jsonrpc.messages.ResponseErrorCode;
031import org.eclipse.lsp4j.DidChangeConfigurationParams;
032import org.eclipse.lsp4j.Hover;
033import org.eclipse.lsp4j.HoverParams;
034import org.eclipse.lsp4j.Location;
035import org.eclipse.lsp4j.LocationLink;
036import org.eclipse.lsp4j.MarkupContent;
037import org.eclipse.lsp4j.MarkupKind;
038import org.eclipse.lsp4j.ReferenceParams;
039import org.eclipse.lsp4j.DidChangeTextDocumentParams;
040import org.eclipse.lsp4j.DidChangeWatchedFilesParams;
041import org.eclipse.lsp4j.DidCloseTextDocumentParams;
042import org.eclipse.lsp4j.DidOpenTextDocumentParams;
043import org.eclipse.lsp4j.DidSaveTextDocumentParams;
044import org.eclipse.lsp4j.DocumentSymbol;
045import org.eclipse.lsp4j.DocumentSymbolParams;
046import org.eclipse.lsp4j.InitializeParams;
047import org.eclipse.lsp4j.InitializeResult;
048import org.eclipse.lsp4j.PublishDiagnosticsParams;
049import org.eclipse.lsp4j.ServerCapabilities;
050import org.eclipse.lsp4j.ServerInfo;
051import org.eclipse.lsp4j.SymbolInformation;
052import org.eclipse.lsp4j.TextDocumentContentChangeEvent;
053import org.eclipse.lsp4j.TextDocumentSyncKind;
054import org.eclipse.lsp4j.jsonrpc.messages.Either;
055import org.eclipse.lsp4j.services.LanguageClient;
056import org.eclipse.lsp4j.services.LanguageClientAware;
057import org.eclipse.lsp4j.services.LanguageServer;
058import org.eclipse.lsp4j.services.TextDocumentService;
059import org.eclipse.lsp4j.services.WorkspaceService;
060
061/**
062 * The Clafer language server. It keeps the text of the open documents, and
063 * analyzes each of them again, completely, whenever one changes, since one
064 * may import another.
065 * <p>
066 * LSP4J delivers the notifications one by one on the thread that reads the
067 * messages, so the documents are changed and analyzed on that thread; the
068 * requests read the latest analysis.
069 */
070public final class ClaferLanguageServer implements LanguageServer, LanguageClientAware {
071
072    /**
073     * The open documents, by URI, in the order they were opened.
074     */
075    private final Map<String, Document> documents = new LinkedHashMap<>();
076    private final IntConsumer exit;
077    private LanguageClient client;
078    private boolean shutdown = false;
079
080    /**
081     * An open document: its text and its latest analysis.
082     */
083    private record Document(String uri, String path, String text, Analysis analysis, Index known) {
084
085        Document(String uri, String path, String text) {
086            this(uri, path, text, null, null);
087        }
088    }
089
090    /**
091     * @param exit what {@code exit} does with the exit code, e.g.,
092     * {@code System::exit}
093     */
094    public ClaferLanguageServer(IntConsumer exit) {
095        this.exit = exit;
096    }
097
098    @Override
099    public void connect(LanguageClient client) {
100        this.client = client;
101    }
102
103    @Override
104    public CompletableFuture<InitializeResult> initialize(InitializeParams params) {
105        ServerCapabilities capabilities = new ServerCapabilities();
106        capabilities.setTextDocumentSync(TextDocumentSyncKind.Full);
107        capabilities.setDocumentSymbolProvider(true);
108        capabilities.setDefinitionProvider(true);
109        capabilities.setHoverProvider(true);
110        capabilities.setReferencesProvider(true);
111        capabilities.setCompletionProvider(new CompletionOptions(false, List.of(".")));
112        capabilities.setRenameProvider(new RenameOptions(true));
113        return CompletableFuture.completedFuture(
114                new InitializeResult(capabilities, new ServerInfo("clafer-ls", Main.number())));
115    }
116
117    @Override
118    public CompletableFuture<Object> shutdown() {
119        shutdown = true;
120        return CompletableFuture.completedFuture(null);
121    }
122
123    @Override
124    public void exit() {
125        exit.accept(shutdown ? 0 : 1);
126    }
127
128    @Override
129    public TextDocumentService getTextDocumentService() {
130        return textDocuments;
131    }
132
133    @Override
134    public WorkspaceService getWorkspaceService() {
135        return workspace;
136    }
137
138    private final TextDocumentService textDocuments = new TextDocumentService() {
139
140        @Override
141        public void didOpen(DidOpenTextDocumentParams params) {
142            String uri = params.getTextDocument().getUri();
143            documents.put(uri, new Document(uri, path(uri), params.getTextDocument().getText()));
144            analyzeAll();
145        }
146
147        @Override
148        public void didChange(DidChangeTextDocumentParams params) {
149            String uri = params.getTextDocument().getUri();
150            Document d = documents.get(uri);
151            if (d == null) {
152                return;
153            }
154            String text = d.text();
155            // full sync: the last change is the whole text
156            for (TextDocumentContentChangeEvent change : params.getContentChanges()) {
157                if (change.getRange() == null) {
158                    text = change.getText();
159                }
160            }
161            documents.put(uri, new Document(uri, d.path(), text, null, d.known()));
162            analyzeAll();
163        }
164
165        @Override
166        public void didClose(DidCloseTextDocumentParams params) {
167            String uri = params.getTextDocument().getUri();
168            if (documents.remove(uri) != null) {
169                publish(uri, List.of());
170                analyzeAll();
171            }
172        }
173
174        @Override
175        public void didSave(DidSaveTextDocumentParams params) {
176        }
177
178        @Override
179        public CompletableFuture<List<Either<SymbolInformation, DocumentSymbol>>> documentSymbol(
180                DocumentSymbolParams params) {
181            Document d = documents.get(params.getTextDocument().getUri());
182            List<Either<SymbolInformation, DocumentSymbol>> symbols = d == null ? List.of()
183                    : d.analysis().outline().stream().map(Either::<SymbolInformation, DocumentSymbol>forRight)
184                            .toList();
185            return CompletableFuture.completedFuture(symbols);
186        }
187
188        @Override
189        public CompletableFuture<Either<List<? extends Location>, List<? extends LocationLink>>> definition(
190                DefinitionParams params) {
191            List<Location> found = index(params.getTextDocument().getUri())
192                    .flatMap(i -> i.definition(params.getPosition())).map(List::of).orElse(List.of());
193            return CompletableFuture.completedFuture(Either.forLeft(found));
194        }
195
196        @Override
197        public CompletableFuture<List<? extends Location>> references(ReferenceParams params) {
198            boolean withDeclaration = params.getContext() == null || params.getContext().isIncludeDeclaration();
199            Optional<Index> index = index(params.getTextDocument().getUri());
200            Optional<Location> declaration = index.flatMap(i -> i.definition(params.getPosition()));
201            List<Location> found = declaration.map(d -> everywhere(d, withDeclaration))
202                    .orElse(index.map(i -> i.references(params.getPosition(), withDeclaration)).orElse(List.of()));
203            return CompletableFuture.completedFuture(found);
204        }
205
206        @Override
207        public CompletableFuture<Hover> hover(HoverParams params) {
208            Optional<Index> index = index(params.getTextDocument().getUri());
209            Hover hover = index.flatMap(i -> i.hover(params.getPosition()).map(text -> {
210                Hover h = new Hover(new MarkupContent(MarkupKind.MARKDOWN, text));
211                i.rangeAt(params.getPosition()).ifPresent(h::setRange);
212                return h;
213            })).orElse(null);
214            return CompletableFuture.completedFuture(hover);
215        }
216
217        @Override
218        public CompletableFuture<Either<List<CompletionItem>, CompletionList>> completion(CompletionParams params) {
219            Document d = documents.get(params.getTextDocument().getUri());
220            List<CompletionItem> items = new ArrayList<>();
221            if (d != null && d.analysis() != null) {
222                for (Index.Completion c : d.analysis().index().completion(params.getPosition(), d.known())) {
223                    CompletionItem item = new CompletionItem(c.label());
224                    item.setKind(c.kind());
225                    item.setDetail(c.detail());
226                    item.setSortText(c.rank() + c.label());
227                    items.add(item);
228                }
229            }
230            return CompletableFuture.completedFuture(Either.forLeft(items));
231        }
232
233        @Override
234        public CompletableFuture<Either3<Range, PrepareRenameResult, PrepareRenameDefaultBehavior>> prepareRename(
235                PrepareRenameParams params) {
236            Optional<Index> index = index(params.getTextDocument().getUri());
237            Position p = params.getPosition();
238            if (index.isEmpty() || index.get().renameTarget(p).isEmpty()) {
239                return CompletableFuture.completedFuture(null);
240            }
241            Range range = index.get().rangeAt(p).orElseThrow();
242            return CompletableFuture.completedFuture(
243                    Either3.forSecond(new PrepareRenameResult(range, index.get().nameAt(p).orElse(""))));
244        }
245
246        @Override
247        public CompletableFuture<WorkspaceEdit> rename(RenameParams params) {
248            try {
249                return CompletableFuture.completedFuture(renameAt(params.getTextDocument().getUri(),
250                        params.getPosition(), params.getNewName()));
251            } catch (ResponseErrorException e) {
252                return CompletableFuture.failedFuture(e);
253            }
254        }
255    };
256
257    private final WorkspaceService workspace = new WorkspaceService() {
258
259        @Override
260        public void didChangeConfiguration(DidChangeConfigurationParams params) {
261        }
262
263        @Override
264        public void didChangeWatchedFiles(DidChangeWatchedFilesParams params) {
265            // an imported file changed on disk
266            analyzeAll();
267        }
268    };
269
270    /**
271     * @return every name in the models of the open documents that refers to
272     * what is declared at a location, each once, the model of each document
273     * in its order
274     */
275    private List<Location> everywhere(Location declaration, boolean withDeclaration) {
276        List<Location> all = new ArrayList<>();
277        for (Document d : documents.values()) {
278            if (d.analysis() == null) {
279                continue;
280            }
281            for (Location l : d.analysis().index().occurrencesOf(declaration, withDeclaration)) {
282                if (all.stream().noneMatch(x -> Index.sameLocation(x, l))) {
283                    all.add(l);
284                }
285            }
286        }
287        return all;
288    }
289
290    /**
291     * The edits that rename a clafer or a local, in every file of the models
292     * of the open documents.
293     */
294    private WorkspaceEdit renameAt(String uri, Position position, String newName) {
295        Index index = index(uri).orElseThrow(() -> refused("The document is not open"));
296        Location declaration = index.renameTarget(position)
297                .orElseThrow(() -> refused("Only the names of clafers and of locals can be renamed"));
298        if (!Names.isClaferName(newName)) {
299            throw refused("'" + newName + "' cannot be the name of a clafer or a local");
300        }
301        if (!index.isLocalAt(position)) {
302            for (Document d : documents.values()) {
303                if (d.analysis() != null && d.analysis().index().occurrencesOf(declaration, true).size() > 0
304                        && !d.analysis().diagnostics().isEmpty()) {
305                    throw refused("Fix the errors of " + d.uri() + " first: the names of a model with errors are"
306                            + " not all known");
307                }
308            }
309        }
310        if (index.nameTaken(position, newName)) {
311            throw refused("The name '" + newName + "' is taken: renaming to it could change what names mean");
312        }
313        Map<String, List<TextEdit>> changes = new LinkedHashMap<>();
314        List<Location> all = new ArrayList<>();
315        for (Document d : documents.values()) {
316            if (d.analysis() != null) {
317                for (Location l : d.analysis().index().renameOccurrences(declaration)) {
318                    if (all.stream().noneMatch(x -> Index.sameLocation(x, l))) {
319                        all.add(l);
320                    }
321                }
322            }
323        }
324        for (Location l : all) {
325            changes.computeIfAbsent(l.getUri(), k -> new ArrayList<>()).add(new TextEdit(l.getRange(), newName));
326        }
327        return new WorkspaceEdit(changes);
328    }
329
330    private static ResponseErrorException refused(String message) {
331        return new ResponseErrorException(new ResponseError(ResponseErrorCode.InvalidParams, message, null));
332    }
333
334    private Optional<Index> index(String uri) {
335        Document d = documents.get(uri);
336        return d == null || d.analysis() == null ? Optional.empty() : Optional.of(d.analysis().index());
337    }
338
339    /**
340     * Analyzes every open document again, and publishes its diagnostics.
341     */
342    private void analyzeAll() {
343        for (Document d : List.copyOf(documents.values())) {
344            Analysis a = Analysis.of(d.uri(), d.path(), d.text(), this::openText);
345            // the latest index whose model had its clafers, for completion while the model is broken
346            Index known = a.index().hasClafers() || d.known() == null ? a.index() : d.known();
347            documents.put(d.uri(), new Document(d.uri(), d.path(), d.text(), a, known));
348            publish(d.uri(), a.diagnostics());
349        }
350    }
351
352    private void publish(String uri, List<org.eclipse.lsp4j.Diagnostic> diagnostics) {
353        if (client != null) {
354            client.publishDiagnostics(new PublishDiagnosticsParams(uri, diagnostics));
355        }
356    }
357
358    /**
359     * @param path a file, as a model names it
360     * @return the text of its open document, if it is open
361     */
362    private Optional<String> openText(String path) {
363        String key = key(path);
364        for (Document d : documents.values()) {
365            if (d.path().equals(key)) {
366                return Optional.of(d.text());
367            }
368        }
369        return Optional.empty();
370    }
371
372    /**
373     * @param uri a document's URI
374     * @return its file, absolute and normalized, or the URI itself if it is
375     * not a file (an unsaved document)
376     */
377    static String path(String uri) {
378        try {
379            URI u = URI.create(uri);
380            if ("file".equals(u.getScheme())) {
381                return Path.of(u).toAbsolutePath().normalize().toString();
382            }
383        } catch (IllegalArgumentException | java.nio.file.FileSystemNotFoundException e) {
384            // not a file
385        }
386        return uri;
387    }
388
389    private static String key(String path) {
390        try {
391            return Path.of(path).toAbsolutePath().normalize().toString();
392        } catch (java.nio.file.InvalidPathException e) {
393            return path;
394        }
395    }
396}