| 1 | //===--- ClangdLSPServer.cpp - LSP server ------------------------*- C++-*-===// |
| 2 | // |
| 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 |
| 6 | // |
| 7 | //===----------------------------------------------------------------------===// |
| 8 | |
| 9 | #include "ClangdLSPServer.h" |
| 10 | #include "ClangdServer.h" |
| 11 | #include "CodeComplete.h" |
| 12 | #include "CompileCommands.h" |
| 13 | #include "Diagnostics.h" |
| 14 | #include "Feature.h" |
| 15 | #include "GlobalCompilationDatabase.h" |
| 16 | #include "LSPBinder.h" |
| 17 | #include "Protocol.h" |
| 18 | #include "SemanticHighlighting.h" |
| 19 | #include "SourceCode.h" |
| 20 | #include "TUScheduler.h" |
| 21 | #include "URI.h" |
| 22 | #include "refactor/Tweak.h" |
| 23 | #include "support/Cancellation.h" |
| 24 | #include "support/Context.h" |
| 25 | #include "support/MemoryTree.h" |
| 26 | #include "support/Trace.h" |
| 27 | #include "clang/Tooling/Core/Replacement.h" |
| 28 | #include "llvm/ADT/ArrayRef.h" |
| 29 | #include "llvm/ADT/FunctionExtras.h" |
| 30 | #include "llvm/ADT/ScopeExit.h" |
| 31 | #include "llvm/ADT/StringRef.h" |
| 32 | #include "llvm/ADT/Twine.h" |
| 33 | #include "llvm/Support/Allocator.h" |
| 34 | #include "llvm/Support/Error.h" |
| 35 | #include "llvm/Support/FormatVariadic.h" |
| 36 | #include "llvm/Support/JSON.h" |
| 37 | #include "llvm/Support/SHA1.h" |
| 38 | #include "llvm/Support/ScopedPrinter.h" |
| 39 | #include "llvm/Support/raw_ostream.h" |
| 40 | #include <chrono> |
| 41 | #include <cstddef> |
| 42 | #include <cstdint> |
| 43 | #include <functional> |
| 44 | #include <memory> |
| 45 | #include <mutex> |
| 46 | #include <optional> |
| 47 | #include <string> |
| 48 | #include <vector> |
| 49 | |
| 50 | namespace clang { |
| 51 | namespace clangd { |
| 52 | namespace { |
| 53 | // Tracks end-to-end latency of high level lsp calls. Measurements are in |
| 54 | // seconds. |
| 55 | constexpr trace::Metric LSPLatency("lsp_latency", trace::Metric::Distribution, |
| 56 | "method_name"); |
| 57 | |
| 58 | // LSP defines file versions as numbers that increase. |
| 59 | // ClangdServer treats them as opaque and therefore uses strings instead. |
| 60 | std::string encodeVersion(std::optional<int64_t> LSPVersion) { |
| 61 | return LSPVersion ? llvm::to_string(*LSPVersion) : ""; |
| 62 | } |
| 63 | std::optional<int64_t> decodeVersion(llvm::StringRef Encoded) { |
| 64 | int64_t Result; |
| 65 | if (llvm::to_integer(Encoded, Result, 10)) |
| 66 | return Result; |
| 67 | if (!Encoded.empty()) // Empty can be e.g. diagnostics on close. |
| 68 | elog("unexpected non-numeric version {0}", Encoded); |
| 69 | return std::nullopt; |
| 70 | } |
| 71 | |
| 72 | const llvm::StringLiteral ApplyFixCommand = "clangd.applyFix"; |
| 73 | const llvm::StringLiteral ApplyTweakCommand = "clangd.applyTweak"; |
| 74 | |
| 75 | /// Transforms a tweak into a code action that would apply it if executed. |
| 76 | /// EXPECTS: T.prepare() was called and returned true. |
| 77 | CodeAction toCodeAction(const ClangdServer::TweakRef &T, const URIForFile &File, |
| 78 | Range Selection) { |
| 79 | CodeAction CA; |
| 80 | CA.title = T.Title; |
| 81 | CA.kind = T.Kind.str(); |
| 82 | // This tweak may have an expensive second stage, we only run it if the user |
| 83 | // actually chooses it in the UI. We reply with a command that would run the |
| 84 | // corresponding tweak. |
| 85 | // FIXME: for some tweaks, computing the edits is cheap and we could send them |
| 86 | // directly. |
| 87 | CA.command.emplace(); |
| 88 | CA.command->title = T.Title; |
| 89 | CA.command->command = std::string(ApplyTweakCommand); |
| 90 | TweakArgs Args; |
| 91 | Args.file = File; |
| 92 | Args.tweakID = T.ID; |
| 93 | Args.selection = Selection; |
| 94 | CA.command->argument = std::move(Args); |
| 95 | return CA; |
| 96 | } |
| 97 | |
| 98 | void adjustSymbolKinds(llvm::MutableArrayRef<DocumentSymbol> Syms, |
| 99 | SymbolKindBitset Kinds) { |
| 100 | for (auto &S : Syms) { |
| 101 | S.kind = adjustKindToCapability(S.kind, Kinds); |
| 102 | adjustSymbolKinds(S.children, Kinds); |
| 103 | } |
| 104 | } |
| 105 | |
| 106 | SymbolKindBitset defaultSymbolKinds() { |
| 107 | SymbolKindBitset Defaults; |
| 108 | for (size_t I = SymbolKindMin; I <= static_cast<size_t>(SymbolKind::Array); |
| 109 | ++I) |
| 110 | Defaults.set(I); |
| 111 | return Defaults; |
| 112 | } |
| 113 | |
| 114 | CompletionItemKindBitset defaultCompletionItemKinds() { |
| 115 | CompletionItemKindBitset Defaults; |
| 116 | for (size_t I = CompletionItemKindMin; |
| 117 | I <= static_cast<size_t>(CompletionItemKind::Reference); ++I) |
| 118 | Defaults.set(I); |
| 119 | return Defaults; |
| 120 | } |
| 121 | |
| 122 | // Makes sure edits in \p FE are applicable to latest file contents reported by |
| 123 | // editor. If not generates an error message containing information about files |
| 124 | // that needs to be saved. |
| 125 | llvm::Error validateEdits(const ClangdServer &Server, const FileEdits &FE) { |
| 126 | size_t InvalidFileCount = 0; |
| 127 | llvm::StringRef LastInvalidFile; |
| 128 | for (const auto &It : FE) { |
| 129 | if (auto Draft = Server.getDraft(It.first())) { |
| 130 | // If the file is open in user's editor, make sure the version we |
| 131 | // saw and current version are compatible as this is the text that |
| 132 | // will be replaced by editors. |
| 133 | if (!It.second.canApplyTo(*Draft)) { |
| 134 | ++InvalidFileCount; |
| 135 | LastInvalidFile = It.first(); |
| 136 | } |
| 137 | } |
| 138 | } |
| 139 | if (!InvalidFileCount) |
| 140 | return llvm::Error::success(); |
| 141 | if (InvalidFileCount == 1) |
| 142 | return error("File must be saved first: {0}", LastInvalidFile); |
| 143 | return error("Files must be saved first: {0} (and {1} others)", |
| 144 | LastInvalidFile, InvalidFileCount - 1); |
| 145 | } |
| 146 | } // namespace |
| 147 | |
| 148 | // MessageHandler dispatches incoming LSP messages. |
| 149 | // It handles cross-cutting concerns: |
| 150 | // - serializes/deserializes protocol objects to JSON |
| 151 | // - logging of inbound messages |
| 152 | // - cancellation handling |
| 153 | // - basic call tracing |
| 154 | // MessageHandler ensures that initialize() is called before any other handler. |
| 155 | class ClangdLSPServer::MessageHandler : public Transport::MessageHandler { |
| 156 | public: |
| 157 | MessageHandler(ClangdLSPServer &Server) : Server(Server) {} |
| 158 | |
| 159 | bool onNotify(llvm::StringRef Method, llvm::json::Value Params) override { |
| 160 | trace::Span Tracer(Method, LSPLatency); |
| 161 | SPAN_ATTACH(Tracer, "Params", Params); |
| 162 | WithContext HandlerContext(handlerContext()); |
| 163 | log("<-- {0}", Method); |
| 164 | if (Method == "exit") |
| 165 | return false; |
| 166 | auto Handler = Server.Handlers.NotificationHandlers.find(Method); |
| 167 | if (Handler != Server.Handlers.NotificationHandlers.end()) { |
| 168 | Handler->second(std::move(Params)); |
| 169 | Server.maybeExportMemoryProfile(); |
| 170 | Server.maybeCleanupMemory(); |
| 171 | } else if (!Server.Server) { |
| 172 | elog("Notification {0} before initialization", Method); |
| 173 | } else if (Method == "$/cancelRequest") { |
| 174 | onCancel(std::move(Params)); |
| 175 | } else { |
| 176 | log("unhandled notification {0}", Method); |
| 177 | } |
| 178 | return true; |
| 179 | } |
| 180 | |
| 181 | bool onCall(llvm::StringRef Method, llvm::json::Value Params, |
| 182 | llvm::json::Value ID) override { |
| 183 | WithContext HandlerContext(handlerContext()); |
| 184 | // Calls can be canceled by the client. Add cancellation context. |
| 185 | WithContext WithCancel(cancelableRequestContext(ID)); |
| 186 | trace::Span Tracer(Method, LSPLatency); |
| 187 | SPAN_ATTACH(Tracer, "Params", Params); |
| 188 | ReplyOnce Reply(ID, Method, &Server, Tracer.Args); |
| 189 | log("<-- {0}({1})", Method, ID); |
| 190 | auto Handler = Server.Handlers.MethodHandlers.find(Method); |
| 191 | if (Handler != Server.Handlers.MethodHandlers.end()) { |
| 192 | Handler->second(std::move(Params), std::move(Reply)); |
| 193 | } else if (!Server.Server) { |
| 194 | elog("Call {0} before initialization.", Method); |
| 195 | Reply(llvm::make_error<LSPError>("server not initialized", |
| 196 | ErrorCode::ServerNotInitialized)); |
| 197 | } else { |
| 198 | Reply(llvm::make_error<LSPError>("method not found", |
| 199 | ErrorCode::MethodNotFound)); |
| 200 | } |
| 201 | return true; |
| 202 | } |
| 203 | |
| 204 | bool onReply(llvm::json::Value ID, |
| 205 | llvm::Expected<llvm::json::Value> Result) override { |
| 206 | WithContext HandlerContext(handlerContext()); |
| 207 | |
| 208 | Callback<llvm::json::Value> ReplyHandler = nullptr; |
| 209 | if (auto IntID = ID.getAsInteger()) { |
| 210 | std::lock_guard<std::mutex> Mutex(CallMutex); |
| 211 | // Find a corresponding callback for the request ID; |
| 212 | for (size_t Index = 0; Index < ReplyCallbacks.size(); ++Index) { |
| 213 | if (ReplyCallbacks[Index].first == *IntID) { |
| 214 | ReplyHandler = std::move(ReplyCallbacks[Index].second); |
| 215 | ReplyCallbacks.erase(ReplyCallbacks.begin() + |
| 216 | Index); // remove the entry |
| 217 | break; |
| 218 | } |
| 219 | } |
| 220 | } |
| 221 | |
| 222 | if (!ReplyHandler) { |
| 223 | // No callback being found, use a default log callback. |
| 224 | ReplyHandler = [&ID](llvm::Expected<llvm::json::Value> Result) { |
| 225 | elog("received a reply with ID {0}, but there was no such call", ID); |
| 226 | if (!Result) |
| 227 | llvm::consumeError(Result.takeError()); |
| 228 | }; |
| 229 | } |
| 230 | |
| 231 | // Log and run the reply handler. |
| 232 | if (Result) { |
| 233 | log("<-- reply({0})", ID); |
| 234 | ReplyHandler(std::move(Result)); |
| 235 | } else { |
| 236 | auto Err = Result.takeError(); |
| 237 | log("<-- reply({0}) error: {1}", ID, Err); |
| 238 | ReplyHandler(std::move(Err)); |
| 239 | } |
| 240 | return true; |
| 241 | } |
| 242 | |
| 243 | // Bind a reply callback to a request. The callback will be invoked when |
| 244 | // clangd receives the reply from the LSP client. |
| 245 | // Return a call id of the request. |
| 246 | llvm::json::Value bindReply(Callback<llvm::json::Value> Reply) { |
| 247 | std::optional<std::pair<int, Callback<llvm::json::Value>>> OldestCB; |
| 248 | int ID; |
| 249 | { |
| 250 | std::lock_guard<std::mutex> Mutex(CallMutex); |
| 251 | ID = NextCallID++; |
| 252 | ReplyCallbacks.emplace_back(ID, std::move(Reply)); |
| 253 | |
| 254 | // If the queue overflows, we assume that the client didn't reply the |
| 255 | // oldest request, and run the corresponding callback which replies an |
| 256 | // error to the client. |
| 257 | if (ReplyCallbacks.size() > MaxReplayCallbacks) { |
| 258 | elog("more than {0} outstanding LSP calls, forgetting about {1}", |
| 259 | MaxReplayCallbacks, ReplyCallbacks.front().first); |
| 260 | OldestCB = std::move(ReplyCallbacks.front()); |
| 261 | ReplyCallbacks.pop_front(); |
| 262 | } |
| 263 | } |
| 264 | if (OldestCB) |
| 265 | OldestCB->second( |
| 266 | error("failed to receive a client reply for request ({0})", |
| 267 | OldestCB->first)); |
| 268 | return ID; |
| 269 | } |
| 270 | |
| 271 | private: |
| 272 | // Function object to reply to an LSP call. |
| 273 | // Each instance must be called exactly once, otherwise: |
| 274 | // - the bug is logged, and (in debug mode) an assert will fire |
| 275 | // - if there was no reply, an error reply is sent |
| 276 | // - if there were multiple replies, only the first is sent |
| 277 | class ReplyOnce { |
| 278 | std::atomic<bool> Replied = {false}; |
| 279 | std::chrono::steady_clock::time_point Start; |
| 280 | llvm::json::Value ID; |
| 281 | std::string Method; |
| 282 | ClangdLSPServer *Server; // Null when moved-from. |
| 283 | llvm::json::Object *TraceArgs; |
| 284 | |
| 285 | public: |
| 286 | ReplyOnce(const llvm::json::Value &ID, llvm::StringRef Method, |
| 287 | ClangdLSPServer *Server, llvm::json::Object *TraceArgs) |
| 288 | : Start(std::chrono::steady_clock::now()), ID(ID), Method(Method), |
| 289 | Server(Server), TraceArgs(TraceArgs) { |
| 290 | assert(Server); |
| 291 | } |
| 292 | ReplyOnce(ReplyOnce &&Other) |
| 293 | : Replied(Other.Replied.load()), Start(Other.Start), |
| 294 | ID(std::move(Other.ID)), Method(std::move(Other.Method)), |
| 295 | Server(Other.Server), TraceArgs(Other.TraceArgs) { |
| 296 | Other.Server = nullptr; |
| 297 | } |
| 298 | ReplyOnce &operator=(ReplyOnce &&) = delete; |
| 299 | ReplyOnce(const ReplyOnce &) = delete; |
| 300 | ReplyOnce &operator=(const ReplyOnce &) = delete; |
| 301 | |
| 302 | ~ReplyOnce() { |
| 303 | // There's one legitimate reason to never reply to a request: clangd's |
| 304 | // request handler send a call to the client (e.g. applyEdit) and the |
| 305 | // client never replied. In this case, the ReplyOnce is owned by |
| 306 | // ClangdLSPServer's reply callback table and is destroyed along with the |
| 307 | // server. We don't attempt to send a reply in this case, there's little |
| 308 | // to be gained from doing so. |
| 309 | if (Server && !Server->IsBeingDestroyed && !Replied) { |
| 310 | elog("No reply to message {0}({1})", Method, ID); |
| 311 | assert(false && "must reply to all calls!"); |
| 312 | (*this)(llvm::make_error<LSPError>("server failed to reply", |
| 313 | ErrorCode::InternalError)); |
| 314 | } |
| 315 | } |
| 316 | |
| 317 | void operator()(llvm::Expected<llvm::json::Value> Reply) { |
| 318 | assert(Server && "moved-from!"); |
| 319 | if (Replied.exchange(true)) { |
| 320 | elog("Replied twice to message {0}({1})", Method, ID); |
| 321 | assert(false && "must reply to each call only once!"); |
| 322 | return; |
| 323 | } |
| 324 | auto Duration = std::chrono::steady_clock::now() - Start; |
| 325 | if (Reply) { |
| 326 | log("--> reply:{0}({1}) {2:ms}", Method, ID, Duration); |
| 327 | if (TraceArgs) |
| 328 | (*TraceArgs)["Reply"] = *Reply; |
| 329 | std::lock_guard<std::mutex> Lock(Server->TranspWriter); |
| 330 | Server->Transp.reply(std::move(ID), std::move(Reply)); |
| 331 | } else { |
| 332 | llvm::Error Err = Reply.takeError(); |
| 333 | log("--> reply:{0}({1}) {2:ms}, error: {3}", Method, ID, Duration, Err); |
| 334 | if (TraceArgs) |
| 335 | (*TraceArgs)["Error"] = llvm::to_string(Err); |
| 336 | std::lock_guard<std::mutex> Lock(Server->TranspWriter); |
| 337 | Server->Transp.reply(std::move(ID), std::move(Err)); |
| 338 | } |
| 339 | } |
| 340 | }; |
| 341 | |
| 342 | // Method calls may be cancelled by ID, so keep track of their state. |
| 343 | // This needs a mutex: handlers may finish on a different thread, and that's |
| 344 | // when we clean up entries in the map. |
| 345 | mutable std::mutex RequestCancelersMutex; |
| 346 | llvm::StringMap<std::pair<Canceler, /*Cookie*/ unsigned>> RequestCancelers; |
| 347 | unsigned NextRequestCookie = 0; // To disambiguate reused IDs, see below. |
| 348 | void onCancel(const llvm::json::Value &Params) { |
| 349 | const llvm::json::Value *ID = nullptr; |
| 350 | if (auto *O = Params.getAsObject()) |
| 351 | ID = O->get("id"); |
| 352 | if (!ID) { |
| 353 | elog("Bad cancellation request: {0}", Params); |
| 354 | return; |
| 355 | } |
| 356 | auto StrID = llvm::to_string(*ID); |
| 357 | std::lock_guard<std::mutex> Lock(RequestCancelersMutex); |
| 358 | auto It = RequestCancelers.find(StrID); |
| 359 | if (It != RequestCancelers.end()) |
| 360 | It->second.first(); // Invoke the canceler. |
| 361 | } |
| 362 | |
| 363 | Context handlerContext() const { |
| 364 | return Context::current().derive( |
| 365 | kCurrentOffsetEncoding, |
| 366 | Server.Opts.Encoding.value_or(OffsetEncoding::UTF16)); |
| 367 | } |
| 368 | |
| 369 | // We run cancelable requests in a context that does two things: |
| 370 | // - allows cancellation using RequestCancelers[ID] |
| 371 | // - cleans up the entry in RequestCancelers when it's no longer needed |
| 372 | // If a client reuses an ID, the last wins and the first cannot be canceled. |
| 373 | Context cancelableRequestContext(const llvm::json::Value &ID) { |
| 374 | auto Task = cancelableTask( |
| 375 | /*Reason=*/static_cast<int>(ErrorCode::RequestCancelled)); |
| 376 | auto StrID = llvm::to_string(ID); // JSON-serialize ID for map key. |
| 377 | auto Cookie = NextRequestCookie++; // No lock, only called on main thread. |
| 378 | { |
| 379 | std::lock_guard<std::mutex> Lock(RequestCancelersMutex); |
| 380 | RequestCancelers[StrID] = {std::move(Task.second), Cookie}; |
| 381 | } |
| 382 | // When the request ends, we can clean up the entry we just added. |
| 383 | // The cookie lets us check that it hasn't been overwritten due to ID |
| 384 | // reuse. |
| 385 | return Task.first.derive(llvm::make_scope_exit([this, StrID, Cookie] { |
| 386 | std::lock_guard<std::mutex> Lock(RequestCancelersMutex); |
| 387 | auto It = RequestCancelers.find(StrID); |
| 388 | if (It != RequestCancelers.end() && It->second.second == Cookie) |
| 389 | RequestCancelers.erase(It); |
| 390 | })); |
| 391 | } |
| 392 | |
| 393 | // The maximum number of callbacks held in clangd. |
| 394 | // |
| 395 | // We bound the maximum size to the pending map to prevent memory leakage |
| 396 | // for cases where LSP clients don't reply for the request. |
| 397 | // This has to go after RequestCancellers and RequestCancellersMutex since it |
| 398 | // can contain a callback that has a cancelable context. |
| 399 | static constexpr int MaxReplayCallbacks = 100; |
| 400 | mutable std::mutex CallMutex; |
| 401 | int NextCallID = 0; /* GUARDED_BY(CallMutex) */ |
| 402 | std::deque<std::pair</*RequestID*/ int, |
| 403 | /*ReplyHandler*/ Callback<llvm::json::Value>>> |
| 404 | ReplyCallbacks; /* GUARDED_BY(CallMutex) */ |
| 405 | |
| 406 | ClangdLSPServer &Server; |
| 407 | }; |
| 408 | constexpr int ClangdLSPServer::MessageHandler::MaxReplayCallbacks; |
| 409 | |
| 410 | // call(), notify(), and reply() wrap the Transport, adding logging and locking. |
| 411 | void ClangdLSPServer::callMethod(StringRef Method, llvm::json::Value Params, |
| 412 | Callback<llvm::json::Value> CB) { |
| 413 | auto ID = MsgHandler->bindReply(std::move(CB)); |
| 414 | log("--> {0}({1})", Method, ID); |
| 415 | std::lock_guard<std::mutex> Lock(TranspWriter); |
| 416 | Transp.call(Method, std::move(Params), ID); |
| 417 | } |
| 418 | |
| 419 | void ClangdLSPServer::notify(llvm::StringRef Method, llvm::json::Value Params) { |
| 420 | log("--> {0}", Method); |
| 421 | maybeCleanupMemory(); |
| 422 | std::lock_guard<std::mutex> Lock(TranspWriter); |
| 423 | Transp.notify(Method, std::move(Params)); |
| 424 | } |
| 425 | |
| 426 | static std::vector<llvm::StringRef> semanticTokenTypes() { |
| 427 | std::vector<llvm::StringRef> Types; |
| 428 | for (unsigned I = 0; I <= static_cast<unsigned>(HighlightingKind::LastKind); |
| 429 | ++I) |
| 430 | Types.push_back(toSemanticTokenType(static_cast<HighlightingKind>(I))); |
| 431 | return Types; |
| 432 | } |
| 433 | |
| 434 | static std::vector<llvm::StringRef> semanticTokenModifiers() { |
| 435 | std::vector<llvm::StringRef> Modifiers; |
| 436 | for (unsigned I = 0; |
| 437 | I <= static_cast<unsigned>(HighlightingModifier::LastModifier); ++I) |
| 438 | Modifiers.push_back( |
| 439 | toSemanticTokenModifier(static_cast<HighlightingModifier>(I))); |
| 440 | return Modifiers; |
| 441 | } |
| 442 | |
| 443 | void ClangdLSPServer::onInitialize(const InitializeParams &Params, |
| 444 | Callback<llvm::json::Value> Reply) { |
| 445 | // Determine character encoding first as it affects constructed ClangdServer. |
| 446 | if (Params.capabilities.offsetEncoding && !Opts.Encoding) { |
| 447 | Opts.Encoding = OffsetEncoding::UTF16; // fallback |
| 448 | for (OffsetEncoding Supported : *Params.capabilities.offsetEncoding) |
| 449 | if (Supported != OffsetEncoding::UnsupportedEncoding) { |
| 450 | Opts.Encoding = Supported; |
| 451 | break; |
| 452 | } |
| 453 | } |
| 454 | |
| 455 | if (Params.capabilities.TheiaSemanticHighlighting && |
| 456 | !Params.capabilities.SemanticTokens) { |
| 457 | elog("Client requested legacy semanticHighlights notification, which is " |
| 458 | "no longer supported. Migrate to standard semanticTokens request"); |
| 459 | } |
| 460 | |
| 461 | if (Params.rootUri && *Params.rootUri) |
| 462 | Opts.WorkspaceRoot = std::string(Params.rootUri->file()); |
| 463 | else if (Params.rootPath && !Params.rootPath->empty()) |
| 464 | Opts.WorkspaceRoot = *Params.rootPath; |
| 465 | if (Server) |
| 466 | return Reply(llvm::make_error<LSPError>("server already initialized", |
| 467 | ErrorCode::InvalidRequest)); |
| 468 | |
| 469 | Opts.CodeComplete.EnableSnippets = Params.capabilities.CompletionSnippets; |
| 470 | Opts.CodeComplete.IncludeFixIts = Params.capabilities.CompletionFixes; |
| 471 | if (!Opts.CodeComplete.BundleOverloads) |
| 472 | Opts.CodeComplete.BundleOverloads = Params.capabilities.HasSignatureHelp; |
| 473 | Opts.CodeComplete.DocumentationFormat = |
| 474 | Params.capabilities.CompletionDocumentationFormat; |
| 475 | Opts.SignatureHelpDocumentationFormat = |
| 476 | Params.capabilities.SignatureHelpDocumentationFormat; |
| 477 | DiagOpts.EmbedFixesInDiagnostics = Params.capabilities.DiagnosticFixes; |
| 478 | DiagOpts.SendDiagnosticCategory = Params.capabilities.DiagnosticCategory; |
| 479 | DiagOpts.EmitRelatedLocations = |
| 480 | Params.capabilities.DiagnosticRelatedInformation; |
| 481 | if (Params.capabilities.WorkspaceSymbolKinds) |
| 482 | SupportedSymbolKinds |= *Params.capabilities.WorkspaceSymbolKinds; |
| 483 | if (Params.capabilities.CompletionItemKinds) |
| 484 | SupportedCompletionItemKinds |= *Params.capabilities.CompletionItemKinds; |
| 485 | SupportsCodeAction = Params.capabilities.CodeActionStructure; |
| 486 | SupportsHierarchicalDocumentSymbol = |
| 487 | Params.capabilities.HierarchicalDocumentSymbol; |
| 488 | SupportsReferenceContainer = Params.capabilities.ReferenceContainer; |
| 489 | SupportFileStatus = Params.initializationOptions.FileStatus; |
| 490 | HoverContentFormat = Params.capabilities.HoverContentFormat; |
| 491 | Opts.LineFoldingOnly = Params.capabilities.LineFoldingOnly; |
| 492 | SupportsOffsetsInSignatureHelp = Params.capabilities.OffsetsInSignatureHelp; |
| 493 | if (Params.capabilities.WorkDoneProgress) |
| 494 | BackgroundIndexProgressState = BackgroundIndexProgress::Empty; |
| 495 | BackgroundIndexSkipCreate = Params.capabilities.ImplicitProgressCreation; |
| 496 | Opts.ImplicitCancellation = !Params.capabilities.CancelsStaleRequests; |
| 497 | |
| 498 | if (Opts.UseDirBasedCDB) { |
| 499 | DirectoryBasedGlobalCompilationDatabase::Options CDBOpts(TFS); |
| 500 | if (const auto &Dir = Params.initializationOptions.compilationDatabasePath) |
| 501 | CDBOpts.CompileCommandsDir = Dir; |
| 502 | CDBOpts.ContextProvider = Opts.ContextProvider; |
| 503 | BaseCDB = |
| 504 | std::make_unique<DirectoryBasedGlobalCompilationDatabase>(CDBOpts); |
| 505 | } |
| 506 | auto Mangler = CommandMangler::detect(); |
| 507 | Mangler.SystemIncludeExtractor = |
| 508 | getSystemIncludeExtractor(llvm::ArrayRef(Opts.QueryDriverGlobs)); |
| 509 | if (Opts.ResourceDir) |
| 510 | Mangler.ResourceDir = *Opts.ResourceDir; |
| 511 | CDB.emplace(BaseCDB.get(), Params.initializationOptions.fallbackFlags, |
| 512 | std::move(Mangler)); |
| 513 | { |
| 514 | // Switch caller's context with LSPServer's background context. Since we |
| 515 | // rather want to propagate information from LSPServer's context into the |
| 516 | // Server, CDB, etc. |
| 517 | WithContext MainContext(BackgroundContext.clone()); |
| 518 | std::optional<WithContextValue> WithOffsetEncoding; |
| 519 | if (Opts.Encoding) |
| 520 | WithOffsetEncoding.emplace(kCurrentOffsetEncoding, *Opts.Encoding); |
| 521 | Server.emplace(*CDB, TFS, Opts, |
| 522 | static_cast<ClangdServer::Callbacks *>(this)); |
| 523 | } |
| 524 | |
| 525 | llvm::json::Object ServerCaps{ |
| 526 | {"textDocumentSync", |
| 527 | llvm::json::Object{ |
| 528 | {"openClose", true}, |
| 529 | {"change", (int)TextDocumentSyncKind::Incremental}, |
| 530 | {"save", true}, |
| 531 | }}, |
| 532 | {"documentFormattingProvider", true}, |
| 533 | {"documentRangeFormattingProvider", true}, |
| 534 | {"documentOnTypeFormattingProvider", |
| 535 | llvm::json::Object{ |
| 536 | {"firstTriggerCharacter", "\n"}, |
| 537 | {"moreTriggerCharacter", {}}, |
| 538 | }}, |
| 539 | {"completionProvider", |
| 540 | llvm::json::Object{ |
| 541 | // We don't set `(` etc as allCommitCharacters as they interact |
| 542 | // poorly with snippet results. |
| 543 | // See https://github.com/clangd/vscode-clangd/issues/357 |
| 544 | // Hopefully we can use them one day without this side-effect: |
| 545 | // https://github.com/microsoft/vscode/issues/42544 |
| 546 | {"resolveProvider", false}, |
| 547 | // We do extra checks, e.g. that > is part of ->. |
| 548 | {"triggerCharacters", {".", "<", ">", ":", "\"", "/", "*"}}, |
| 549 | }}, |
| 550 | {"semanticTokensProvider", |
| 551 | llvm::json::Object{ |
| 552 | {"full", llvm::json::Object{{"delta", true}}}, |
| 553 | {"range", false}, |
| 554 | {"legend", |
| 555 | llvm::json::Object{{"tokenTypes", semanticTokenTypes()}, |
| 556 | {"tokenModifiers", semanticTokenModifiers()}}}, |
| 557 | }}, |
| 558 | {"signatureHelpProvider", |
| 559 | llvm::json::Object{ |
| 560 | {"triggerCharacters", {"(", ")", "{", "}", "<", ">", ","}}, |
| 561 | }}, |
| 562 | {"declarationProvider", true}, |
| 563 | {"definitionProvider", true}, |
| 564 | {"implementationProvider", true}, |
| 565 | {"typeDefinitionProvider", true}, |
| 566 | {"documentHighlightProvider", true}, |
| 567 | {"documentLinkProvider", |
| 568 | llvm::json::Object{ |
| 569 | {"resolveProvider", false}, |
| 570 | }}, |
| 571 | {"hoverProvider", true}, |
| 572 | {"selectionRangeProvider", true}, |
| 573 | {"documentSymbolProvider", true}, |
| 574 | {"workspaceSymbolProvider", true}, |
| 575 | {"referencesProvider", true}, |
| 576 | {"astProvider", true}, // clangd extension |
| 577 | {"typeHierarchyProvider", true}, |
| 578 | // Unfortunately our extension made use of the same capability name as the |
| 579 | // standard. Advertise this capability to tell clients that implement our |
| 580 | // extension we really have support for the standardized one as well. |
| 581 | {"standardTypeHierarchyProvider", true}, // clangd extension |
| 582 | {"memoryUsageProvider", true}, // clangd extension |
| 583 | {"compilationDatabase", // clangd extension |
| 584 | llvm::json::Object{{"automaticReload", true}}}, |
| 585 | {"callHierarchyProvider", true}, |
| 586 | {"clangdInlayHintsProvider", true}, |
| 587 | {"inlayHintProvider", true}, |
| 588 | {"foldingRangeProvider", true}, |
| 589 | }; |
| 590 | |
| 591 | { |
| 592 | LSPBinder Binder(Handlers, *this); |
| 593 | bindMethods(Binder, Params.capabilities); |
| 594 | if (Opts.FeatureModules) |
| 595 | for (auto &Mod : *Opts.FeatureModules) |
| 596 | Mod.initializeLSP(Binder, Params.rawCapabilities, ServerCaps); |
| 597 | } |
| 598 | |
| 599 | // Per LSP, renameProvider can be either boolean or RenameOptions. |
| 600 | // RenameOptions will be specified if the client states it supports prepare. |
| 601 | ServerCaps["renameProvider"] = |
| 602 | Params.capabilities.RenamePrepareSupport |
| 603 | ? llvm::json::Object{{"prepareProvider", true}} |
| 604 | : llvm::json::Value(true); |
| 605 | |
| 606 | // Per LSP, codeActionProvider can be either boolean or CodeActionOptions. |
| 607 | // CodeActionOptions is only valid if the client supports action literal |
| 608 | // via textDocument.codeAction.codeActionLiteralSupport. |
| 609 | ServerCaps["codeActionProvider"] = |
| 610 | Params.capabilities.CodeActionStructure |
| 611 | ? llvm::json::Object{{"codeActionKinds", |
| 612 | {CodeAction::QUICKFIX_KIND, |
| 613 | CodeAction::REFACTOR_KIND, |
| 614 | CodeAction::INFO_KIND}}} |
| 615 | : llvm::json::Value(true); |
| 616 | |
| 617 | |
| 618 | std::vector<llvm::StringRef> Commands; |
| 619 | for (llvm::StringRef Command : Handlers.CommandHandlers.keys()) |
| 620 | Commands.push_back(Command); |
| 621 | llvm::sort(Commands); |
| 622 | ServerCaps["executeCommandProvider"] = |
| 623 | llvm::json::Object{{"commands", Commands}}; |
| 624 | |
| 625 | llvm::json::Object Result{ |
| 626 | {{"serverInfo", |
| 627 | llvm::json::Object{ |
| 628 | {"name", "clangd"}, |
| 629 | {"version", llvm::formatv("{0} {1} {2}", versionString(), |
| 630 | featureString(), platformString())}}}, |
| 631 | {"capabilities", std::move(ServerCaps)}}}; |
| 632 | if (Opts.Encoding) |
| 633 | Result["offsetEncoding"] = *Opts.Encoding; |
| 634 | Reply(std::move(Result)); |
| 635 | |
| 636 | // Apply settings after we're fully initialized. |
| 637 | // This can start background indexing and in turn trigger LSP notifications. |
| 638 | applyConfiguration(Params.initializationOptions.ConfigSettings); |
| 639 | } |
| 640 | |
| 641 | void ClangdLSPServer::onInitialized(const InitializedParams &Params) {} |
| 642 | |
| 643 | void ClangdLSPServer::onShutdown(const NoParams &, |
| 644 | Callback<std::nullptr_t> Reply) { |
| 645 | // Do essentially nothing, just say we're ready to exit. |
| 646 | ShutdownRequestReceived = true; |
| 647 | Reply(nullptr); |
| 648 | } |
| 649 | |
| 650 | // sync is a clangd extension: it blocks until all background work completes. |
| 651 | // It blocks the calling thread, so no messages are processed until it returns! |
| 652 | void ClangdLSPServer::onSync(const NoParams &, Callback<std::nullptr_t> Reply) { |
| 653 | if (Server->blockUntilIdleForTest(/*TimeoutSeconds=*/60)) |
| 654 | Reply(nullptr); |
| 655 | else |
| 656 | Reply(error("Not idle after a minute")); |
| 657 | } |
| 658 | |
| 659 | void ClangdLSPServer::onDocumentDidOpen( |
| 660 | const DidOpenTextDocumentParams &Params) { |
| 661 | PathRef File = Params.textDocument.uri.file(); |
| 662 | |
| 663 | const std::string &Contents = Params.textDocument.text; |
| 664 | |
| 665 | Server->addDocument(File, Contents, |
| 666 | encodeVersion(Params.textDocument.version), |
| 667 | WantDiagnostics::Yes); |
| 668 | } |
| 669 | |
| 670 | void ClangdLSPServer::onDocumentDidChange( |
| 671 | const DidChangeTextDocumentParams &Params) { |
| 672 | auto WantDiags = WantDiagnostics::Auto; |
| 673 | if (Params.wantDiagnostics) |
| 674 | WantDiags = |
| 675 | *Params.wantDiagnostics ? WantDiagnostics::Yes : WantDiagnostics::No; |
| 676 | |
| 677 | PathRef File = Params.textDocument.uri.file(); |
| 678 | auto Code = Server->getDraft(File); |
| 679 | if (!Code) { |
| 680 | log("Trying to incrementally change non-added document: {0}", File); |
| 681 | return; |
| 682 | } |
| 683 | std::string NewCode(*Code); |
| 684 | for (const auto &Change : Params.contentChanges) { |
| 685 | if (auto Err = applyChange(NewCode, Change)) { |
| 686 | // If this fails, we are most likely going to be not in sync anymore with |
| 687 | // the client. It is better to remove the draft and let further |
| 688 | // operations fail rather than giving wrong results. |
| 689 | Server->removeDocument(File); |
| 690 | elog("Failed to update {0}: {1}", File, std::move(Err)); |
| 691 | return; |
| 692 | } |
| 693 | } |
| 694 | Server->addDocument(File, NewCode, encodeVersion(Params.textDocument.version), |
| 695 | WantDiags, Params.forceRebuild); |
| 696 | } |
| 697 | |
| 698 | void ClangdLSPServer::onDocumentDidSave( |
| 699 | const DidSaveTextDocumentParams &Params) { |
| 700 | Server->reparseOpenFilesIfNeeded([](llvm::StringRef) { return true; }); |
| 701 | } |
| 702 | |
| 703 | void ClangdLSPServer::onFileEvent(const DidChangeWatchedFilesParams &Params) { |
| 704 | // We could also reparse all open files here. However: |
| 705 | // - this could be frequent, and revalidating all the preambles isn't free |
| 706 | // - this is useful e.g. when switching git branches, but we're likely to see |
| 707 | // fresh headers but still have the old-branch main-file content |
| 708 | Server->onFileEvent(Params); |
| 709 | // FIXME: observe config files, immediately expire time-based caches, reparse: |
| 710 | // - compile_commands.json and compile_flags.txt |
| 711 | // - .clang_format and .clang-tidy |
| 712 | // - .clangd and clangd/config.yaml |
| 713 | } |
| 714 | |
| 715 | void ClangdLSPServer::onCommand(const ExecuteCommandParams &Params, |
| 716 | Callback<llvm::json::Value> Reply) { |
| 717 | auto It = Handlers.CommandHandlers.find(Params.command); |
| 718 | if (It == Handlers.CommandHandlers.end()) { |
| 719 | return Reply(llvm::make_error<LSPError>( |
| 720 | llvm::formatv("Unsupported command \"{0}\".", Params.command).str(), |
| 721 | ErrorCode::InvalidParams)); |
| 722 | } |
| 723 | It->second(Params.argument, std::move(Reply)); |
| 724 | } |
| 725 | |
| 726 | void ClangdLSPServer::onCommandApplyEdit(const WorkspaceEdit &WE, |
| 727 | Callback<llvm::json::Value> Reply) { |
| 728 | // The flow for "apply-fix" : |
| 729 | // 1. We publish a diagnostic, including fixits |
| 730 | // 2. The user clicks on the diagnostic, the editor asks us for code actions |
| 731 | // 3. We send code actions, with the fixit embedded as context |
| 732 | // 4. The user selects the fixit, the editor asks us to apply it |
| 733 | // 5. We unwrap the changes and send them back to the editor |
| 734 | // 6. The editor applies the changes (applyEdit), and sends us a reply |
| 735 | // 7. We unwrap the reply and send a reply to the editor. |
| 736 | applyEdit(WE, "Fix applied.", std::move(Reply)); |
| 737 | } |
| 738 | |
| 739 | void ClangdLSPServer::onCommandApplyTweak(const TweakArgs &Args, |
| 740 | Callback<llvm::json::Value> Reply) { |
| 741 | auto Action = [this, Reply = std::move(Reply)]( |
| 742 | llvm::Expected<Tweak::Effect> R) mutable { |
| 743 | if (!R) |
| 744 | return Reply(R.takeError()); |
| 745 | |
| 746 | assert(R->ShowMessage || (!R->ApplyEdits.empty() && "tweak has no effect")); |
| 747 | |
| 748 | if (R->ShowMessage) { |
| 749 | ShowMessageParams Msg; |
| 750 | Msg.message = *R->ShowMessage; |
| 751 | Msg.type = MessageType::Info; |
| 752 | ShowMessage(Msg); |
| 753 | } |
| 754 | // When no edit is specified, make sure we Reply(). |
| 755 | if (R->ApplyEdits.empty()) |
| 756 | return Reply("Tweak applied."); |
| 757 | |
| 758 | if (auto Err = validateEdits(*Server, R->ApplyEdits)) |
| 759 | return Reply(std::move(Err)); |
| 760 | |
| 761 | WorkspaceEdit WE; |
| 762 | for (const auto &It : R->ApplyEdits) { |
| 763 | WE.changes[URI::createFile(It.first()).toString()] = |
| 764 | It.second.asTextEdits(); |
| 765 | } |
| 766 | // ApplyEdit will take care of calling Reply(). |
| 767 | return applyEdit(std::move(WE), "Tweak applied.", std::move(Reply)); |
| 768 | }; |
| 769 | Server->applyTweak(Args.file.file(), Args.selection, Args.tweakID, |
| 770 | std::move(Action)); |
| 771 | } |
| 772 | |
| 773 | void ClangdLSPServer::applyEdit(WorkspaceEdit WE, llvm::json::Value Success, |
| 774 | Callback<llvm::json::Value> Reply) { |
| 775 | ApplyWorkspaceEditParams Edit; |
| 776 | Edit.edit = std::move(WE); |
| 777 | ApplyWorkspaceEdit( |
| 778 | Edit, [Reply = std::move(Reply), SuccessMessage = std::move(Success)]( |
| 779 | llvm::Expected<ApplyWorkspaceEditResponse> Response) mutable { |
| 780 | if (!Response) |
| 781 | return Reply(Response.takeError()); |
| 782 | if (!Response->applied) { |
| 783 | std::string Reason = Response->failureReason |
| 784 | ? *Response->failureReason |
| 785 | : "unknown reason"; |
| 786 | return Reply(error("edits were not applied: {0}", Reason)); |
| 787 | } |
| 788 | return Reply(SuccessMessage); |
| 789 | }); |
| 790 | } |
| 791 | |
| 792 | void ClangdLSPServer::onWorkspaceSymbol( |
| 793 | const WorkspaceSymbolParams &Params, |
| 794 | Callback<std::vector<SymbolInformation>> Reply) { |
| 795 | Server->workspaceSymbols( |
| 796 | Params.query, Params.limit.value_or(Opts.CodeComplete.Limit), |
| 797 | [Reply = std::move(Reply), |
| 798 | this](llvm::Expected<std::vector<SymbolInformation>> Items) mutable { |
| 799 | if (!Items) |
| 800 | return Reply(Items.takeError()); |
| 801 | for (auto &Sym : *Items) |
| 802 | Sym.kind = adjustKindToCapability(Sym.kind, SupportedSymbolKinds); |
| 803 | |
| 804 | Reply(std::move(*Items)); |
| 805 | }); |
| 806 | } |
| 807 | |
| 808 | void ClangdLSPServer::onPrepareRename(const TextDocumentPositionParams &Params, |
| 809 | Callback<std::optional<Range>> Reply) { |
| 810 | Server->prepareRename( |
| 811 | Params.textDocument.uri.file(), Params.position, /*NewName*/ std::nullopt, |
| 812 | Opts.Rename, |
| 813 | [Reply = std::move(Reply)](llvm::Expected<RenameResult> Result) mutable { |
| 814 | if (!Result) |
| 815 | return Reply(Result.takeError()); |
| 816 | return Reply(std::move(Result->Target)); |
| 817 | }); |
| 818 | } |
| 819 | |
| 820 | void ClangdLSPServer::onRename(const RenameParams &Params, |
| 821 | Callback<WorkspaceEdit> Reply) { |
| 822 | Path File = std::string(Params.textDocument.uri.file()); |
| 823 | if (!Server->getDraft(File)) |
| 824 | return Reply(llvm::make_error<LSPError>( |
| 825 | "onRename called for non-added file", ErrorCode::InvalidParams)); |
| 826 | Server->rename(File, Params.position, Params.newName, Opts.Rename, |
| 827 | [File, Params, Reply = std::move(Reply), |
| 828 | this](llvm::Expected<RenameResult> R) mutable { |
| 829 | if (!R) |
| 830 | return Reply(R.takeError()); |
| 831 | if (auto Err = validateEdits(*Server, R->GlobalChanges)) |
| 832 | return Reply(std::move(Err)); |
| 833 | WorkspaceEdit Result; |
| 834 | for (const auto &Rep : R->GlobalChanges) { |
| 835 | Result.changes[URI::createFile(Rep.first()).toString()] = |
| 836 | Rep.second.asTextEdits(); |
| 837 | } |
| 838 | Reply(Result); |
| 839 | }); |
| 840 | } |
| 841 | |
| 842 | void ClangdLSPServer::onDocumentDidClose( |
| 843 | const DidCloseTextDocumentParams &Params) { |
| 844 | PathRef File = Params.textDocument.uri.file(); |
| 845 | Server->removeDocument(File); |
| 846 | |
| 847 | { |
| 848 | std::lock_guard<std::mutex> Lock(FixItsMutex); |
| 849 | FixItsMap.erase(File); |
| 850 | } |
| 851 | { |
| 852 | std::lock_guard<std::mutex> HLock(SemanticTokensMutex); |
| 853 | LastSemanticTokens.erase(File); |
| 854 | } |
| 855 | // clangd will not send updates for this file anymore, so we empty out the |
| 856 | // list of diagnostics shown on the client (e.g. in the "Problems" pane of |
| 857 | // VSCode). Note that this cannot race with actual diagnostics responses |
| 858 | // because removeDocument() guarantees no diagnostic callbacks will be |
| 859 | // executed after it returns. |
| 860 | PublishDiagnosticsParams Notification; |
| 861 | Notification.uri = URIForFile::canonicalize(File, /*TUPath=*/File); |
| 862 | PublishDiagnostics(Notification); |
| 863 | } |
| 864 | |
| 865 | void ClangdLSPServer::onDocumentOnTypeFormatting( |
| 866 | const DocumentOnTypeFormattingParams &Params, |
| 867 | Callback<std::vector<TextEdit>> Reply) { |
| 868 | auto File = Params.textDocument.uri.file(); |
| 869 | Server->formatOnType(File, Params.position, Params.ch, std::move(Reply)); |
| 870 | } |
| 871 | |
| 872 | void ClangdLSPServer::onDocumentRangeFormatting( |
| 873 | const DocumentRangeFormattingParams &Params, |
| 874 | Callback<std::vector<TextEdit>> Reply) { |
| 875 | auto File = Params.textDocument.uri.file(); |
| 876 | auto Code = Server->getDraft(File); |
| 877 | Server->formatFile(File, Params.range, |
| 878 | [Code = std::move(Code), Reply = std::move(Reply)]( |
| 879 | llvm::Expected<tooling::Replacements> Result) mutable { |
| 880 | if (Result) |
| 881 | Reply(replacementsToEdits(*Code, Result.get())); |
| 882 | else |
| 883 | Reply(Result.takeError()); |
| 884 | }); |
| 885 | } |
| 886 | |
| 887 | void ClangdLSPServer::onDocumentFormatting( |
| 888 | const DocumentFormattingParams &Params, |
| 889 | Callback<std::vector<TextEdit>> Reply) { |
| 890 | auto File = Params.textDocument.uri.file(); |
| 891 | auto Code = Server->getDraft(File); |
| 892 | Server->formatFile(File, |
| 893 | /*Rng=*/std::nullopt, |
| 894 | [Code = std::move(Code), Reply = std::move(Reply)]( |
| 895 | llvm::Expected<tooling::Replacements> Result) mutable { |
| 896 | if (Result) |
| 897 | Reply(replacementsToEdits(*Code, Result.get())); |
| 898 | else |
| 899 | Reply(Result.takeError()); |
| 900 | }); |
| 901 | } |
| 902 | |
| 903 | /// The functions constructs a flattened view of the DocumentSymbol hierarchy. |
| 904 | /// Used by the clients that do not support the hierarchical view. |
| 905 | static std::vector<SymbolInformation> |
| 906 | flattenSymbolHierarchy(llvm::ArrayRef<DocumentSymbol> Symbols, |
| 907 | const URIForFile &FileURI) { |
| 908 | std::vector<SymbolInformation> Results; |
| 909 | std::function<void(const DocumentSymbol &, llvm::StringRef)> Process = |
| 910 | [&](const DocumentSymbol &S, std::optional<llvm::StringRef> ParentName) { |
| 911 | SymbolInformation SI; |
| 912 | SI.containerName = std::string(ParentName ? "" : *ParentName); |
| 913 | SI.name = S.name; |
| 914 | SI.kind = S.kind; |
| 915 | SI.location.range = S.range; |
| 916 | SI.location.uri = FileURI; |
| 917 | |
| 918 | Results.push_back(std::move(SI)); |
| 919 | std::string FullName = |
| 920 | !ParentName ? S.name : (ParentName->str() + "::" + S.name); |
| 921 | for (auto &C : S.children) |
| 922 | Process(C, /*ParentName=*/FullName); |
| 923 | }; |
| 924 | for (auto &S : Symbols) |
| 925 | Process(S, /*ParentName=*/""); |
| 926 | return Results; |
| 927 | } |
| 928 | |
| 929 | void ClangdLSPServer::onDocumentSymbol(const DocumentSymbolParams &Params, |
| 930 | Callback<llvm::json::Value> Reply) { |
| 931 | URIForFile FileURI = Params.textDocument.uri; |
| 932 | Server->documentSymbols( |
| 933 | Params.textDocument.uri.file(), |
| 934 | [this, FileURI, Reply = std::move(Reply)]( |
| 935 | llvm::Expected<std::vector<DocumentSymbol>> Items) mutable { |
| 936 | if (!Items) |
| 937 | return Reply(Items.takeError()); |
| 938 | adjustSymbolKinds(*Items, SupportedSymbolKinds); |
| 939 | if (SupportsHierarchicalDocumentSymbol) |
| 940 | return Reply(std::move(*Items)); |
| 941 | return Reply(flattenSymbolHierarchy(*Items, FileURI)); |
| 942 | }); |
| 943 | } |
| 944 | |
| 945 | void ClangdLSPServer::onFoldingRange( |
| 946 | const FoldingRangeParams &Params, |
| 947 | Callback<std::vector<FoldingRange>> Reply) { |
| 948 | Server->foldingRanges(Params.textDocument.uri.file(), std::move(Reply)); |
| 949 | } |
| 950 | |
| 951 | static std::optional<Command> asCommand(const CodeAction &Action) { |
| 952 | Command Cmd; |
| 953 | if (Action.command && Action.edit) |
| 954 | return std::nullopt; // Not representable. (We never emit these anyway). |
| 955 | if (Action.command) { |
| 956 | Cmd = *Action.command; |
| 957 | } else if (Action.edit) { |
| 958 | Cmd.command = std::string(ApplyFixCommand); |
| 959 | Cmd.argument = *Action.edit; |
| 960 | } else { |
| 961 | return std::nullopt; |
| 962 | } |
| 963 | Cmd.title = Action.title; |
| 964 | if (Action.kind && *Action.kind == CodeAction::QUICKFIX_KIND) |
| 965 | Cmd.title = "Apply fix: " + Cmd.title; |
| 966 | return Cmd; |
| 967 | } |
| 968 | |
| 969 | void ClangdLSPServer::onCodeAction(const CodeActionParams &Params, |
| 970 | Callback<llvm::json::Value> Reply) { |
| 971 | URIForFile File = Params.textDocument.uri; |
| 972 | // Checks whether a particular CodeActionKind is included in the response. |
| 973 | auto KindAllowed = [Only(Params.context.only)](llvm::StringRef Kind) { |
| 974 | if (Only.empty()) |
| 975 | return true; |
| 976 | return llvm::any_of(Only, [&](llvm::StringRef Base) { |
| 977 | return Kind.consume_front(Base) && (Kind.empty() || Kind.startswith(".")); |
| 978 | }); |
| 979 | }; |
| 980 | |
| 981 | // We provide a code action for Fixes on the specified diagnostics. |
| 982 | std::vector<CodeAction> FixIts; |
| 983 | if (KindAllowed(CodeAction::QUICKFIX_KIND)) { |
| 984 | for (const Diagnostic &D : Params.context.diagnostics) { |
| 985 | for (auto &F : getFixes(File.file(), D)) { |
| 986 | FixIts.push_back(toCodeAction(F, Params.textDocument.uri)); |
| 987 | FixIts.back().diagnostics = {D}; |
| 988 | } |
| 989 | } |
| 990 | } |
| 991 | |
| 992 | // Now enumerate the semantic code actions. |
| 993 | auto ConsumeActions = |
| 994 | [Diags = Params.context.diagnostics, Reply = std::move(Reply), File, |
| 995 | Selection = Params.range, FixIts = std::move(FixIts), this]( |
| 996 | llvm::Expected<std::vector<ClangdServer::TweakRef>> Tweaks) mutable { |
| 997 | if (!Tweaks) |
| 998 | return Reply(Tweaks.takeError()); |
| 999 | |
| 1000 | std::vector<CodeAction> Actions = std::move(FixIts); |
| 1001 | Actions.reserve(Actions.size() + Tweaks->size()); |
| 1002 | for (const auto &T : *Tweaks) |
| 1003 | Actions.push_back(toCodeAction(T, File, Selection)); |
| 1004 | |
| 1005 | // If there's exactly one quick-fix, call it "preferred". |
| 1006 | // We never consider refactorings etc as preferred. |
| 1007 | CodeAction *OnlyFix = nullptr; |
| 1008 | for (auto &Action : Actions) { |
| 1009 | if (Action.kind && *Action.kind == CodeAction::QUICKFIX_KIND) { |
| 1010 | if (OnlyFix) { |
| 1011 | OnlyFix = nullptr; |
| 1012 | break; |
| 1013 | } |
| 1014 | OnlyFix = &Action; |
| 1015 | } |
| 1016 | } |
| 1017 | if (OnlyFix) { |
| 1018 | OnlyFix->isPreferred = true; |
| 1019 | if (Diags.size() == 1 && Diags.front().range == Selection) |
| 1020 | OnlyFix->diagnostics = {Diags.front()}; |
| 1021 | } |
| 1022 | |
| 1023 | if (SupportsCodeAction) |
| 1024 | return Reply(llvm::json::Array(Actions)); |
| 1025 | std::vector<Command> Commands; |
| 1026 | for (const auto &Action : Actions) { |
| 1027 | if (auto Command = asCommand(Action)) |
| 1028 | Commands.push_back(std::move(*Command)); |
| 1029 | } |
| 1030 | return Reply(llvm::json::Array(Commands)); |
| 1031 | }; |
| 1032 | Server->enumerateTweaks( |
| 1033 | File.file(), Params.range, |
| 1034 | [this, KindAllowed(std::move(KindAllowed))](const Tweak &T) { |
| 1035 | return Opts.TweakFilter(T) && KindAllowed(T.kind()); |
| 1036 | }, |
| 1037 | std::move(ConsumeActions)); |
| 1038 | } |
| 1039 | |
| 1040 | void ClangdLSPServer::onCompletion(const CompletionParams &Params, |
| 1041 | Callback<CompletionList> Reply) { |
| 1042 | if (!shouldRunCompletion(Params)) { |
| 1043 | // Clients sometimes auto-trigger completions in undesired places (e.g. |
| 1044 | // 'a >^ '), we return empty results in those cases. |
| 1045 | vlog("ignored auto-triggered completion, preceding char did not match"); |
| 1046 | return Reply(CompletionList()); |
| 1047 | } |
| 1048 | auto Opts = this->Opts.CodeComplete; |
| 1049 | if (Params.limit && *Params.limit >= 0) |
| 1050 | Opts.Limit = *Params.limit; |
| 1051 | Server->codeComplete(Params.textDocument.uri.file(), Params.position, Opts, |
| 1052 | [Reply = std::move(Reply), Opts, |
| 1053 | this](llvm::Expected<CodeCompleteResult> List) mutable { |
| 1054 | if (!List) |
| 1055 | return Reply(List.takeError()); |
| 1056 | CompletionList LSPList; |
| 1057 | LSPList.isIncomplete = List->HasMore; |
| 1058 | for (const auto &R : List->Completions) { |
| 1059 | CompletionItem C = R.render(Opts); |
| 1060 | C.kind = adjustKindToCapability( |
| 1061 | C.kind, SupportedCompletionItemKinds); |
| 1062 | LSPList.items.push_back(std::move(C)); |
| 1063 | } |
| 1064 | return Reply(std::move(LSPList)); |
| 1065 | }); |
| 1066 | } |
| 1067 | |
| 1068 | void ClangdLSPServer::onSignatureHelp(const TextDocumentPositionParams &Params, |
| 1069 | Callback<SignatureHelp> Reply) { |
| 1070 | Server->signatureHelp(Params.textDocument.uri.file(), Params.position, |
| 1071 | Opts.SignatureHelpDocumentationFormat, |
| 1072 | [Reply = std::move(Reply), this]( |
| 1073 | llvm::Expected<SignatureHelp> Signature) mutable { |
| 1074 | if (!Signature) |
| 1075 | return Reply(Signature.takeError()); |
| 1076 | if (SupportsOffsetsInSignatureHelp) |
| 1077 | return Reply(std::move(*Signature)); |
| 1078 | // Strip out the offsets from signature help for |
| 1079 | // clients that only support string labels. |
| 1080 | for (auto &SigInfo : Signature->signatures) { |
| 1081 | for (auto &Param : SigInfo.parameters) |
| 1082 | Param.labelOffsets.reset(); |
| 1083 | } |
| 1084 | return Reply(std::move(*Signature)); |
| 1085 | }); |
| 1086 | } |
| 1087 | |
| 1088 | // Go to definition has a toggle function: if def and decl are distinct, then |
| 1089 | // the first press gives you the def, the second gives you the matching def. |
| 1090 | // getToggle() returns the counterpart location that under the cursor. |
| 1091 | // |
| 1092 | // We return the toggled location alone (ignoring other symbols) to encourage |
| 1093 | // editors to "bounce" quickly between locations, without showing a menu. |
| 1094 | static Location *getToggle(const TextDocumentPositionParams &Point, |
| 1095 | LocatedSymbol &Sym) { |
| 1096 | // Toggle only makes sense with two distinct locations. |
| 1097 | if (!Sym.Definition || *Sym.Definition == Sym.PreferredDeclaration) |
| 1098 | return nullptr; |
| 1099 | if (Sym.Definition->uri.file() == Point.textDocument.uri.file() && |
| 1100 | Sym.Definition->range.contains(Point.position)) |
| 1101 | return &Sym.PreferredDeclaration; |
| 1102 | if (Sym.PreferredDeclaration.uri.file() == Point.textDocument.uri.file() && |
| 1103 | Sym.PreferredDeclaration.range.contains(Point.position)) |
| 1104 | return &*Sym.Definition; |
| 1105 | return nullptr; |
| 1106 | } |
| 1107 | |
| 1108 | void ClangdLSPServer::onGoToDefinition(const TextDocumentPositionParams &Params, |
| 1109 | Callback<std::vector<Location>> Reply) { |
| 1110 | Server->locateSymbolAt( |
| 1111 | Params.textDocument.uri.file(), Params.position, |
| 1112 | [Params, Reply = std::move(Reply)]( |
| 1113 | llvm::Expected<std::vector<LocatedSymbol>> Symbols) mutable { |
| 1114 | if (!Symbols) |
| 1115 | return Reply(Symbols.takeError()); |
| 1116 | std::vector<Location> Defs; |
| 1117 | for (auto &S : *Symbols) { |
| 1118 | if (Location *Toggle = getToggle(Params, S)) |
| 1119 | return Reply(std::vector<Location>{std::move(*Toggle)}); |
| 1120 | Defs.push_back(S.Definition.value_or(S.PreferredDeclaration)); |
| 1121 | } |
| 1122 | Reply(std::move(Defs)); |
| 1123 | }); |
| 1124 | } |
| 1125 | |
| 1126 | void ClangdLSPServer::onGoToDeclaration( |
| 1127 | const TextDocumentPositionParams &Params, |
| 1128 | Callback<std::vector<Location>> Reply) { |
| 1129 | Server->locateSymbolAt( |
| 1130 | Params.textDocument.uri.file(), Params.position, |
| 1131 | [Params, Reply = std::move(Reply)]( |
| 1132 | llvm::Expected<std::vector<LocatedSymbol>> Symbols) mutable { |
| 1133 | if (!Symbols) |
| 1134 | return Reply(Symbols.takeError()); |
| 1135 | std::vector<Location> Decls; |
| 1136 | for (auto &S : *Symbols) { |
| 1137 | if (Location *Toggle = getToggle(Params, S)) |
| 1138 | return Reply(std::vector<Location>{std::move(*Toggle)}); |
| 1139 | Decls.push_back(std::move(S.PreferredDeclaration)); |
| 1140 | } |
| 1141 | Reply(std::move(Decls)); |
| 1142 | }); |
| 1143 | } |
| 1144 | |
| 1145 | void ClangdLSPServer::onSwitchSourceHeader( |
| 1146 | const TextDocumentIdentifier &Params, |
| 1147 | Callback<std::optional<URIForFile>> Reply) { |
| 1148 | Server->switchSourceHeader( |
| 1149 | Params.uri.file(), |
| 1150 | [Reply = std::move(Reply), |
| 1151 | Params](llvm::Expected<std::optional<clangd::Path>> Path) mutable { |
| 1152 | if (!Path) |
| 1153 | return Reply(Path.takeError()); |
| 1154 | if (*Path) |
| 1155 | return Reply(URIForFile::canonicalize(**Path, Params.uri.file())); |
| 1156 | return Reply(std::nullopt); |
| 1157 | }); |
| 1158 | } |
| 1159 | |
| 1160 | void ClangdLSPServer::onDocumentHighlight( |
| 1161 | const TextDocumentPositionParams &Params, |
| 1162 | Callback<std::vector<DocumentHighlight>> Reply) { |
| 1163 | Server->findDocumentHighlights(Params.textDocument.uri.file(), |
| 1164 | Params.position, std::move(Reply)); |
| 1165 | } |
| 1166 | |
| 1167 | void ClangdLSPServer::onHover(const TextDocumentPositionParams &Params, |
| 1168 | Callback<std::optional<Hover>> Reply) { |
| 1169 | Server->findHover(Params.textDocument.uri.file(), Params.position, |
| 1170 | [Reply = std::move(Reply), |
| 1171 | this](llvm::Expected<std::optional<HoverInfo>> H) mutable { |
| 1172 | if (!H) |
| 1173 | return Reply(H.takeError()); |
| 1174 | if (!*H) |
| 1175 | return Reply(std::nullopt); |
| 1176 | |
| 1177 | Hover R; |
| 1178 | R.contents.kind = HoverContentFormat; |
| 1179 | R.range = (*H)->SymRange; |
| 1180 | switch (HoverContentFormat) { |
| 1181 | case MarkupKind::PlainText: |
| 1182 | R.contents.value = (*H)->present().asPlainText(); |
| 1183 | return Reply(std::move(R)); |
| 1184 | case MarkupKind::Markdown: |
| 1185 | R.contents.value = (*H)->present().asMarkdown(); |
| 1186 | return Reply(std::move(R)); |
| 1187 | }; |
| 1188 | llvm_unreachable("unhandled MarkupKind"); |
| 1189 | }); |
| 1190 | } |
| 1191 | |
| 1192 | // Our extension has a different representation on the wire than the standard. |
| 1193 | // https://clangd.llvm.org/extensions#type-hierarchy |
| 1194 | llvm::json::Value serializeTHIForExtension(TypeHierarchyItem THI) { |
| 1195 | llvm::json::Object Result{{ |
| 1196 | {"name", std::move(THI.name)}, |
| 1197 | {"kind", static_cast<int>(THI.kind)}, |
| 1198 | {"uri", std::move(THI.uri)}, |
| 1199 | {"range", THI.range}, |
| 1200 | {"selectionRange", THI.selectionRange}, |
| 1201 | {"data", std::move(THI.data)}, |
| 1202 | }}; |
| 1203 | if (THI.deprecated) |
| 1204 | Result["deprecated"] = THI.deprecated; |
| 1205 | if (THI.detail) |
| 1206 | Result["detail"] = std::move(*THI.detail); |
| 1207 | |
| 1208 | if (THI.parents) { |
| 1209 | llvm::json::Array Parents; |
| 1210 | for (auto &Parent : *THI.parents) |
| 1211 | Parents.emplace_back(serializeTHIForExtension(std::move(Parent))); |
| 1212 | Result["parents"] = std::move(Parents); |
| 1213 | } |
| 1214 | |
| 1215 | if (THI.children) { |
| 1216 | llvm::json::Array Children; |
| 1217 | for (auto &child : *THI.children) |
| 1218 | Children.emplace_back(serializeTHIForExtension(std::move(child))); |
| 1219 | Result["children"] = std::move(Children); |
| 1220 | } |
| 1221 | return Result; |
| 1222 | } |
| 1223 | |
| 1224 | void ClangdLSPServer::onTypeHierarchy(const TypeHierarchyPrepareParams &Params, |
| 1225 | Callback<llvm::json::Value> Reply) { |
| 1226 | auto Serialize = |
| 1227 | [Reply = std::move(Reply)]( |
| 1228 | llvm::Expected<std::vector<TypeHierarchyItem>> Resp) mutable { |
| 1229 | if (!Resp) { |
| 1230 | Reply(Resp.takeError()); |
| 1231 | return; |
| 1232 | } |
| 1233 | if (Resp->empty()) { |
| 1234 | Reply(nullptr); |
| 1235 | return; |
| 1236 | } |
| 1237 | Reply(serializeTHIForExtension(std::move(Resp->front()))); |
| 1238 | }; |
| 1239 | Server->typeHierarchy(Params.textDocument.uri.file(), Params.position, |
| 1240 | Params.resolve, Params.direction, std::move(Serialize)); |
| 1241 | } |
| 1242 | |
| 1243 | void ClangdLSPServer::onResolveTypeHierarchy( |
| 1244 | const ResolveTypeHierarchyItemParams &Params, |
| 1245 | Callback<llvm::json::Value> Reply) { |
| 1246 | auto Serialize = |
| 1247 | [Reply = std::move(Reply)]( |
| 1248 | llvm::Expected<std::optional<TypeHierarchyItem>> Resp) mutable { |
| 1249 | if (!Resp) { |
| 1250 | Reply(Resp.takeError()); |
| 1251 | return; |
| 1252 | } |
| 1253 | if (!*Resp) { |
| 1254 | Reply(std::move(*Resp)); |
| 1255 | return; |
| 1256 | } |
| 1257 | Reply(serializeTHIForExtension(std::move(**Resp))); |
| 1258 | }; |
| 1259 | Server->resolveTypeHierarchy(Params.item, Params.resolve, Params.direction, |
| 1260 | std::move(Serialize)); |
| 1261 | } |
| 1262 | |
| 1263 | void ClangdLSPServer::onPrepareTypeHierarchy( |
| 1264 | const TypeHierarchyPrepareParams &Params, |
| 1265 | Callback<std::vector<TypeHierarchyItem>> Reply) { |
| 1266 | Server->typeHierarchy(Params.textDocument.uri.file(), Params.position, |
| 1267 | Params.resolve, Params.direction, std::move(Reply)); |
| 1268 | } |
| 1269 | |
| 1270 | void ClangdLSPServer::onSuperTypes( |
| 1271 | const ResolveTypeHierarchyItemParams &Params, |
| 1272 | Callback<std::optional<std::vector<TypeHierarchyItem>>> Reply) { |
| 1273 | Server->superTypes(Params.item, std::move(Reply)); |
| 1274 | } |
| 1275 | |
| 1276 | void ClangdLSPServer::onSubTypes( |
| 1277 | const ResolveTypeHierarchyItemParams &Params, |
| 1278 | Callback<std::vector<TypeHierarchyItem>> Reply) { |
| 1279 | Server->subTypes(Params.item, std::move(Reply)); |
| 1280 | } |
| 1281 | |
| 1282 | void ClangdLSPServer::onPrepareCallHierarchy( |
| 1283 | const CallHierarchyPrepareParams &Params, |
| 1284 | Callback<std::vector<CallHierarchyItem>> Reply) { |
| 1285 | Server->prepareCallHierarchy(Params.textDocument.uri.file(), Params.position, |
| 1286 | std::move(Reply)); |
| 1287 | } |
| 1288 | |
| 1289 | void ClangdLSPServer::onCallHierarchyIncomingCalls( |
| 1290 | const CallHierarchyIncomingCallsParams &Params, |
| 1291 | Callback<std::vector<CallHierarchyIncomingCall>> Reply) { |
| 1292 | Server->incomingCalls(Params.item, std::move(Reply)); |
| 1293 | } |
| 1294 | |
| 1295 | void ClangdLSPServer::onClangdInlayHints(const InlayHintsParams &Params, |
| 1296 | Callback<llvm::json::Value> Reply) { |
| 1297 | // Our extension has a different representation on the wire than the standard. |
| 1298 | // We have a "range" property and "kind" is represented as a string, not as an |
| 1299 | // enum value. |
| 1300 | // https://clangd.llvm.org/extensions#inlay-hints |
| 1301 | auto Serialize = [Reply = std::move(Reply)]( |
| 1302 | llvm::Expected<std::vector<InlayHint>> Hints) mutable { |
| 1303 | if (!Hints) { |
| 1304 | Reply(Hints.takeError()); |
| 1305 | return; |
| 1306 | } |
| 1307 | llvm::json::Array Result; |
| 1308 | Result.reserve(Hints->size()); |
| 1309 | for (auto &Hint : *Hints) { |
| 1310 | Result.emplace_back(llvm::json::Object{ |
| 1311 | {"kind", llvm::to_string(Hint.kind)}, |
| 1312 | {"range", Hint.range}, |
| 1313 | {"position", Hint.position}, |
| 1314 | // Extension doesn't have paddingLeft/Right so adjust the label |
| 1315 | // accordingly. |
| 1316 | {"label", |
| 1317 | ((Hint.paddingLeft ? " " : "") + llvm::StringRef(Hint.label) + |
| 1318 | (Hint.paddingRight ? " " : "")) |
| 1319 | .str()}, |
| 1320 | }); |
| 1321 | } |
| 1322 | Reply(std::move(Result)); |
| 1323 | }; |
| 1324 | Server->inlayHints(Params.textDocument.uri.file(), Params.range, |
| 1325 | std::move(Serialize)); |
| 1326 | } |
| 1327 | |
| 1328 | void ClangdLSPServer::onInlayHint(const InlayHintsParams &Params, |
| 1329 | Callback<std::vector<InlayHint>> Reply) { |
| 1330 | Server->inlayHints(Params.textDocument.uri.file(), Params.range, |
| 1331 | std::move(Reply)); |
| 1332 | } |
| 1333 | |
| 1334 | void ClangdLSPServer::applyConfiguration( |
| 1335 | const ConfigurationSettings &Settings) { |
| 1336 | // Per-file update to the compilation database. |
| 1337 | llvm::StringSet<> ModifiedFiles; |
| 1338 | for (auto &Entry : Settings.compilationDatabaseChanges) { |
| 1339 | PathRef File = Entry.first; |
| 1340 | auto Old = CDB->getCompileCommand(File); |
| 1341 | auto New = |
| 1342 | tooling::CompileCommand(std::move(Entry.second.workingDirectory), File, |
| 1343 | std::move(Entry.second.compilationCommand), |
| 1344 | /*Output=*/""); |
| 1345 | if (Old != New) { |
| 1346 | CDB->setCompileCommand(File, std::move(New)); |
| 1347 | ModifiedFiles.insert(File); |
| 1348 | } |
| 1349 | } |
| 1350 | |
| 1351 | Server->reparseOpenFilesIfNeeded( |
| 1352 | [&](llvm::StringRef File) { return ModifiedFiles.count(File) != 0; }); |
| 1353 | } |
| 1354 | |
| 1355 | void ClangdLSPServer::maybeExportMemoryProfile() { |
| 1356 | if (!trace::enabled() || !ShouldProfile()) |
| 1357 | return; |
| 1358 | |
| 1359 | static constexpr trace::Metric MemoryUsage( |
| 1360 | "memory_usage", trace::Metric::Value, "component_name"); |
| 1361 | trace::Span Tracer("ProfileBrief"); |
| 1362 | MemoryTree MT; |
| 1363 | profile(MT); |
| 1364 | record(MT, "clangd_lsp_server", MemoryUsage); |
| 1365 | } |
| 1366 | |
| 1367 | void ClangdLSPServer::maybeCleanupMemory() { |
| 1368 | if (!Opts.MemoryCleanup || !ShouldCleanupMemory()) |
| 1369 | return; |
| 1370 | Opts.MemoryCleanup(); |
| 1371 | } |
| 1372 | |
| 1373 | // FIXME: This function needs to be properly tested. |
| 1374 | void ClangdLSPServer::onChangeConfiguration( |
| 1375 | const DidChangeConfigurationParams &Params) { |
| 1376 | applyConfiguration(Params.settings); |
| 1377 | } |
| 1378 | |
| 1379 | void ClangdLSPServer::onReference( |
| 1380 | const ReferenceParams &Params, |
| 1381 | Callback<std::vector<ReferenceLocation>> Reply) { |
| 1382 | Server->findReferences(Params.textDocument.uri.file(), Params.position, |
| 1383 | Opts.ReferencesLimit, SupportsReferenceContainer, |
| 1384 | [Reply = std::move(Reply), |
| 1385 | IncludeDecl(Params.context.includeDeclaration)]( |
| 1386 | llvm::Expected<ReferencesResult> Refs) mutable { |
| 1387 | if (!Refs) |
| 1388 | return Reply(Refs.takeError()); |
| 1389 | // Filter out declarations if the client asked. |
| 1390 | std::vector<ReferenceLocation> Result; |
| 1391 | Result.reserve(Refs->References.size()); |
| 1392 | for (auto &Ref : Refs->References) { |
| 1393 | bool IsDecl = |
| 1394 | Ref.Attributes & ReferencesResult::Declaration; |
| 1395 | if (IncludeDecl || !IsDecl) |
| 1396 | Result.push_back(std::move(Ref.Loc)); |
| 1397 | } |
| 1398 | return Reply(std::move(Result)); |
| 1399 | }); |
| 1400 | } |
| 1401 | |
| 1402 | void ClangdLSPServer::onGoToType(const TextDocumentPositionParams &Params, |
| 1403 | Callback<std::vector<Location>> Reply) { |
| 1404 | Server->findType( |
| 1405 | Params.textDocument.uri.file(), Params.position, |
| 1406 | [Reply = std::move(Reply)]( |
| 1407 | llvm::Expected<std::vector<LocatedSymbol>> Types) mutable { |
| 1408 | if (!Types) |
| 1409 | return Reply(Types.takeError()); |
| 1410 | std::vector<Location> Response; |
| 1411 | for (const LocatedSymbol &Sym : *Types) |
| 1412 | Response.push_back(Sym.PreferredDeclaration); |
| 1413 | return Reply(std::move(Response)); |
| 1414 | }); |
| 1415 | } |
| 1416 | |
| 1417 | void ClangdLSPServer::onGoToImplementation( |
| 1418 | const TextDocumentPositionParams &Params, |
| 1419 | Callback<std::vector<Location>> Reply) { |
| 1420 | Server->findImplementations( |
| 1421 | Params.textDocument.uri.file(), Params.position, |
| 1422 | [Reply = std::move(Reply)]( |
| 1423 | llvm::Expected<std::vector<LocatedSymbol>> Overrides) mutable { |
| 1424 | if (!Overrides) |
| 1425 | return Reply(Overrides.takeError()); |
| 1426 | std::vector<Location> Impls; |
| 1427 | for (const LocatedSymbol &Sym : *Overrides) |
| 1428 | Impls.push_back(Sym.PreferredDeclaration); |
| 1429 | return Reply(std::move(Impls)); |
| 1430 | }); |
| 1431 | } |
| 1432 | |
| 1433 | void ClangdLSPServer::onSymbolInfo(const TextDocumentPositionParams &Params, |
| 1434 | Callback<std::vector<SymbolDetails>> Reply) { |
| 1435 | Server->symbolInfo(Params.textDocument.uri.file(), Params.position, |
| 1436 | std::move(Reply)); |
| 1437 | } |
| 1438 | |
| 1439 | void ClangdLSPServer::onSelectionRange( |
| 1440 | const SelectionRangeParams &Params, |
| 1441 | Callback<std::vector<SelectionRange>> Reply) { |
| 1442 | Server->semanticRanges( |
| 1443 | Params.textDocument.uri.file(), Params.positions, |
| 1444 | [Reply = std::move(Reply)]( |
| 1445 | llvm::Expected<std::vector<SelectionRange>> Ranges) mutable { |
| 1446 | if (!Ranges) |
| 1447 | return Reply(Ranges.takeError()); |
| 1448 | return Reply(std::move(*Ranges)); |
| 1449 | }); |
| 1450 | } |
| 1451 | |
| 1452 | void ClangdLSPServer::onDocumentLink( |
| 1453 | const DocumentLinkParams &Params, |
| 1454 | Callback<std::vector<DocumentLink>> Reply) { |
| 1455 | |
| 1456 | // TODO(forster): This currently resolves all targets eagerly. This is slow, |
| 1457 | // because it blocks on the preamble/AST being built. We could respond to the |
| 1458 | // request faster by using string matching or the lexer to find the includes |
| 1459 | // and resolving the targets lazily. |
| 1460 | Server->documentLinks( |
| 1461 | Params.textDocument.uri.file(), |
| 1462 | [Reply = std::move(Reply)]( |
| 1463 | llvm::Expected<std::vector<DocumentLink>> Links) mutable { |
| 1464 | if (!Links) { |
| 1465 | return Reply(Links.takeError()); |
| 1466 | } |
| 1467 | return Reply(std::move(Links)); |
| 1468 | }); |
| 1469 | } |
| 1470 | |
| 1471 | // Increment a numeric string: "" -> 1 -> 2 -> ... -> 9 -> 10 -> 11 ... |
| 1472 | static void increment(std::string &S) { |
| 1473 | for (char &C : llvm::reverse(S)) { |
| 1474 | if (C != '9') { |
| 1475 | ++C; |
| 1476 | return; |
| 1477 | } |
| 1478 | C = '0'; |
| 1479 | } |
| 1480 | S.insert(S.begin(), '1'); |
| 1481 | } |
| 1482 | |
| 1483 | void ClangdLSPServer::onSemanticTokens(const SemanticTokensParams &Params, |
| 1484 | Callback<SemanticTokens> CB) { |
| 1485 | auto File = Params.textDocument.uri.file(); |
| 1486 | Server->semanticHighlights( |
| 1487 | Params.textDocument.uri.file(), |
| 1488 | [this, File(File.str()), CB(std::move(CB)), Code(Server->getDraft(File))]( |
| 1489 | llvm::Expected<std::vector<HighlightingToken>> HT) mutable { |
| 1490 | if (!HT) |
| 1491 | return CB(HT.takeError()); |
| 1492 | SemanticTokens Result; |
| 1493 | Result.tokens = toSemanticTokens(*HT, *Code); |
| 1494 | { |
| 1495 | std::lock_guard<std::mutex> Lock(SemanticTokensMutex); |
| 1496 | auto &Last = LastSemanticTokens[File]; |
| 1497 | |
| 1498 | Last.tokens = Result.tokens; |
| 1499 | increment(Last.resultId); |
| 1500 | Result.resultId = Last.resultId; |
| 1501 | } |
| 1502 | CB(std::move(Result)); |
| 1503 | }); |
| 1504 | } |
| 1505 | |
| 1506 | void ClangdLSPServer::onSemanticTokensDelta( |
| 1507 | const SemanticTokensDeltaParams &Params, |
| 1508 | Callback<SemanticTokensOrDelta> CB) { |
| 1509 | auto File = Params.textDocument.uri.file(); |
| 1510 | Server->semanticHighlights( |
| 1511 | Params.textDocument.uri.file(), |
| 1512 | [this, PrevResultID(Params.previousResultId), File(File.str()), |
| 1513 | CB(std::move(CB)), Code(Server->getDraft(File))]( |
| 1514 | llvm::Expected<std::vector<HighlightingToken>> HT) mutable { |
| 1515 | if (!HT) |
| 1516 | return CB(HT.takeError()); |
| 1517 | std::vector<SemanticToken> Toks = toSemanticTokens(*HT, *Code); |
| 1518 | |
| 1519 | SemanticTokensOrDelta Result; |
| 1520 | { |
| 1521 | std::lock_guard<std::mutex> Lock(SemanticTokensMutex); |
| 1522 | auto &Last = LastSemanticTokens[File]; |
| 1523 | |
| 1524 | if (PrevResultID == Last.resultId) { |
| 1525 | Result.edits = diffTokens(Last.tokens, Toks); |
| 1526 | } else { |
| 1527 | vlog("semanticTokens/full/delta: wanted edits vs {0} but last " |
| 1528 | "result had ID {1}. Returning full token list.", |
| 1529 | PrevResultID, Last.resultId); |
| 1530 | Result.tokens = Toks; |
| 1531 | } |
| 1532 | |
| 1533 | Last.tokens = std::move(Toks); |
| 1534 | increment(Last.resultId); |
| 1535 | Result.resultId = Last.resultId; |
| 1536 | } |
| 1537 | |
| 1538 | CB(std::move(Result)); |
| 1539 | }); |
| 1540 | } |
| 1541 | |
| 1542 | void ClangdLSPServer::onMemoryUsage(const NoParams &, |
| 1543 | Callback<MemoryTree> Reply) { |
| 1544 | llvm::BumpPtrAllocator DetailAlloc; |
| 1545 | MemoryTree MT(&DetailAlloc); |
| 1546 | profile(MT); |
| 1547 | Reply(std::move(MT)); |
| 1548 | } |
| 1549 | |
| 1550 | void ClangdLSPServer::onAST(const ASTParams &Params, |
| 1551 | Callback<std::optional<ASTNode>> CB) { |
| 1552 | Server->getAST(Params.textDocument.uri.file(), Params.range, std::move(CB)); |
| 1553 | } |
| 1554 | |
| 1555 | ClangdLSPServer::ClangdLSPServer(Transport &Transp, const ThreadsafeFS &TFS, |
| 1556 | const ClangdLSPServer::Options &Opts) |
| 1557 | : ShouldProfile(/*Period=*/std::chrono::minutes(5), |
| 1558 | /*Delay=*/std::chrono::minutes(1)), |
| 1559 | ShouldCleanupMemory(/*Period=*/std::chrono::minutes(1), |
| 1560 | /*Delay=*/std::chrono::minutes(1)), |
| 1561 | BackgroundContext(Context::current().clone()), Transp(Transp), |
| 1562 | MsgHandler(new MessageHandler(*this)), TFS(TFS), |
| 1563 | SupportedSymbolKinds(defaultSymbolKinds()), |
| 1564 | SupportedCompletionItemKinds(defaultCompletionItemKinds()), Opts(Opts) { |
| 1565 | if (Opts.ConfigProvider) { |
| 1566 | assert(!Opts.ContextProvider && |
| 1567 | "Only one of ConfigProvider and ContextProvider allowed!"); |
| 1568 | this->Opts.ContextProvider = ClangdServer::createConfiguredContextProvider( |
| 1569 | Opts.ConfigProvider, this); |
| 1570 | } |
| 1571 | LSPBinder Bind(this->Handlers, *this); |
| 1572 | Bind.method("initialize", this, &ClangdLSPServer::onInitialize); |
| 1573 | } |
| 1574 | |
| 1575 | void ClangdLSPServer::bindMethods(LSPBinder &Bind, |
| 1576 | const ClientCapabilities &Caps) { |
| 1577 | // clang-format off |
| 1578 | Bind.notification("initialized", this, &ClangdLSPServer::onInitialized); |
| 1579 | Bind.method("shutdown", this, &ClangdLSPServer::onShutdown); |
| 1580 | Bind.method("sync", this, &ClangdLSPServer::onSync); |
| 1581 | Bind.method("textDocument/rangeFormatting", this, &ClangdLSPServer::onDocumentRangeFormatting); |
| 1582 | Bind.method("textDocument/onTypeFormatting", this, &ClangdLSPServer::onDocumentOnTypeFormatting); |
| 1583 | Bind.method("textDocument/formatting", this, &ClangdLSPServer::onDocumentFormatting); |
| 1584 | Bind.method("textDocument/codeAction", this, &ClangdLSPServer::onCodeAction); |
| 1585 | Bind.method("textDocument/completion", this, &ClangdLSPServer::onCompletion); |
| 1586 | Bind.method("textDocument/signatureHelp", this, &ClangdLSPServer::onSignatureHelp); |
| 1587 | Bind.method("textDocument/definition", this, &ClangdLSPServer::onGoToDefinition); |
| 1588 | Bind.method("textDocument/declaration", this, &ClangdLSPServer::onGoToDeclaration); |
| 1589 | Bind.method("textDocument/typeDefinition", this, &ClangdLSPServer::onGoToType); |
| 1590 | Bind.method("textDocument/implementation", this, &ClangdLSPServer::onGoToImplementation); |
| 1591 | Bind.method("textDocument/references", this, &ClangdLSPServer::onReference); |
| 1592 | Bind.method("textDocument/switchSourceHeader", this, &ClangdLSPServer::onSwitchSourceHeader); |
| 1593 | Bind.method("textDocument/prepareRename", this, &ClangdLSPServer::onPrepareRename); |
| 1594 | Bind.method("textDocument/rename", this, &ClangdLSPServer::onRename); |
| 1595 | Bind.method("textDocument/hover", this, &ClangdLSPServer::onHover); |
| 1596 | Bind.method("textDocument/documentSymbol", this, &ClangdLSPServer::onDocumentSymbol); |
| 1597 | Bind.method("workspace/executeCommand", this, &ClangdLSPServer::onCommand); |
| 1598 | Bind.method("textDocument/documentHighlight", this, &ClangdLSPServer::onDocumentHighlight); |
| 1599 | Bind.method("workspace/symbol", this, &ClangdLSPServer::onWorkspaceSymbol); |
| 1600 | Bind.method("textDocument/ast", this, &ClangdLSPServer::onAST); |
| 1601 | Bind.notification("textDocument/didOpen", this, &ClangdLSPServer::onDocumentDidOpen); |
| 1602 | Bind.notification("textDocument/didClose", this, &ClangdLSPServer::onDocumentDidClose); |
| 1603 | Bind.notification("textDocument/didChange", this, &ClangdLSPServer::onDocumentDidChange); |
| 1604 | Bind.notification("textDocument/didSave", this, &ClangdLSPServer::onDocumentDidSave); |
| 1605 | Bind.notification("workspace/didChangeWatchedFiles", this, &ClangdLSPServer::onFileEvent); |
| 1606 | Bind.notification("workspace/didChangeConfiguration", this, &ClangdLSPServer::onChangeConfiguration); |
| 1607 | Bind.method("textDocument/symbolInfo", this, &ClangdLSPServer::onSymbolInfo); |
| 1608 | Bind.method("textDocument/typeHierarchy", this, &ClangdLSPServer::onTypeHierarchy); |
| 1609 | Bind.method("typeHierarchy/resolve", this, &ClangdLSPServer::onResolveTypeHierarchy); |
| 1610 | Bind.method("textDocument/prepareTypeHierarchy", this, &ClangdLSPServer::onPrepareTypeHierarchy); |
| 1611 | Bind.method("typeHierarchy/supertypes", this, &ClangdLSPServer::onSuperTypes); |
| 1612 | Bind.method("typeHierarchy/subtypes", this, &ClangdLSPServer::onSubTypes); |
| 1613 | Bind.method("textDocument/prepareCallHierarchy", this, &ClangdLSPServer::onPrepareCallHierarchy); |
| 1614 | Bind.method("callHierarchy/incomingCalls", this, &ClangdLSPServer::onCallHierarchyIncomingCalls); |
| 1615 | Bind.method("textDocument/selectionRange", this, &ClangdLSPServer::onSelectionRange); |
| 1616 | Bind.method("textDocument/documentLink", this, &ClangdLSPServer::onDocumentLink); |
| 1617 | Bind.method("textDocument/semanticTokens/full", this, &ClangdLSPServer::onSemanticTokens); |
| 1618 | Bind.method("textDocument/semanticTokens/full/delta", this, &ClangdLSPServer::onSemanticTokensDelta); |
| 1619 | Bind.method("clangd/inlayHints", this, &ClangdLSPServer::onClangdInlayHints); |
| 1620 | Bind.method("textDocument/inlayHint", this, &ClangdLSPServer::onInlayHint); |
| 1621 | Bind.method("$/memoryUsage", this, &ClangdLSPServer::onMemoryUsage); |
| 1622 | Bind.method("textDocument/foldingRange", this, &ClangdLSPServer::onFoldingRange); |
| 1623 | Bind.command(ApplyFixCommand, this, &ClangdLSPServer::onCommandApplyEdit); |
| 1624 | Bind.command(ApplyTweakCommand, this, &ClangdLSPServer::onCommandApplyTweak); |
| 1625 | |
| 1626 | ApplyWorkspaceEdit = Bind.outgoingMethod("workspace/applyEdit"); |
| 1627 | PublishDiagnostics = Bind.outgoingNotification("textDocument/publishDiagnostics"); |
| 1628 | ShowMessage = Bind.outgoingNotification("window/showMessage"); |
| 1629 | NotifyFileStatus = Bind.outgoingNotification("textDocument/clangd.fileStatus"); |
| 1630 | CreateWorkDoneProgress = Bind.outgoingMethod("window/workDoneProgress/create"); |
| 1631 | BeginWorkDoneProgress = Bind.outgoingNotification("$/progress"); |
| 1632 | ReportWorkDoneProgress = Bind.outgoingNotification("$/progress"); |
| 1633 | EndWorkDoneProgress = Bind.outgoingNotification("$/progress"); |
| 1634 | if(Caps.SemanticTokenRefreshSupport) |
| 1635 | SemanticTokensRefresh = Bind.outgoingMethod("workspace/semanticTokens/refresh"); |
| 1636 | // clang-format on |
| 1637 | } |
| 1638 | |
| 1639 | ClangdLSPServer::~ClangdLSPServer() { |
| 1640 | IsBeingDestroyed = true; |
| 1641 | // Explicitly destroy ClangdServer first, blocking on threads it owns. |
| 1642 | // This ensures they don't access any other members. |
| 1643 | Server.reset(); |
| 1644 | } |
| 1645 | |
| 1646 | bool ClangdLSPServer::run() { |
| 1647 | // Run the Language Server loop. |
| 1648 | bool CleanExit = true; |
| 1649 | if (auto Err = Transp.loop(*MsgHandler)) { |
| 1650 | elog("Transport error: {0}", std::move(Err)); |
| 1651 | CleanExit = false; |
| 1652 | } |
| 1653 | |
| 1654 | return CleanExit && ShutdownRequestReceived; |
| 1655 | } |
| 1656 | |
| 1657 | void ClangdLSPServer::profile(MemoryTree &MT) const { |
| 1658 | if (Server) |
| 1659 | Server->profile(MT.child("clangd_server")); |
| 1660 | } |
| 1661 | |
| 1662 | std::vector<Fix> ClangdLSPServer::getFixes(llvm::StringRef File, |
| 1663 | const clangd::Diagnostic &D) { |
| 1664 | std::lock_guard<std::mutex> Lock(FixItsMutex); |
| 1665 | auto DiagToFixItsIter = FixItsMap.find(File); |
| 1666 | if (DiagToFixItsIter == FixItsMap.end()) |
| 1667 | return {}; |
| 1668 | |
| 1669 | const auto &DiagToFixItsMap = DiagToFixItsIter->second; |
| 1670 | auto FixItsIter = DiagToFixItsMap.find(D); |
| 1671 | if (FixItsIter == DiagToFixItsMap.end()) |
| 1672 | return {}; |
| 1673 | |
| 1674 | return FixItsIter->second; |
| 1675 | } |
| 1676 | |
| 1677 | // A completion request is sent when the user types '>' or ':', but we only |
| 1678 | // want to trigger on '->' and '::'. We check the preceeding text to make |
| 1679 | // sure it matches what we expected. |
| 1680 | // Running the lexer here would be more robust (e.g. we can detect comments |
| 1681 | // and avoid triggering completion there), but we choose to err on the side |
| 1682 | // of simplicity here. |
| 1683 | bool ClangdLSPServer::shouldRunCompletion( |
| 1684 | const CompletionParams &Params) const { |
| 1685 | if (Params.context.triggerKind != CompletionTriggerKind::TriggerCharacter) |
| 1686 | return true; |
| 1687 | auto Code = Server->getDraft(Params.textDocument.uri.file()); |
| 1688 | if (!Code) |
| 1689 | return true; // completion code will log the error for untracked doc. |
| 1690 | auto Offset = positionToOffset(*Code, Params.position, |
| 1691 | /*AllowColumnsBeyondLineLength=*/false); |
| 1692 | if (!Offset) { |
| 1693 | vlog("could not convert position '{0}' to offset for file '{1}'", |
| 1694 | Params.position, Params.textDocument.uri.file()); |
| 1695 | return true; |
| 1696 | } |
| 1697 | return allowImplicitCompletion(*Code, *Offset); |
| 1698 | } |
| 1699 | |
| 1700 | void ClangdLSPServer::onDiagnosticsReady(PathRef File, llvm::StringRef Version, |
| 1701 | std::vector<Diag> Diagnostics) { |
| 1702 | PublishDiagnosticsParams Notification; |
| 1703 | Notification.version = decodeVersion(Version); |
| 1704 | Notification.uri = URIForFile::canonicalize(File, /*TUPath=*/File); |
| 1705 | DiagnosticToReplacementMap LocalFixIts; // Temporary storage |
| 1706 | for (auto &Diag : Diagnostics) { |
| 1707 | toLSPDiags(Diag, Notification.uri, DiagOpts, |
| 1708 | [&](clangd::Diagnostic Diag, llvm::ArrayRef<Fix> Fixes) { |
| 1709 | auto &FixItsForDiagnostic = LocalFixIts[Diag]; |
| 1710 | llvm::copy(Fixes, std::back_inserter(FixItsForDiagnostic)); |
| 1711 | Notification.diagnostics.push_back(std::move(Diag)); |
| 1712 | }); |
| 1713 | } |
| 1714 | |
| 1715 | // Cache FixIts |
| 1716 | { |
| 1717 | std::lock_guard<std::mutex> Lock(FixItsMutex); |
| 1718 | FixItsMap[File] = LocalFixIts; |
| 1719 | } |
| 1720 | |
| 1721 | // Send a notification to the LSP client. |
| 1722 | PublishDiagnostics(Notification); |
| 1723 | } |
| 1724 | |
| 1725 | void ClangdLSPServer::onBackgroundIndexProgress( |
| 1726 | const BackgroundQueue::Stats &Stats) { |
| 1727 | static const char ProgressToken[] = "backgroundIndexProgress"; |
| 1728 | |
| 1729 | // The background index did some work, maybe we need to cleanup |
| 1730 | maybeCleanupMemory(); |
| 1731 | |
| 1732 | std::lock_guard<std::mutex> Lock(BackgroundIndexProgressMutex); |
| 1733 | |
| 1734 | auto NotifyProgress = [this](const BackgroundQueue::Stats &Stats) { |
| 1735 | if (BackgroundIndexProgressState != BackgroundIndexProgress::Live) { |
| 1736 | WorkDoneProgressBegin Begin; |
| 1737 | Begin.percentage = true; |
| 1738 | Begin.title = "indexing"; |
| 1739 | BeginWorkDoneProgress({ProgressToken, std::move(Begin)}); |
| 1740 | BackgroundIndexProgressState = BackgroundIndexProgress::Live; |
| 1741 | } |
| 1742 | |
| 1743 | if (Stats.Completed < Stats.Enqueued) { |
| 1744 | assert(Stats.Enqueued > Stats.LastIdle); |
| 1745 | WorkDoneProgressReport Report; |
| 1746 | Report.percentage = 100 * (Stats.Completed - Stats.LastIdle) / |
| 1747 | (Stats.Enqueued - Stats.LastIdle); |
| 1748 | Report.message = |
| 1749 | llvm::formatv("{0}/{1}", Stats.Completed - Stats.LastIdle, |
| 1750 | Stats.Enqueued - Stats.LastIdle); |
| 1751 | ReportWorkDoneProgress({ProgressToken, std::move(Report)}); |
| 1752 | } else { |
| 1753 | assert(Stats.Completed == Stats.Enqueued); |
| 1754 | EndWorkDoneProgress({ProgressToken, WorkDoneProgressEnd()}); |
| 1755 | BackgroundIndexProgressState = BackgroundIndexProgress::Empty; |
| 1756 | } |
| 1757 | }; |
| 1758 | |
| 1759 | switch (BackgroundIndexProgressState) { |
| 1760 | case BackgroundIndexProgress::Unsupported: |
| 1761 | return; |
| 1762 | case BackgroundIndexProgress::Creating: |
| 1763 | // Cache this update for when the progress bar is available. |
| 1764 | PendingBackgroundIndexProgress = Stats; |
| 1765 | return; |
| 1766 | case BackgroundIndexProgress::Empty: { |
| 1767 | if (BackgroundIndexSkipCreate) { |
| 1768 | NotifyProgress(Stats); |
| 1769 | break; |
| 1770 | } |
| 1771 | // Cache this update for when the progress bar is available. |
| 1772 | PendingBackgroundIndexProgress = Stats; |
| 1773 | BackgroundIndexProgressState = BackgroundIndexProgress::Creating; |
| 1774 | WorkDoneProgressCreateParams CreateRequest; |
| 1775 | CreateRequest.token = ProgressToken; |
| 1776 | CreateWorkDoneProgress( |
| 1777 | CreateRequest, |
| 1778 | [this, NotifyProgress](llvm::Expected<std::nullptr_t> E) { |
| 1779 | std::lock_guard<std::mutex> Lock(BackgroundIndexProgressMutex); |
| 1780 | if (E) { |
| 1781 | NotifyProgress(this->PendingBackgroundIndexProgress); |
| 1782 | } else { |
| 1783 | elog("Failed to create background index progress bar: {0}", |
| 1784 | E.takeError()); |
| 1785 | // give up forever rather than thrashing about |
| 1786 | BackgroundIndexProgressState = BackgroundIndexProgress::Unsupported; |
| 1787 | } |
| 1788 | }); |
| 1789 | break; |
| 1790 | } |
| 1791 | case BackgroundIndexProgress::Live: |
| 1792 | NotifyProgress(Stats); |
| 1793 | break; |
| 1794 | } |
| 1795 | } |
| 1796 | |
| 1797 | void ClangdLSPServer::onFileUpdated(PathRef File, const TUStatus &Status) { |
| 1798 | if (!SupportFileStatus) |
| 1799 | return; |
| 1800 | // FIXME: we don't emit "BuildingFile" and `RunningAction`, as these |
| 1801 | // two statuses are running faster in practice, which leads the UI constantly |
| 1802 | // changing, and doesn't provide much value. We may want to emit status at a |
| 1803 | // reasonable time interval (e.g. 0.5s). |
| 1804 | if (Status.PreambleActivity == PreambleAction::Idle && |
| 1805 | (Status.ASTActivity.K == ASTAction::Building || |
| 1806 | Status.ASTActivity.K == ASTAction::RunningAction)) |
| 1807 | return; |
| 1808 | NotifyFileStatus(Status.render(File)); |
| 1809 | } |
| 1810 | |
| 1811 | void ClangdLSPServer::onSemanticsMaybeChanged(PathRef File) { |
| 1812 | if (SemanticTokensRefresh) { |
| 1813 | SemanticTokensRefresh(NoParams{}, [](llvm::Expected<std::nullptr_t> E) { |
| 1814 | if (E) |
| 1815 | return; |
| 1816 | elog("Failed to refresh semantic tokens: {0}", E.takeError()); |
| 1817 | }); |
| 1818 | } |
| 1819 | } |
| 1820 | |
| 1821 | } // namespace clangd |
| 1822 | } // namespace clang |