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