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