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 | |
Sam McCall | a69698f | 2019-03-27 17:47:49 +0000 | [diff] [blame] | 467 | llvm::json::Object Result{ |
Sam McCall | 0930ab0 | 2017-11-07 15:49:35 +0000 | [diff] [blame] | 468 | {{"capabilities", |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 469 | llvm::json::Object{ |
Simon Marchi | 9808262 | 2018-03-26 14:41:40 +0000 | [diff] [blame] | 470 | {"textDocumentSync", (int)TextDocumentSyncKind::Incremental}, |
Sam McCall | 0930ab0 | 2017-11-07 15:49:35 +0000 | [diff] [blame] | 471 | {"documentFormattingProvider", true}, |
| 472 | {"documentRangeFormattingProvider", true}, |
| 473 | {"documentOnTypeFormattingProvider", |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 474 | llvm::json::Object{ |
Sam McCall | 25c6257 | 2019-06-10 14:26:21 +0000 | [diff] [blame] | 475 | {"firstTriggerCharacter", "\n"}, |
Sam McCall | 0930ab0 | 2017-11-07 15:49:35 +0000 | [diff] [blame] | 476 | {"moreTriggerCharacter", {}}, |
| 477 | }}, |
| 478 | {"codeActionProvider", true}, |
| 479 | {"completionProvider", |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 480 | llvm::json::Object{ |
Sam McCall | 0930ab0 | 2017-11-07 15:49:35 +0000 | [diff] [blame] | 481 | {"resolveProvider", false}, |
Ilya Biryukov | b0826bd | 2019-01-03 13:37:12 +0000 | [diff] [blame] | 482 | // We do extra checks for '>' and ':' in completion to only |
| 483 | // trigger on '->' and '::'. |
Sam McCall | 0930ab0 | 2017-11-07 15:49:35 +0000 | [diff] [blame] | 484 | {"triggerCharacters", {".", ">", ":"}}, |
| 485 | }}, |
| 486 | {"signatureHelpProvider", |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 487 | llvm::json::Object{ |
Sam McCall | 0930ab0 | 2017-11-07 15:49:35 +0000 | [diff] [blame] | 488 | {"triggerCharacters", {"(", ","}}, |
| 489 | }}, |
Sam McCall | 866ba2c | 2019-02-01 11:26:13 +0000 | [diff] [blame] | 490 | {"declarationProvider", true}, |
Sam McCall | 0930ab0 | 2017-11-07 15:49:35 +0000 | [diff] [blame] | 491 | {"definitionProvider", true}, |
Ilya Biryukov | 0e6a51f | 2017-12-12 12:27:47 +0000 | [diff] [blame] | 492 | {"documentHighlightProvider", true}, |
Marc-Andre Laperle | 3e618ed | 2018-02-16 21:38:15 +0000 | [diff] [blame] | 493 | {"hoverProvider", true}, |
Haojian Wu | f429ab6 | 2019-07-24 07:49:23 +0000 | [diff] [blame] | 494 | {"renameProvider", std::move(RenameProvider)}, |
Marc-Andre Laperle | 1be6970 | 2018-07-05 19:35:01 +0000 | [diff] [blame] | 495 | {"documentSymbolProvider", true}, |
Marc-Andre Laperle | b387b6e | 2018-04-23 20:00:52 +0000 | [diff] [blame] | 496 | {"workspaceSymbolProvider", true}, |
Sam McCall | 1ad142f | 2018-09-05 11:53:07 +0000 | [diff] [blame] | 497 | {"referencesProvider", true}, |
Sam McCall | 0930ab0 | 2017-11-07 15:49:35 +0000 | [diff] [blame] | 498 | {"executeCommandProvider", |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 499 | llvm::json::Object{ |
Ilya Biryukov | cce67a3 | 2019-01-29 14:17:36 +0000 | [diff] [blame] | 500 | {"commands", |
| 501 | {ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND, |
| 502 | ExecuteCommandParams::CLANGD_APPLY_TWEAK}}, |
Sam McCall | 0930ab0 | 2017-11-07 15:49:35 +0000 | [diff] [blame] | 503 | }}, |
Kadir Cetinkaya | 8665802 | 2019-03-19 09:27:04 +0000 | [diff] [blame] | 504 | {"typeHierarchyProvider", true}, |
Sam McCall | a69698f | 2019-03-27 17:47:49 +0000 | [diff] [blame] | 505 | }}}}; |
| 506 | if (NegotiatedOffsetEncoding) |
| 507 | Result["offsetEncoding"] = *NegotiatedOffsetEncoding; |
Johan Vikstrom | a848dab | 2019-07-04 07:53:12 +0000 | [diff] [blame] | 508 | if (Params.capabilities.SemanticHighlighting) |
| 509 | Result.getObject("capabilities") |
| 510 | ->insert( |
| 511 | {"semanticHighlighting", |
Haojian Wu | 1ca2ee4 | 2019-07-04 12:27:21 +0000 | [diff] [blame] | 512 | llvm::json::Object{{"scopes", buildHighlightScopeLookupTable()}}}); |
Sam McCall | a69698f | 2019-03-27 17:47:49 +0000 | [diff] [blame] | 513 | Reply(std::move(Result)); |
Ilya Biryukov | afb5554 | 2017-05-16 14:40:30 +0000 | [diff] [blame] | 514 | } |
| 515 | |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 516 | void ClangdLSPServer::onShutdown(const ShutdownParams &Params, |
| 517 | Callback<std::nullptr_t> Reply) { |
Ilya Biryukov | 0d9b8a3 | 2017-10-25 08:45:41 +0000 | [diff] [blame] | 518 | // Do essentially nothing, just say we're ready to exit. |
| 519 | ShutdownRequestReceived = true; |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 520 | Reply(nullptr); |
Sam McCall | 8a5dded | 2017-10-12 13:29:58 +0000 | [diff] [blame] | 521 | } |
Ilya Biryukov | afb5554 | 2017-05-16 14:40:30 +0000 | [diff] [blame] | 522 | |
Sam McCall | 422c828 | 2018-11-26 16:00:11 +0000 | [diff] [blame] | 523 | // sync is a clangd extension: it blocks until all background work completes. |
| 524 | // It blocks the calling thread, so no messages are processed until it returns! |
| 525 | void ClangdLSPServer::onSync(const NoParams &Params, |
| 526 | Callback<std::nullptr_t> Reply) { |
| 527 | if (Server->blockUntilIdleForTest(/*TimeoutSeconds=*/60)) |
| 528 | Reply(nullptr); |
| 529 | else |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 530 | Reply(llvm::createStringError(llvm::inconvertibleErrorCode(), |
| 531 | "Not idle after a minute")); |
Sam McCall | 422c828 | 2018-11-26 16:00:11 +0000 | [diff] [blame] | 532 | } |
| 533 | |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 534 | void ClangdLSPServer::onDocumentDidOpen( |
| 535 | const DidOpenTextDocumentParams &Params) { |
Simon Marchi | 9569fd5 | 2018-03-16 14:30:42 +0000 | [diff] [blame] | 536 | PathRef File = Params.textDocument.uri.file(); |
Ilya Biryukov | b10ef47 | 2018-06-13 09:20:41 +0000 | [diff] [blame] | 537 | |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 538 | const std::string &Contents = Params.textDocument.text; |
Simon Marchi | 9569fd5 | 2018-03-16 14:30:42 +0000 | [diff] [blame] | 539 | |
Simon Marchi | 9808262 | 2018-03-26 14:41:40 +0000 | [diff] [blame] | 540 | DraftMgr.addDraft(File, Contents); |
Ilya Biryukov | 652364b | 2018-09-26 05:48:29 +0000 | [diff] [blame] | 541 | Server->addDocument(File, Contents, WantDiagnostics::Yes); |
Ilya Biryukov | afb5554 | 2017-05-16 14:40:30 +0000 | [diff] [blame] | 542 | } |
| 543 | |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 544 | void ClangdLSPServer::onDocumentDidChange( |
| 545 | const DidChangeTextDocumentParams &Params) { |
Eric Liu | 51fed18 | 2018-02-22 18:40:39 +0000 | [diff] [blame] | 546 | auto WantDiags = WantDiagnostics::Auto; |
| 547 | if (Params.wantDiagnostics.hasValue()) |
| 548 | WantDiags = Params.wantDiagnostics.getValue() ? WantDiagnostics::Yes |
| 549 | : WantDiagnostics::No; |
Simon Marchi | 9569fd5 | 2018-03-16 14:30:42 +0000 | [diff] [blame] | 550 | |
| 551 | PathRef File = Params.textDocument.uri.file(); |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 552 | llvm::Expected<std::string> Contents = |
Simon Marchi | 9808262 | 2018-03-26 14:41:40 +0000 | [diff] [blame] | 553 | DraftMgr.updateDraft(File, Params.contentChanges); |
| 554 | if (!Contents) { |
| 555 | // If this fails, we are most likely going to be not in sync anymore with |
| 556 | // the client. It is better to remove the draft and let further operations |
| 557 | // fail rather than giving wrong results. |
| 558 | DraftMgr.removeDraft(File); |
Ilya Biryukov | 652364b | 2018-09-26 05:48:29 +0000 | [diff] [blame] | 559 | Server->removeDocument(File); |
Sam McCall | bed5885 | 2018-07-11 10:35:11 +0000 | [diff] [blame] | 560 | elog("Failed to update {0}: {1}", File, Contents.takeError()); |
Simon Marchi | 9808262 | 2018-03-26 14:41:40 +0000 | [diff] [blame] | 561 | return; |
| 562 | } |
Simon Marchi | 9569fd5 | 2018-03-16 14:30:42 +0000 | [diff] [blame] | 563 | |
Ilya Biryukov | 652364b | 2018-09-26 05:48:29 +0000 | [diff] [blame] | 564 | Server->addDocument(File, *Contents, WantDiags); |
Ilya Biryukov | afb5554 | 2017-05-16 14:40:30 +0000 | [diff] [blame] | 565 | } |
| 566 | |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 567 | void ClangdLSPServer::onFileEvent(const DidChangeWatchedFilesParams &Params) { |
Ilya Biryukov | 652364b | 2018-09-26 05:48:29 +0000 | [diff] [blame] | 568 | Server->onFileEvent(Params); |
Marc-Andre Laperle | bf11424 | 2017-10-02 18:00:37 +0000 | [diff] [blame] | 569 | } |
| 570 | |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 571 | void ClangdLSPServer::onCommand(const ExecuteCommandParams &Params, |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 572 | Callback<llvm::json::Value> Reply) { |
Haojian Wu | f251634 | 2019-08-05 12:48:09 +0000 | [diff] [blame] | 573 | auto ApplyEdit = [this](WorkspaceEdit WE, |
| 574 | Callback<ApplyWorkspaceEditResponse> Reply) { |
Eric Liu | c5105f9 | 2018-02-16 14:15:55 +0000 | [diff] [blame] | 575 | ApplyWorkspaceEditParams Edit; |
| 576 | Edit.edit = std::move(WE); |
Haojian Wu | f251634 | 2019-08-05 12:48:09 +0000 | [diff] [blame] | 577 | call("workspace/applyEdit", std::move(Edit), std::move(Reply)); |
Eric Liu | c5105f9 | 2018-02-16 14:15:55 +0000 | [diff] [blame] | 578 | }; |
Haojian Wu | f251634 | 2019-08-05 12:48:09 +0000 | [diff] [blame] | 579 | // FIXME: this lambda is tangled and confusing, refactor it. |
| 580 | auto ReplyAfterApplyingEdit = |
| 581 | [](decltype(Reply) Reply, std::string SuccessMessage, |
| 582 | llvm::Expected<ApplyWorkspaceEditResponse> Response) { |
| 583 | if (!Response) |
| 584 | return Reply(Response.takeError()); |
| 585 | if (!Response->applied) { |
| 586 | std::string Reason = Response->failureReason |
| 587 | ? *Response->failureReason |
| 588 | : "unknown reason"; |
| 589 | return Reply(llvm::createStringError( |
| 590 | llvm::inconvertibleErrorCode(), |
| 591 | ("edits were not applied: " + Reason).c_str())); |
| 592 | } |
| 593 | return Reply(SuccessMessage); |
| 594 | }; |
Marc-Andre Laperle | e7ec16a | 2017-11-03 13:39:15 +0000 | [diff] [blame] | 595 | if (Params.command == ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND && |
| 596 | Params.workspaceEdit) { |
| 597 | // The flow for "apply-fix" : |
| 598 | // 1. We publish a diagnostic, including fixits |
| 599 | // 2. The user clicks on the diagnostic, the editor asks us for code actions |
| 600 | // 3. We send code actions, with the fixit embedded as context |
| 601 | // 4. The user selects the fixit, the editor asks us to apply it |
| 602 | // 5. We unwrap the changes and send them back to the editor |
Haojian Wu | f251634 | 2019-08-05 12:48:09 +0000 | [diff] [blame] | 603 | // 6. The editor applies the changes (applyEdit), and sends us a reply |
| 604 | // 7. We unwrap the reply and send a reply to the editor. |
| 605 | ApplyEdit(*Params.workspaceEdit, |
| 606 | Bind(ReplyAfterApplyingEdit, std::move(Reply), |
| 607 | std::string("Fix applied."))); |
Ilya Biryukov | cce67a3 | 2019-01-29 14:17:36 +0000 | [diff] [blame] | 608 | } else if (Params.command == ExecuteCommandParams::CLANGD_APPLY_TWEAK && |
| 609 | Params.tweakArgs) { |
| 610 | auto Code = DraftMgr.getDraft(Params.tweakArgs->file.file()); |
| 611 | if (!Code) |
| 612 | return Reply(llvm::createStringError( |
| 613 | llvm::inconvertibleErrorCode(), |
| 614 | "trying to apply a code action for a non-added file")); |
| 615 | |
Benjamin Kramer | 9880b5d | 2019-08-15 14:16:06 +0000 | [diff] [blame^] | 616 | auto Action = [this, ApplyEdit, ReplyAfterApplyingEdit, |
| 617 | Reply = std::move(Reply), File = Params.tweakArgs->file, |
| 618 | Code = std::move(*Code)]( |
| 619 | llvm::Expected<Tweak::Effect> R) mutable { |
Ilya Biryukov | cce67a3 | 2019-01-29 14:17:36 +0000 | [diff] [blame] | 620 | if (!R) |
| 621 | return Reply(R.takeError()); |
| 622 | |
Sam McCall | 395fde7 | 2019-06-18 13:37:54 +0000 | [diff] [blame] | 623 | if (R->ApplyEdit) { |
| 624 | WorkspaceEdit WE; |
| 625 | WE.changes.emplace(); |
Sam McCall | 08372eb | 2019-06-19 07:29:10 +0000 | [diff] [blame] | 626 | (*WE.changes)[File.uri()] = replacementsToEdits(Code, *R->ApplyEdit); |
Haojian Wu | f251634 | 2019-08-05 12:48:09 +0000 | [diff] [blame] | 627 | ApplyEdit(std::move(WE), Bind(ReplyAfterApplyingEdit, std::move(Reply), |
| 628 | std::string("Tweak applied."))); |
Sam McCall | 395fde7 | 2019-06-18 13:37:54 +0000 | [diff] [blame] | 629 | } |
| 630 | if (R->ShowMessage) { |
| 631 | ShowMessageParams Msg; |
| 632 | Msg.message = *R->ShowMessage; |
| 633 | Msg.type = MessageType::Info; |
| 634 | notify("window/showMessage", Msg); |
Haojian Wu | f251634 | 2019-08-05 12:48:09 +0000 | [diff] [blame] | 635 | Reply("Tweak applied."); |
Sam McCall | 395fde7 | 2019-06-18 13:37:54 +0000 | [diff] [blame] | 636 | } |
Ilya Biryukov | cce67a3 | 2019-01-29 14:17:36 +0000 | [diff] [blame] | 637 | }; |
| 638 | Server->applyTweak(Params.tweakArgs->file.file(), |
| 639 | Params.tweakArgs->selection, Params.tweakArgs->tweakID, |
Benjamin Kramer | 9880b5d | 2019-08-15 14:16:06 +0000 | [diff] [blame^] | 640 | std::move(Action)); |
Marc-Andre Laperle | e7ec16a | 2017-11-03 13:39:15 +0000 | [diff] [blame] | 641 | } else { |
| 642 | // We should not get here because ExecuteCommandParams would not have |
| 643 | // parsed in the first place and this handler should not be called. But if |
| 644 | // more commands are added, this will be here has a safe guard. |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 645 | Reply(llvm::make_error<LSPError>( |
| 646 | llvm::formatv("Unsupported command \"{0}\".", Params.command).str(), |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 647 | ErrorCode::InvalidParams)); |
Marc-Andre Laperle | e7ec16a | 2017-11-03 13:39:15 +0000 | [diff] [blame] | 648 | } |
| 649 | } |
| 650 | |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 651 | void ClangdLSPServer::onWorkspaceSymbol( |
| 652 | const WorkspaceSymbolParams &Params, |
| 653 | Callback<std::vector<SymbolInformation>> Reply) { |
Ilya Biryukov | 652364b | 2018-09-26 05:48:29 +0000 | [diff] [blame] | 654 | Server->workspaceSymbols( |
Marc-Andre Laperle | b387b6e | 2018-04-23 20:00:52 +0000 | [diff] [blame] | 655 | Params.query, CCOpts.Limit, |
Benjamin Kramer | 9880b5d | 2019-08-15 14:16:06 +0000 | [diff] [blame^] | 656 | [Reply = std::move(Reply), |
| 657 | this](llvm::Expected<std::vector<SymbolInformation>> Items) mutable { |
| 658 | if (!Items) |
| 659 | return Reply(Items.takeError()); |
| 660 | for (auto &Sym : *Items) |
| 661 | Sym.kind = adjustKindToCapability(Sym.kind, SupportedSymbolKinds); |
Marc-Andre Laperle | b387b6e | 2018-04-23 20:00:52 +0000 | [diff] [blame] | 662 | |
Benjamin Kramer | 9880b5d | 2019-08-15 14:16:06 +0000 | [diff] [blame^] | 663 | Reply(std::move(*Items)); |
| 664 | }); |
Marc-Andre Laperle | b387b6e | 2018-04-23 20:00:52 +0000 | [diff] [blame] | 665 | } |
| 666 | |
Haojian Wu | f429ab6 | 2019-07-24 07:49:23 +0000 | [diff] [blame] | 667 | void ClangdLSPServer::onPrepareRename(const TextDocumentPositionParams &Params, |
| 668 | Callback<llvm::Optional<Range>> Reply) { |
| 669 | Server->prepareRename(Params.textDocument.uri.file(), Params.position, |
| 670 | std::move(Reply)); |
| 671 | } |
| 672 | |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 673 | void ClangdLSPServer::onRename(const RenameParams &Params, |
| 674 | Callback<WorkspaceEdit> Reply) { |
Ilya Biryukov | 7d60d20 | 2018-02-16 12:20:47 +0000 | [diff] [blame] | 675 | Path File = Params.textDocument.uri.file(); |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 676 | llvm::Optional<std::string> Code = DraftMgr.getDraft(File); |
Ilya Biryukov | 261c72e | 2018-01-17 12:30:24 +0000 | [diff] [blame] | 677 | if (!Code) |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 678 | return Reply(llvm::make_error<LSPError>( |
| 679 | "onRename called for non-added file", ErrorCode::InvalidParams)); |
Ilya Biryukov | 261c72e | 2018-01-17 12:30:24 +0000 | [diff] [blame] | 680 | |
Benjamin Kramer | 9880b5d | 2019-08-15 14:16:06 +0000 | [diff] [blame^] | 681 | Server->rename(File, Params.position, Params.newName, /*WantFormat=*/true, |
| 682 | [File, Code, Params, Reply = std::move(Reply)]( |
| 683 | llvm::Expected<std::vector<TextEdit>> Edits) mutable { |
| 684 | if (!Edits) |
| 685 | return Reply(Edits.takeError()); |
Ilya Biryukov | 261c72e | 2018-01-17 12:30:24 +0000 | [diff] [blame] | 686 | |
Benjamin Kramer | 9880b5d | 2019-08-15 14:16:06 +0000 | [diff] [blame^] | 687 | WorkspaceEdit WE; |
| 688 | WE.changes = {{Params.textDocument.uri.uri(), *Edits}}; |
| 689 | Reply(WE); |
| 690 | }); |
Haojian Wu | 345099c | 2017-11-09 11:30:04 +0000 | [diff] [blame] | 691 | } |
| 692 | |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 693 | void ClangdLSPServer::onDocumentDidClose( |
| 694 | const DidCloseTextDocumentParams &Params) { |
Simon Marchi | 9569fd5 | 2018-03-16 14:30:42 +0000 | [diff] [blame] | 695 | PathRef File = Params.textDocument.uri.file(); |
| 696 | DraftMgr.removeDraft(File); |
Ilya Biryukov | 652364b | 2018-09-26 05:48:29 +0000 | [diff] [blame] | 697 | Server->removeDocument(File); |
Ilya Biryukov | 49c1071 | 2019-03-25 10:15:11 +0000 | [diff] [blame] | 698 | |
| 699 | { |
| 700 | std::lock_guard<std::mutex> Lock(FixItsMutex); |
| 701 | FixItsMap.erase(File); |
| 702 | } |
Johan Vikstrom | c2653ef2 | 2019-08-01 08:08:44 +0000 | [diff] [blame] | 703 | { |
| 704 | std::lock_guard<std::mutex> HLock(HighlightingsMutex); |
| 705 | FileToHighlightings.erase(File); |
| 706 | } |
Ilya Biryukov | 49c1071 | 2019-03-25 10:15:11 +0000 | [diff] [blame] | 707 | // clangd will not send updates for this file anymore, so we empty out the |
| 708 | // list of diagnostics shown on the client (e.g. in the "Problems" pane of |
| 709 | // VSCode). Note that this cannot race with actual diagnostics responses |
| 710 | // because removeDocument() guarantees no diagnostic callbacks will be |
| 711 | // executed after it returns. |
| 712 | publishDiagnostics(URIForFile::canonicalize(File, /*TUPath=*/File), {}); |
Ilya Biryukov | afb5554 | 2017-05-16 14:40:30 +0000 | [diff] [blame] | 713 | } |
| 714 | |
Sam McCall | 4db732a | 2017-09-30 10:08:52 +0000 | [diff] [blame] | 715 | void ClangdLSPServer::onDocumentOnTypeFormatting( |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 716 | const DocumentOnTypeFormattingParams &Params, |
| 717 | Callback<std::vector<TextEdit>> Reply) { |
Ilya Biryukov | 7d60d20 | 2018-02-16 12:20:47 +0000 | [diff] [blame] | 718 | auto File = Params.textDocument.uri.file(); |
Simon Marchi | 9569fd5 | 2018-03-16 14:30:42 +0000 | [diff] [blame] | 719 | auto Code = DraftMgr.getDraft(File); |
Ilya Biryukov | 261c72e | 2018-01-17 12:30:24 +0000 | [diff] [blame] | 720 | if (!Code) |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 721 | return Reply(llvm::make_error<LSPError>( |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 722 | "onDocumentOnTypeFormatting called for non-added file", |
| 723 | ErrorCode::InvalidParams)); |
Ilya Biryukov | 261c72e | 2018-01-17 12:30:24 +0000 | [diff] [blame] | 724 | |
Sam McCall | 25c6257 | 2019-06-10 14:26:21 +0000 | [diff] [blame] | 725 | Reply(Server->formatOnType(*Code, File, Params.position, Params.ch)); |
Ilya Biryukov | afb5554 | 2017-05-16 14:40:30 +0000 | [diff] [blame] | 726 | } |
| 727 | |
Sam McCall | 4db732a | 2017-09-30 10:08:52 +0000 | [diff] [blame] | 728 | void ClangdLSPServer::onDocumentRangeFormatting( |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 729 | const DocumentRangeFormattingParams &Params, |
| 730 | Callback<std::vector<TextEdit>> Reply) { |
Ilya Biryukov | 7d60d20 | 2018-02-16 12:20:47 +0000 | [diff] [blame] | 731 | auto File = Params.textDocument.uri.file(); |
Simon Marchi | 9569fd5 | 2018-03-16 14:30:42 +0000 | [diff] [blame] | 732 | auto Code = DraftMgr.getDraft(File); |
Ilya Biryukov | 261c72e | 2018-01-17 12:30:24 +0000 | [diff] [blame] | 733 | if (!Code) |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 734 | return Reply(llvm::make_error<LSPError>( |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 735 | "onDocumentRangeFormatting called for non-added file", |
| 736 | ErrorCode::InvalidParams)); |
Ilya Biryukov | 261c72e | 2018-01-17 12:30:24 +0000 | [diff] [blame] | 737 | |
Ilya Biryukov | 652364b | 2018-09-26 05:48:29 +0000 | [diff] [blame] | 738 | auto ReplacementsOrError = Server->formatRange(*Code, File, Params.range); |
Raoul Wols | 212bcf8 | 2017-12-12 20:25:06 +0000 | [diff] [blame] | 739 | if (ReplacementsOrError) |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 740 | Reply(replacementsToEdits(*Code, ReplacementsOrError.get())); |
Raoul Wols | 212bcf8 | 2017-12-12 20:25:06 +0000 | [diff] [blame] | 741 | else |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 742 | Reply(ReplacementsOrError.takeError()); |
Ilya Biryukov | afb5554 | 2017-05-16 14:40:30 +0000 | [diff] [blame] | 743 | } |
| 744 | |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 745 | void ClangdLSPServer::onDocumentFormatting( |
| 746 | const DocumentFormattingParams &Params, |
| 747 | Callback<std::vector<TextEdit>> Reply) { |
Ilya Biryukov | 7d60d20 | 2018-02-16 12:20:47 +0000 | [diff] [blame] | 748 | auto File = Params.textDocument.uri.file(); |
Simon Marchi | 9569fd5 | 2018-03-16 14:30:42 +0000 | [diff] [blame] | 749 | auto Code = DraftMgr.getDraft(File); |
Ilya Biryukov | 261c72e | 2018-01-17 12:30:24 +0000 | [diff] [blame] | 750 | if (!Code) |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 751 | return Reply(llvm::make_error<LSPError>( |
| 752 | "onDocumentFormatting called for non-added file", |
| 753 | ErrorCode::InvalidParams)); |
Ilya Biryukov | 261c72e | 2018-01-17 12:30:24 +0000 | [diff] [blame] | 754 | |
Ilya Biryukov | 652364b | 2018-09-26 05:48:29 +0000 | [diff] [blame] | 755 | auto ReplacementsOrError = Server->formatFile(*Code, File); |
Raoul Wols | 212bcf8 | 2017-12-12 20:25:06 +0000 | [diff] [blame] | 756 | if (ReplacementsOrError) |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 757 | Reply(replacementsToEdits(*Code, ReplacementsOrError.get())); |
Raoul Wols | 212bcf8 | 2017-12-12 20:25:06 +0000 | [diff] [blame] | 758 | else |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 759 | Reply(ReplacementsOrError.takeError()); |
Sam McCall | 4db732a | 2017-09-30 10:08:52 +0000 | [diff] [blame] | 760 | } |
| 761 | |
Ilya Biryukov | 19d7560 | 2018-11-23 15:21:19 +0000 | [diff] [blame] | 762 | /// The functions constructs a flattened view of the DocumentSymbol hierarchy. |
| 763 | /// Used by the clients that do not support the hierarchical view. |
| 764 | static std::vector<SymbolInformation> |
| 765 | flattenSymbolHierarchy(llvm::ArrayRef<DocumentSymbol> Symbols, |
| 766 | const URIForFile &FileURI) { |
| 767 | |
| 768 | std::vector<SymbolInformation> Results; |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 769 | std::function<void(const DocumentSymbol &, llvm::StringRef)> Process = |
| 770 | [&](const DocumentSymbol &S, llvm::Optional<llvm::StringRef> ParentName) { |
Ilya Biryukov | 19d7560 | 2018-11-23 15:21:19 +0000 | [diff] [blame] | 771 | SymbolInformation SI; |
| 772 | SI.containerName = ParentName ? "" : *ParentName; |
| 773 | SI.name = S.name; |
| 774 | SI.kind = S.kind; |
| 775 | SI.location.range = S.range; |
| 776 | SI.location.uri = FileURI; |
| 777 | |
| 778 | Results.push_back(std::move(SI)); |
| 779 | std::string FullName = |
| 780 | !ParentName ? S.name : (ParentName->str() + "::" + S.name); |
| 781 | for (auto &C : S.children) |
| 782 | Process(C, /*ParentName=*/FullName); |
| 783 | }; |
| 784 | for (auto &S : Symbols) |
| 785 | Process(S, /*ParentName=*/""); |
| 786 | return Results; |
| 787 | } |
| 788 | |
| 789 | void ClangdLSPServer::onDocumentSymbol(const DocumentSymbolParams &Params, |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 790 | Callback<llvm::json::Value> Reply) { |
Ilya Biryukov | 19d7560 | 2018-11-23 15:21:19 +0000 | [diff] [blame] | 791 | URIForFile FileURI = Params.textDocument.uri; |
Ilya Biryukov | 652364b | 2018-09-26 05:48:29 +0000 | [diff] [blame] | 792 | Server->documentSymbols( |
Marc-Andre Laperle | 1be6970 | 2018-07-05 19:35:01 +0000 | [diff] [blame] | 793 | Params.textDocument.uri.file(), |
Benjamin Kramer | 9880b5d | 2019-08-15 14:16:06 +0000 | [diff] [blame^] | 794 | [this, FileURI, Reply = std::move(Reply)]( |
| 795 | llvm::Expected<std::vector<DocumentSymbol>> Items) mutable { |
| 796 | if (!Items) |
| 797 | return Reply(Items.takeError()); |
| 798 | adjustSymbolKinds(*Items, SupportedSymbolKinds); |
| 799 | if (SupportsHierarchicalDocumentSymbol) |
| 800 | return Reply(std::move(*Items)); |
| 801 | else |
| 802 | return Reply(flattenSymbolHierarchy(*Items, FileURI)); |
| 803 | }); |
Marc-Andre Laperle | 1be6970 | 2018-07-05 19:35:01 +0000 | [diff] [blame] | 804 | } |
| 805 | |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 806 | static llvm::Optional<Command> asCommand(const CodeAction &Action) { |
Sam McCall | 20841d4 | 2018-10-16 16:29:41 +0000 | [diff] [blame] | 807 | Command Cmd; |
| 808 | if (Action.command && Action.edit) |
Sam McCall | c008af6 | 2018-10-20 15:30:37 +0000 | [diff] [blame] | 809 | return None; // Not representable. (We never emit these anyway). |
Sam McCall | 20841d4 | 2018-10-16 16:29:41 +0000 | [diff] [blame] | 810 | if (Action.command) { |
| 811 | Cmd = *Action.command; |
| 812 | } else if (Action.edit) { |
| 813 | Cmd.command = Command::CLANGD_APPLY_FIX_COMMAND; |
| 814 | Cmd.workspaceEdit = *Action.edit; |
| 815 | } else { |
Sam McCall | c008af6 | 2018-10-20 15:30:37 +0000 | [diff] [blame] | 816 | return None; |
Sam McCall | 20841d4 | 2018-10-16 16:29:41 +0000 | [diff] [blame] | 817 | } |
| 818 | Cmd.title = Action.title; |
| 819 | if (Action.kind && *Action.kind == CodeAction::QUICKFIX_KIND) |
| 820 | Cmd.title = "Apply fix: " + Cmd.title; |
| 821 | return Cmd; |
| 822 | } |
| 823 | |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 824 | void ClangdLSPServer::onCodeAction(const CodeActionParams &Params, |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 825 | Callback<llvm::json::Value> Reply) { |
Ilya Biryukov | cce67a3 | 2019-01-29 14:17:36 +0000 | [diff] [blame] | 826 | URIForFile File = Params.textDocument.uri; |
| 827 | auto Code = DraftMgr.getDraft(File.file()); |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 828 | if (!Code) |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 829 | return Reply(llvm::make_error<LSPError>( |
| 830 | "onCodeAction called for non-added file", ErrorCode::InvalidParams)); |
Sam McCall | 20841d4 | 2018-10-16 16:29:41 +0000 | [diff] [blame] | 831 | // We provide a code action for Fixes on the specified diagnostics. |
Ilya Biryukov | cce67a3 | 2019-01-29 14:17:36 +0000 | [diff] [blame] | 832 | std::vector<CodeAction> FixIts; |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 833 | for (const Diagnostic &D : Params.context.diagnostics) { |
Ilya Biryukov | cce67a3 | 2019-01-29 14:17:36 +0000 | [diff] [blame] | 834 | for (auto &F : getFixes(File.file(), D)) { |
| 835 | FixIts.push_back(toCodeAction(F, Params.textDocument.uri)); |
| 836 | FixIts.back().diagnostics = {D}; |
Sam McCall | dd0566b | 2017-11-06 15:40:30 +0000 | [diff] [blame] | 837 | } |
Ilya Biryukov | afb5554 | 2017-05-16 14:40:30 +0000 | [diff] [blame] | 838 | } |
Sam McCall | 20841d4 | 2018-10-16 16:29:41 +0000 | [diff] [blame] | 839 | |
Ilya Biryukov | cce67a3 | 2019-01-29 14:17:36 +0000 | [diff] [blame] | 840 | // Now enumerate the semantic code actions. |
| 841 | auto ConsumeActions = |
Benjamin Kramer | 9880b5d | 2019-08-15 14:16:06 +0000 | [diff] [blame^] | 842 | [Reply = std::move(Reply), File, Code = std::move(*Code), |
| 843 | Selection = Params.range, FixIts = std::move(FixIts), this]( |
| 844 | llvm::Expected<std::vector<ClangdServer::TweakRef>> Tweaks) mutable { |
Ilya Biryukov | c6ed778 | 2019-01-30 14:24:17 +0000 | [diff] [blame] | 845 | if (!Tweaks) |
| 846 | return Reply(Tweaks.takeError()); |
Ilya Biryukov | cce67a3 | 2019-01-29 14:17:36 +0000 | [diff] [blame] | 847 | |
| 848 | std::vector<CodeAction> Actions = std::move(FixIts); |
| 849 | Actions.reserve(Actions.size() + Tweaks->size()); |
| 850 | for (const auto &T : *Tweaks) |
| 851 | Actions.push_back(toCodeAction(T, File, Selection)); |
| 852 | |
| 853 | if (SupportsCodeAction) |
| 854 | return Reply(llvm::json::Array(Actions)); |
| 855 | std::vector<Command> Commands; |
| 856 | for (const auto &Action : Actions) { |
| 857 | if (auto Command = asCommand(Action)) |
| 858 | Commands.push_back(std::move(*Command)); |
| 859 | } |
| 860 | return Reply(llvm::json::Array(Commands)); |
| 861 | }; |
| 862 | |
Benjamin Kramer | 9880b5d | 2019-08-15 14:16:06 +0000 | [diff] [blame^] | 863 | Server->enumerateTweaks(File.file(), Params.range, std::move(ConsumeActions)); |
Ilya Biryukov | afb5554 | 2017-05-16 14:40:30 +0000 | [diff] [blame] | 864 | } |
| 865 | |
Ilya Biryukov | b0826bd | 2019-01-03 13:37:12 +0000 | [diff] [blame] | 866 | void ClangdLSPServer::onCompletion(const CompletionParams &Params, |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 867 | Callback<CompletionList> Reply) { |
Ilya Biryukov | a7a1147 | 2019-06-07 16:24:38 +0000 | [diff] [blame] | 868 | if (!shouldRunCompletion(Params)) { |
| 869 | // Clients sometimes auto-trigger completions in undesired places (e.g. |
| 870 | // 'a >^ '), we return empty results in those cases. |
| 871 | vlog("ignored auto-triggered completion, preceding char did not match"); |
| 872 | return Reply(CompletionList()); |
| 873 | } |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 874 | Server->codeComplete(Params.textDocument.uri.file(), Params.position, CCOpts, |
Benjamin Kramer | 9880b5d | 2019-08-15 14:16:06 +0000 | [diff] [blame^] | 875 | [Reply = std::move(Reply), |
| 876 | this](llvm::Expected<CodeCompleteResult> List) mutable { |
| 877 | if (!List) |
| 878 | return Reply(List.takeError()); |
| 879 | CompletionList LSPList; |
| 880 | LSPList.isIncomplete = List->HasMore; |
| 881 | for (const auto &R : List->Completions) { |
| 882 | CompletionItem C = R.render(CCOpts); |
| 883 | C.kind = adjustKindToCapability( |
| 884 | C.kind, SupportedCompletionItemKinds); |
| 885 | LSPList.items.push_back(std::move(C)); |
| 886 | } |
| 887 | return Reply(std::move(LSPList)); |
| 888 | }); |
Ilya Biryukov | d9bdfe0 | 2017-10-06 11:54:17 +0000 | [diff] [blame] | 889 | } |
| 890 | |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 891 | void ClangdLSPServer::onSignatureHelp(const TextDocumentPositionParams &Params, |
| 892 | Callback<SignatureHelp> Reply) { |
Ilya Biryukov | 652364b | 2018-09-26 05:48:29 +0000 | [diff] [blame] | 893 | Server->signatureHelp(Params.textDocument.uri.file(), Params.position, |
Benjamin Kramer | 9880b5d | 2019-08-15 14:16:06 +0000 | [diff] [blame^] | 894 | [Reply = std::move(Reply), this]( |
| 895 | llvm::Expected<SignatureHelp> Signature) mutable { |
| 896 | if (!Signature) |
| 897 | return Reply(Signature.takeError()); |
| 898 | if (SupportsOffsetsInSignatureHelp) |
| 899 | return Reply(std::move(*Signature)); |
| 900 | // Strip out the offsets from signature help for |
| 901 | // clients that only support string labels. |
| 902 | for (auto &SigInfo : Signature->signatures) { |
| 903 | for (auto &Param : SigInfo.parameters) |
| 904 | Param.labelOffsets.reset(); |
| 905 | } |
| 906 | return Reply(std::move(*Signature)); |
| 907 | }); |
Ilya Biryukov | 652364b | 2018-09-26 05:48:29 +0000 | [diff] [blame] | 908 | } |
| 909 | |
Sam McCall | 0dbab7f | 2019-02-02 05:56:00 +0000 | [diff] [blame] | 910 | // Go to definition has a toggle function: if def and decl are distinct, then |
| 911 | // the first press gives you the def, the second gives you the matching def. |
| 912 | // getToggle() returns the counterpart location that under the cursor. |
| 913 | // |
| 914 | // We return the toggled location alone (ignoring other symbols) to encourage |
| 915 | // editors to "bounce" quickly between locations, without showing a menu. |
| 916 | static Location *getToggle(const TextDocumentPositionParams &Point, |
| 917 | LocatedSymbol &Sym) { |
| 918 | // Toggle only makes sense with two distinct locations. |
| 919 | if (!Sym.Definition || *Sym.Definition == Sym.PreferredDeclaration) |
| 920 | return nullptr; |
| 921 | if (Sym.Definition->uri.file() == Point.textDocument.uri.file() && |
| 922 | Sym.Definition->range.contains(Point.position)) |
| 923 | return &Sym.PreferredDeclaration; |
| 924 | if (Sym.PreferredDeclaration.uri.file() == Point.textDocument.uri.file() && |
| 925 | Sym.PreferredDeclaration.range.contains(Point.position)) |
| 926 | return &*Sym.Definition; |
| 927 | return nullptr; |
| 928 | } |
| 929 | |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 930 | void ClangdLSPServer::onGoToDefinition(const TextDocumentPositionParams &Params, |
| 931 | Callback<std::vector<Location>> Reply) { |
Sam McCall | 866ba2c | 2019-02-01 11:26:13 +0000 | [diff] [blame] | 932 | Server->locateSymbolAt( |
| 933 | Params.textDocument.uri.file(), Params.position, |
Benjamin Kramer | 9880b5d | 2019-08-15 14:16:06 +0000 | [diff] [blame^] | 934 | [Params, Reply = std::move(Reply)]( |
| 935 | llvm::Expected<std::vector<LocatedSymbol>> Symbols) mutable { |
| 936 | if (!Symbols) |
| 937 | return Reply(Symbols.takeError()); |
| 938 | std::vector<Location> Defs; |
| 939 | for (auto &S : *Symbols) { |
| 940 | if (Location *Toggle = getToggle(Params, S)) |
| 941 | return Reply(std::vector<Location>{std::move(*Toggle)}); |
| 942 | Defs.push_back(S.Definition.getValueOr(S.PreferredDeclaration)); |
| 943 | } |
| 944 | Reply(std::move(Defs)); |
| 945 | }); |
Sam McCall | 866ba2c | 2019-02-01 11:26:13 +0000 | [diff] [blame] | 946 | } |
| 947 | |
| 948 | void ClangdLSPServer::onGoToDeclaration( |
| 949 | const TextDocumentPositionParams &Params, |
| 950 | Callback<std::vector<Location>> Reply) { |
| 951 | Server->locateSymbolAt( |
| 952 | Params.textDocument.uri.file(), Params.position, |
Benjamin Kramer | 9880b5d | 2019-08-15 14:16:06 +0000 | [diff] [blame^] | 953 | [Params, Reply = std::move(Reply)]( |
| 954 | llvm::Expected<std::vector<LocatedSymbol>> Symbols) mutable { |
| 955 | if (!Symbols) |
| 956 | return Reply(Symbols.takeError()); |
| 957 | std::vector<Location> Decls; |
| 958 | for (auto &S : *Symbols) { |
| 959 | if (Location *Toggle = getToggle(Params, S)) |
| 960 | return Reply(std::vector<Location>{std::move(*Toggle)}); |
| 961 | Decls.push_back(std::move(S.PreferredDeclaration)); |
| 962 | } |
| 963 | Reply(std::move(Decls)); |
| 964 | }); |
Marc-Andre Laperle | 2cbf037 | 2017-06-28 16:12:10 +0000 | [diff] [blame] | 965 | } |
| 966 | |
Sam McCall | 111fe84 | 2019-05-07 07:55:35 +0000 | [diff] [blame] | 967 | void ClangdLSPServer::onSwitchSourceHeader( |
| 968 | const TextDocumentIdentifier &Params, |
Sam McCall | b9ec3e9 | 2019-05-07 08:30:32 +0000 | [diff] [blame] | 969 | Callback<llvm::Optional<URIForFile>> Reply) { |
Sam McCall | 111fe84 | 2019-05-07 07:55:35 +0000 | [diff] [blame] | 970 | if (auto Result = Server->switchSourceHeader(Params.uri.file())) |
Sam McCall | b9ec3e9 | 2019-05-07 08:30:32 +0000 | [diff] [blame] | 971 | Reply(URIForFile::canonicalize(*Result, Params.uri.file())); |
Sam McCall | 111fe84 | 2019-05-07 07:55:35 +0000 | [diff] [blame] | 972 | else |
| 973 | Reply(llvm::None); |
Marc-Andre Laperle | 6571b3e | 2017-09-28 03:14:40 +0000 | [diff] [blame] | 974 | } |
| 975 | |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 976 | void ClangdLSPServer::onDocumentHighlight( |
| 977 | const TextDocumentPositionParams &Params, |
| 978 | Callback<std::vector<DocumentHighlight>> Reply) { |
| 979 | Server->findDocumentHighlights(Params.textDocument.uri.file(), |
| 980 | Params.position, std::move(Reply)); |
Ilya Biryukov | 0e6a51f | 2017-12-12 12:27:47 +0000 | [diff] [blame] | 981 | } |
| 982 | |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 983 | void ClangdLSPServer::onHover(const TextDocumentPositionParams &Params, |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 984 | Callback<llvm::Optional<Hover>> Reply) { |
Ilya Biryukov | 652364b | 2018-09-26 05:48:29 +0000 | [diff] [blame] | 985 | Server->findHover(Params.textDocument.uri.file(), Params.position, |
Benjamin Kramer | 9880b5d | 2019-08-15 14:16:06 +0000 | [diff] [blame^] | 986 | [Reply = std::move(Reply), this]( |
| 987 | llvm::Expected<llvm::Optional<HoverInfo>> H) mutable { |
| 988 | if (!H) |
| 989 | return Reply(H.takeError()); |
| 990 | if (!*H) |
| 991 | return Reply(llvm::None); |
Ilya Biryukov | f9169d0 | 2019-05-29 10:01:00 +0000 | [diff] [blame] | 992 | |
Benjamin Kramer | 9880b5d | 2019-08-15 14:16:06 +0000 | [diff] [blame^] | 993 | Hover R; |
| 994 | R.contents.kind = HoverContentFormat; |
| 995 | R.range = (*H)->SymRange; |
| 996 | switch (HoverContentFormat) { |
| 997 | case MarkupKind::PlainText: |
| 998 | R.contents.value = (*H)->present().renderAsPlainText(); |
| 999 | return Reply(std::move(R)); |
| 1000 | case MarkupKind::Markdown: |
| 1001 | R.contents.value = (*H)->present().renderAsMarkdown(); |
| 1002 | return Reply(std::move(R)); |
| 1003 | }; |
| 1004 | llvm_unreachable("unhandled MarkupKind"); |
| 1005 | }); |
Marc-Andre Laperle | 3e618ed | 2018-02-16 21:38:15 +0000 | [diff] [blame] | 1006 | } |
| 1007 | |
Kadir Cetinkaya | 8665802 | 2019-03-19 09:27:04 +0000 | [diff] [blame] | 1008 | void ClangdLSPServer::onTypeHierarchy( |
| 1009 | const TypeHierarchyParams &Params, |
| 1010 | Callback<Optional<TypeHierarchyItem>> Reply) { |
| 1011 | Server->typeHierarchy(Params.textDocument.uri.file(), Params.position, |
| 1012 | Params.resolve, Params.direction, std::move(Reply)); |
| 1013 | } |
| 1014 | |
Nathan Ridge | 087b044 | 2019-07-13 03:24:48 +0000 | [diff] [blame] | 1015 | void ClangdLSPServer::onResolveTypeHierarchy( |
| 1016 | const ResolveTypeHierarchyItemParams &Params, |
| 1017 | Callback<Optional<TypeHierarchyItem>> Reply) { |
| 1018 | Server->resolveTypeHierarchy(Params.item, Params.resolve, Params.direction, |
| 1019 | std::move(Reply)); |
| 1020 | } |
| 1021 | |
Simon Marchi | 8801678 | 2018-08-01 11:28:49 +0000 | [diff] [blame] | 1022 | void ClangdLSPServer::applyConfiguration( |
Sam McCall | bc90461 | 2018-10-25 04:22:52 +0000 | [diff] [blame] | 1023 | const ConfigurationSettings &Settings) { |
Simon Marchi | abeed66 | 2018-10-16 15:55:03 +0000 | [diff] [blame] | 1024 | // Per-file update to the compilation database. |
Sam McCall | bc90461 | 2018-10-25 04:22:52 +0000 | [diff] [blame] | 1025 | bool ShouldReparseOpenFiles = false; |
| 1026 | for (auto &Entry : Settings.compilationDatabaseChanges) { |
| 1027 | /// The opened files need to be reparsed only when some existing |
| 1028 | /// entries are changed. |
| 1029 | PathRef File = Entry.first; |
Sam McCall | c55d09a | 2018-11-02 13:09:36 +0000 | [diff] [blame] | 1030 | auto Old = CDB->getCompileCommand(File); |
| 1031 | auto New = |
| 1032 | tooling::CompileCommand(std::move(Entry.second.workingDirectory), File, |
| 1033 | std::move(Entry.second.compilationCommand), |
| 1034 | /*Output=*/""); |
Sam McCall | 6980edb | 2018-11-02 14:07:51 +0000 | [diff] [blame] | 1035 | if (Old != New) { |
Sam McCall | c55d09a | 2018-11-02 13:09:36 +0000 | [diff] [blame] | 1036 | CDB->setCompileCommand(File, std::move(New)); |
Sam McCall | 6980edb | 2018-11-02 14:07:51 +0000 | [diff] [blame] | 1037 | ShouldReparseOpenFiles = true; |
| 1038 | } |
Alex Lorenz | f808786 | 2018-08-01 17:39:29 +0000 | [diff] [blame] | 1039 | } |
Sam McCall | bc90461 | 2018-10-25 04:22:52 +0000 | [diff] [blame] | 1040 | if (ShouldReparseOpenFiles) |
| 1041 | reparseOpenedFiles(); |
Simon Marchi | 5178f92 | 2018-02-22 14:00:39 +0000 | [diff] [blame] | 1042 | } |
| 1043 | |
Johan Vikstrom | a848dab | 2019-07-04 07:53:12 +0000 | [diff] [blame] | 1044 | void ClangdLSPServer::publishSemanticHighlighting( |
| 1045 | SemanticHighlightingParams Params) { |
| 1046 | notify("textDocument/semanticHighlighting", Params); |
| 1047 | } |
| 1048 | |
Ilya Biryukov | 49c1071 | 2019-03-25 10:15:11 +0000 | [diff] [blame] | 1049 | void ClangdLSPServer::publishDiagnostics( |
| 1050 | const URIForFile &File, std::vector<clangd::Diagnostic> Diagnostics) { |
| 1051 | // Publish diagnostics. |
| 1052 | notify("textDocument/publishDiagnostics", |
| 1053 | llvm::json::Object{ |
| 1054 | {"uri", File}, |
| 1055 | {"diagnostics", std::move(Diagnostics)}, |
| 1056 | }); |
| 1057 | } |
| 1058 | |
Simon Marchi | 8801678 | 2018-08-01 11:28:49 +0000 | [diff] [blame] | 1059 | // FIXME: This function needs to be properly tested. |
| 1060 | void ClangdLSPServer::onChangeConfiguration( |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 1061 | const DidChangeConfigurationParams &Params) { |
Simon Marchi | 8801678 | 2018-08-01 11:28:49 +0000 | [diff] [blame] | 1062 | applyConfiguration(Params.settings); |
| 1063 | } |
| 1064 | |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 1065 | void ClangdLSPServer::onReference(const ReferenceParams &Params, |
| 1066 | Callback<std::vector<Location>> Reply) { |
Ilya Biryukov | 652364b | 2018-09-26 05:48:29 +0000 | [diff] [blame] | 1067 | Server->findReferences(Params.textDocument.uri.file(), Params.position, |
Haojian Wu | c34f022 | 2019-01-14 18:11:09 +0000 | [diff] [blame] | 1068 | CCOpts.Limit, std::move(Reply)); |
Sam McCall | 1ad142f | 2018-09-05 11:53:07 +0000 | [diff] [blame] | 1069 | } |
| 1070 | |
Jan Korous | b406701 | 2018-11-27 16:40:46 +0000 | [diff] [blame] | 1071 | void ClangdLSPServer::onSymbolInfo(const TextDocumentPositionParams &Params, |
| 1072 | Callback<std::vector<SymbolDetails>> Reply) { |
| 1073 | Server->symbolInfo(Params.textDocument.uri.file(), Params.position, |
| 1074 | std::move(Reply)); |
| 1075 | } |
| 1076 | |
Sam McCall | a69698f | 2019-03-27 17:47:49 +0000 | [diff] [blame] | 1077 | ClangdLSPServer::ClangdLSPServer( |
| 1078 | class Transport &Transp, const FileSystemProvider &FSProvider, |
| 1079 | const clangd::CodeCompleteOptions &CCOpts, |
| 1080 | llvm::Optional<Path> CompileCommandsDir, bool UseDirBasedCDB, |
| 1081 | llvm::Optional<OffsetEncoding> ForcedOffsetEncoding, |
| 1082 | const ClangdServer::Options &Opts) |
Haojian Wu | 1ca0c58 | 2019-01-22 09:39:05 +0000 | [diff] [blame] | 1083 | : Transp(Transp), MsgHandler(new MessageHandler(*this)), |
| 1084 | FSProvider(FSProvider), CCOpts(CCOpts), |
Sam McCall | d1c9d11 | 2018-10-23 14:19:54 +0000 | [diff] [blame] | 1085 | SupportedSymbolKinds(defaultSymbolKinds()), |
Kadir Cetinkaya | 133d46f | 2018-09-27 17:13:07 +0000 | [diff] [blame] | 1086 | SupportedCompletionItemKinds(defaultCompletionItemKinds()), |
Sam McCall | c55d09a | 2018-11-02 13:09:36 +0000 | [diff] [blame] | 1087 | UseDirBasedCDB(UseDirBasedCDB), |
Sam McCall | a69698f | 2019-03-27 17:47:49 +0000 | [diff] [blame] | 1088 | CompileCommandsDir(std::move(CompileCommandsDir)), ClangdServerOpts(Opts), |
| 1089 | NegotiatedOffsetEncoding(ForcedOffsetEncoding) { |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 1090 | // clang-format off |
| 1091 | MsgHandler->bind("initialize", &ClangdLSPServer::onInitialize); |
| 1092 | MsgHandler->bind("shutdown", &ClangdLSPServer::onShutdown); |
Sam McCall | 422c828 | 2018-11-26 16:00:11 +0000 | [diff] [blame] | 1093 | MsgHandler->bind("sync", &ClangdLSPServer::onSync); |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 1094 | MsgHandler->bind("textDocument/rangeFormatting", &ClangdLSPServer::onDocumentRangeFormatting); |
| 1095 | MsgHandler->bind("textDocument/onTypeFormatting", &ClangdLSPServer::onDocumentOnTypeFormatting); |
| 1096 | MsgHandler->bind("textDocument/formatting", &ClangdLSPServer::onDocumentFormatting); |
| 1097 | MsgHandler->bind("textDocument/codeAction", &ClangdLSPServer::onCodeAction); |
| 1098 | MsgHandler->bind("textDocument/completion", &ClangdLSPServer::onCompletion); |
| 1099 | MsgHandler->bind("textDocument/signatureHelp", &ClangdLSPServer::onSignatureHelp); |
| 1100 | MsgHandler->bind("textDocument/definition", &ClangdLSPServer::onGoToDefinition); |
Sam McCall | 866ba2c | 2019-02-01 11:26:13 +0000 | [diff] [blame] | 1101 | MsgHandler->bind("textDocument/declaration", &ClangdLSPServer::onGoToDeclaration); |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 1102 | MsgHandler->bind("textDocument/references", &ClangdLSPServer::onReference); |
| 1103 | MsgHandler->bind("textDocument/switchSourceHeader", &ClangdLSPServer::onSwitchSourceHeader); |
Haojian Wu | f429ab6 | 2019-07-24 07:49:23 +0000 | [diff] [blame] | 1104 | MsgHandler->bind("textDocument/prepareRename", &ClangdLSPServer::onPrepareRename); |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 1105 | MsgHandler->bind("textDocument/rename", &ClangdLSPServer::onRename); |
| 1106 | MsgHandler->bind("textDocument/hover", &ClangdLSPServer::onHover); |
| 1107 | MsgHandler->bind("textDocument/documentSymbol", &ClangdLSPServer::onDocumentSymbol); |
| 1108 | MsgHandler->bind("workspace/executeCommand", &ClangdLSPServer::onCommand); |
| 1109 | MsgHandler->bind("textDocument/documentHighlight", &ClangdLSPServer::onDocumentHighlight); |
| 1110 | MsgHandler->bind("workspace/symbol", &ClangdLSPServer::onWorkspaceSymbol); |
| 1111 | MsgHandler->bind("textDocument/didOpen", &ClangdLSPServer::onDocumentDidOpen); |
| 1112 | MsgHandler->bind("textDocument/didClose", &ClangdLSPServer::onDocumentDidClose); |
| 1113 | MsgHandler->bind("textDocument/didChange", &ClangdLSPServer::onDocumentDidChange); |
| 1114 | MsgHandler->bind("workspace/didChangeWatchedFiles", &ClangdLSPServer::onFileEvent); |
| 1115 | MsgHandler->bind("workspace/didChangeConfiguration", &ClangdLSPServer::onChangeConfiguration); |
Jan Korous | b406701 | 2018-11-27 16:40:46 +0000 | [diff] [blame] | 1116 | MsgHandler->bind("textDocument/symbolInfo", &ClangdLSPServer::onSymbolInfo); |
Kadir Cetinkaya | 8665802 | 2019-03-19 09:27:04 +0000 | [diff] [blame] | 1117 | MsgHandler->bind("textDocument/typeHierarchy", &ClangdLSPServer::onTypeHierarchy); |
Nathan Ridge | 087b044 | 2019-07-13 03:24:48 +0000 | [diff] [blame] | 1118 | MsgHandler->bind("typeHierarchy/resolve", &ClangdLSPServer::onResolveTypeHierarchy); |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 1119 | // clang-format on |
| 1120 | } |
| 1121 | |
Haojian Wu | f251634 | 2019-08-05 12:48:09 +0000 | [diff] [blame] | 1122 | ClangdLSPServer::~ClangdLSPServer() { IsBeingDestroyed = true; } |
Ilya Biryukov | 38d7977 | 2017-05-16 09:38:59 +0000 | [diff] [blame] | 1123 | |
Sam McCall | dc8f3cf | 2018-10-17 07:32:05 +0000 | [diff] [blame] | 1124 | bool ClangdLSPServer::run() { |
Ilya Biryukov | afb5554 | 2017-05-16 14:40:30 +0000 | [diff] [blame] | 1125 | // Run the Language Server loop. |
Sam McCall | dc8f3cf | 2018-10-17 07:32:05 +0000 | [diff] [blame] | 1126 | bool CleanExit = true; |
Sam McCall | 2c30fbc | 2018-10-18 12:32:04 +0000 | [diff] [blame] | 1127 | if (auto Err = Transp.loop(*MsgHandler)) { |
Sam McCall | dc8f3cf | 2018-10-17 07:32:05 +0000 | [diff] [blame] | 1128 | elog("Transport error: {0}", std::move(Err)); |
| 1129 | CleanExit = false; |
| 1130 | } |
Ilya Biryukov | afb5554 | 2017-05-16 14:40:30 +0000 | [diff] [blame] | 1131 | |
Ilya Biryukov | 652364b | 2018-09-26 05:48:29 +0000 | [diff] [blame] | 1132 | // Destroy ClangdServer to ensure all worker threads finish. |
| 1133 | Server.reset(); |
Sam McCall | dc8f3cf | 2018-10-17 07:32:05 +0000 | [diff] [blame] | 1134 | return CleanExit && ShutdownRequestReceived; |
Ilya Biryukov | 38d7977 | 2017-05-16 09:38:59 +0000 | [diff] [blame] | 1135 | } |
| 1136 | |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 1137 | std::vector<Fix> ClangdLSPServer::getFixes(llvm::StringRef File, |
Ilya Biryukov | 71028b8 | 2018-03-12 15:28:22 +0000 | [diff] [blame] | 1138 | const clangd::Diagnostic &D) { |
Ilya Biryukov | 38d7977 | 2017-05-16 09:38:59 +0000 | [diff] [blame] | 1139 | std::lock_guard<std::mutex> Lock(FixItsMutex); |
| 1140 | auto DiagToFixItsIter = FixItsMap.find(File); |
| 1141 | if (DiagToFixItsIter == FixItsMap.end()) |
| 1142 | return {}; |
| 1143 | |
| 1144 | const auto &DiagToFixItsMap = DiagToFixItsIter->second; |
| 1145 | auto FixItsIter = DiagToFixItsMap.find(D); |
| 1146 | if (FixItsIter == DiagToFixItsMap.end()) |
| 1147 | return {}; |
| 1148 | |
| 1149 | return FixItsIter->second; |
| 1150 | } |
| 1151 | |
Ilya Biryukov | b0826bd | 2019-01-03 13:37:12 +0000 | [diff] [blame] | 1152 | bool ClangdLSPServer::shouldRunCompletion( |
| 1153 | const CompletionParams &Params) const { |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 1154 | llvm::StringRef Trigger = Params.context.triggerCharacter; |
Ilya Biryukov | b0826bd | 2019-01-03 13:37:12 +0000 | [diff] [blame] | 1155 | if (Params.context.triggerKind != CompletionTriggerKind::TriggerCharacter || |
| 1156 | (Trigger != ">" && Trigger != ":")) |
| 1157 | return true; |
| 1158 | |
| 1159 | auto Code = DraftMgr.getDraft(Params.textDocument.uri.file()); |
| 1160 | if (!Code) |
| 1161 | return true; // completion code will log the error for untracked doc. |
| 1162 | |
| 1163 | // A completion request is sent when the user types '>' or ':', but we only |
| 1164 | // want to trigger on '->' and '::'. We check the preceeding character to make |
| 1165 | // sure it matches what we expected. |
| 1166 | // Running the lexer here would be more robust (e.g. we can detect comments |
| 1167 | // and avoid triggering completion there), but we choose to err on the side |
| 1168 | // of simplicity here. |
| 1169 | auto Offset = positionToOffset(*Code, Params.position, |
| 1170 | /*AllowColumnsBeyondLineLength=*/false); |
| 1171 | if (!Offset) { |
| 1172 | vlog("could not convert position '{0}' to offset for file '{1}'", |
| 1173 | Params.position, Params.textDocument.uri.file()); |
| 1174 | return true; |
| 1175 | } |
| 1176 | if (*Offset < 2) |
| 1177 | return false; |
| 1178 | |
| 1179 | if (Trigger == ">") |
| 1180 | return (*Code)[*Offset - 2] == '-'; // trigger only on '->'. |
| 1181 | if (Trigger == ":") |
| 1182 | return (*Code)[*Offset - 2] == ':'; // trigger only on '::'. |
| 1183 | assert(false && "unhandled trigger character"); |
| 1184 | return true; |
| 1185 | } |
| 1186 | |
Johan Vikstrom | a848dab | 2019-07-04 07:53:12 +0000 | [diff] [blame] | 1187 | void ClangdLSPServer::onHighlightingsReady( |
Johan Vikstrom | c2653ef2 | 2019-08-01 08:08:44 +0000 | [diff] [blame] | 1188 | PathRef File, std::vector<HighlightingToken> Highlightings, int NumLines) { |
| 1189 | std::vector<HighlightingToken> Old; |
| 1190 | std::vector<HighlightingToken> HighlightingsCopy = Highlightings; |
| 1191 | { |
| 1192 | std::lock_guard<std::mutex> Lock(HighlightingsMutex); |
| 1193 | Old = std::move(FileToHighlightings[File]); |
| 1194 | FileToHighlightings[File] = std::move(HighlightingsCopy); |
| 1195 | } |
| 1196 | // LSP allows us to send incremental edits of highlightings. Also need to diff |
| 1197 | // to remove highlightings from tokens that should no longer have them. |
| 1198 | std::vector<LineHighlightings> Diffed = |
| 1199 | diffHighlightings(Highlightings, Old, NumLines); |
Johan Vikstrom | a848dab | 2019-07-04 07:53:12 +0000 | [diff] [blame] | 1200 | publishSemanticHighlighting( |
| 1201 | {{URIForFile::canonicalize(File, /*TUPath=*/File)}, |
Johan Vikstrom | c2653ef2 | 2019-08-01 08:08:44 +0000 | [diff] [blame] | 1202 | toSemanticHighlightingInformation(Diffed)}); |
Johan Vikstrom | a848dab | 2019-07-04 07:53:12 +0000 | [diff] [blame] | 1203 | } |
| 1204 | |
Sam McCall | a7bb0cc | 2018-03-12 23:22:35 +0000 | [diff] [blame] | 1205 | void ClangdLSPServer::onDiagnosticsReady(PathRef File, |
| 1206 | std::vector<Diag> Diagnostics) { |
Eric Liu | 4d814a9 | 2018-11-28 10:30:42 +0000 | [diff] [blame] | 1207 | auto URI = URIForFile::canonicalize(File, /*TUPath=*/File); |
Sam McCall | 16e7070 | 2018-10-24 07:59:38 +0000 | [diff] [blame] | 1208 | std::vector<Diagnostic> LSPDiagnostics; |
Ilya Biryukov | 38d7977 | 2017-05-16 09:38:59 +0000 | [diff] [blame] | 1209 | DiagnosticToReplacementMap LocalFixIts; // Temporary storage |
Sam McCall | a7bb0cc | 2018-03-12 23:22:35 +0000 | [diff] [blame] | 1210 | for (auto &Diag : Diagnostics) { |
Sam McCall | 16e7070 | 2018-10-24 07:59:38 +0000 | [diff] [blame] | 1211 | toLSPDiags(Diag, URI, DiagOpts, |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 1212 | [&](clangd::Diagnostic Diag, llvm::ArrayRef<Fix> Fixes) { |
Sam McCall | 16e7070 | 2018-10-24 07:59:38 +0000 | [diff] [blame] | 1213 | auto &FixItsForDiagnostic = LocalFixIts[Diag]; |
| 1214 | llvm::copy(Fixes, std::back_inserter(FixItsForDiagnostic)); |
| 1215 | LSPDiagnostics.push_back(std::move(Diag)); |
| 1216 | }); |
Ilya Biryukov | 38d7977 | 2017-05-16 09:38:59 +0000 | [diff] [blame] | 1217 | } |
| 1218 | |
| 1219 | // Cache FixIts |
| 1220 | { |
Ilya Biryukov | 38d7977 | 2017-05-16 09:38:59 +0000 | [diff] [blame] | 1221 | std::lock_guard<std::mutex> Lock(FixItsMutex); |
| 1222 | FixItsMap[File] = LocalFixIts; |
| 1223 | } |
| 1224 | |
Ilya Biryukov | 49c1071 | 2019-03-25 10:15:11 +0000 | [diff] [blame] | 1225 | // Send a notification to the LSP client. |
| 1226 | publishDiagnostics(URI, std::move(LSPDiagnostics)); |
Ilya Biryukov | 38d7977 | 2017-05-16 09:38:59 +0000 | [diff] [blame] | 1227 | } |
Simon Marchi | 9569fd5 | 2018-03-16 14:30:42 +0000 | [diff] [blame] | 1228 | |
Haojian Wu | b618849 | 2018-12-20 15:39:12 +0000 | [diff] [blame] | 1229 | void ClangdLSPServer::onFileUpdated(PathRef File, const TUStatus &Status) { |
| 1230 | if (!SupportFileStatus) |
| 1231 | return; |
| 1232 | // FIXME: we don't emit "BuildingFile" and `RunningAction`, as these |
| 1233 | // two statuses are running faster in practice, which leads the UI constantly |
| 1234 | // changing, and doesn't provide much value. We may want to emit status at a |
| 1235 | // reasonable time interval (e.g. 0.5s). |
| 1236 | if (Status.Action.S == TUAction::BuildingFile || |
| 1237 | Status.Action.S == TUAction::RunningAction) |
| 1238 | return; |
| 1239 | notify("textDocument/clangd.fileStatus", Status.render(File)); |
| 1240 | } |
| 1241 | |
Simon Marchi | 9569fd5 | 2018-03-16 14:30:42 +0000 | [diff] [blame] | 1242 | void ClangdLSPServer::reparseOpenedFiles() { |
| 1243 | for (const Path &FilePath : DraftMgr.getActiveFiles()) |
Ilya Biryukov | 652364b | 2018-09-26 05:48:29 +0000 | [diff] [blame] | 1244 | Server->addDocument(FilePath, *DraftMgr.getDraft(FilePath), |
| 1245 | WantDiagnostics::Auto); |
Simon Marchi | 9569fd5 | 2018-03-16 14:30:42 +0000 | [diff] [blame] | 1246 | } |
Alex Lorenz | f808786 | 2018-08-01 17:39:29 +0000 | [diff] [blame] | 1247 | |
Sam McCall | c008af6 | 2018-10-20 15:30:37 +0000 | [diff] [blame] | 1248 | } // namespace clangd |
| 1249 | } // namespace clang |