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