Ilya Biryukov | 38d7977 | 2017-05-16 09:38:59 +0000 | [diff] [blame] | 1 | //===--- ClangdLSPServer.cpp - LSP server ------------------------*- C++-*-===// |
| 2 | // |
Chandler Carruth | 2946cd7 | 2019-01-19 08:50:56 +0000 | [diff] [blame] | 3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 4 | // See https://llvm.org/LICENSE.txt for license information. |
| 5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
Ilya Biryukov | 38d7977 | 2017-05-16 09:38:59 +0000 | [diff] [blame] | 6 | // |
Kirill Bobyrev | 8e35f1e | 2018-08-14 16:03:32 +0000 | [diff] [blame] | 7 | //===----------------------------------------------------------------------===// |
Ilya Biryukov | 38d7977 | 2017-05-16 09:38:59 +0000 | [diff] [blame] | 8 | |
| 9 | #include "ClangdLSPServer.h" |
Kadir Cetinkaya | 35871fd | 2020-09-28 15:09:55 +0200 | [diff] [blame] | 10 | #include "ClangdServer.h" |
Sam McCall | 032727f | 2020-05-06 01:39:59 +0200 | [diff] [blame] | 11 | #include "CodeComplete.h" |
Ilya Biryukov | 71028b8 | 2018-03-12 15:28:22 +0000 | [diff] [blame] | 12 | #include "Diagnostics.h" |
Kadir Cetinkaya | 5b27093 | 2019-09-09 12:28:44 +0000 | [diff] [blame] | 13 | #include "DraftStore.h" |
Sam McCall | 8adc4d1 | 2020-10-16 20:03:48 +0200 | [diff] [blame] | 14 | #include "DumpAST.h" |
Kadir Cetinkaya | 256247c | 2019-06-26 07:45:27 +0000 | [diff] [blame] | 15 | #include "GlobalCompilationDatabase.h" |
Ilya Biryukov | cce67a3 | 2019-01-29 14:17:36 +0000 | [diff] [blame] | 16 | #include "Protocol.h" |
Johan Vikstrom | a848dab | 2019-07-04 07:53:12 +0000 | [diff] [blame] | 17 | #include "SemanticHighlighting.h" |
Sam McCall | b536a2a | 2017-12-19 12:23:48 +0000 | [diff] [blame] | 18 | #include "SourceCode.h" |
Kadir Cetinkaya | 6b85032 | 2020-03-17 19:08:23 +0100 | [diff] [blame] | 19 | #include "TUScheduler.h" |
Eric Liu | 78ed91a7 | 2018-01-29 15:37:46 +0000 | [diff] [blame] | 20 | #include "URI.h" |
Sam McCall | 395fde7 | 2019-06-18 13:37:54 +0000 | [diff] [blame] | 21 | #include "refactor/Tweak.h" |
Sam McCall | ad97ccf | 2020-04-28 17:49:17 +0200 | [diff] [blame] | 22 | #include "support/Context.h" |
Kadir Cetinkaya | 35871fd | 2020-09-28 15:09:55 +0200 | [diff] [blame] | 23 | #include "support/MemoryTree.h" |
Sam McCall | ad97ccf | 2020-04-28 17:49:17 +0200 | [diff] [blame] | 24 | #include "support/Trace.h" |
Sam McCall | 8adc4d1 | 2020-10-16 20:03:48 +0200 | [diff] [blame] | 25 | #include "clang/AST/ASTContext.h" |
Sam McCall | 6f7dca9 | 2020-03-03 12:25:46 +0100 | [diff] [blame] | 26 | #include "clang/Basic/Version.h" |
Ilya Biryukov | cce67a3 | 2019-01-29 14:17:36 +0000 | [diff] [blame] | 27 | #include "clang/Tooling/Core/Replacement.h" |
Kadir Cetinkaya | 256247c | 2019-06-26 07:45:27 +0000 | [diff] [blame] | 28 | #include "llvm/ADT/ArrayRef.h" |
Sam McCall | a69698f | 2019-03-27 17:47:49 +0000 | [diff] [blame] | 29 | #include "llvm/ADT/Optional.h" |
Kadir Cetinkaya | 689bf93 | 2018-08-24 13:09:41 +0000 | [diff] [blame] | 30 | #include "llvm/ADT/ScopeExit.h" |
Kadir Cetinkaya | 5b27093 | 2019-09-09 12:28:44 +0000 | [diff] [blame] | 31 | #include "llvm/ADT/StringRef.h" |
Utkarsh Saxena | 55925da | 2019-09-24 13:38:33 +0000 | [diff] [blame] | 32 | #include "llvm/ADT/iterator_range.h" |
Kadir Cetinkaya | 35871fd | 2020-09-28 15:09:55 +0200 | [diff] [blame] | 33 | #include "llvm/Support/Allocator.h" |
Simon Marchi | 9569fd5 | 2018-03-16 14:30:42 +0000 | [diff] [blame] | 34 | #include "llvm/Support/Errc.h" |
Ilya Biryukov | cce67a3 | 2019-01-29 14:17:36 +0000 | [diff] [blame] | 35 | #include "llvm/Support/Error.h" |
Marc-Andre Laperle | e7ec16a | 2017-11-03 13:39:15 +0000 | [diff] [blame] | 36 | #include "llvm/Support/FormatVariadic.h" |
Utkarsh Saxena | 55925da | 2019-09-24 13:38:33 +0000 | [diff] [blame] | 37 | #include "llvm/Support/JSON.h" |
Eric Liu | 5740ff5 | 2018-01-31 16:26:27 +0000 | [diff] [blame] | 38 | #include "llvm/Support/Path.h" |
Kadir Cetinkaya | 5b27093 | 2019-09-09 12:28:44 +0000 | [diff] [blame] | 39 | #include "llvm/Support/SHA1.h" |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 40 | #include "llvm/Support/ScopedPrinter.h" |
Kadir Cetinkaya | d0f2874 | 2020-10-13 00:10:04 +0200 | [diff] [blame] | 41 | #include "llvm/Support/raw_ostream.h" |
Kadir Cetinkaya | 35871fd | 2020-09-28 15:09:55 +0200 | [diff] [blame] | 42 | #include <chrono> |
Kadir Cetinkaya | 5b27093 | 2019-09-09 12:28:44 +0000 | [diff] [blame] | 43 | #include <cstddef> |
Kadir Cetinkaya | d0f2874 | 2020-10-13 00:10:04 +0200 | [diff] [blame] | 44 | #include <cstdint> |
| 45 | #include <functional> |
Utkarsh Saxena | 55925da | 2019-09-24 13:38:33 +0000 | [diff] [blame] | 46 | #include <memory> |
Sam McCall | 7d20e80 | 2020-01-22 19:41:45 +0100 | [diff] [blame] | 47 | #include <mutex> |
Kadir Cetinkaya | 5b27093 | 2019-09-09 12:28:44 +0000 | [diff] [blame] | 48 | #include <string> |
Utkarsh Saxena | 55925da | 2019-09-24 13:38:33 +0000 | [diff] [blame] | 49 | #include <vector> |
Marc-Andre Laperle | e7ec16a | 2017-11-03 13:39:15 +0000 | [diff] [blame] | 50 | |
Sam McCall | c008af6 | 2018-10-20 15:30:37 +0000 | [diff] [blame] | 51 | namespace clang { |
| 52 | namespace clangd { |
Ilya Biryukov | afb5554 | 2017-05-16 14:40:30 +0000 | [diff] [blame] | 53 | namespace { |
Sam McCall | 2cd33e6 | 2020-03-04 00:33:29 +0100 | [diff] [blame] | 54 | |
Kadir Cetinkaya | e64f99c | 2020-04-16 23:12:09 +0200 | [diff] [blame] | 55 | // Tracks end-to-end latency of high level lsp calls. Measurements are in |
| 56 | // seconds. |
| 57 | constexpr trace::Metric LSPLatency("lsp_latency", trace::Metric::Distribution, |
| 58 | "method_name"); |
| 59 | |
Sam McCall | 2cd33e6 | 2020-03-04 00:33:29 +0100 | [diff] [blame] | 60 | // LSP defines file versions as numbers that increase. |
| 61 | // ClangdServer treats them as opaque and therefore uses strings instead. |
| 62 | std::string encodeVersion(int64_t LSPVersion) { |
| 63 | return llvm::to_string(LSPVersion); |
| 64 | } |
| 65 | llvm::Optional<int64_t> decodeVersion(llvm::StringRef Encoded) { |
| 66 | int64_t Result; |
| 67 | if (llvm::to_integer(Encoded, Result, 10)) |
| 68 | return Result; |
Kadir Cetinkaya | bceca7a | 2020-09-11 11:30:06 +0200 | [diff] [blame] | 69 | if (!Encoded.empty()) // Empty can be e.g. diagnostics on close. |
Sam McCall | 2cd33e6 | 2020-03-04 00:33:29 +0100 | [diff] [blame] | 70 | elog("unexpected non-numeric version {0}", Encoded); |
| 71 | return llvm::None; |
| 72 | } |
| 73 | |
Ilya Biryukov | cce67a3 | 2019-01-29 14:17:36 +0000 | [diff] [blame] | 74 | /// Transforms a tweak into a code action that would apply it if executed. |
| 75 | /// EXPECTS: T.prepare() was called and returned true. |
| 76 | CodeAction toCodeAction(const ClangdServer::TweakRef &T, const URIForFile &File, |
| 77 | Range Selection) { |
| 78 | CodeAction CA; |
| 79 | CA.title = T.Title; |
Sam McCall | 17747d2 | 2020-09-28 18:12:37 +0200 | [diff] [blame] | 80 | CA.kind = T.Kind.str(); |
Ilya Biryukov | cce67a3 | 2019-01-29 14:17:36 +0000 | [diff] [blame] | 81 | // This tweak may have an expensive second stage, we only run it if the user |
| 82 | // actually chooses it in the UI. We reply with a command that would run the |
| 83 | // corresponding tweak. |
| 84 | // FIXME: for some tweaks, computing the edits is cheap and we could send them |
| 85 | // directly. |
| 86 | CA.command.emplace(); |
| 87 | CA.command->title = T.Title; |
Benjamin Kramer | adcd026 | 2020-01-28 20:23:46 +0100 | [diff] [blame] | 88 | CA.command->command = std::string(Command::CLANGD_APPLY_TWEAK); |
Ilya Biryukov | cce67a3 | 2019-01-29 14:17:36 +0000 | [diff] [blame] | 89 | CA.command->tweakArgs.emplace(); |
| 90 | CA.command->tweakArgs->file = File; |
| 91 | CA.command->tweakArgs->tweakID = T.ID; |
| 92 | CA.command->tweakArgs->selection = Selection; |
| 93 | return CA; |
Simon Pilgrim | e9a136b | 2019-02-03 14:08:30 +0000 | [diff] [blame] | 94 | } |
Ilya Biryukov | cce67a3 | 2019-01-29 14:17:36 +0000 | [diff] [blame] | 95 | |
Ilya Biryukov | 19d7560 | 2018-11-23 15:21:19 +0000 | [diff] [blame] | 96 | void adjustSymbolKinds(llvm::MutableArrayRef<DocumentSymbol> Syms, |
| 97 | SymbolKindBitset Kinds) { |
| 98 | for (auto &S : Syms) { |
| 99 | S.kind = adjustKindToCapability(S.kind, Kinds); |
| 100 | adjustSymbolKinds(S.children, Kinds); |
| 101 | } |
| 102 | } |
| 103 | |
Marc-Andre Laperle | b387b6e | 2018-04-23 20:00:52 +0000 | [diff] [blame] | 104 | SymbolKindBitset defaultSymbolKinds() { |
| 105 | SymbolKindBitset Defaults; |
| 106 | for (size_t I = SymbolKindMin; I <= static_cast<size_t>(SymbolKind::Array); |
| 107 | ++I) |
| 108 | Defaults.set(I); |
| 109 | return Defaults; |
| 110 | } |
| 111 | |
Kadir Cetinkaya | 133d46f | 2018-09-27 17:13:07 +0000 | [diff] [blame] | 112 | CompletionItemKindBitset defaultCompletionItemKinds() { |
| 113 | CompletionItemKindBitset Defaults; |
| 114 | for (size_t I = CompletionItemKindMin; |
| 115 | I <= static_cast<size_t>(CompletionItemKind::Reference); ++I) |
| 116 | Defaults.set(I); |
| 117 | return Defaults; |
| 118 | } |
| 119 | |
Haojian Wu | 1ca2ee4 | 2019-07-04 12:27:21 +0000 | [diff] [blame] | 120 | // Build a lookup table (HighlightingKind => {TextMate Scopes}), which is sent |
| 121 | // to the LSP client. |
| 122 | std::vector<std::vector<std::string>> buildHighlightScopeLookupTable() { |
| 123 | std::vector<std::vector<std::string>> LookupTable; |
| 124 | // HighlightingKind is using as the index. |
Ilya Biryukov | 63d5d16 | 2019-09-09 08:57:17 +0000 | [diff] [blame] | 125 | for (int KindValue = 0; KindValue <= (int)HighlightingKind::LastKind; |
Haojian Wu | 1ca2ee4 | 2019-07-04 12:27:21 +0000 | [diff] [blame] | 126 | ++KindValue) |
Benjamin Kramer | adcd026 | 2020-01-28 20:23:46 +0100 | [diff] [blame] | 127 | LookupTable.push_back( |
| 128 | {std::string(toTextMateScope((HighlightingKind)(KindValue)))}); |
Haojian Wu | 1ca2ee4 | 2019-07-04 12:27:21 +0000 | [diff] [blame] | 129 | return LookupTable; |
| 130 | } |
| 131 | |
Haojian Wu | 852bafa | 2019-10-23 14:40:20 +0200 | [diff] [blame] | 132 | // Makes sure edits in \p FE are applicable to latest file contents reported by |
Kadir Cetinkaya | 5b27093 | 2019-09-09 12:28:44 +0000 | [diff] [blame] | 133 | // editor. If not generates an error message containing information about files |
| 134 | // that needs to be saved. |
Haojian Wu | 852bafa | 2019-10-23 14:40:20 +0200 | [diff] [blame] | 135 | llvm::Error validateEdits(const DraftStore &DraftMgr, const FileEdits &FE) { |
Kadir Cetinkaya | 5b27093 | 2019-09-09 12:28:44 +0000 | [diff] [blame] | 136 | size_t InvalidFileCount = 0; |
| 137 | llvm::StringRef LastInvalidFile; |
Haojian Wu | 852bafa | 2019-10-23 14:40:20 +0200 | [diff] [blame] | 138 | for (const auto &It : FE) { |
Kadir Cetinkaya | 5b27093 | 2019-09-09 12:28:44 +0000 | [diff] [blame] | 139 | if (auto Draft = DraftMgr.getDraft(It.first())) { |
| 140 | // If the file is open in user's editor, make sure the version we |
| 141 | // saw and current version are compatible as this is the text that |
| 142 | // will be replaced by editors. |
Sam McCall | caf5a4d | 2020-03-03 15:57:39 +0100 | [diff] [blame] | 143 | if (!It.second.canApplyTo(Draft->Contents)) { |
Kadir Cetinkaya | 5b27093 | 2019-09-09 12:28:44 +0000 | [diff] [blame] | 144 | ++InvalidFileCount; |
| 145 | LastInvalidFile = It.first(); |
| 146 | } |
| 147 | } |
| 148 | } |
| 149 | if (!InvalidFileCount) |
| 150 | return llvm::Error::success(); |
| 151 | if (InvalidFileCount == 1) |
Sam McCall | 30667c9 | 2020-07-08 21:49:38 +0200 | [diff] [blame] | 152 | return error("File must be saved first: {0}", LastInvalidFile); |
| 153 | return error("Files must be saved first: {0} (and {1} others)", |
| 154 | LastInvalidFile, InvalidFileCount - 1); |
Kadir Cetinkaya | 5b27093 | 2019-09-09 12:28:44 +0000 | [diff] [blame] | 155 | } |
Ilya Biryukov | afb5554 | 2017-05-16 14:40:30 +0000 | [diff] [blame] | 156 | } // namespace |
| 157 | |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 158 | // MessageHandler dispatches incoming LSP messages. |
| 159 | // It handles cross-cutting concerns: |
| 160 | // - serializes/deserializes protocol objects to JSON |
| 161 | // - logging of inbound messages |
| 162 | // - cancellation handling |
| 163 | // - basic call tracing |
Sam McCall | 3d0adbe | 2018-10-18 14:41:50 +0000 | [diff] [blame] | 164 | // MessageHandler ensures that initialize() is called before any other handler. |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 165 | class ClangdLSPServer::MessageHandler : public Transport::MessageHandler { |
| 166 | public: |
| 167 | MessageHandler(ClangdLSPServer &Server) : Server(Server) {} |
| 168 | |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 169 | bool onNotify(llvm::StringRef Method, llvm::json::Value Params) override { |
Sam McCall | a69698f | 2019-03-27 17:47:49 +0000 | [diff] [blame] | 170 | WithContext HandlerContext(handlerContext()); |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 171 | log("<-- {0}", Method); |
| 172 | if (Method == "exit") |
| 173 | return false; |
Kadir Cetinkaya | 35871fd | 2020-09-28 15:09:55 +0200 | [diff] [blame] | 174 | if (!Server.Server) { |
Sam McCall | 3d0adbe | 2018-10-18 14:41:50 +0000 | [diff] [blame] | 175 | elog("Notification {0} before initialization", Method); |
Kadir Cetinkaya | 35871fd | 2020-09-28 15:09:55 +0200 | [diff] [blame] | 176 | } else if (Method == "$/cancelRequest") { |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 177 | onCancel(std::move(Params)); |
Kadir Cetinkaya | 35871fd | 2020-09-28 15:09:55 +0200 | [diff] [blame] | 178 | } else if (auto Handler = Notifications.lookup(Method)) { |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 179 | Handler(std::move(Params)); |
Kadir Cetinkaya | 35871fd | 2020-09-28 15:09:55 +0200 | [diff] [blame] | 180 | Server.maybeExportMemoryProfile(); |
| 181 | } else { |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 182 | log("unhandled notification {0}", Method); |
Kadir Cetinkaya | 35871fd | 2020-09-28 15:09:55 +0200 | [diff] [blame] | 183 | } |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 184 | return true; |
| 185 | } |
| 186 | |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 187 | bool onCall(llvm::StringRef Method, llvm::json::Value Params, |
| 188 | llvm::json::Value ID) override { |
Sam McCall | a69698f | 2019-03-27 17:47:49 +0000 | [diff] [blame] | 189 | WithContext HandlerContext(handlerContext()); |
Sam McCall | e2f3a73 | 2018-10-24 14:26:26 +0000 | [diff] [blame] | 190 | // Calls can be canceled by the client. Add cancellation context. |
| 191 | WithContext WithCancel(cancelableRequestContext(ID)); |
Kadir Cetinkaya | e64f99c | 2020-04-16 23:12:09 +0200 | [diff] [blame] | 192 | trace::Span Tracer(Method, LSPLatency); |
Sam McCall | e2f3a73 | 2018-10-24 14:26:26 +0000 | [diff] [blame] | 193 | SPAN_ATTACH(Tracer, "Params", Params); |
| 194 | ReplyOnce Reply(ID, Method, &Server, Tracer.Args); |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 195 | log("<-- {0}({1})", Method, ID); |
Sam McCall | 3d0adbe | 2018-10-18 14:41:50 +0000 | [diff] [blame] | 196 | if (!Server.Server && Method != "initialize") { |
| 197 | elog("Call {0} before initialization.", Method); |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 198 | Reply(llvm::make_error<LSPError>("server not initialized", |
| 199 | ErrorCode::ServerNotInitialized)); |
Sam McCall | 3d0adbe | 2018-10-18 14:41:50 +0000 | [diff] [blame] | 200 | } else if (auto Handler = Calls.lookup(Method)) |
Sam McCall | e2f3a73 | 2018-10-24 14:26:26 +0000 | [diff] [blame] | 201 | Handler(std::move(Params), std::move(Reply)); |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 202 | else |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 203 | Reply(llvm::make_error<LSPError>("method not found", |
| 204 | ErrorCode::MethodNotFound)); |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 205 | return true; |
| 206 | } |
| 207 | |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 208 | bool onReply(llvm::json::Value ID, |
| 209 | llvm::Expected<llvm::json::Value> Result) override { |
Sam McCall | a69698f | 2019-03-27 17:47:49 +0000 | [diff] [blame] | 210 | WithContext HandlerContext(handlerContext()); |
Haojian Wu | f251634 | 2019-08-05 12:48:09 +0000 | [diff] [blame] | 211 | |
| 212 | Callback<llvm::json::Value> ReplyHandler = nullptr; |
| 213 | if (auto IntID = ID.getAsInteger()) { |
| 214 | std::lock_guard<std::mutex> Mutex(CallMutex); |
| 215 | // Find a corresponding callback for the request ID; |
| 216 | for (size_t Index = 0; Index < ReplyCallbacks.size(); ++Index) { |
| 217 | if (ReplyCallbacks[Index].first == *IntID) { |
| 218 | ReplyHandler = std::move(ReplyCallbacks[Index].second); |
| 219 | ReplyCallbacks.erase(ReplyCallbacks.begin() + |
| 220 | Index); // remove the entry |
| 221 | break; |
| 222 | } |
| 223 | } |
| 224 | } |
| 225 | |
| 226 | if (!ReplyHandler) { |
| 227 | // No callback being found, use a default log callback. |
| 228 | ReplyHandler = [&ID](llvm::Expected<llvm::json::Value> Result) { |
| 229 | elog("received a reply with ID {0}, but there was no such call", ID); |
| 230 | if (!Result) |
| 231 | llvm::consumeError(Result.takeError()); |
| 232 | }; |
| 233 | } |
| 234 | |
| 235 | // Log and run the reply handler. |
| 236 | if (Result) { |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 237 | log("<-- reply({0})", ID); |
Haojian Wu | f251634 | 2019-08-05 12:48:09 +0000 | [diff] [blame] | 238 | ReplyHandler(std::move(Result)); |
| 239 | } else { |
| 240 | auto Err = Result.takeError(); |
| 241 | log("<-- reply({0}) error: {1}", ID, Err); |
| 242 | ReplyHandler(std::move(Err)); |
| 243 | } |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 244 | return true; |
| 245 | } |
| 246 | |
| 247 | // Bind an LSP method name to a call. |
Sam McCall | e2f3a73 | 2018-10-24 14:26:26 +0000 | [diff] [blame] | 248 | template <typename Param, typename Result> |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 249 | void bind(const char *Method, |
Sam McCall | e2f3a73 | 2018-10-24 14:26:26 +0000 | [diff] [blame] | 250 | void (ClangdLSPServer::*Handler)(const Param &, Callback<Result>)) { |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 251 | Calls[Method] = [Method, Handler, this](llvm::json::Value RawParams, |
Sam McCall | e2f3a73 | 2018-10-24 14:26:26 +0000 | [diff] [blame] | 252 | ReplyOnce Reply) { |
Sam McCall | fa69b60 | 2020-09-24 01:14:12 +0200 | [diff] [blame] | 253 | auto P = parse<Param>(RawParams, Method, "request"); |
| 254 | if (!P) |
| 255 | return Reply(P.takeError()); |
| 256 | (Server.*Handler)(*P, std::move(Reply)); |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 257 | }; |
| 258 | } |
| 259 | |
Haojian Wu | f251634 | 2019-08-05 12:48:09 +0000 | [diff] [blame] | 260 | // Bind a reply callback to a request. The callback will be invoked when |
| 261 | // clangd receives the reply from the LSP client. |
| 262 | // Return a call id of the request. |
| 263 | llvm::json::Value bindReply(Callback<llvm::json::Value> Reply) { |
| 264 | llvm::Optional<std::pair<int, Callback<llvm::json::Value>>> OldestCB; |
| 265 | int ID; |
| 266 | { |
| 267 | std::lock_guard<std::mutex> Mutex(CallMutex); |
| 268 | ID = NextCallID++; |
| 269 | ReplyCallbacks.emplace_back(ID, std::move(Reply)); |
| 270 | |
| 271 | // If the queue overflows, we assume that the client didn't reply the |
| 272 | // oldest request, and run the corresponding callback which replies an |
| 273 | // error to the client. |
| 274 | if (ReplyCallbacks.size() > MaxReplayCallbacks) { |
| 275 | elog("more than {0} outstanding LSP calls, forgetting about {1}", |
| 276 | MaxReplayCallbacks, ReplyCallbacks.front().first); |
| 277 | OldestCB = std::move(ReplyCallbacks.front()); |
| 278 | ReplyCallbacks.pop_front(); |
| 279 | } |
| 280 | } |
| 281 | if (OldestCB) |
Sam McCall | 30667c9 | 2020-07-08 21:49:38 +0200 | [diff] [blame] | 282 | OldestCB->second( |
| 283 | error("failed to receive a client reply for request ({0})", |
| 284 | OldestCB->first)); |
Haojian Wu | f251634 | 2019-08-05 12:48:09 +0000 | [diff] [blame] | 285 | return ID; |
| 286 | } |
| 287 | |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 288 | // Bind an LSP method name to a notification. |
| 289 | template <typename Param> |
| 290 | void bind(const char *Method, |
| 291 | void (ClangdLSPServer::*Handler)(const Param &)) { |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 292 | Notifications[Method] = [Method, Handler, |
| 293 | this](llvm::json::Value RawParams) { |
Sam McCall | fa69b60 | 2020-09-24 01:14:12 +0200 | [diff] [blame] | 294 | llvm::Expected<Param> P = parse<Param>(RawParams, Method, "request"); |
| 295 | if (!P) |
| 296 | return llvm::consumeError(P.takeError()); |
Kadir Cetinkaya | e64f99c | 2020-04-16 23:12:09 +0200 | [diff] [blame] | 297 | trace::Span Tracer(Method, LSPLatency); |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 298 | SPAN_ATTACH(Tracer, "Params", RawParams); |
Sam McCall | fa69b60 | 2020-09-24 01:14:12 +0200 | [diff] [blame] | 299 | (Server.*Handler)(*P); |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 300 | }; |
| 301 | } |
| 302 | |
| 303 | private: |
Sam McCall | e2f3a73 | 2018-10-24 14:26:26 +0000 | [diff] [blame] | 304 | // Function object to reply to an LSP call. |
| 305 | // Each instance must be called exactly once, otherwise: |
| 306 | // - the bug is logged, and (in debug mode) an assert will fire |
| 307 | // - if there was no reply, an error reply is sent |
| 308 | // - if there were multiple replies, only the first is sent |
| 309 | class ReplyOnce { |
| 310 | std::atomic<bool> Replied = {false}; |
Sam McCall | d7babe4 | 2018-10-24 15:18:40 +0000 | [diff] [blame] | 311 | std::chrono::steady_clock::time_point Start; |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 312 | llvm::json::Value ID; |
Sam McCall | e2f3a73 | 2018-10-24 14:26:26 +0000 | [diff] [blame] | 313 | std::string Method; |
| 314 | ClangdLSPServer *Server; // Null when moved-from. |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 315 | llvm::json::Object *TraceArgs; |
Sam McCall | e2f3a73 | 2018-10-24 14:26:26 +0000 | [diff] [blame] | 316 | |
| 317 | public: |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 318 | ReplyOnce(const llvm::json::Value &ID, llvm::StringRef Method, |
| 319 | ClangdLSPServer *Server, llvm::json::Object *TraceArgs) |
Sam McCall | d7babe4 | 2018-10-24 15:18:40 +0000 | [diff] [blame] | 320 | : Start(std::chrono::steady_clock::now()), ID(ID), Method(Method), |
| 321 | Server(Server), TraceArgs(TraceArgs) { |
Sam McCall | e2f3a73 | 2018-10-24 14:26:26 +0000 | [diff] [blame] | 322 | assert(Server); |
| 323 | } |
| 324 | ReplyOnce(ReplyOnce &&Other) |
Sam McCall | d7babe4 | 2018-10-24 15:18:40 +0000 | [diff] [blame] | 325 | : Replied(Other.Replied.load()), Start(Other.Start), |
| 326 | ID(std::move(Other.ID)), Method(std::move(Other.Method)), |
| 327 | Server(Other.Server), TraceArgs(Other.TraceArgs) { |
Sam McCall | e2f3a73 | 2018-10-24 14:26:26 +0000 | [diff] [blame] | 328 | Other.Server = nullptr; |
| 329 | } |
Ilya Biryukov | 22fa465 | 2019-01-03 13:28:05 +0000 | [diff] [blame] | 330 | ReplyOnce &operator=(ReplyOnce &&) = delete; |
Sam McCall | e2f3a73 | 2018-10-24 14:26:26 +0000 | [diff] [blame] | 331 | ReplyOnce(const ReplyOnce &) = delete; |
Ilya Biryukov | 22fa465 | 2019-01-03 13:28:05 +0000 | [diff] [blame] | 332 | ReplyOnce &operator=(const ReplyOnce &) = delete; |
Sam McCall | e2f3a73 | 2018-10-24 14:26:26 +0000 | [diff] [blame] | 333 | |
| 334 | ~ReplyOnce() { |
Haojian Wu | f251634 | 2019-08-05 12:48:09 +0000 | [diff] [blame] | 335 | // There's one legitimate reason to never reply to a request: clangd's |
| 336 | // request handler send a call to the client (e.g. applyEdit) and the |
| 337 | // client never replied. In this case, the ReplyOnce is owned by |
| 338 | // ClangdLSPServer's reply callback table and is destroyed along with the |
| 339 | // server. We don't attempt to send a reply in this case, there's little |
| 340 | // to be gained from doing so. |
| 341 | if (Server && !Server->IsBeingDestroyed && !Replied) { |
Sam McCall | e2f3a73 | 2018-10-24 14:26:26 +0000 | [diff] [blame] | 342 | elog("No reply to message {0}({1})", Method, ID); |
| 343 | assert(false && "must reply to all calls!"); |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 344 | (*this)(llvm::make_error<LSPError>("server failed to reply", |
| 345 | ErrorCode::InternalError)); |
Sam McCall | e2f3a73 | 2018-10-24 14:26:26 +0000 | [diff] [blame] | 346 | } |
| 347 | } |
| 348 | |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 349 | void operator()(llvm::Expected<llvm::json::Value> Reply) { |
Sam McCall | e2f3a73 | 2018-10-24 14:26:26 +0000 | [diff] [blame] | 350 | assert(Server && "moved-from!"); |
| 351 | if (Replied.exchange(true)) { |
| 352 | elog("Replied twice to message {0}({1})", Method, ID); |
| 353 | assert(false && "must reply to each call only once!"); |
| 354 | return; |
| 355 | } |
Sam McCall | d7babe4 | 2018-10-24 15:18:40 +0000 | [diff] [blame] | 356 | auto Duration = std::chrono::steady_clock::now() - Start; |
| 357 | if (Reply) { |
| 358 | log("--> reply:{0}({1}) {2:ms}", Method, ID, Duration); |
| 359 | if (TraceArgs) |
Sam McCall | e2f3a73 | 2018-10-24 14:26:26 +0000 | [diff] [blame] | 360 | (*TraceArgs)["Reply"] = *Reply; |
Sam McCall | d7babe4 | 2018-10-24 15:18:40 +0000 | [diff] [blame] | 361 | std::lock_guard<std::mutex> Lock(Server->TranspWriter); |
| 362 | Server->Transp.reply(std::move(ID), std::move(Reply)); |
| 363 | } else { |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 364 | llvm::Error Err = Reply.takeError(); |
Sam McCall | d7babe4 | 2018-10-24 15:18:40 +0000 | [diff] [blame] | 365 | log("--> reply:{0}({1}) {2:ms}, error: {3}", Method, ID, Duration, Err); |
| 366 | if (TraceArgs) |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 367 | (*TraceArgs)["Error"] = llvm::to_string(Err); |
Sam McCall | d7babe4 | 2018-10-24 15:18:40 +0000 | [diff] [blame] | 368 | std::lock_guard<std::mutex> Lock(Server->TranspWriter); |
| 369 | Server->Transp.reply(std::move(ID), std::move(Err)); |
Sam McCall | e2f3a73 | 2018-10-24 14:26:26 +0000 | [diff] [blame] | 370 | } |
Sam McCall | e2f3a73 | 2018-10-24 14:26:26 +0000 | [diff] [blame] | 371 | } |
| 372 | }; |
| 373 | |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 374 | llvm::StringMap<std::function<void(llvm::json::Value)>> Notifications; |
| 375 | llvm::StringMap<std::function<void(llvm::json::Value, ReplyOnce)>> Calls; |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 376 | |
| 377 | // Method calls may be cancelled by ID, so keep track of their state. |
| 378 | // This needs a mutex: handlers may finish on a different thread, and that's |
| 379 | // when we clean up entries in the map. |
| 380 | mutable std::mutex RequestCancelersMutex; |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 381 | llvm::StringMap<std::pair<Canceler, /*Cookie*/ unsigned>> RequestCancelers; |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 382 | unsigned NextRequestCookie = 0; // To disambiguate reused IDs, see below. |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 383 | void onCancel(const llvm::json::Value &Params) { |
| 384 | const llvm::json::Value *ID = nullptr; |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 385 | if (auto *O = Params.getAsObject()) |
| 386 | ID = O->get("id"); |
| 387 | if (!ID) { |
| 388 | elog("Bad cancellation request: {0}", Params); |
| 389 | return; |
| 390 | } |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 391 | auto StrID = llvm::to_string(*ID); |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 392 | std::lock_guard<std::mutex> Lock(RequestCancelersMutex); |
| 393 | auto It = RequestCancelers.find(StrID); |
| 394 | if (It != RequestCancelers.end()) |
| 395 | It->second.first(); // Invoke the canceler. |
| 396 | } |
Sam McCall | a69698f | 2019-03-27 17:47:49 +0000 | [diff] [blame] | 397 | |
| 398 | Context handlerContext() const { |
| 399 | return Context::current().derive( |
| 400 | kCurrentOffsetEncoding, |
Sam McCall | 6342b38 | 2020-09-30 10:56:43 +0200 | [diff] [blame] | 401 | Server.Opts.Encoding.getValueOr(OffsetEncoding::UTF16)); |
Sam McCall | a69698f | 2019-03-27 17:47:49 +0000 | [diff] [blame] | 402 | } |
| 403 | |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 404 | // We run cancelable requests in a context that does two things: |
| 405 | // - allows cancellation using RequestCancelers[ID] |
| 406 | // - cleans up the entry in RequestCancelers when it's no longer needed |
| 407 | // If a client reuses an ID, the last wins and the first cannot be canceled. |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 408 | Context cancelableRequestContext(const llvm::json::Value &ID) { |
Sam McCall | 31db1e0 | 2020-04-11 18:19:50 +0200 | [diff] [blame] | 409 | auto Task = cancelableTask( |
| 410 | /*Reason=*/static_cast<int>(ErrorCode::RequestCancelled)); |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 411 | auto StrID = llvm::to_string(ID); // JSON-serialize ID for map key. |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 412 | auto Cookie = NextRequestCookie++; // No lock, only called on main thread. |
| 413 | { |
| 414 | std::lock_guard<std::mutex> Lock(RequestCancelersMutex); |
| 415 | RequestCancelers[StrID] = {std::move(Task.second), Cookie}; |
| 416 | } |
| 417 | // When the request ends, we can clean up the entry we just added. |
| 418 | // The cookie lets us check that it hasn't been overwritten due to ID |
| 419 | // reuse. |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 420 | return Task.first.derive(llvm::make_scope_exit([this, StrID, Cookie] { |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 421 | std::lock_guard<std::mutex> Lock(RequestCancelersMutex); |
| 422 | auto It = RequestCancelers.find(StrID); |
| 423 | if (It != RequestCancelers.end() && It->second.second == Cookie) |
| 424 | RequestCancelers.erase(It); |
| 425 | })); |
| 426 | } |
| 427 | |
Kadir Cetinkaya | 9a3a87d | 2019-10-09 13:59:31 +0000 | [diff] [blame] | 428 | // The maximum number of callbacks held in clangd. |
| 429 | // |
| 430 | // We bound the maximum size to the pending map to prevent memory leakage |
| 431 | // for cases where LSP clients don't reply for the request. |
| 432 | // This has to go after RequestCancellers and RequestCancellersMutex since it |
| 433 | // can contain a callback that has a cancelable context. |
| 434 | static constexpr int MaxReplayCallbacks = 100; |
| 435 | mutable std::mutex CallMutex; |
| 436 | int NextCallID = 0; /* GUARDED_BY(CallMutex) */ |
| 437 | std::deque<std::pair</*RequestID*/ int, |
| 438 | /*ReplyHandler*/ Callback<llvm::json::Value>>> |
| 439 | ReplyCallbacks; /* GUARDED_BY(CallMutex) */ |
| 440 | |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 441 | ClangdLSPServer &Server; |
| 442 | }; |
Haojian Wu | f251634 | 2019-08-05 12:48:09 +0000 | [diff] [blame] | 443 | constexpr int ClangdLSPServer::MessageHandler::MaxReplayCallbacks; |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 444 | |
| 445 | // call(), notify(), and reply() wrap the Transport, adding logging and locking. |
Haojian Wu | f251634 | 2019-08-05 12:48:09 +0000 | [diff] [blame] | 446 | void ClangdLSPServer::callRaw(StringRef Method, llvm::json::Value Params, |
| 447 | Callback<llvm::json::Value> CB) { |
| 448 | auto ID = MsgHandler->bindReply(std::move(CB)); |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 449 | log("--> {0}({1})", Method, ID); |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 450 | std::lock_guard<std::mutex> Lock(TranspWriter); |
| 451 | Transp.call(Method, std::move(Params), ID); |
| 452 | } |
| 453 | |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 454 | void ClangdLSPServer::notify(llvm::StringRef Method, llvm::json::Value Params) { |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 455 | log("--> {0}", Method); |
| 456 | std::lock_guard<std::mutex> Lock(TranspWriter); |
| 457 | Transp.notify(Method, std::move(Params)); |
| 458 | } |
| 459 | |
Sam McCall | 71177ac | 2020-03-24 02:24:47 +0100 | [diff] [blame] | 460 | static std::vector<llvm::StringRef> semanticTokenTypes() { |
| 461 | std::vector<llvm::StringRef> Types; |
| 462 | for (unsigned I = 0; I <= static_cast<unsigned>(HighlightingKind::LastKind); |
| 463 | ++I) |
| 464 | Types.push_back(toSemanticTokenType(static_cast<HighlightingKind>(I))); |
| 465 | return Types; |
| 466 | } |
| 467 | |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 468 | void ClangdLSPServer::onInitialize(const InitializeParams &Params, |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 469 | Callback<llvm::json::Value> Reply) { |
Sam McCall | a69698f | 2019-03-27 17:47:49 +0000 | [diff] [blame] | 470 | // Determine character encoding first as it affects constructed ClangdServer. |
Sam McCall | 6342b38 | 2020-09-30 10:56:43 +0200 | [diff] [blame] | 471 | if (Params.capabilities.offsetEncoding && !Opts.Encoding) { |
| 472 | Opts.Encoding = OffsetEncoding::UTF16; // fallback |
Sam McCall | a69698f | 2019-03-27 17:47:49 +0000 | [diff] [blame] | 473 | for (OffsetEncoding Supported : *Params.capabilities.offsetEncoding) |
| 474 | if (Supported != OffsetEncoding::UnsupportedEncoding) { |
Sam McCall | 6342b38 | 2020-09-30 10:56:43 +0200 | [diff] [blame] | 475 | Opts.Encoding = Supported; |
Sam McCall | a69698f | 2019-03-27 17:47:49 +0000 | [diff] [blame] | 476 | break; |
| 477 | } |
| 478 | } |
Sam McCall | a69698f | 2019-03-27 17:47:49 +0000 | [diff] [blame] | 479 | |
Sam McCall | 7ba0779 | 2020-09-29 10:37:46 +0200 | [diff] [blame] | 480 | Opts.TheiaSemanticHighlighting = |
Sam McCall | edf6a19 | 2020-03-24 00:31:14 +0100 | [diff] [blame] | 481 | Params.capabilities.TheiaSemanticHighlighting; |
Sam McCall | fc83010 | 2020-04-01 12:02:28 +0200 | [diff] [blame] | 482 | if (Params.capabilities.TheiaSemanticHighlighting && |
| 483 | Params.capabilities.SemanticTokens) { |
| 484 | log("Client supports legacy semanticHighlights notification and standard " |
| 485 | "semanticTokens request, choosing the latter (no notifications)."); |
Sam McCall | 7ba0779 | 2020-09-29 10:37:46 +0200 | [diff] [blame] | 486 | Opts.TheiaSemanticHighlighting = false; |
Sam McCall | fc83010 | 2020-04-01 12:02:28 +0200 | [diff] [blame] | 487 | } |
| 488 | |
Sam McCall | 0d9b40f | 2018-10-19 15:42:23 +0000 | [diff] [blame] | 489 | if (Params.rootUri && *Params.rootUri) |
Sam McCall | 7ba0779 | 2020-09-29 10:37:46 +0200 | [diff] [blame] | 490 | Opts.WorkspaceRoot = std::string(Params.rootUri->file()); |
Sam McCall | 0d9b40f | 2018-10-19 15:42:23 +0000 | [diff] [blame] | 491 | else if (Params.rootPath && !Params.rootPath->empty()) |
Sam McCall | 7ba0779 | 2020-09-29 10:37:46 +0200 | [diff] [blame] | 492 | Opts.WorkspaceRoot = *Params.rootPath; |
Sam McCall | 3d0adbe | 2018-10-18 14:41:50 +0000 | [diff] [blame] | 493 | if (Server) |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 494 | return Reply(llvm::make_error<LSPError>("server already initialized", |
| 495 | ErrorCode::InvalidRequest)); |
Sam McCall | bc90461 | 2018-10-25 04:22:52 +0000 | [diff] [blame] | 496 | if (const auto &Dir = Params.initializationOptions.compilationDatabasePath) |
Sam McCall | 7ba0779 | 2020-09-29 10:37:46 +0200 | [diff] [blame] | 497 | Opts.CompileCommandsDir = Dir; |
| 498 | if (Opts.UseDirBasedCDB) { |
Jonas Devlieghere | 1c705d9 | 2019-08-14 23:52:23 +0000 | [diff] [blame] | 499 | BaseCDB = std::make_unique<DirectoryBasedGlobalCompilationDatabase>( |
Sam McCall | 7ba0779 | 2020-09-29 10:37:46 +0200 | [diff] [blame] | 500 | Opts.CompileCommandsDir); |
| 501 | BaseCDB = getQueryDriverDatabase(llvm::makeArrayRef(Opts.QueryDriverGlobs), |
| 502 | std::move(BaseCDB)); |
Kadir Cetinkaya | 256247c | 2019-06-26 07:45:27 +0000 | [diff] [blame] | 503 | } |
Sam McCall | 99768b2 | 2019-11-29 19:37:48 +0100 | [diff] [blame] | 504 | auto Mangler = CommandMangler::detect(); |
Sam McCall | 7ba0779 | 2020-09-29 10:37:46 +0200 | [diff] [blame] | 505 | if (Opts.ResourceDir) |
| 506 | Mangler.ResourceDir = *Opts.ResourceDir; |
Kadir Cetinkaya | be6b35d | 2019-01-22 09:10:20 +0000 | [diff] [blame] | 507 | CDB.emplace(BaseCDB.get(), Params.initializationOptions.fallbackFlags, |
Sam McCall | 2a3ac01 | 2020-06-09 22:54:42 +0200 | [diff] [blame] | 508 | tooling::ArgumentsAdjuster(std::move(Mangler))); |
Kadir Cetinkaya | 9d66247 | 2019-10-15 14:20:52 +0000 | [diff] [blame] | 509 | { |
| 510 | // Switch caller's context with LSPServer's background context. Since we |
| 511 | // rather want to propagate information from LSPServer's context into the |
| 512 | // Server, CDB, etc. |
| 513 | WithContext MainContext(BackgroundContext.clone()); |
| 514 | llvm::Optional<WithContextValue> WithOffsetEncoding; |
Sam McCall | 6342b38 | 2020-09-30 10:56:43 +0200 | [diff] [blame] | 515 | if (Opts.Encoding) |
| 516 | WithOffsetEncoding.emplace(kCurrentOffsetEncoding, *Opts.Encoding); |
Sam McCall | 7ba0779 | 2020-09-29 10:37:46 +0200 | [diff] [blame] | 517 | Server.emplace(*CDB, TFS, Opts, |
Sam McCall | 6ef1cce | 2020-01-24 14:08:56 +0100 | [diff] [blame] | 518 | static_cast<ClangdServer::Callbacks *>(this)); |
Kadir Cetinkaya | 9d66247 | 2019-10-15 14:20:52 +0000 | [diff] [blame] | 519 | } |
Sam McCall | bc90461 | 2018-10-25 04:22:52 +0000 | [diff] [blame] | 520 | applyConfiguration(Params.initializationOptions.ConfigSettings); |
Simon Marchi | 8801678 | 2018-08-01 11:28:49 +0000 | [diff] [blame] | 521 | |
Sam McCall | 7ba0779 | 2020-09-29 10:37:46 +0200 | [diff] [blame] | 522 | Opts.CodeComplete.EnableSnippets = Params.capabilities.CompletionSnippets; |
| 523 | Opts.CodeComplete.IncludeFixIts = Params.capabilities.CompletionFixes; |
| 524 | if (!Opts.CodeComplete.BundleOverloads.hasValue()) |
| 525 | Opts.CodeComplete.BundleOverloads = Params.capabilities.HasSignatureHelp; |
| 526 | Opts.CodeComplete.DocumentationFormat = |
Sam McCall | a3a27a7 | 2020-04-30 10:49:32 +0200 | [diff] [blame] | 527 | Params.capabilities.CompletionDocumentationFormat; |
Sam McCall | bf6a2fc | 2018-10-17 07:33:42 +0000 | [diff] [blame] | 528 | DiagOpts.EmbedFixesInDiagnostics = Params.capabilities.DiagnosticFixes; |
| 529 | DiagOpts.SendDiagnosticCategory = Params.capabilities.DiagnosticCategory; |
Sam McCall | c9e4ee9 | 2019-04-18 15:17:07 +0000 | [diff] [blame] | 530 | DiagOpts.EmitRelatedLocations = |
| 531 | Params.capabilities.DiagnosticRelatedInformation; |
Sam McCall | bf6a2fc | 2018-10-17 07:33:42 +0000 | [diff] [blame] | 532 | if (Params.capabilities.WorkspaceSymbolKinds) |
| 533 | SupportedSymbolKinds |= *Params.capabilities.WorkspaceSymbolKinds; |
| 534 | if (Params.capabilities.CompletionItemKinds) |
| 535 | SupportedCompletionItemKinds |= *Params.capabilities.CompletionItemKinds; |
| 536 | SupportsCodeAction = Params.capabilities.CodeActionStructure; |
Ilya Biryukov | 19d7560 | 2018-11-23 15:21:19 +0000 | [diff] [blame] | 537 | SupportsHierarchicalDocumentSymbol = |
| 538 | Params.capabilities.HierarchicalDocumentSymbol; |
Haojian Wu | b618849 | 2018-12-20 15:39:12 +0000 | [diff] [blame] | 539 | SupportFileStatus = Params.initializationOptions.FileStatus; |
Ilya Biryukov | f9169d0 | 2019-05-29 10:01:00 +0000 | [diff] [blame] | 540 | HoverContentFormat = Params.capabilities.HoverContentFormat; |
Ilya Biryukov | 4ef0f82 | 2019-06-04 09:36:59 +0000 | [diff] [blame] | 541 | SupportsOffsetsInSignatureHelp = Params.capabilities.OffsetsInSignatureHelp; |
Sam McCall | 7d20e80 | 2020-01-22 19:41:45 +0100 | [diff] [blame] | 542 | if (Params.capabilities.WorkDoneProgress) |
| 543 | BackgroundIndexProgressState = BackgroundIndexProgress::Empty; |
| 544 | BackgroundIndexSkipCreate = Params.capabilities.ImplicitProgressCreation; |
Haojian Wu | f429ab6 | 2019-07-24 07:49:23 +0000 | [diff] [blame] | 545 | |
| 546 | // Per LSP, renameProvider can be either boolean or RenameOptions. |
| 547 | // RenameOptions will be specified if the client states it supports prepare. |
| 548 | llvm::json::Value RenameProvider = |
| 549 | llvm::json::Object{{"prepareProvider", true}}; |
| 550 | if (!Params.capabilities.RenamePrepareSupport) // Only boolean allowed per LSP |
| 551 | RenameProvider = true; |
| 552 | |
Haojian Wu | 08d93f1 | 2019-08-22 14:53:45 +0000 | [diff] [blame] | 553 | // Per LSP, codeActionProvide can be either boolean or CodeActionOptions. |
| 554 | // CodeActionOptions is only valid if the client supports action literal |
| 555 | // via textDocument.codeAction.codeActionLiteralSupport. |
| 556 | llvm::json::Value CodeActionProvider = true; |
| 557 | if (Params.capabilities.CodeActionStructure) |
| 558 | CodeActionProvider = llvm::json::Object{ |
| 559 | {"codeActionKinds", |
| 560 | {CodeAction::QUICKFIX_KIND, CodeAction::REFACTOR_KIND, |
| 561 | CodeAction::INFO_KIND}}}; |
| 562 | |
Sam McCall | a69698f | 2019-03-27 17:47:49 +0000 | [diff] [blame] | 563 | llvm::json::Object Result{ |
Sam McCall | 6f7dca9 | 2020-03-03 12:25:46 +0100 | [diff] [blame] | 564 | {{"serverInfo", |
| 565 | llvm::json::Object{{"name", "clangd"}, |
| 566 | {"version", getClangToolFullVersion("clangd")}}}, |
| 567 | {"capabilities", |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 568 | llvm::json::Object{ |
Sam McCall | 596b63a | 2020-04-10 03:27:37 +0200 | [diff] [blame] | 569 | {"textDocumentSync", |
| 570 | llvm::json::Object{ |
| 571 | {"openClose", true}, |
| 572 | {"change", (int)TextDocumentSyncKind::Incremental}, |
| 573 | {"save", true}, |
| 574 | }}, |
Sam McCall | 0930ab0 | 2017-11-07 15:49:35 +0000 | [diff] [blame] | 575 | {"documentFormattingProvider", true}, |
| 576 | {"documentRangeFormattingProvider", true}, |
| 577 | {"documentOnTypeFormattingProvider", |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 578 | llvm::json::Object{ |
Sam McCall | 25c6257 | 2019-06-10 14:26:21 +0000 | [diff] [blame] | 579 | {"firstTriggerCharacter", "\n"}, |
Sam McCall | 0930ab0 | 2017-11-07 15:49:35 +0000 | [diff] [blame] | 580 | {"moreTriggerCharacter", {}}, |
| 581 | }}, |
Haojian Wu | 08d93f1 | 2019-08-22 14:53:45 +0000 | [diff] [blame] | 582 | {"codeActionProvider", std::move(CodeActionProvider)}, |
Sam McCall | 0930ab0 | 2017-11-07 15:49:35 +0000 | [diff] [blame] | 583 | {"completionProvider", |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 584 | llvm::json::Object{ |
Kirill Bobyrev | 9d11e67 | 2020-08-26 17:08:00 +0200 | [diff] [blame] | 585 | {"allCommitCharacters", |
| 586 | {" ", "\t", "(", ")", "[", "]", "{", "}", "<", |
| 587 | ">", ":", ";", ",", "+", "-", "/", "*", "%", |
| 588 | "^", "&", "#", "?", ".", "=", "\"", "'", "|"}}, |
Sam McCall | 0930ab0 | 2017-11-07 15:49:35 +0000 | [diff] [blame] | 589 | {"resolveProvider", false}, |
Sam McCall | 032727f | 2020-05-06 01:39:59 +0200 | [diff] [blame] | 590 | // We do extra checks, e.g. that > is part of ->. |
| 591 | {"triggerCharacters", {".", "<", ">", ":", "\"", "/"}}, |
Sam McCall | 0930ab0 | 2017-11-07 15:49:35 +0000 | [diff] [blame] | 592 | }}, |
Sam McCall | 71177ac | 2020-03-24 02:24:47 +0100 | [diff] [blame] | 593 | {"semanticTokensProvider", |
| 594 | llvm::json::Object{ |
Sam McCall | 5fea54b | 2020-07-10 16:08:14 +0200 | [diff] [blame] | 595 | {"full", llvm::json::Object{{"delta", true}}}, |
| 596 | {"range", false}, |
Sam McCall | 71177ac | 2020-03-24 02:24:47 +0100 | [diff] [blame] | 597 | {"legend", |
| 598 | llvm::json::Object{{"tokenTypes", semanticTokenTypes()}, |
| 599 | {"tokenModifiers", llvm::json::Array()}}}, |
| 600 | }}, |
Sam McCall | 0930ab0 | 2017-11-07 15:49:35 +0000 | [diff] [blame] | 601 | {"signatureHelpProvider", |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 602 | llvm::json::Object{ |
Sam McCall | 0930ab0 | 2017-11-07 15:49:35 +0000 | [diff] [blame] | 603 | {"triggerCharacters", {"(", ","}}, |
| 604 | }}, |
Sam McCall | 866ba2c | 2019-02-01 11:26:13 +0000 | [diff] [blame] | 605 | {"declarationProvider", true}, |
Sam McCall | 0930ab0 | 2017-11-07 15:49:35 +0000 | [diff] [blame] | 606 | {"definitionProvider", true}, |
Utkarsh Saxena | b31486a | 2020-11-18 13:25:09 +0100 | [diff] [blame] | 607 | {"implementationProvider", true}, |
Ilya Biryukov | 0e6a51f | 2017-12-12 12:27:47 +0000 | [diff] [blame] | 608 | {"documentHighlightProvider", true}, |
Sam McCall | 8d7ecc1 | 2019-12-16 19:08:51 +0100 | [diff] [blame] | 609 | {"documentLinkProvider", |
| 610 | llvm::json::Object{ |
| 611 | {"resolveProvider", false}, |
| 612 | }}, |
Marc-Andre Laperle | 3e618ed | 2018-02-16 21:38:15 +0000 | [diff] [blame] | 613 | {"hoverProvider", true}, |
Haojian Wu | f429ab6 | 2019-07-24 07:49:23 +0000 | [diff] [blame] | 614 | {"renameProvider", std::move(RenameProvider)}, |
Utkarsh Saxena | 55925da | 2019-09-24 13:38:33 +0000 | [diff] [blame] | 615 | {"selectionRangeProvider", true}, |
Marc-Andre Laperle | 1be6970 | 2018-07-05 19:35:01 +0000 | [diff] [blame] | 616 | {"documentSymbolProvider", true}, |
Marc-Andre Laperle | b387b6e | 2018-04-23 20:00:52 +0000 | [diff] [blame] | 617 | {"workspaceSymbolProvider", true}, |
Sam McCall | 1ad142f | 2018-09-05 11:53:07 +0000 | [diff] [blame] | 618 | {"referencesProvider", true}, |
Sam McCall | 8adc4d1 | 2020-10-16 20:03:48 +0200 | [diff] [blame] | 619 | {"astProvider", true}, |
Sam McCall | 0930ab0 | 2017-11-07 15:49:35 +0000 | [diff] [blame] | 620 | {"executeCommandProvider", |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 621 | llvm::json::Object{ |
Ilya Biryukov | cce67a3 | 2019-01-29 14:17:36 +0000 | [diff] [blame] | 622 | {"commands", |
| 623 | {ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND, |
| 624 | ExecuteCommandParams::CLANGD_APPLY_TWEAK}}, |
Sam McCall | 0930ab0 | 2017-11-07 15:49:35 +0000 | [diff] [blame] | 625 | }}, |
Kadir Cetinkaya | 8665802 | 2019-03-19 09:27:04 +0000 | [diff] [blame] | 626 | {"typeHierarchyProvider", true}, |
Kadir Cetinkaya | d0f2874 | 2020-10-13 00:10:04 +0200 | [diff] [blame] | 627 | {"memoryUsageProvider", true}, // clangd extension. |
Nathan Ridge | 0a4f99c | 2020-11-15 22:45:17 -0500 | [diff] [blame^] | 628 | {"callHierarchyProvider", true}, |
Sam McCall | a69698f | 2019-03-27 17:47:49 +0000 | [diff] [blame] | 629 | }}}}; |
Sam McCall | 6342b38 | 2020-09-30 10:56:43 +0200 | [diff] [blame] | 630 | if (Opts.Encoding) |
| 631 | Result["offsetEncoding"] = *Opts.Encoding; |
Sam McCall | 7ba0779 | 2020-09-29 10:37:46 +0200 | [diff] [blame] | 632 | if (Opts.TheiaSemanticHighlighting) |
Johan Vikstrom | a848dab | 2019-07-04 07:53:12 +0000 | [diff] [blame] | 633 | Result.getObject("capabilities") |
| 634 | ->insert( |
| 635 | {"semanticHighlighting", |
Haojian Wu | 1ca2ee4 | 2019-07-04 12:27:21 +0000 | [diff] [blame] | 636 | llvm::json::Object{{"scopes", buildHighlightScopeLookupTable()}}}); |
Sam McCall | 7ba0779 | 2020-09-29 10:37:46 +0200 | [diff] [blame] | 637 | if (Opts.FoldingRanges) |
Kirill Bobyrev | 7a514c9 | 2020-07-14 09:28:38 +0200 | [diff] [blame] | 638 | Result.getObject("capabilities")->insert({"foldingRangeProvider", true}); |
Sam McCall | a69698f | 2019-03-27 17:47:49 +0000 | [diff] [blame] | 639 | Reply(std::move(Result)); |
Ilya Biryukov | afb5554 | 2017-05-16 14:40:30 +0000 | [diff] [blame] | 640 | } |
| 641 | |
Sam McCall | 8a2d294 | 2020-03-03 12:12:14 +0100 | [diff] [blame] | 642 | void ClangdLSPServer::onInitialized(const InitializedParams &Params) {} |
| 643 | |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 644 | void ClangdLSPServer::onShutdown(const ShutdownParams &Params, |
| 645 | Callback<std::nullptr_t> Reply) { |
Ilya Biryukov | 0d9b8a3 | 2017-10-25 08:45:41 +0000 | [diff] [blame] | 646 | // Do essentially nothing, just say we're ready to exit. |
| 647 | ShutdownRequestReceived = true; |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 648 | Reply(nullptr); |
Sam McCall | 8a5dded | 2017-10-12 13:29:58 +0000 | [diff] [blame] | 649 | } |
Ilya Biryukov | afb5554 | 2017-05-16 14:40:30 +0000 | [diff] [blame] | 650 | |
Sam McCall | 422c828 | 2018-11-26 16:00:11 +0000 | [diff] [blame] | 651 | // sync is a clangd extension: it blocks until all background work completes. |
| 652 | // It blocks the calling thread, so no messages are processed until it returns! |
| 653 | void ClangdLSPServer::onSync(const NoParams &Params, |
| 654 | Callback<std::nullptr_t> Reply) { |
| 655 | if (Server->blockUntilIdleForTest(/*TimeoutSeconds=*/60)) |
| 656 | Reply(nullptr); |
| 657 | else |
Sam McCall | 30667c9 | 2020-07-08 21:49:38 +0200 | [diff] [blame] | 658 | Reply(error("Not idle after a minute")); |
Sam McCall | 422c828 | 2018-11-26 16:00:11 +0000 | [diff] [blame] | 659 | } |
| 660 | |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 661 | void ClangdLSPServer::onDocumentDidOpen( |
| 662 | const DidOpenTextDocumentParams &Params) { |
Simon Marchi | 9569fd5 | 2018-03-16 14:30:42 +0000 | [diff] [blame] | 663 | PathRef File = Params.textDocument.uri.file(); |
Ilya Biryukov | b10ef47 | 2018-06-13 09:20:41 +0000 | [diff] [blame] | 664 | |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 665 | const std::string &Contents = Params.textDocument.text; |
Simon Marchi | 9569fd5 | 2018-03-16 14:30:42 +0000 | [diff] [blame] | 666 | |
Sam McCall | 2cd33e6 | 2020-03-04 00:33:29 +0100 | [diff] [blame] | 667 | auto Version = DraftMgr.addDraft(File, Params.textDocument.version, Contents); |
| 668 | Server->addDocument(File, Contents, encodeVersion(Version), |
| 669 | WantDiagnostics::Yes); |
Ilya Biryukov | afb5554 | 2017-05-16 14:40:30 +0000 | [diff] [blame] | 670 | } |
| 671 | |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 672 | void ClangdLSPServer::onDocumentDidChange( |
| 673 | const DidChangeTextDocumentParams &Params) { |
Eric Liu | 51fed18 | 2018-02-22 18:40:39 +0000 | [diff] [blame] | 674 | auto WantDiags = WantDiagnostics::Auto; |
| 675 | if (Params.wantDiagnostics.hasValue()) |
| 676 | WantDiags = Params.wantDiagnostics.getValue() ? WantDiagnostics::Yes |
| 677 | : WantDiagnostics::No; |
Simon Marchi | 9569fd5 | 2018-03-16 14:30:42 +0000 | [diff] [blame] | 678 | |
| 679 | PathRef File = Params.textDocument.uri.file(); |
Sam McCall | caf5a4d | 2020-03-03 15:57:39 +0100 | [diff] [blame] | 680 | llvm::Expected<DraftStore::Draft> Draft = DraftMgr.updateDraft( |
| 681 | File, Params.textDocument.version, Params.contentChanges); |
| 682 | if (!Draft) { |
Simon Marchi | 9808262 | 2018-03-26 14:41:40 +0000 | [diff] [blame] | 683 | // If this fails, we are most likely going to be not in sync anymore with |
| 684 | // the client. It is better to remove the draft and let further operations |
| 685 | // fail rather than giving wrong results. |
| 686 | DraftMgr.removeDraft(File); |
Ilya Biryukov | 652364b | 2018-09-26 05:48:29 +0000 | [diff] [blame] | 687 | Server->removeDocument(File); |
Sam McCall | caf5a4d | 2020-03-03 15:57:39 +0100 | [diff] [blame] | 688 | elog("Failed to update {0}: {1}", File, Draft.takeError()); |
Simon Marchi | 9808262 | 2018-03-26 14:41:40 +0000 | [diff] [blame] | 689 | return; |
| 690 | } |
Simon Marchi | 9569fd5 | 2018-03-16 14:30:42 +0000 | [diff] [blame] | 691 | |
Sam McCall | 2cd33e6 | 2020-03-04 00:33:29 +0100 | [diff] [blame] | 692 | Server->addDocument(File, Draft->Contents, encodeVersion(Draft->Version), |
| 693 | WantDiags, Params.forceRebuild); |
Ilya Biryukov | afb5554 | 2017-05-16 14:40:30 +0000 | [diff] [blame] | 694 | } |
| 695 | |
Sam McCall | 596b63a | 2020-04-10 03:27:37 +0200 | [diff] [blame] | 696 | void ClangdLSPServer::onDocumentDidSave( |
| 697 | const DidSaveTextDocumentParams &Params) { |
| 698 | reparseOpenFilesIfNeeded([](llvm::StringRef) { return true; }); |
| 699 | } |
| 700 | |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 701 | void ClangdLSPServer::onFileEvent(const DidChangeWatchedFilesParams &Params) { |
Sam McCall | 596b63a | 2020-04-10 03:27:37 +0200 | [diff] [blame] | 702 | // We could also reparse all open files here. However: |
| 703 | // - this could be frequent, and revalidating all the preambles isn't free |
| 704 | // - this is useful e.g. when switching git branches, but we're likely to see |
| 705 | // fresh headers but still have the old-branch main-file content |
Ilya Biryukov | 652364b | 2018-09-26 05:48:29 +0000 | [diff] [blame] | 706 | Server->onFileEvent(Params); |
Marc-Andre Laperle | bf11424 | 2017-10-02 18:00:37 +0000 | [diff] [blame] | 707 | } |
| 708 | |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 709 | void ClangdLSPServer::onCommand(const ExecuteCommandParams &Params, |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 710 | Callback<llvm::json::Value> Reply) { |
Ilya Biryukov | 1286400 | 2019-08-16 12:46:41 +0000 | [diff] [blame] | 711 | auto ApplyEdit = [this](WorkspaceEdit WE, std::string SuccessMessage, |
| 712 | decltype(Reply) Reply) { |
Eric Liu | c5105f9 | 2018-02-16 14:15:55 +0000 | [diff] [blame] | 713 | ApplyWorkspaceEditParams Edit; |
| 714 | Edit.edit = std::move(WE); |
Ilya Biryukov | 1286400 | 2019-08-16 12:46:41 +0000 | [diff] [blame] | 715 | call<ApplyWorkspaceEditResponse>( |
| 716 | "workspace/applyEdit", std::move(Edit), |
| 717 | [Reply = std::move(Reply), SuccessMessage = std::move(SuccessMessage)]( |
| 718 | llvm::Expected<ApplyWorkspaceEditResponse> Response) mutable { |
| 719 | if (!Response) |
| 720 | return Reply(Response.takeError()); |
| 721 | if (!Response->applied) { |
| 722 | std::string Reason = Response->failureReason |
| 723 | ? *Response->failureReason |
| 724 | : "unknown reason"; |
Sam McCall | 30667c9 | 2020-07-08 21:49:38 +0200 | [diff] [blame] | 725 | return Reply(error("edits were not applied: {0}", Reason)); |
Ilya Biryukov | 1286400 | 2019-08-16 12:46:41 +0000 | [diff] [blame] | 726 | } |
| 727 | return Reply(SuccessMessage); |
| 728 | }); |
Eric Liu | c5105f9 | 2018-02-16 14:15:55 +0000 | [diff] [blame] | 729 | }; |
Ilya Biryukov | 1286400 | 2019-08-16 12:46:41 +0000 | [diff] [blame] | 730 | |
Marc-Andre Laperle | e7ec16a | 2017-11-03 13:39:15 +0000 | [diff] [blame] | 731 | if (Params.command == ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND && |
| 732 | Params.workspaceEdit) { |
| 733 | // The flow for "apply-fix" : |
| 734 | // 1. We publish a diagnostic, including fixits |
| 735 | // 2. The user clicks on the diagnostic, the editor asks us for code actions |
| 736 | // 3. We send code actions, with the fixit embedded as context |
| 737 | // 4. The user selects the fixit, the editor asks us to apply it |
| 738 | // 5. We unwrap the changes and send them back to the editor |
Haojian Wu | f251634 | 2019-08-05 12:48:09 +0000 | [diff] [blame] | 739 | // 6. The editor applies the changes (applyEdit), and sends us a reply |
| 740 | // 7. We unwrap the reply and send a reply to the editor. |
Ilya Biryukov | 1286400 | 2019-08-16 12:46:41 +0000 | [diff] [blame] | 741 | ApplyEdit(*Params.workspaceEdit, "Fix applied.", std::move(Reply)); |
Ilya Biryukov | cce67a3 | 2019-01-29 14:17:36 +0000 | [diff] [blame] | 742 | } else if (Params.command == ExecuteCommandParams::CLANGD_APPLY_TWEAK && |
| 743 | Params.tweakArgs) { |
| 744 | auto Code = DraftMgr.getDraft(Params.tweakArgs->file.file()); |
| 745 | if (!Code) |
Sam McCall | 30667c9 | 2020-07-08 21:49:38 +0200 | [diff] [blame] | 746 | return Reply(error("trying to apply a code action for a non-added file")); |
Ilya Biryukov | cce67a3 | 2019-01-29 14:17:36 +0000 | [diff] [blame] | 747 | |
Ilya Biryukov | 1286400 | 2019-08-16 12:46:41 +0000 | [diff] [blame] | 748 | auto Action = [this, ApplyEdit, Reply = std::move(Reply), |
| 749 | File = Params.tweakArgs->file, Code = std::move(*Code)]( |
Benjamin Kramer | 9880b5d | 2019-08-15 14:16:06 +0000 | [diff] [blame] | 750 | llvm::Expected<Tweak::Effect> R) mutable { |
Ilya Biryukov | cce67a3 | 2019-01-29 14:17:36 +0000 | [diff] [blame] | 751 | if (!R) |
| 752 | return Reply(R.takeError()); |
| 753 | |
Kadir Cetinkaya | 5b27093 | 2019-09-09 12:28:44 +0000 | [diff] [blame] | 754 | assert(R->ShowMessage || |
| 755 | (!R->ApplyEdits.empty() && "tweak has no effect")); |
Ilya Biryukov | 1286400 | 2019-08-16 12:46:41 +0000 | [diff] [blame] | 756 | |
Sam McCall | 395fde7 | 2019-06-18 13:37:54 +0000 | [diff] [blame] | 757 | if (R->ShowMessage) { |
| 758 | ShowMessageParams Msg; |
| 759 | Msg.message = *R->ShowMessage; |
| 760 | Msg.type = MessageType::Info; |
| 761 | notify("window/showMessage", Msg); |
| 762 | } |
Ilya Biryukov | 1286400 | 2019-08-16 12:46:41 +0000 | [diff] [blame] | 763 | // When no edit is specified, make sure we Reply(). |
Kadir Cetinkaya | 5b27093 | 2019-09-09 12:28:44 +0000 | [diff] [blame] | 764 | if (R->ApplyEdits.empty()) |
| 765 | return Reply("Tweak applied."); |
| 766 | |
Haojian Wu | 852bafa | 2019-10-23 14:40:20 +0200 | [diff] [blame] | 767 | if (auto Err = validateEdits(DraftMgr, R->ApplyEdits)) |
Kadir Cetinkaya | 5b27093 | 2019-09-09 12:28:44 +0000 | [diff] [blame] | 768 | return Reply(std::move(Err)); |
| 769 | |
| 770 | WorkspaceEdit WE; |
| 771 | WE.changes.emplace(); |
| 772 | for (const auto &It : R->ApplyEdits) { |
Kadir Cetinkaya | e95e516 | 2019-10-02 09:12:01 +0000 | [diff] [blame] | 773 | (*WE.changes)[URI::createFile(It.first()).toString()] = |
Kadir Cetinkaya | 5b27093 | 2019-09-09 12:28:44 +0000 | [diff] [blame] | 774 | It.second.asTextEdits(); |
| 775 | } |
| 776 | // ApplyEdit will take care of calling Reply(). |
| 777 | return ApplyEdit(std::move(WE), "Tweak applied.", std::move(Reply)); |
Ilya Biryukov | cce67a3 | 2019-01-29 14:17:36 +0000 | [diff] [blame] | 778 | }; |
| 779 | Server->applyTweak(Params.tweakArgs->file.file(), |
| 780 | Params.tweakArgs->selection, Params.tweakArgs->tweakID, |
Benjamin Kramer | 9880b5d | 2019-08-15 14:16:06 +0000 | [diff] [blame] | 781 | std::move(Action)); |
Marc-Andre Laperle | e7ec16a | 2017-11-03 13:39:15 +0000 | [diff] [blame] | 782 | } else { |
| 783 | // We should not get here because ExecuteCommandParams would not have |
| 784 | // parsed in the first place and this handler should not be called. But if |
| 785 | // more commands are added, this will be here has a safe guard. |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 786 | Reply(llvm::make_error<LSPError>( |
| 787 | llvm::formatv("Unsupported command \"{0}\".", Params.command).str(), |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 788 | ErrorCode::InvalidParams)); |
Marc-Andre Laperle | e7ec16a | 2017-11-03 13:39:15 +0000 | [diff] [blame] | 789 | } |
| 790 | } |
| 791 | |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 792 | void ClangdLSPServer::onWorkspaceSymbol( |
| 793 | const WorkspaceSymbolParams &Params, |
| 794 | Callback<std::vector<SymbolInformation>> Reply) { |
Ilya Biryukov | 652364b | 2018-09-26 05:48:29 +0000 | [diff] [blame] | 795 | Server->workspaceSymbols( |
Sam McCall | 7ba0779 | 2020-09-29 10:37:46 +0200 | [diff] [blame] | 796 | Params.query, Opts.CodeComplete.Limit, |
Benjamin Kramer | 9880b5d | 2019-08-15 14:16:06 +0000 | [diff] [blame] | 797 | [Reply = std::move(Reply), |
| 798 | this](llvm::Expected<std::vector<SymbolInformation>> Items) mutable { |
| 799 | if (!Items) |
| 800 | return Reply(Items.takeError()); |
| 801 | for (auto &Sym : *Items) |
| 802 | Sym.kind = adjustKindToCapability(Sym.kind, SupportedSymbolKinds); |
Marc-Andre Laperle | b387b6e | 2018-04-23 20:00:52 +0000 | [diff] [blame] | 803 | |
Benjamin Kramer | 9880b5d | 2019-08-15 14:16:06 +0000 | [diff] [blame] | 804 | Reply(std::move(*Items)); |
| 805 | }); |
Marc-Andre Laperle | b387b6e | 2018-04-23 20:00:52 +0000 | [diff] [blame] | 806 | } |
| 807 | |
Haojian Wu | f429ab6 | 2019-07-24 07:49:23 +0000 | [diff] [blame] | 808 | void ClangdLSPServer::onPrepareRename(const TextDocumentPositionParams &Params, |
| 809 | Callback<llvm::Optional<Range>> Reply) { |
Haojian Wu | 0f0cbcc | 2020-10-02 16:01:25 +0200 | [diff] [blame] | 810 | Server->prepareRename( |
Haojian Wu | 9c09e20 | 2020-10-07 21:16:45 +0200 | [diff] [blame] | 811 | Params.textDocument.uri.file(), Params.position, /*NewName*/ llvm::None, |
| 812 | Opts.Rename, |
Haojian Wu | 0f0cbcc | 2020-10-02 16:01:25 +0200 | [diff] [blame] | 813 | [Reply = std::move(Reply)](llvm::Expected<RenameResult> Result) mutable { |
| 814 | if (!Result) |
| 815 | return Reply(Result.takeError()); |
| 816 | return Reply(std::move(Result->Target)); |
| 817 | }); |
Haojian Wu | f429ab6 | 2019-07-24 07:49:23 +0000 | [diff] [blame] | 818 | } |
| 819 | |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 820 | void ClangdLSPServer::onRename(const RenameParams &Params, |
| 821 | Callback<WorkspaceEdit> Reply) { |
Benjamin Kramer | adcd026 | 2020-01-28 20:23:46 +0100 | [diff] [blame] | 822 | Path File = std::string(Params.textDocument.uri.file()); |
Sam McCall | caf5a4d | 2020-03-03 15:57:39 +0100 | [diff] [blame] | 823 | if (!DraftMgr.getDraft(File)) |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 824 | return Reply(llvm::make_error<LSPError>( |
| 825 | "onRename called for non-added file", ErrorCode::InvalidParams)); |
Haojian Wu | 852bafa | 2019-10-23 14:40:20 +0200 | [diff] [blame] | 826 | Server->rename( |
Sam McCall | 7ba0779 | 2020-09-29 10:37:46 +0200 | [diff] [blame] | 827 | File, Params.position, Params.newName, Opts.Rename, |
Haojian Wu | 852bafa | 2019-10-23 14:40:20 +0200 | [diff] [blame] | 828 | [File, Params, Reply = std::move(Reply), |
Haojian Wu | 0f0cbcc | 2020-10-02 16:01:25 +0200 | [diff] [blame] | 829 | this](llvm::Expected<RenameResult> R) mutable { |
| 830 | if (!R) |
| 831 | return Reply(R.takeError()); |
| 832 | if (auto Err = validateEdits(DraftMgr, R->GlobalChanges)) |
Haojian Wu | 852bafa | 2019-10-23 14:40:20 +0200 | [diff] [blame] | 833 | return Reply(std::move(Err)); |
| 834 | WorkspaceEdit Result; |
| 835 | Result.changes.emplace(); |
Haojian Wu | 0f0cbcc | 2020-10-02 16:01:25 +0200 | [diff] [blame] | 836 | for (const auto &Rep : R->GlobalChanges) { |
Haojian Wu | 852bafa | 2019-10-23 14:40:20 +0200 | [diff] [blame] | 837 | (*Result.changes)[URI::createFile(Rep.first()).toString()] = |
| 838 | Rep.second.asTextEdits(); |
| 839 | } |
| 840 | Reply(Result); |
| 841 | }); |
Haojian Wu | 345099c | 2017-11-09 11:30:04 +0000 | [diff] [blame] | 842 | } |
| 843 | |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 844 | void ClangdLSPServer::onDocumentDidClose( |
| 845 | const DidCloseTextDocumentParams &Params) { |
Simon Marchi | 9569fd5 | 2018-03-16 14:30:42 +0000 | [diff] [blame] | 846 | PathRef File = Params.textDocument.uri.file(); |
| 847 | DraftMgr.removeDraft(File); |
Ilya Biryukov | 652364b | 2018-09-26 05:48:29 +0000 | [diff] [blame] | 848 | Server->removeDocument(File); |
Ilya Biryukov | 49c1071 | 2019-03-25 10:15:11 +0000 | [diff] [blame] | 849 | |
| 850 | { |
| 851 | std::lock_guard<std::mutex> Lock(FixItsMutex); |
| 852 | FixItsMap.erase(File); |
| 853 | } |
Johan Vikstrom | c2653ef2 | 2019-08-01 08:08:44 +0000 | [diff] [blame] | 854 | { |
| 855 | std::lock_guard<std::mutex> HLock(HighlightingsMutex); |
| 856 | FileToHighlightings.erase(File); |
| 857 | } |
Sam McCall | 9e3063e | 2020-04-01 16:21:44 +0200 | [diff] [blame] | 858 | { |
| 859 | std::lock_guard<std::mutex> HLock(SemanticTokensMutex); |
| 860 | LastSemanticTokens.erase(File); |
| 861 | } |
Ilya Biryukov | 49c1071 | 2019-03-25 10:15:11 +0000 | [diff] [blame] | 862 | // clangd will not send updates for this file anymore, so we empty out the |
| 863 | // list of diagnostics shown on the client (e.g. in the "Problems" pane of |
| 864 | // VSCode). Note that this cannot race with actual diagnostics responses |
| 865 | // because removeDocument() guarantees no diagnostic callbacks will be |
| 866 | // executed after it returns. |
Sam McCall | 6525a6b | 2020-03-03 12:44:40 +0100 | [diff] [blame] | 867 | PublishDiagnosticsParams Notification; |
| 868 | Notification.uri = URIForFile::canonicalize(File, /*TUPath=*/File); |
| 869 | publishDiagnostics(Notification); |
Ilya Biryukov | afb5554 | 2017-05-16 14:40:30 +0000 | [diff] [blame] | 870 | } |
| 871 | |
Sam McCall | 4db732a | 2017-09-30 10:08:52 +0000 | [diff] [blame] | 872 | void ClangdLSPServer::onDocumentOnTypeFormatting( |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 873 | const DocumentOnTypeFormattingParams &Params, |
| 874 | Callback<std::vector<TextEdit>> Reply) { |
Ilya Biryukov | 7d60d20 | 2018-02-16 12:20:47 +0000 | [diff] [blame] | 875 | auto File = Params.textDocument.uri.file(); |
Simon Marchi | 9569fd5 | 2018-03-16 14:30:42 +0000 | [diff] [blame] | 876 | auto Code = DraftMgr.getDraft(File); |
Ilya Biryukov | 261c72e | 2018-01-17 12:30:24 +0000 | [diff] [blame] | 877 | if (!Code) |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 878 | return Reply(llvm::make_error<LSPError>( |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 879 | "onDocumentOnTypeFormatting called for non-added file", |
| 880 | ErrorCode::InvalidParams)); |
Ilya Biryukov | 261c72e | 2018-01-17 12:30:24 +0000 | [diff] [blame] | 881 | |
Sam McCall | ffa63dd | 2020-06-26 12:57:29 +0200 | [diff] [blame] | 882 | Server->formatOnType(File, Code->Contents, Params.position, Params.ch, |
| 883 | std::move(Reply)); |
Ilya Biryukov | afb5554 | 2017-05-16 14:40:30 +0000 | [diff] [blame] | 884 | } |
| 885 | |
Sam McCall | 4db732a | 2017-09-30 10:08:52 +0000 | [diff] [blame] | 886 | void ClangdLSPServer::onDocumentRangeFormatting( |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 887 | const DocumentRangeFormattingParams &Params, |
| 888 | Callback<std::vector<TextEdit>> Reply) { |
Ilya Biryukov | 7d60d20 | 2018-02-16 12:20:47 +0000 | [diff] [blame] | 889 | auto File = Params.textDocument.uri.file(); |
Simon Marchi | 9569fd5 | 2018-03-16 14:30:42 +0000 | [diff] [blame] | 890 | auto Code = DraftMgr.getDraft(File); |
Ilya Biryukov | 261c72e | 2018-01-17 12:30:24 +0000 | [diff] [blame] | 891 | if (!Code) |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 892 | return Reply(llvm::make_error<LSPError>( |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 893 | "onDocumentRangeFormatting called for non-added file", |
| 894 | ErrorCode::InvalidParams)); |
Ilya Biryukov | 261c72e | 2018-01-17 12:30:24 +0000 | [diff] [blame] | 895 | |
Sam McCall | ffa63dd | 2020-06-26 12:57:29 +0200 | [diff] [blame] | 896 | Server->formatRange( |
| 897 | File, Code->Contents, Params.range, |
| 898 | [Code = Code->Contents, Reply = std::move(Reply)]( |
| 899 | llvm::Expected<tooling::Replacements> Result) mutable { |
| 900 | if (Result) |
| 901 | Reply(replacementsToEdits(Code, Result.get())); |
| 902 | else |
| 903 | Reply(Result.takeError()); |
| 904 | }); |
Ilya Biryukov | afb5554 | 2017-05-16 14:40:30 +0000 | [diff] [blame] | 905 | } |
| 906 | |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 907 | void ClangdLSPServer::onDocumentFormatting( |
| 908 | const DocumentFormattingParams &Params, |
| 909 | Callback<std::vector<TextEdit>> Reply) { |
Ilya Biryukov | 7d60d20 | 2018-02-16 12:20:47 +0000 | [diff] [blame] | 910 | auto File = Params.textDocument.uri.file(); |
Simon Marchi | 9569fd5 | 2018-03-16 14:30:42 +0000 | [diff] [blame] | 911 | auto Code = DraftMgr.getDraft(File); |
Ilya Biryukov | 261c72e | 2018-01-17 12:30:24 +0000 | [diff] [blame] | 912 | if (!Code) |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 913 | return Reply(llvm::make_error<LSPError>( |
| 914 | "onDocumentFormatting called for non-added file", |
| 915 | ErrorCode::InvalidParams)); |
Ilya Biryukov | 261c72e | 2018-01-17 12:30:24 +0000 | [diff] [blame] | 916 | |
Sam McCall | ffa63dd | 2020-06-26 12:57:29 +0200 | [diff] [blame] | 917 | Server->formatFile(File, Code->Contents, |
| 918 | [Code = Code->Contents, Reply = std::move(Reply)]( |
| 919 | llvm::Expected<tooling::Replacements> Result) mutable { |
| 920 | if (Result) |
| 921 | Reply(replacementsToEdits(Code, Result.get())); |
| 922 | else |
| 923 | Reply(Result.takeError()); |
| 924 | }); |
Sam McCall | 4db732a | 2017-09-30 10:08:52 +0000 | [diff] [blame] | 925 | } |
| 926 | |
Ilya Biryukov | 19d7560 | 2018-11-23 15:21:19 +0000 | [diff] [blame] | 927 | /// The functions constructs a flattened view of the DocumentSymbol hierarchy. |
| 928 | /// Used by the clients that do not support the hierarchical view. |
| 929 | static std::vector<SymbolInformation> |
| 930 | flattenSymbolHierarchy(llvm::ArrayRef<DocumentSymbol> Symbols, |
| 931 | const URIForFile &FileURI) { |
Ilya Biryukov | 19d7560 | 2018-11-23 15:21:19 +0000 | [diff] [blame] | 932 | std::vector<SymbolInformation> Results; |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 933 | std::function<void(const DocumentSymbol &, llvm::StringRef)> Process = |
| 934 | [&](const DocumentSymbol &S, llvm::Optional<llvm::StringRef> ParentName) { |
Ilya Biryukov | 19d7560 | 2018-11-23 15:21:19 +0000 | [diff] [blame] | 935 | SymbolInformation SI; |
Benjamin Kramer | adcd026 | 2020-01-28 20:23:46 +0100 | [diff] [blame] | 936 | SI.containerName = std::string(ParentName ? "" : *ParentName); |
Ilya Biryukov | 19d7560 | 2018-11-23 15:21:19 +0000 | [diff] [blame] | 937 | SI.name = S.name; |
| 938 | SI.kind = S.kind; |
| 939 | SI.location.range = S.range; |
| 940 | SI.location.uri = FileURI; |
| 941 | |
| 942 | Results.push_back(std::move(SI)); |
| 943 | std::string FullName = |
| 944 | !ParentName ? S.name : (ParentName->str() + "::" + S.name); |
| 945 | for (auto &C : S.children) |
| 946 | Process(C, /*ParentName=*/FullName); |
| 947 | }; |
| 948 | for (auto &S : Symbols) |
| 949 | Process(S, /*ParentName=*/""); |
| 950 | return Results; |
| 951 | } |
| 952 | |
| 953 | void ClangdLSPServer::onDocumentSymbol(const DocumentSymbolParams &Params, |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 954 | Callback<llvm::json::Value> Reply) { |
Ilya Biryukov | 19d7560 | 2018-11-23 15:21:19 +0000 | [diff] [blame] | 955 | URIForFile FileURI = Params.textDocument.uri; |
Ilya Biryukov | 652364b | 2018-09-26 05:48:29 +0000 | [diff] [blame] | 956 | Server->documentSymbols( |
Marc-Andre Laperle | 1be6970 | 2018-07-05 19:35:01 +0000 | [diff] [blame] | 957 | Params.textDocument.uri.file(), |
Benjamin Kramer | 9880b5d | 2019-08-15 14:16:06 +0000 | [diff] [blame] | 958 | [this, FileURI, Reply = std::move(Reply)]( |
| 959 | llvm::Expected<std::vector<DocumentSymbol>> Items) mutable { |
| 960 | if (!Items) |
| 961 | return Reply(Items.takeError()); |
| 962 | adjustSymbolKinds(*Items, SupportedSymbolKinds); |
| 963 | if (SupportsHierarchicalDocumentSymbol) |
| 964 | return Reply(std::move(*Items)); |
| 965 | else |
| 966 | return Reply(flattenSymbolHierarchy(*Items, FileURI)); |
| 967 | }); |
Marc-Andre Laperle | 1be6970 | 2018-07-05 19:35:01 +0000 | [diff] [blame] | 968 | } |
| 969 | |
Kirill Bobyrev | 7a514c9 | 2020-07-14 09:28:38 +0200 | [diff] [blame] | 970 | void ClangdLSPServer::onFoldingRange( |
| 971 | const FoldingRangeParams &Params, |
| 972 | Callback<std::vector<FoldingRange>> Reply) { |
| 973 | Server->foldingRanges(Params.textDocument.uri.file(), std::move(Reply)); |
| 974 | } |
| 975 | |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 976 | static llvm::Optional<Command> asCommand(const CodeAction &Action) { |
Sam McCall | 20841d4 | 2018-10-16 16:29:41 +0000 | [diff] [blame] | 977 | Command Cmd; |
| 978 | if (Action.command && Action.edit) |
Sam McCall | c008af6 | 2018-10-20 15:30:37 +0000 | [diff] [blame] | 979 | return None; // Not representable. (We never emit these anyway). |
Sam McCall | 20841d4 | 2018-10-16 16:29:41 +0000 | [diff] [blame] | 980 | if (Action.command) { |
| 981 | Cmd = *Action.command; |
| 982 | } else if (Action.edit) { |
Benjamin Kramer | adcd026 | 2020-01-28 20:23:46 +0100 | [diff] [blame] | 983 | Cmd.command = std::string(Command::CLANGD_APPLY_FIX_COMMAND); |
Sam McCall | 20841d4 | 2018-10-16 16:29:41 +0000 | [diff] [blame] | 984 | Cmd.workspaceEdit = *Action.edit; |
| 985 | } else { |
Sam McCall | c008af6 | 2018-10-20 15:30:37 +0000 | [diff] [blame] | 986 | return None; |
Sam McCall | 20841d4 | 2018-10-16 16:29:41 +0000 | [diff] [blame] | 987 | } |
| 988 | Cmd.title = Action.title; |
| 989 | if (Action.kind && *Action.kind == CodeAction::QUICKFIX_KIND) |
| 990 | Cmd.title = "Apply fix: " + Cmd.title; |
| 991 | return Cmd; |
| 992 | } |
| 993 | |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 994 | void ClangdLSPServer::onCodeAction(const CodeActionParams &Params, |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 995 | Callback<llvm::json::Value> Reply) { |
Ilya Biryukov | cce67a3 | 2019-01-29 14:17:36 +0000 | [diff] [blame] | 996 | URIForFile File = Params.textDocument.uri; |
| 997 | auto Code = DraftMgr.getDraft(File.file()); |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 998 | if (!Code) |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 999 | return Reply(llvm::make_error<LSPError>( |
| 1000 | "onCodeAction called for non-added file", ErrorCode::InvalidParams)); |
Sam McCall | 5627ae6 | 2020-10-09 15:17:26 +0200 | [diff] [blame] | 1001 | |
| 1002 | // Checks whether a particular CodeActionKind is included in the response. |
| 1003 | auto KindAllowed = [Only(Params.context.only)](llvm::StringRef Kind) { |
| 1004 | if (Only.empty()) |
| 1005 | return true; |
| 1006 | return llvm::any_of(Only, [&](llvm::StringRef Base) { |
| 1007 | return Kind.consume_front(Base) && (Kind.empty() || Kind.startswith(".")); |
| 1008 | }); |
| 1009 | }; |
| 1010 | |
Sam McCall | 20841d4 | 2018-10-16 16:29:41 +0000 | [diff] [blame] | 1011 | // We provide a code action for Fixes on the specified diagnostics. |
Ilya Biryukov | cce67a3 | 2019-01-29 14:17:36 +0000 | [diff] [blame] | 1012 | std::vector<CodeAction> FixIts; |
Sam McCall | 5627ae6 | 2020-10-09 15:17:26 +0200 | [diff] [blame] | 1013 | if (KindAllowed(CodeAction::QUICKFIX_KIND)) { |
| 1014 | for (const Diagnostic &D : Params.context.diagnostics) { |
| 1015 | for (auto &F : getFixes(File.file(), D)) { |
| 1016 | FixIts.push_back(toCodeAction(F, Params.textDocument.uri)); |
| 1017 | FixIts.back().diagnostics = {D}; |
| 1018 | } |
Sam McCall | dd0566b | 2017-11-06 15:40:30 +0000 | [diff] [blame] | 1019 | } |
Ilya Biryukov | afb5554 | 2017-05-16 14:40:30 +0000 | [diff] [blame] | 1020 | } |
Sam McCall | 20841d4 | 2018-10-16 16:29:41 +0000 | [diff] [blame] | 1021 | |
Ilya Biryukov | cce67a3 | 2019-01-29 14:17:36 +0000 | [diff] [blame] | 1022 | // Now enumerate the semantic code actions. |
| 1023 | auto ConsumeActions = |
Benjamin Kramer | 9880b5d | 2019-08-15 14:16:06 +0000 | [diff] [blame] | 1024 | [Reply = std::move(Reply), File, Code = std::move(*Code), |
| 1025 | Selection = Params.range, FixIts = std::move(FixIts), this]( |
| 1026 | llvm::Expected<std::vector<ClangdServer::TweakRef>> Tweaks) mutable { |
Ilya Biryukov | c6ed778 | 2019-01-30 14:24:17 +0000 | [diff] [blame] | 1027 | if (!Tweaks) |
| 1028 | return Reply(Tweaks.takeError()); |
Ilya Biryukov | cce67a3 | 2019-01-29 14:17:36 +0000 | [diff] [blame] | 1029 | |
| 1030 | std::vector<CodeAction> Actions = std::move(FixIts); |
| 1031 | Actions.reserve(Actions.size() + Tweaks->size()); |
| 1032 | for (const auto &T : *Tweaks) |
| 1033 | Actions.push_back(toCodeAction(T, File, Selection)); |
| 1034 | |
Sam McCall | 8392685 | 2020-09-29 16:28:50 +0200 | [diff] [blame] | 1035 | // If there's exactly one quick-fix, call it "preferred". |
| 1036 | // We never consider refactorings etc as preferred. |
| 1037 | CodeAction *OnlyFix = nullptr; |
| 1038 | for (auto &Action : Actions) { |
| 1039 | if (Action.kind && *Action.kind == CodeAction::QUICKFIX_KIND) { |
| 1040 | if (OnlyFix) { |
| 1041 | OnlyFix->isPreferred = false; |
| 1042 | break; |
| 1043 | } |
| 1044 | Action.isPreferred = true; |
| 1045 | OnlyFix = &Action; |
| 1046 | } |
| 1047 | } |
| 1048 | |
Ilya Biryukov | cce67a3 | 2019-01-29 14:17:36 +0000 | [diff] [blame] | 1049 | if (SupportsCodeAction) |
| 1050 | return Reply(llvm::json::Array(Actions)); |
| 1051 | std::vector<Command> Commands; |
| 1052 | for (const auto &Action : Actions) { |
| 1053 | if (auto Command = asCommand(Action)) |
| 1054 | Commands.push_back(std::move(*Command)); |
| 1055 | } |
| 1056 | return Reply(llvm::json::Array(Commands)); |
| 1057 | }; |
Sam McCall | 7530b25 | 2020-10-02 11:34:40 +0200 | [diff] [blame] | 1058 | Server->enumerateTweaks( |
| 1059 | File.file(), Params.range, |
Sam McCall | 5627ae6 | 2020-10-09 15:17:26 +0200 | [diff] [blame] | 1060 | [this, KindAllowed(std::move(KindAllowed))](const Tweak &T) { |
| 1061 | return Opts.TweakFilter(T) && KindAllowed(T.kind()); |
Sam McCall | 7530b25 | 2020-10-02 11:34:40 +0200 | [diff] [blame] | 1062 | }, |
| 1063 | std::move(ConsumeActions)); |
Ilya Biryukov | afb5554 | 2017-05-16 14:40:30 +0000 | [diff] [blame] | 1064 | } |
| 1065 | |
Ilya Biryukov | b0826bd | 2019-01-03 13:37:12 +0000 | [diff] [blame] | 1066 | void ClangdLSPServer::onCompletion(const CompletionParams &Params, |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 1067 | Callback<CompletionList> Reply) { |
Ilya Biryukov | a7a1147 | 2019-06-07 16:24:38 +0000 | [diff] [blame] | 1068 | if (!shouldRunCompletion(Params)) { |
| 1069 | // Clients sometimes auto-trigger completions in undesired places (e.g. |
| 1070 | // 'a >^ '), we return empty results in those cases. |
| 1071 | vlog("ignored auto-triggered completion, preceding char did not match"); |
| 1072 | return Reply(CompletionList()); |
| 1073 | } |
Kadir Cetinkaya | 9407686 | 2020-10-12 14:24:05 +0200 | [diff] [blame] | 1074 | Server->codeComplete( |
| 1075 | Params.textDocument.uri.file(), Params.position, Opts.CodeComplete, |
| 1076 | [Reply = std::move(Reply), |
| 1077 | this](llvm::Expected<CodeCompleteResult> List) mutable { |
| 1078 | if (!List) |
| 1079 | return Reply(List.takeError()); |
| 1080 | CompletionList LSPList; |
| 1081 | LSPList.isIncomplete = List->HasMore; |
| 1082 | for (const auto &R : List->Completions) { |
| 1083 | CompletionItem C = R.render(Opts.CodeComplete); |
| 1084 | C.kind = adjustKindToCapability(C.kind, SupportedCompletionItemKinds); |
| 1085 | LSPList.items.push_back(std::move(C)); |
| 1086 | } |
| 1087 | return Reply(std::move(LSPList)); |
| 1088 | }); |
Ilya Biryukov | d9bdfe0 | 2017-10-06 11:54:17 +0000 | [diff] [blame] | 1089 | } |
| 1090 | |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 1091 | void ClangdLSPServer::onSignatureHelp(const TextDocumentPositionParams &Params, |
| 1092 | Callback<SignatureHelp> Reply) { |
Ilya Biryukov | 652364b | 2018-09-26 05:48:29 +0000 | [diff] [blame] | 1093 | Server->signatureHelp(Params.textDocument.uri.file(), Params.position, |
Benjamin Kramer | 9880b5d | 2019-08-15 14:16:06 +0000 | [diff] [blame] | 1094 | [Reply = std::move(Reply), this]( |
| 1095 | llvm::Expected<SignatureHelp> Signature) mutable { |
| 1096 | if (!Signature) |
| 1097 | return Reply(Signature.takeError()); |
| 1098 | if (SupportsOffsetsInSignatureHelp) |
| 1099 | return Reply(std::move(*Signature)); |
| 1100 | // Strip out the offsets from signature help for |
| 1101 | // clients that only support string labels. |
| 1102 | for (auto &SigInfo : Signature->signatures) { |
| 1103 | for (auto &Param : SigInfo.parameters) |
| 1104 | Param.labelOffsets.reset(); |
| 1105 | } |
| 1106 | return Reply(std::move(*Signature)); |
| 1107 | }); |
Ilya Biryukov | 652364b | 2018-09-26 05:48:29 +0000 | [diff] [blame] | 1108 | } |
| 1109 | |
Sam McCall | 0dbab7f | 2019-02-02 05:56:00 +0000 | [diff] [blame] | 1110 | // Go to definition has a toggle function: if def and decl are distinct, then |
| 1111 | // the first press gives you the def, the second gives you the matching def. |
| 1112 | // getToggle() returns the counterpart location that under the cursor. |
| 1113 | // |
| 1114 | // We return the toggled location alone (ignoring other symbols) to encourage |
| 1115 | // editors to "bounce" quickly between locations, without showing a menu. |
| 1116 | static Location *getToggle(const TextDocumentPositionParams &Point, |
| 1117 | LocatedSymbol &Sym) { |
| 1118 | // Toggle only makes sense with two distinct locations. |
| 1119 | if (!Sym.Definition || *Sym.Definition == Sym.PreferredDeclaration) |
| 1120 | return nullptr; |
| 1121 | if (Sym.Definition->uri.file() == Point.textDocument.uri.file() && |
| 1122 | Sym.Definition->range.contains(Point.position)) |
| 1123 | return &Sym.PreferredDeclaration; |
| 1124 | if (Sym.PreferredDeclaration.uri.file() == Point.textDocument.uri.file() && |
| 1125 | Sym.PreferredDeclaration.range.contains(Point.position)) |
| 1126 | return &*Sym.Definition; |
| 1127 | return nullptr; |
| 1128 | } |
| 1129 | |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 1130 | void ClangdLSPServer::onGoToDefinition(const TextDocumentPositionParams &Params, |
| 1131 | Callback<std::vector<Location>> Reply) { |
Sam McCall | 866ba2c | 2019-02-01 11:26:13 +0000 | [diff] [blame] | 1132 | Server->locateSymbolAt( |
| 1133 | Params.textDocument.uri.file(), Params.position, |
Benjamin Kramer | 9880b5d | 2019-08-15 14:16:06 +0000 | [diff] [blame] | 1134 | [Params, Reply = std::move(Reply)]( |
| 1135 | llvm::Expected<std::vector<LocatedSymbol>> Symbols) mutable { |
| 1136 | if (!Symbols) |
| 1137 | return Reply(Symbols.takeError()); |
| 1138 | std::vector<Location> Defs; |
| 1139 | for (auto &S : *Symbols) { |
| 1140 | if (Location *Toggle = getToggle(Params, S)) |
| 1141 | return Reply(std::vector<Location>{std::move(*Toggle)}); |
| 1142 | Defs.push_back(S.Definition.getValueOr(S.PreferredDeclaration)); |
| 1143 | } |
| 1144 | Reply(std::move(Defs)); |
| 1145 | }); |
Sam McCall | 866ba2c | 2019-02-01 11:26:13 +0000 | [diff] [blame] | 1146 | } |
| 1147 | |
| 1148 | void ClangdLSPServer::onGoToDeclaration( |
| 1149 | const TextDocumentPositionParams &Params, |
| 1150 | Callback<std::vector<Location>> Reply) { |
| 1151 | Server->locateSymbolAt( |
| 1152 | Params.textDocument.uri.file(), Params.position, |
Benjamin Kramer | 9880b5d | 2019-08-15 14:16:06 +0000 | [diff] [blame] | 1153 | [Params, Reply = std::move(Reply)]( |
| 1154 | llvm::Expected<std::vector<LocatedSymbol>> Symbols) mutable { |
| 1155 | if (!Symbols) |
| 1156 | return Reply(Symbols.takeError()); |
| 1157 | std::vector<Location> Decls; |
| 1158 | for (auto &S : *Symbols) { |
| 1159 | if (Location *Toggle = getToggle(Params, S)) |
| 1160 | return Reply(std::vector<Location>{std::move(*Toggle)}); |
| 1161 | Decls.push_back(std::move(S.PreferredDeclaration)); |
| 1162 | } |
| 1163 | Reply(std::move(Decls)); |
| 1164 | }); |
Marc-Andre Laperle | 2cbf037 | 2017-06-28 16:12:10 +0000 | [diff] [blame] | 1165 | } |
| 1166 | |
Sam McCall | 111fe84 | 2019-05-07 07:55:35 +0000 | [diff] [blame] | 1167 | void ClangdLSPServer::onSwitchSourceHeader( |
| 1168 | const TextDocumentIdentifier &Params, |
Sam McCall | b9ec3e9 | 2019-05-07 08:30:32 +0000 | [diff] [blame] | 1169 | Callback<llvm::Optional<URIForFile>> Reply) { |
Haojian Wu | d6d5edd | 2019-10-01 10:21:15 +0000 | [diff] [blame] | 1170 | Server->switchSourceHeader( |
| 1171 | Params.uri.file(), |
| 1172 | [Reply = std::move(Reply), |
| 1173 | Params](llvm::Expected<llvm::Optional<clangd::Path>> Path) mutable { |
| 1174 | if (!Path) |
| 1175 | return Reply(Path.takeError()); |
| 1176 | if (*Path) |
Haojian Wu | 77c9700 | 2019-10-07 11:37:25 +0000 | [diff] [blame] | 1177 | return Reply(URIForFile::canonicalize(**Path, Params.uri.file())); |
Haojian Wu | d6d5edd | 2019-10-01 10:21:15 +0000 | [diff] [blame] | 1178 | return Reply(llvm::None); |
| 1179 | }); |
Marc-Andre Laperle | 6571b3e | 2017-09-28 03:14:40 +0000 | [diff] [blame] | 1180 | } |
| 1181 | |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 1182 | void ClangdLSPServer::onDocumentHighlight( |
| 1183 | const TextDocumentPositionParams &Params, |
| 1184 | Callback<std::vector<DocumentHighlight>> Reply) { |
| 1185 | Server->findDocumentHighlights(Params.textDocument.uri.file(), |
| 1186 | Params.position, std::move(Reply)); |
Ilya Biryukov | 0e6a51f | 2017-12-12 12:27:47 +0000 | [diff] [blame] | 1187 | } |
| 1188 | |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 1189 | void ClangdLSPServer::onHover(const TextDocumentPositionParams &Params, |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 1190 | Callback<llvm::Optional<Hover>> Reply) { |
Ilya Biryukov | 652364b | 2018-09-26 05:48:29 +0000 | [diff] [blame] | 1191 | Server->findHover(Params.textDocument.uri.file(), Params.position, |
Benjamin Kramer | 9880b5d | 2019-08-15 14:16:06 +0000 | [diff] [blame] | 1192 | [Reply = std::move(Reply), this]( |
| 1193 | llvm::Expected<llvm::Optional<HoverInfo>> H) mutable { |
| 1194 | if (!H) |
| 1195 | return Reply(H.takeError()); |
| 1196 | if (!*H) |
| 1197 | return Reply(llvm::None); |
Ilya Biryukov | f9169d0 | 2019-05-29 10:01:00 +0000 | [diff] [blame] | 1198 | |
Benjamin Kramer | 9880b5d | 2019-08-15 14:16:06 +0000 | [diff] [blame] | 1199 | Hover R; |
| 1200 | R.contents.kind = HoverContentFormat; |
| 1201 | R.range = (*H)->SymRange; |
| 1202 | switch (HoverContentFormat) { |
| 1203 | case MarkupKind::PlainText: |
Kadir Cetinkaya | 597c6b6 | 2019-12-10 10:28:37 +0100 | [diff] [blame] | 1204 | R.contents.value = (*H)->present().asPlainText(); |
Benjamin Kramer | 9880b5d | 2019-08-15 14:16:06 +0000 | [diff] [blame] | 1205 | return Reply(std::move(R)); |
| 1206 | case MarkupKind::Markdown: |
Kadir Cetinkaya | 597c6b6 | 2019-12-10 10:28:37 +0100 | [diff] [blame] | 1207 | R.contents.value = (*H)->present().asMarkdown(); |
Benjamin Kramer | 9880b5d | 2019-08-15 14:16:06 +0000 | [diff] [blame] | 1208 | return Reply(std::move(R)); |
| 1209 | }; |
| 1210 | llvm_unreachable("unhandled MarkupKind"); |
| 1211 | }); |
Marc-Andre Laperle | 3e618ed | 2018-02-16 21:38:15 +0000 | [diff] [blame] | 1212 | } |
| 1213 | |
Kadir Cetinkaya | 8665802 | 2019-03-19 09:27:04 +0000 | [diff] [blame] | 1214 | void ClangdLSPServer::onTypeHierarchy( |
| 1215 | const TypeHierarchyParams &Params, |
| 1216 | Callback<Optional<TypeHierarchyItem>> Reply) { |
| 1217 | Server->typeHierarchy(Params.textDocument.uri.file(), Params.position, |
| 1218 | Params.resolve, Params.direction, std::move(Reply)); |
| 1219 | } |
| 1220 | |
Nathan Ridge | 087b044 | 2019-07-13 03:24:48 +0000 | [diff] [blame] | 1221 | void ClangdLSPServer::onResolveTypeHierarchy( |
| 1222 | const ResolveTypeHierarchyItemParams &Params, |
| 1223 | Callback<Optional<TypeHierarchyItem>> Reply) { |
| 1224 | Server->resolveTypeHierarchy(Params.item, Params.resolve, Params.direction, |
| 1225 | std::move(Reply)); |
| 1226 | } |
| 1227 | |
Nathan Ridge | 0a4f99c | 2020-11-15 22:45:17 -0500 | [diff] [blame^] | 1228 | void ClangdLSPServer::onPrepareCallHierarchy( |
| 1229 | const CallHierarchyPrepareParams &Params, |
| 1230 | Callback<std::vector<CallHierarchyItem>> Reply) { |
| 1231 | Server->prepareCallHierarchy(Params.textDocument.uri.file(), Params.position, |
| 1232 | std::move(Reply)); |
| 1233 | } |
| 1234 | |
| 1235 | void ClangdLSPServer::onCallHierarchyIncomingCalls( |
| 1236 | const CallHierarchyIncomingCallsParams &Params, |
| 1237 | Callback<std::vector<CallHierarchyIncomingCall>> Reply) { |
| 1238 | Server->incomingCalls(Params.item, std::move(Reply)); |
| 1239 | } |
| 1240 | |
| 1241 | void ClangdLSPServer::onCallHierarchyOutgoingCalls( |
| 1242 | const CallHierarchyOutgoingCallsParams &Params, |
| 1243 | Callback<std::vector<CallHierarchyOutgoingCall>> Reply) { |
| 1244 | // FIXME: To be implemented. |
| 1245 | Reply(std::vector<CallHierarchyOutgoingCall>{}); |
| 1246 | } |
| 1247 | |
Simon Marchi | 8801678 | 2018-08-01 11:28:49 +0000 | [diff] [blame] | 1248 | void ClangdLSPServer::applyConfiguration( |
Sam McCall | bc90461 | 2018-10-25 04:22:52 +0000 | [diff] [blame] | 1249 | const ConfigurationSettings &Settings) { |
Simon Marchi | abeed66 | 2018-10-16 15:55:03 +0000 | [diff] [blame] | 1250 | // Per-file update to the compilation database. |
David Goldman | 60249c2 | 2020-01-13 17:01:10 -0500 | [diff] [blame] | 1251 | llvm::StringSet<> ModifiedFiles; |
Sam McCall | bc90461 | 2018-10-25 04:22:52 +0000 | [diff] [blame] | 1252 | for (auto &Entry : Settings.compilationDatabaseChanges) { |
Sam McCall | bc90461 | 2018-10-25 04:22:52 +0000 | [diff] [blame] | 1253 | PathRef File = Entry.first; |
Sam McCall | c55d09a | 2018-11-02 13:09:36 +0000 | [diff] [blame] | 1254 | auto Old = CDB->getCompileCommand(File); |
| 1255 | auto New = |
| 1256 | tooling::CompileCommand(std::move(Entry.second.workingDirectory), File, |
| 1257 | std::move(Entry.second.compilationCommand), |
| 1258 | /*Output=*/""); |
Sam McCall | 6980edb | 2018-11-02 14:07:51 +0000 | [diff] [blame] | 1259 | if (Old != New) { |
Sam McCall | c55d09a | 2018-11-02 13:09:36 +0000 | [diff] [blame] | 1260 | CDB->setCompileCommand(File, std::move(New)); |
David Goldman | 60249c2 | 2020-01-13 17:01:10 -0500 | [diff] [blame] | 1261 | ModifiedFiles.insert(File); |
Sam McCall | 6980edb | 2018-11-02 14:07:51 +0000 | [diff] [blame] | 1262 | } |
Alex Lorenz | f808786 | 2018-08-01 17:39:29 +0000 | [diff] [blame] | 1263 | } |
David Goldman | 60249c2 | 2020-01-13 17:01:10 -0500 | [diff] [blame] | 1264 | |
Sam McCall | 596b63a | 2020-04-10 03:27:37 +0200 | [diff] [blame] | 1265 | reparseOpenFilesIfNeeded( |
| 1266 | [&](llvm::StringRef File) { return ModifiedFiles.count(File) != 0; }); |
Simon Marchi | 5178f92 | 2018-02-22 14:00:39 +0000 | [diff] [blame] | 1267 | } |
| 1268 | |
Sam McCall | edf6a19 | 2020-03-24 00:31:14 +0100 | [diff] [blame] | 1269 | void ClangdLSPServer::publishTheiaSemanticHighlighting( |
| 1270 | const TheiaSemanticHighlightingParams &Params) { |
Johan Vikstrom | a848dab | 2019-07-04 07:53:12 +0000 | [diff] [blame] | 1271 | notify("textDocument/semanticHighlighting", Params); |
| 1272 | } |
| 1273 | |
Ilya Biryukov | 49c1071 | 2019-03-25 10:15:11 +0000 | [diff] [blame] | 1274 | void ClangdLSPServer::publishDiagnostics( |
Sam McCall | 6525a6b | 2020-03-03 12:44:40 +0100 | [diff] [blame] | 1275 | const PublishDiagnosticsParams &Params) { |
| 1276 | notify("textDocument/publishDiagnostics", Params); |
Ilya Biryukov | 49c1071 | 2019-03-25 10:15:11 +0000 | [diff] [blame] | 1277 | } |
| 1278 | |
Kadir Cetinkaya | 35871fd | 2020-09-28 15:09:55 +0200 | [diff] [blame] | 1279 | void ClangdLSPServer::maybeExportMemoryProfile() { |
| 1280 | if (!trace::enabled()) |
| 1281 | return; |
| 1282 | // Profiling might be expensive, so we throttle it to happen once every 5 |
| 1283 | // minutes. |
| 1284 | static constexpr auto ProfileInterval = std::chrono::minutes(5); |
| 1285 | auto Now = std::chrono::steady_clock::now(); |
| 1286 | if (Now < NextProfileTime) |
| 1287 | return; |
| 1288 | |
| 1289 | static constexpr trace::Metric MemoryUsage( |
| 1290 | "memory_usage", trace::Metric::Value, "component_name"); |
| 1291 | trace::Span Tracer("ProfileBrief"); |
| 1292 | MemoryTree MT; |
| 1293 | profile(MT); |
| 1294 | record(MT, "clangd_lsp_server", MemoryUsage); |
| 1295 | NextProfileTime = Now + ProfileInterval; |
| 1296 | } |
| 1297 | |
Simon Marchi | 8801678 | 2018-08-01 11:28:49 +0000 | [diff] [blame] | 1298 | // FIXME: This function needs to be properly tested. |
| 1299 | void ClangdLSPServer::onChangeConfiguration( |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 1300 | const DidChangeConfigurationParams &Params) { |
Simon Marchi | 8801678 | 2018-08-01 11:28:49 +0000 | [diff] [blame] | 1301 | applyConfiguration(Params.settings); |
| 1302 | } |
| 1303 | |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 1304 | void ClangdLSPServer::onReference(const ReferenceParams &Params, |
| 1305 | Callback<std::vector<Location>> Reply) { |
Ilya Biryukov | 652364b | 2018-09-26 05:48:29 +0000 | [diff] [blame] | 1306 | Server->findReferences(Params.textDocument.uri.file(), Params.position, |
Sam McCall | 7ba0779 | 2020-09-29 10:37:46 +0200 | [diff] [blame] | 1307 | Opts.CodeComplete.Limit, |
Haojian Wu | 5181ada | 2019-11-18 11:35:00 +0100 | [diff] [blame] | 1308 | [Reply = std::move(Reply)]( |
| 1309 | llvm::Expected<ReferencesResult> Refs) mutable { |
| 1310 | if (!Refs) |
| 1311 | return Reply(Refs.takeError()); |
| 1312 | return Reply(std::move(Refs->References)); |
| 1313 | }); |
Sam McCall | 1ad142f | 2018-09-05 11:53:07 +0000 | [diff] [blame] | 1314 | } |
| 1315 | |
Utkarsh Saxena | b31486a | 2020-11-18 13:25:09 +0100 | [diff] [blame] | 1316 | void ClangdLSPServer::onGoToImplementation( |
| 1317 | const TextDocumentPositionParams &Params, |
| 1318 | Callback<std::vector<Location>> Reply) { |
| 1319 | Server->findImplementations( |
| 1320 | Params.textDocument.uri.file(), Params.position, |
| 1321 | [Reply = std::move(Reply)]( |
| 1322 | llvm::Expected<std::vector<LocatedSymbol>> Overrides) mutable { |
| 1323 | if (!Overrides) |
| 1324 | return Reply(Overrides.takeError()); |
| 1325 | std::vector<Location> Impls; |
| 1326 | for (const LocatedSymbol &Sym : *Overrides) |
| 1327 | Impls.push_back(Sym.PreferredDeclaration); |
| 1328 | return Reply(std::move(Impls)); |
| 1329 | }); |
| 1330 | } |
| 1331 | |
Jan Korous | b406701 | 2018-11-27 16:40:46 +0000 | [diff] [blame] | 1332 | void ClangdLSPServer::onSymbolInfo(const TextDocumentPositionParams &Params, |
| 1333 | Callback<std::vector<SymbolDetails>> Reply) { |
| 1334 | Server->symbolInfo(Params.textDocument.uri.file(), Params.position, |
| 1335 | std::move(Reply)); |
| 1336 | } |
| 1337 | |
Utkarsh Saxena | 55925da | 2019-09-24 13:38:33 +0000 | [diff] [blame] | 1338 | void ClangdLSPServer::onSelectionRange( |
| 1339 | const SelectionRangeParams &Params, |
| 1340 | Callback<std::vector<SelectionRange>> Reply) { |
Utkarsh Saxena | 55925da | 2019-09-24 13:38:33 +0000 | [diff] [blame] | 1341 | Server->semanticRanges( |
Sam McCall | 8f237f9 | 2020-03-25 00:51:50 +0100 | [diff] [blame] | 1342 | Params.textDocument.uri.file(), Params.positions, |
Utkarsh Saxena | 55925da | 2019-09-24 13:38:33 +0000 | [diff] [blame] | 1343 | [Reply = std::move(Reply)]( |
Sam McCall | 8f237f9 | 2020-03-25 00:51:50 +0100 | [diff] [blame] | 1344 | llvm::Expected<std::vector<SelectionRange>> Ranges) mutable { |
| 1345 | if (!Ranges) |
Utkarsh Saxena | 55925da | 2019-09-24 13:38:33 +0000 | [diff] [blame] | 1346 | return Reply(Ranges.takeError()); |
Sam McCall | 8f237f9 | 2020-03-25 00:51:50 +0100 | [diff] [blame] | 1347 | return Reply(std::move(*Ranges)); |
Utkarsh Saxena | 55925da | 2019-09-24 13:38:33 +0000 | [diff] [blame] | 1348 | }); |
| 1349 | } |
| 1350 | |
Sam McCall | 8d7ecc1 | 2019-12-16 19:08:51 +0100 | [diff] [blame] | 1351 | void ClangdLSPServer::onDocumentLink( |
| 1352 | const DocumentLinkParams &Params, |
| 1353 | Callback<std::vector<DocumentLink>> Reply) { |
| 1354 | |
| 1355 | // TODO(forster): This currently resolves all targets eagerly. This is slow, |
| 1356 | // because it blocks on the preamble/AST being built. We could respond to the |
| 1357 | // request faster by using string matching or the lexer to find the includes |
| 1358 | // and resolving the targets lazily. |
| 1359 | Server->documentLinks( |
| 1360 | Params.textDocument.uri.file(), |
| 1361 | [Reply = std::move(Reply)]( |
| 1362 | llvm::Expected<std::vector<DocumentLink>> Links) mutable { |
| 1363 | if (!Links) { |
| 1364 | return Reply(Links.takeError()); |
| 1365 | } |
| 1366 | return Reply(std::move(Links)); |
| 1367 | }); |
| 1368 | } |
| 1369 | |
Sam McCall | 9e3063e | 2020-04-01 16:21:44 +0200 | [diff] [blame] | 1370 | // Increment a numeric string: "" -> 1 -> 2 -> ... -> 9 -> 10 -> 11 ... |
| 1371 | static void increment(std::string &S) { |
| 1372 | for (char &C : llvm::reverse(S)) { |
| 1373 | if (C != '9') { |
| 1374 | ++C; |
| 1375 | return; |
| 1376 | } |
| 1377 | C = '0'; |
| 1378 | } |
| 1379 | S.insert(S.begin(), '1'); |
| 1380 | } |
| 1381 | |
Sam McCall | 71177ac | 2020-03-24 02:24:47 +0100 | [diff] [blame] | 1382 | void ClangdLSPServer::onSemanticTokens(const SemanticTokensParams &Params, |
| 1383 | Callback<SemanticTokens> CB) { |
| 1384 | Server->semanticHighlights( |
| 1385 | Params.textDocument.uri.file(), |
Sam McCall | 9e3063e | 2020-04-01 16:21:44 +0200 | [diff] [blame] | 1386 | [this, File(Params.textDocument.uri.file().str()), CB(std::move(CB))]( |
| 1387 | llvm::Expected<std::vector<HighlightingToken>> HT) mutable { |
| 1388 | if (!HT) |
| 1389 | return CB(HT.takeError()); |
Sam McCall | 71177ac | 2020-03-24 02:24:47 +0100 | [diff] [blame] | 1390 | SemanticTokens Result; |
Sam McCall | 9e3063e | 2020-04-01 16:21:44 +0200 | [diff] [blame] | 1391 | Result.tokens = toSemanticTokens(*HT); |
| 1392 | { |
| 1393 | std::lock_guard<std::mutex> Lock(SemanticTokensMutex); |
Kadir Cetinkaya | e64f99c | 2020-04-16 23:12:09 +0200 | [diff] [blame] | 1394 | auto &Last = LastSemanticTokens[File]; |
Sam McCall | 9e3063e | 2020-04-01 16:21:44 +0200 | [diff] [blame] | 1395 | |
| 1396 | Last.tokens = Result.tokens; |
| 1397 | increment(Last.resultId); |
| 1398 | Result.resultId = Last.resultId; |
| 1399 | } |
| 1400 | CB(std::move(Result)); |
| 1401 | }); |
| 1402 | } |
| 1403 | |
Sam McCall | 5fea54b | 2020-07-10 16:08:14 +0200 | [diff] [blame] | 1404 | void ClangdLSPServer::onSemanticTokensDelta( |
| 1405 | const SemanticTokensDeltaParams &Params, |
| 1406 | Callback<SemanticTokensOrDelta> CB) { |
Sam McCall | 9e3063e | 2020-04-01 16:21:44 +0200 | [diff] [blame] | 1407 | Server->semanticHighlights( |
| 1408 | Params.textDocument.uri.file(), |
| 1409 | [this, PrevResultID(Params.previousResultId), |
| 1410 | File(Params.textDocument.uri.file().str()), CB(std::move(CB))]( |
| 1411 | llvm::Expected<std::vector<HighlightingToken>> HT) mutable { |
| 1412 | if (!HT) |
| 1413 | return CB(HT.takeError()); |
| 1414 | std::vector<SemanticToken> Toks = toSemanticTokens(*HT); |
| 1415 | |
Sam McCall | 5fea54b | 2020-07-10 16:08:14 +0200 | [diff] [blame] | 1416 | SemanticTokensOrDelta Result; |
Sam McCall | 9e3063e | 2020-04-01 16:21:44 +0200 | [diff] [blame] | 1417 | { |
| 1418 | std::lock_guard<std::mutex> Lock(SemanticTokensMutex); |
Kadir Cetinkaya | e64f99c | 2020-04-16 23:12:09 +0200 | [diff] [blame] | 1419 | auto &Last = LastSemanticTokens[File]; |
Sam McCall | 9e3063e | 2020-04-01 16:21:44 +0200 | [diff] [blame] | 1420 | |
| 1421 | if (PrevResultID == Last.resultId) { |
| 1422 | Result.edits = diffTokens(Last.tokens, Toks); |
| 1423 | } else { |
Sam McCall | 5fea54b | 2020-07-10 16:08:14 +0200 | [diff] [blame] | 1424 | vlog("semanticTokens/full/delta: wanted edits vs {0} but last " |
| 1425 | "result had ID {1}. Returning full token list.", |
Sam McCall | 9e3063e | 2020-04-01 16:21:44 +0200 | [diff] [blame] | 1426 | PrevResultID, Last.resultId); |
| 1427 | Result.tokens = Toks; |
| 1428 | } |
| 1429 | |
| 1430 | Last.tokens = std::move(Toks); |
| 1431 | increment(Last.resultId); |
| 1432 | Result.resultId = Last.resultId; |
| 1433 | } |
| 1434 | |
Sam McCall | 71177ac | 2020-03-24 02:24:47 +0100 | [diff] [blame] | 1435 | CB(std::move(Result)); |
| 1436 | }); |
| 1437 | } |
| 1438 | |
Kadir Cetinkaya | d0f2874 | 2020-10-13 00:10:04 +0200 | [diff] [blame] | 1439 | void ClangdLSPServer::onMemoryUsage(const NoParams &, |
| 1440 | Callback<MemoryTree> Reply) { |
| 1441 | llvm::BumpPtrAllocator DetailAlloc; |
| 1442 | MemoryTree MT(&DetailAlloc); |
| 1443 | profile(MT); |
| 1444 | Reply(std::move(MT)); |
| 1445 | } |
| 1446 | |
Sam McCall | 8adc4d1 | 2020-10-16 20:03:48 +0200 | [diff] [blame] | 1447 | void ClangdLSPServer::onAST(const ASTParams &Params, |
| 1448 | Callback<llvm::Optional<ASTNode>> CB) { |
| 1449 | Server->getAST(Params.textDocument.uri.file(), Params.range, std::move(CB)); |
| 1450 | } |
| 1451 | |
Sam McCall | 7ba0779 | 2020-09-29 10:37:46 +0200 | [diff] [blame] | 1452 | ClangdLSPServer::ClangdLSPServer(class Transport &Transp, |
| 1453 | const ThreadsafeFS &TFS, |
| 1454 | const ClangdLSPServer::Options &Opts) |
Kadir Cetinkaya | 9d66247 | 2019-10-15 14:20:52 +0000 | [diff] [blame] | 1455 | : BackgroundContext(Context::current().clone()), Transp(Transp), |
Sam McCall | 7ba0779 | 2020-09-29 10:37:46 +0200 | [diff] [blame] | 1456 | MsgHandler(new MessageHandler(*this)), TFS(TFS), |
| 1457 | SupportedSymbolKinds(defaultSymbolKinds()), |
| 1458 | SupportedCompletionItemKinds(defaultCompletionItemKinds()), Opts(Opts) { |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 1459 | // clang-format off |
| 1460 | MsgHandler->bind("initialize", &ClangdLSPServer::onInitialize); |
Sam McCall | 8a2d294 | 2020-03-03 12:12:14 +0100 | [diff] [blame] | 1461 | MsgHandler->bind("initialized", &ClangdLSPServer::onInitialized); |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 1462 | MsgHandler->bind("shutdown", &ClangdLSPServer::onShutdown); |
Sam McCall | 422c828 | 2018-11-26 16:00:11 +0000 | [diff] [blame] | 1463 | MsgHandler->bind("sync", &ClangdLSPServer::onSync); |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 1464 | MsgHandler->bind("textDocument/rangeFormatting", &ClangdLSPServer::onDocumentRangeFormatting); |
| 1465 | MsgHandler->bind("textDocument/onTypeFormatting", &ClangdLSPServer::onDocumentOnTypeFormatting); |
| 1466 | MsgHandler->bind("textDocument/formatting", &ClangdLSPServer::onDocumentFormatting); |
| 1467 | MsgHandler->bind("textDocument/codeAction", &ClangdLSPServer::onCodeAction); |
| 1468 | MsgHandler->bind("textDocument/completion", &ClangdLSPServer::onCompletion); |
| 1469 | MsgHandler->bind("textDocument/signatureHelp", &ClangdLSPServer::onSignatureHelp); |
| 1470 | MsgHandler->bind("textDocument/definition", &ClangdLSPServer::onGoToDefinition); |
Sam McCall | 866ba2c | 2019-02-01 11:26:13 +0000 | [diff] [blame] | 1471 | MsgHandler->bind("textDocument/declaration", &ClangdLSPServer::onGoToDeclaration); |
Utkarsh Saxena | b31486a | 2020-11-18 13:25:09 +0100 | [diff] [blame] | 1472 | MsgHandler->bind("textDocument/implementation", &ClangdLSPServer::onGoToImplementation); |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 1473 | MsgHandler->bind("textDocument/references", &ClangdLSPServer::onReference); |
| 1474 | MsgHandler->bind("textDocument/switchSourceHeader", &ClangdLSPServer::onSwitchSourceHeader); |
Haojian Wu | f429ab6 | 2019-07-24 07:49:23 +0000 | [diff] [blame] | 1475 | MsgHandler->bind("textDocument/prepareRename", &ClangdLSPServer::onPrepareRename); |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 1476 | MsgHandler->bind("textDocument/rename", &ClangdLSPServer::onRename); |
| 1477 | MsgHandler->bind("textDocument/hover", &ClangdLSPServer::onHover); |
| 1478 | MsgHandler->bind("textDocument/documentSymbol", &ClangdLSPServer::onDocumentSymbol); |
| 1479 | MsgHandler->bind("workspace/executeCommand", &ClangdLSPServer::onCommand); |
| 1480 | MsgHandler->bind("textDocument/documentHighlight", &ClangdLSPServer::onDocumentHighlight); |
| 1481 | MsgHandler->bind("workspace/symbol", &ClangdLSPServer::onWorkspaceSymbol); |
Sam McCall | 8adc4d1 | 2020-10-16 20:03:48 +0200 | [diff] [blame] | 1482 | MsgHandler->bind("textDocument/ast", &ClangdLSPServer::onAST); |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 1483 | MsgHandler->bind("textDocument/didOpen", &ClangdLSPServer::onDocumentDidOpen); |
| 1484 | MsgHandler->bind("textDocument/didClose", &ClangdLSPServer::onDocumentDidClose); |
| 1485 | MsgHandler->bind("textDocument/didChange", &ClangdLSPServer::onDocumentDidChange); |
Sam McCall | 596b63a | 2020-04-10 03:27:37 +0200 | [diff] [blame] | 1486 | MsgHandler->bind("textDocument/didSave", &ClangdLSPServer::onDocumentDidSave); |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 1487 | MsgHandler->bind("workspace/didChangeWatchedFiles", &ClangdLSPServer::onFileEvent); |
| 1488 | MsgHandler->bind("workspace/didChangeConfiguration", &ClangdLSPServer::onChangeConfiguration); |
Jan Korous | b406701 | 2018-11-27 16:40:46 +0000 | [diff] [blame] | 1489 | MsgHandler->bind("textDocument/symbolInfo", &ClangdLSPServer::onSymbolInfo); |
Kadir Cetinkaya | 8665802 | 2019-03-19 09:27:04 +0000 | [diff] [blame] | 1490 | MsgHandler->bind("textDocument/typeHierarchy", &ClangdLSPServer::onTypeHierarchy); |
Nathan Ridge | 087b044 | 2019-07-13 03:24:48 +0000 | [diff] [blame] | 1491 | MsgHandler->bind("typeHierarchy/resolve", &ClangdLSPServer::onResolveTypeHierarchy); |
Nathan Ridge | 0a4f99c | 2020-11-15 22:45:17 -0500 | [diff] [blame^] | 1492 | MsgHandler->bind("textDocument/prepareCallHierarchy", &ClangdLSPServer::onPrepareCallHierarchy); |
| 1493 | MsgHandler->bind("callHierarchy/incomingCalls", &ClangdLSPServer::onCallHierarchyIncomingCalls); |
| 1494 | MsgHandler->bind("callHierarchy/outgoingCalls", &ClangdLSPServer::onCallHierarchyOutgoingCalls); |
Utkarsh Saxena | 55925da | 2019-09-24 13:38:33 +0000 | [diff] [blame] | 1495 | MsgHandler->bind("textDocument/selectionRange", &ClangdLSPServer::onSelectionRange); |
Sam McCall | 8d7ecc1 | 2019-12-16 19:08:51 +0100 | [diff] [blame] | 1496 | MsgHandler->bind("textDocument/documentLink", &ClangdLSPServer::onDocumentLink); |
Sam McCall | 5fea54b | 2020-07-10 16:08:14 +0200 | [diff] [blame] | 1497 | MsgHandler->bind("textDocument/semanticTokens/full", &ClangdLSPServer::onSemanticTokens); |
| 1498 | MsgHandler->bind("textDocument/semanticTokens/full/delta", &ClangdLSPServer::onSemanticTokensDelta); |
Kadir Cetinkaya | d0f2874 | 2020-10-13 00:10:04 +0200 | [diff] [blame] | 1499 | MsgHandler->bind("$/memoryUsage", &ClangdLSPServer::onMemoryUsage); |
Kirill Bobyrev | 7a514c9 | 2020-07-14 09:28:38 +0200 | [diff] [blame] | 1500 | if (Opts.FoldingRanges) |
| 1501 | MsgHandler->bind("textDocument/foldingRange", &ClangdLSPServer::onFoldingRange); |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 1502 | // clang-format on |
Kadir Cetinkaya | 35871fd | 2020-09-28 15:09:55 +0200 | [diff] [blame] | 1503 | |
| 1504 | // Delay first profile until we've finished warming up. |
| 1505 | NextProfileTime = std::chrono::steady_clock::now() + std::chrono::minutes(1); |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 1506 | } |
| 1507 | |
Kadir Cetinkaya | 6b85032 | 2020-03-17 19:08:23 +0100 | [diff] [blame] | 1508 | ClangdLSPServer::~ClangdLSPServer() { |
| 1509 | IsBeingDestroyed = true; |
Sam McCall | 8bda5f2 | 2019-10-23 11:11:18 +0200 | [diff] [blame] | 1510 | // Explicitly destroy ClangdServer first, blocking on threads it owns. |
| 1511 | // This ensures they don't access any other members. |
| 1512 | Server.reset(); |
| 1513 | } |
Ilya Biryukov | 38d7977 | 2017-05-16 09:38:59 +0000 | [diff] [blame] | 1514 | |
Sam McCall | dc8f3cf | 2018-10-17 07:32:05 +0000 | [diff] [blame] | 1515 | bool ClangdLSPServer::run() { |
Ilya Biryukov | afb5554 | 2017-05-16 14:40:30 +0000 | [diff] [blame] | 1516 | // Run the Language Server loop. |
Sam McCall | dc8f3cf | 2018-10-17 07:32:05 +0000 | [diff] [blame] | 1517 | bool CleanExit = true; |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 1518 | if (auto Err = Transp.loop(*MsgHandler)) { |
Sam McCall | dc8f3cf | 2018-10-17 07:32:05 +0000 | [diff] [blame] | 1519 | elog("Transport error: {0}", std::move(Err)); |
| 1520 | CleanExit = false; |
| 1521 | } |
Ilya Biryukov | afb5554 | 2017-05-16 14:40:30 +0000 | [diff] [blame] | 1522 | |
Sam McCall | dc8f3cf | 2018-10-17 07:32:05 +0000 | [diff] [blame] | 1523 | return CleanExit && ShutdownRequestReceived; |
Ilya Biryukov | 38d7977 | 2017-05-16 09:38:59 +0000 | [diff] [blame] | 1524 | } |
| 1525 | |
Kadir Cetinkaya | 35871fd | 2020-09-28 15:09:55 +0200 | [diff] [blame] | 1526 | void ClangdLSPServer::profile(MemoryTree &MT) const { |
| 1527 | if (Server) |
| 1528 | Server->profile(MT.child("clangd_server")); |
| 1529 | } |
| 1530 | |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 1531 | std::vector<Fix> ClangdLSPServer::getFixes(llvm::StringRef File, |
Ilya Biryukov | 71028b8 | 2018-03-12 15:28:22 +0000 | [diff] [blame] | 1532 | const clangd::Diagnostic &D) { |
Ilya Biryukov | 38d7977 | 2017-05-16 09:38:59 +0000 | [diff] [blame] | 1533 | std::lock_guard<std::mutex> Lock(FixItsMutex); |
| 1534 | auto DiagToFixItsIter = FixItsMap.find(File); |
| 1535 | if (DiagToFixItsIter == FixItsMap.end()) |
| 1536 | return {}; |
| 1537 | |
| 1538 | const auto &DiagToFixItsMap = DiagToFixItsIter->second; |
| 1539 | auto FixItsIter = DiagToFixItsMap.find(D); |
| 1540 | if (FixItsIter == DiagToFixItsMap.end()) |
| 1541 | return {}; |
| 1542 | |
| 1543 | return FixItsIter->second; |
| 1544 | } |
| 1545 | |
Sam McCall | 032727f | 2020-05-06 01:39:59 +0200 | [diff] [blame] | 1546 | // A completion request is sent when the user types '>' or ':', but we only |
| 1547 | // want to trigger on '->' and '::'. We check the preceeding text to make |
| 1548 | // sure it matches what we expected. |
| 1549 | // Running the lexer here would be more robust (e.g. we can detect comments |
| 1550 | // and avoid triggering completion there), but we choose to err on the side |
| 1551 | // of simplicity here. |
Ilya Biryukov | b0826bd | 2019-01-03 13:37:12 +0000 | [diff] [blame] | 1552 | bool ClangdLSPServer::shouldRunCompletion( |
| 1553 | const CompletionParams &Params) const { |
Sam McCall | 032727f | 2020-05-06 01:39:59 +0200 | [diff] [blame] | 1554 | if (Params.context.triggerKind != CompletionTriggerKind::TriggerCharacter) |
Ilya Biryukov | b0826bd | 2019-01-03 13:37:12 +0000 | [diff] [blame] | 1555 | return true; |
Ilya Biryukov | b0826bd | 2019-01-03 13:37:12 +0000 | [diff] [blame] | 1556 | auto Code = DraftMgr.getDraft(Params.textDocument.uri.file()); |
| 1557 | if (!Code) |
| 1558 | return true; // completion code will log the error for untracked doc. |
Sam McCall | caf5a4d | 2020-03-03 15:57:39 +0100 | [diff] [blame] | 1559 | auto Offset = positionToOffset(Code->Contents, Params.position, |
Ilya Biryukov | b0826bd | 2019-01-03 13:37:12 +0000 | [diff] [blame] | 1560 | /*AllowColumnsBeyondLineLength=*/false); |
| 1561 | if (!Offset) { |
| 1562 | vlog("could not convert position '{0}' to offset for file '{1}'", |
| 1563 | Params.position, Params.textDocument.uri.file()); |
| 1564 | return true; |
| 1565 | } |
Sam McCall | 032727f | 2020-05-06 01:39:59 +0200 | [diff] [blame] | 1566 | return allowImplicitCompletion(Code->Contents, *Offset); |
Ilya Biryukov | b0826bd | 2019-01-03 13:37:12 +0000 | [diff] [blame] | 1567 | } |
| 1568 | |
Johan Vikstrom | a848dab | 2019-07-04 07:53:12 +0000 | [diff] [blame] | 1569 | void ClangdLSPServer::onHighlightingsReady( |
Sam McCall | 2cd33e6 | 2020-03-04 00:33:29 +0100 | [diff] [blame] | 1570 | PathRef File, llvm::StringRef Version, |
| 1571 | std::vector<HighlightingToken> Highlightings) { |
Johan Vikstrom | c2653ef2 | 2019-08-01 08:08:44 +0000 | [diff] [blame] | 1572 | std::vector<HighlightingToken> Old; |
| 1573 | std::vector<HighlightingToken> HighlightingsCopy = Highlightings; |
| 1574 | { |
| 1575 | std::lock_guard<std::mutex> Lock(HighlightingsMutex); |
| 1576 | Old = std::move(FileToHighlightings[File]); |
| 1577 | FileToHighlightings[File] = std::move(HighlightingsCopy); |
| 1578 | } |
| 1579 | // LSP allows us to send incremental edits of highlightings. Also need to diff |
| 1580 | // to remove highlightings from tokens that should no longer have them. |
Haojian Wu | 0a6000f | 2019-08-26 08:38:45 +0000 | [diff] [blame] | 1581 | std::vector<LineHighlightings> Diffed = diffHighlightings(Highlightings, Old); |
Sam McCall | edf6a19 | 2020-03-24 00:31:14 +0100 | [diff] [blame] | 1582 | TheiaSemanticHighlightingParams Notification; |
Sam McCall | 2cd33e6 | 2020-03-04 00:33:29 +0100 | [diff] [blame] | 1583 | Notification.TextDocument.uri = |
| 1584 | URIForFile::canonicalize(File, /*TUPath=*/File); |
| 1585 | Notification.TextDocument.version = decodeVersion(Version); |
Sam McCall | edf6a19 | 2020-03-24 00:31:14 +0100 | [diff] [blame] | 1586 | Notification.Lines = toTheiaSemanticHighlightingInformation(Diffed); |
| 1587 | publishTheiaSemanticHighlighting(Notification); |
Johan Vikstrom | a848dab | 2019-07-04 07:53:12 +0000 | [diff] [blame] | 1588 | } |
| 1589 | |
Sam McCall | 2cd33e6 | 2020-03-04 00:33:29 +0100 | [diff] [blame] | 1590 | void ClangdLSPServer::onDiagnosticsReady(PathRef File, llvm::StringRef Version, |
Sam McCall | a7bb0cc | 2018-03-12 23:22:35 +0000 | [diff] [blame] | 1591 | std::vector<Diag> Diagnostics) { |
Sam McCall | 6525a6b | 2020-03-03 12:44:40 +0100 | [diff] [blame] | 1592 | PublishDiagnosticsParams Notification; |
Sam McCall | 2cd33e6 | 2020-03-04 00:33:29 +0100 | [diff] [blame] | 1593 | Notification.version = decodeVersion(Version); |
Sam McCall | 6525a6b | 2020-03-03 12:44:40 +0100 | [diff] [blame] | 1594 | Notification.uri = URIForFile::canonicalize(File, /*TUPath=*/File); |
Ilya Biryukov | 38d7977 | 2017-05-16 09:38:59 +0000 | [diff] [blame] | 1595 | DiagnosticToReplacementMap LocalFixIts; // Temporary storage |
Sam McCall | a7bb0cc | 2018-03-12 23:22:35 +0000 | [diff] [blame] | 1596 | for (auto &Diag : Diagnostics) { |
Sam McCall | 6525a6b | 2020-03-03 12:44:40 +0100 | [diff] [blame] | 1597 | toLSPDiags(Diag, Notification.uri, DiagOpts, |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 1598 | [&](clangd::Diagnostic Diag, llvm::ArrayRef<Fix> Fixes) { |
Sam McCall | 16e7070 | 2018-10-24 07:59:38 +0000 | [diff] [blame] | 1599 | auto &FixItsForDiagnostic = LocalFixIts[Diag]; |
| 1600 | llvm::copy(Fixes, std::back_inserter(FixItsForDiagnostic)); |
Sam McCall | 6525a6b | 2020-03-03 12:44:40 +0100 | [diff] [blame] | 1601 | Notification.diagnostics.push_back(std::move(Diag)); |
Sam McCall | 16e7070 | 2018-10-24 07:59:38 +0000 | [diff] [blame] | 1602 | }); |
Ilya Biryukov | 38d7977 | 2017-05-16 09:38:59 +0000 | [diff] [blame] | 1603 | } |
| 1604 | |
| 1605 | // Cache FixIts |
| 1606 | { |
Ilya Biryukov | 38d7977 | 2017-05-16 09:38:59 +0000 | [diff] [blame] | 1607 | std::lock_guard<std::mutex> Lock(FixItsMutex); |
| 1608 | FixItsMap[File] = LocalFixIts; |
| 1609 | } |
| 1610 | |
Ilya Biryukov | 49c1071 | 2019-03-25 10:15:11 +0000 | [diff] [blame] | 1611 | // Send a notification to the LSP client. |
Sam McCall | 6525a6b | 2020-03-03 12:44:40 +0100 | [diff] [blame] | 1612 | publishDiagnostics(Notification); |
Ilya Biryukov | 38d7977 | 2017-05-16 09:38:59 +0000 | [diff] [blame] | 1613 | } |
Simon Marchi | 9569fd5 | 2018-03-16 14:30:42 +0000 | [diff] [blame] | 1614 | |
Sam McCall | 7d20e80 | 2020-01-22 19:41:45 +0100 | [diff] [blame] | 1615 | void ClangdLSPServer::onBackgroundIndexProgress( |
| 1616 | const BackgroundQueue::Stats &Stats) { |
| 1617 | static const char ProgressToken[] = "backgroundIndexProgress"; |
| 1618 | std::lock_guard<std::mutex> Lock(BackgroundIndexProgressMutex); |
| 1619 | |
| 1620 | auto NotifyProgress = [this](const BackgroundQueue::Stats &Stats) { |
| 1621 | if (BackgroundIndexProgressState != BackgroundIndexProgress::Live) { |
| 1622 | WorkDoneProgressBegin Begin; |
| 1623 | Begin.percentage = true; |
| 1624 | Begin.title = "indexing"; |
| 1625 | progress(ProgressToken, std::move(Begin)); |
| 1626 | BackgroundIndexProgressState = BackgroundIndexProgress::Live; |
| 1627 | } |
| 1628 | |
| 1629 | if (Stats.Completed < Stats.Enqueued) { |
| 1630 | assert(Stats.Enqueued > Stats.LastIdle); |
| 1631 | WorkDoneProgressReport Report; |
| 1632 | Report.percentage = 100.0 * (Stats.Completed - Stats.LastIdle) / |
| 1633 | (Stats.Enqueued - Stats.LastIdle); |
| 1634 | Report.message = |
| 1635 | llvm::formatv("{0}/{1}", Stats.Completed - Stats.LastIdle, |
| 1636 | Stats.Enqueued - Stats.LastIdle); |
| 1637 | progress(ProgressToken, std::move(Report)); |
| 1638 | } else { |
| 1639 | assert(Stats.Completed == Stats.Enqueued); |
| 1640 | progress(ProgressToken, WorkDoneProgressEnd()); |
| 1641 | BackgroundIndexProgressState = BackgroundIndexProgress::Empty; |
| 1642 | } |
| 1643 | }; |
| 1644 | |
| 1645 | switch (BackgroundIndexProgressState) { |
| 1646 | case BackgroundIndexProgress::Unsupported: |
| 1647 | return; |
| 1648 | case BackgroundIndexProgress::Creating: |
| 1649 | // Cache this update for when the progress bar is available. |
| 1650 | PendingBackgroundIndexProgress = Stats; |
| 1651 | return; |
| 1652 | case BackgroundIndexProgress::Empty: { |
| 1653 | if (BackgroundIndexSkipCreate) { |
| 1654 | NotifyProgress(Stats); |
| 1655 | break; |
| 1656 | } |
| 1657 | // Cache this update for when the progress bar is available. |
| 1658 | PendingBackgroundIndexProgress = Stats; |
| 1659 | BackgroundIndexProgressState = BackgroundIndexProgress::Creating; |
| 1660 | WorkDoneProgressCreateParams CreateRequest; |
| 1661 | CreateRequest.token = ProgressToken; |
| 1662 | call<std::nullptr_t>( |
| 1663 | "window/workDoneProgress/create", CreateRequest, |
| 1664 | [this, NotifyProgress](llvm::Expected<std::nullptr_t> E) { |
| 1665 | std::lock_guard<std::mutex> Lock(BackgroundIndexProgressMutex); |
| 1666 | if (E) { |
| 1667 | NotifyProgress(this->PendingBackgroundIndexProgress); |
| 1668 | } else { |
| 1669 | elog("Failed to create background index progress bar: {0}", |
| 1670 | E.takeError()); |
| 1671 | // give up forever rather than thrashing about |
| 1672 | BackgroundIndexProgressState = BackgroundIndexProgress::Unsupported; |
| 1673 | } |
| 1674 | }); |
| 1675 | break; |
| 1676 | } |
| 1677 | case BackgroundIndexProgress::Live: |
| 1678 | NotifyProgress(Stats); |
| 1679 | break; |
| 1680 | } |
| 1681 | } |
| 1682 | |
Haojian Wu | b618849 | 2018-12-20 15:39:12 +0000 | [diff] [blame] | 1683 | void ClangdLSPServer::onFileUpdated(PathRef File, const TUStatus &Status) { |
| 1684 | if (!SupportFileStatus) |
| 1685 | return; |
| 1686 | // FIXME: we don't emit "BuildingFile" and `RunningAction`, as these |
| 1687 | // two statuses are running faster in practice, which leads the UI constantly |
| 1688 | // changing, and doesn't provide much value. We may want to emit status at a |
| 1689 | // reasonable time interval (e.g. 0.5s). |
Kadir Cetinkaya | 6b85032 | 2020-03-17 19:08:23 +0100 | [diff] [blame] | 1690 | if (Status.PreambleActivity == PreambleAction::Idle && |
| 1691 | (Status.ASTActivity.K == ASTAction::Building || |
| 1692 | Status.ASTActivity.K == ASTAction::RunningAction)) |
Haojian Wu | b618849 | 2018-12-20 15:39:12 +0000 | [diff] [blame] | 1693 | return; |
| 1694 | notify("textDocument/clangd.fileStatus", Status.render(File)); |
| 1695 | } |
| 1696 | |
Sam McCall | 596b63a | 2020-04-10 03:27:37 +0200 | [diff] [blame] | 1697 | void ClangdLSPServer::reparseOpenFilesIfNeeded( |
| 1698 | llvm::function_ref<bool(llvm::StringRef File)> Filter) { |
David Goldman | 60249c2 | 2020-01-13 17:01:10 -0500 | [diff] [blame] | 1699 | // Reparse only opened files that were modified. |
Simon Marchi | 9569fd5 | 2018-03-16 14:30:42 +0000 | [diff] [blame] | 1700 | for (const Path &FilePath : DraftMgr.getActiveFiles()) |
Sam McCall | 596b63a | 2020-04-10 03:27:37 +0200 | [diff] [blame] | 1701 | if (Filter(FilePath)) |
Sam McCall | 2cd33e6 | 2020-03-04 00:33:29 +0100 | [diff] [blame] | 1702 | if (auto Draft = DraftMgr.getDraft(FilePath)) // else disappeared in race? |
| 1703 | Server->addDocument(FilePath, std::move(Draft->Contents), |
| 1704 | encodeVersion(Draft->Version), |
| 1705 | WantDiagnostics::Auto); |
Simon Marchi | 9569fd5 | 2018-03-16 14:30:42 +0000 | [diff] [blame] | 1706 | } |
Alex Lorenz | f808786 | 2018-08-01 17:39:29 +0000 | [diff] [blame] | 1707 | |
Sam McCall | c008af6 | 2018-10-20 15:30:37 +0000 | [diff] [blame] | 1708 | } // namespace clangd |
| 1709 | } // namespace clang |