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