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