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