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