1 //===--- ClangdServer.cpp - Main clangd server code --------------*- 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 "ClangdServer.h" 10 #include "CodeComplete.h" 11 #include "Config.h" 12 #include "Diagnostics.h" 13 #include "DumpAST.h" 14 #include "FindSymbols.h" 15 #include "Format.h" 16 #include "HeaderSourceSwitch.h" 17 #include "Headers.h" 18 #include "InlayHints.h" 19 #include "ParsedAST.h" 20 #include "Preamble.h" 21 #include "Protocol.h" 22 #include "SemanticHighlighting.h" 23 #include "SemanticSelection.h" 24 #include "SourceCode.h" 25 #include "TUScheduler.h" 26 #include "XRefs.h" 27 #include "index/CanonicalIncludes.h" 28 #include "index/FileIndex.h" 29 #include "index/Merge.h" 30 #include "refactor/Rename.h" 31 #include "refactor/Tweak.h" 32 #include "support/Logger.h" 33 #include "support/Markup.h" 34 #include "support/MemoryTree.h" 35 #include "support/ThreadsafeFS.h" 36 #include "support/Trace.h" 37 #include "clang/Format/Format.h" 38 #include "clang/Frontend/CompilerInstance.h" 39 #include "clang/Frontend/CompilerInvocation.h" 40 #include "clang/Lex/Preprocessor.h" 41 #include "clang/Tooling/CompilationDatabase.h" 42 #include "clang/Tooling/Core/Replacement.h" 43 #include "llvm/ADT/ArrayRef.h" 44 #include "llvm/ADT/Optional.h" 45 #include "llvm/ADT/STLExtras.h" 46 #include "llvm/ADT/ScopeExit.h" 47 #include "llvm/ADT/StringExtras.h" 48 #include "llvm/ADT/StringRef.h" 49 #include "llvm/Support/Errc.h" 50 #include "llvm/Support/Error.h" 51 #include "llvm/Support/FileSystem.h" 52 #include "llvm/Support/Path.h" 53 #include "llvm/Support/ScopedPrinter.h" 54 #include "llvm/Support/raw_ostream.h" 55 #include <algorithm> 56 #include <chrono> 57 #include <future> 58 #include <memory> 59 #include <mutex> 60 #include <string> 61 #include <type_traits> 62 63 namespace clang { 64 namespace clangd { 65 namespace { 66 67 // Update the FileIndex with new ASTs and plumb the diagnostics responses. 68 struct UpdateIndexCallbacks : public ParsingCallbacks { 69 UpdateIndexCallbacks(FileIndex *FIndex, 70 ClangdServer::Callbacks *ServerCallbacks) 71 : FIndex(FIndex), ServerCallbacks(ServerCallbacks) {} 72 73 void onPreambleAST(PathRef Path, llvm::StringRef Version, ASTContext &Ctx, 74 std::shared_ptr<clang::Preprocessor> PP, 75 const CanonicalIncludes &CanonIncludes) override { 76 if (FIndex) 77 FIndex->updatePreamble(Path, Version, Ctx, std::move(PP), CanonIncludes); 78 } 79 80 void onMainAST(PathRef Path, ParsedAST &AST, PublishFn Publish) override { 81 if (FIndex) 82 FIndex->updateMain(Path, AST); 83 84 assert(AST.getDiagnostics().hasValue() && 85 "We issue callback only with fresh preambles"); 86 std::vector<Diag> Diagnostics = *AST.getDiagnostics(); 87 if (ServerCallbacks) 88 Publish([&]() { 89 ServerCallbacks->onDiagnosticsReady(Path, AST.version(), 90 std::move(Diagnostics)); 91 }); 92 } 93 94 void onFailedAST(PathRef Path, llvm::StringRef Version, 95 std::vector<Diag> Diags, PublishFn Publish) override { 96 if (ServerCallbacks) 97 Publish( 98 [&]() { ServerCallbacks->onDiagnosticsReady(Path, Version, Diags); }); 99 } 100 101 void onFileUpdated(PathRef File, const TUStatus &Status) override { 102 if (ServerCallbacks) 103 ServerCallbacks->onFileUpdated(File, Status); 104 } 105 106 void onPreamblePublished(PathRef File) override { 107 if (ServerCallbacks) 108 ServerCallbacks->onSemanticsMaybeChanged(File); 109 } 110 111 private: 112 FileIndex *FIndex; 113 ClangdServer::Callbacks *ServerCallbacks; 114 }; 115 116 class DraftStoreFS : public ThreadsafeFS { 117 public: 118 DraftStoreFS(const ThreadsafeFS &Base, const DraftStore &Drafts) 119 : Base(Base), DirtyFiles(Drafts) {} 120 121 private: 122 llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> viewImpl() const override { 123 auto OFS = llvm::makeIntrusiveRefCnt<llvm::vfs::OverlayFileSystem>( 124 Base.view(llvm::None)); 125 OFS->pushOverlay(DirtyFiles.asVFS()); 126 return OFS; 127 } 128 129 const ThreadsafeFS &Base; 130 const DraftStore &DirtyFiles; 131 }; 132 133 } // namespace 134 135 ClangdServer::Options ClangdServer::optsForTest() { 136 ClangdServer::Options Opts; 137 Opts.UpdateDebounce = DebouncePolicy::fixed(/*zero*/ {}); 138 Opts.StorePreamblesInMemory = true; 139 Opts.AsyncThreadsCount = 4; // Consistent! 140 return Opts; 141 } 142 143 ClangdServer::Options::operator TUScheduler::Options() const { 144 TUScheduler::Options Opts; 145 Opts.AsyncThreadsCount = AsyncThreadsCount; 146 Opts.RetentionPolicy = RetentionPolicy; 147 Opts.StorePreamblesInMemory = StorePreamblesInMemory; 148 Opts.UpdateDebounce = UpdateDebounce; 149 Opts.ContextProvider = ContextProvider; 150 return Opts; 151 } 152 153 ClangdServer::ClangdServer(const GlobalCompilationDatabase &CDB, 154 const ThreadsafeFS &TFS, const Options &Opts, 155 Callbacks *Callbacks) 156 : FeatureModules(Opts.FeatureModules), CDB(CDB), TFS(TFS), 157 DynamicIdx(Opts.BuildDynamicSymbolIndex ? new FileIndex() : nullptr), 158 ClangTidyProvider(Opts.ClangTidyProvider), 159 WorkspaceRoot(Opts.WorkspaceRoot), 160 Transient(Opts.ImplicitCancellation ? TUScheduler::InvalidateOnUpdate 161 : TUScheduler::NoInvalidation), 162 DirtyFS(std::make_unique<DraftStoreFS>(TFS, DraftMgr)) { 163 // Pass a callback into `WorkScheduler` to extract symbols from a newly 164 // parsed file and rebuild the file index synchronously each time an AST 165 // is parsed. 166 WorkScheduler.emplace( 167 CDB, TUScheduler::Options(Opts), 168 std::make_unique<UpdateIndexCallbacks>(DynamicIdx.get(), Callbacks)); 169 // Adds an index to the stack, at higher priority than existing indexes. 170 auto AddIndex = [&](SymbolIndex *Idx) { 171 if (this->Index != nullptr) { 172 MergedIdx.push_back(std::make_unique<MergedIndex>(Idx, this->Index)); 173 this->Index = MergedIdx.back().get(); 174 } else { 175 this->Index = Idx; 176 } 177 }; 178 if (Opts.StaticIndex) 179 AddIndex(Opts.StaticIndex); 180 if (Opts.BackgroundIndex) { 181 BackgroundIndex::Options BGOpts; 182 BGOpts.ThreadPoolSize = std::max(Opts.AsyncThreadsCount, 1u); 183 BGOpts.OnProgress = [Callbacks](BackgroundQueue::Stats S) { 184 if (Callbacks) 185 Callbacks->onBackgroundIndexProgress(S); 186 }; 187 BGOpts.ContextProvider = Opts.ContextProvider; 188 BackgroundIdx = std::make_unique<BackgroundIndex>( 189 TFS, CDB, 190 BackgroundIndexStorage::createDiskBackedStorageFactory( 191 [&CDB](llvm::StringRef File) { return CDB.getProjectInfo(File); }), 192 std::move(BGOpts)); 193 AddIndex(BackgroundIdx.get()); 194 } 195 if (DynamicIdx) 196 AddIndex(DynamicIdx.get()); 197 198 if (Opts.FeatureModules) { 199 FeatureModule::Facilities F{ 200 *this->WorkScheduler, 201 this->Index, 202 this->TFS, 203 }; 204 for (auto &Mod : *Opts.FeatureModules) 205 Mod.initialize(F); 206 } 207 } 208 209 ClangdServer::~ClangdServer() { 210 // Destroying TUScheduler first shuts down request threads that might 211 // otherwise access members concurrently. 212 // (Nobody can be using TUScheduler because we're on the main thread). 213 WorkScheduler.reset(); 214 // Now requests have stopped, we can shut down feature modules. 215 if (FeatureModules) { 216 for (auto &Mod : *FeatureModules) 217 Mod.stop(); 218 for (auto &Mod : *FeatureModules) 219 Mod.blockUntilIdle(Deadline::infinity()); 220 } 221 } 222 223 void ClangdServer::addDocument(PathRef File, llvm::StringRef Contents, 224 llvm::StringRef Version, 225 WantDiagnostics WantDiags, bool ForceRebuild) { 226 std::string ActualVersion = DraftMgr.addDraft(File, Version, Contents); 227 ParseOptions Opts; 228 229 // Compile command is set asynchronously during update, as it can be slow. 230 ParseInputs Inputs; 231 Inputs.TFS = &TFS; 232 Inputs.Contents = std::string(Contents); 233 Inputs.Version = std::move(ActualVersion); 234 Inputs.ForceRebuild = ForceRebuild; 235 Inputs.Opts = std::move(Opts); 236 Inputs.Index = Index; 237 Inputs.ClangTidyProvider = ClangTidyProvider; 238 Inputs.FeatureModules = FeatureModules; 239 bool NewFile = WorkScheduler->update(File, Inputs, WantDiags); 240 // If we loaded Foo.h, we want to make sure Foo.cpp is indexed. 241 if (NewFile && BackgroundIdx) 242 BackgroundIdx->boostRelated(File); 243 } 244 245 void ClangdServer::reparseOpenFilesIfNeeded( 246 llvm::function_ref<bool(llvm::StringRef File)> Filter) { 247 // Reparse only opened files that were modified. 248 for (const Path &FilePath : DraftMgr.getActiveFiles()) 249 if (Filter(FilePath)) 250 if (auto Draft = DraftMgr.getDraft(FilePath)) // else disappeared in race? 251 addDocument(FilePath, *Draft->Contents, Draft->Version, 252 WantDiagnostics::Auto); 253 } 254 255 std::shared_ptr<const std::string> ClangdServer::getDraft(PathRef File) const { 256 auto Draft = DraftMgr.getDraft(File); 257 if (!Draft) 258 return nullptr; 259 return std::move(Draft->Contents); 260 } 261 262 std::function<Context(PathRef)> 263 ClangdServer::createConfiguredContextProvider(const config::Provider *Provider, 264 Callbacks *Publish) { 265 if (!Provider) 266 return [](llvm::StringRef) { return Context::current().clone(); }; 267 268 struct Impl { 269 const config::Provider *Provider; 270 ClangdServer::Callbacks *Publish; 271 std::mutex PublishMu; 272 273 Impl(const config::Provider *Provider, ClangdServer::Callbacks *Publish) 274 : Provider(Provider), Publish(Publish) {} 275 276 Context operator()(llvm::StringRef File) { 277 config::Params Params; 278 // Don't reread config files excessively often. 279 // FIXME: when we see a config file change event, use the event timestamp? 280 Params.FreshTime = 281 std::chrono::steady_clock::now() - std::chrono::seconds(5); 282 llvm::SmallString<256> PosixPath; 283 if (!File.empty()) { 284 assert(llvm::sys::path::is_absolute(File)); 285 llvm::sys::path::native(File, PosixPath, llvm::sys::path::Style::posix); 286 Params.Path = PosixPath.str(); 287 } 288 289 llvm::StringMap<std::vector<Diag>> ReportableDiagnostics; 290 Config C = Provider->getConfig(Params, [&](const llvm::SMDiagnostic &D) { 291 // Create the map entry even for note diagnostics we don't report. 292 // This means that when the file is parsed with no warnings, we 293 // publish an empty set of diagnostics, clearing any the client has. 294 handleDiagnostic(D, !Publish || D.getFilename().empty() 295 ? nullptr 296 : &ReportableDiagnostics[D.getFilename()]); 297 }); 298 // Blindly publish diagnostics for the (unopened) parsed config files. 299 // We must avoid reporting diagnostics for *the same file* concurrently. 300 // Source diags are published elsewhere, but those are different files. 301 if (!ReportableDiagnostics.empty()) { 302 std::lock_guard<std::mutex> Lock(PublishMu); 303 for (auto &Entry : ReportableDiagnostics) 304 Publish->onDiagnosticsReady(Entry.first(), /*Version=*/"", 305 std::move(Entry.second)); 306 } 307 return Context::current().derive(Config::Key, std::move(C)); 308 } 309 310 void handleDiagnostic(const llvm::SMDiagnostic &D, 311 std::vector<Diag> *ClientDiagnostics) { 312 switch (D.getKind()) { 313 case llvm::SourceMgr::DK_Error: 314 elog("config error at {0}:{1}:{2}: {3}", D.getFilename(), D.getLineNo(), 315 D.getColumnNo(), D.getMessage()); 316 break; 317 case llvm::SourceMgr::DK_Warning: 318 log("config warning at {0}:{1}:{2}: {3}", D.getFilename(), 319 D.getLineNo(), D.getColumnNo(), D.getMessage()); 320 break; 321 case llvm::SourceMgr::DK_Note: 322 case llvm::SourceMgr::DK_Remark: 323 vlog("config note at {0}:{1}:{2}: {3}", D.getFilename(), D.getLineNo(), 324 D.getColumnNo(), D.getMessage()); 325 ClientDiagnostics = nullptr; // Don't emit notes as LSP diagnostics. 326 break; 327 } 328 if (ClientDiagnostics) 329 ClientDiagnostics->push_back(toDiag(D, Diag::ClangdConfig)); 330 } 331 }; 332 333 // Copyable wrapper. 334 return [I(std::make_shared<Impl>(Provider, Publish))](llvm::StringRef Path) { 335 return (*I)(Path); 336 }; 337 } 338 339 void ClangdServer::removeDocument(PathRef File) { 340 DraftMgr.removeDraft(File); 341 WorkScheduler->remove(File); 342 } 343 344 void ClangdServer::codeComplete(PathRef File, Position Pos, 345 const clangd::CodeCompleteOptions &Opts, 346 Callback<CodeCompleteResult> CB) { 347 // Copy completion options for passing them to async task handler. 348 auto CodeCompleteOpts = Opts; 349 if (!CodeCompleteOpts.Index) // Respect overridden index. 350 CodeCompleteOpts.Index = Index; 351 352 auto Task = [Pos, CodeCompleteOpts, File = File.str(), CB = std::move(CB), 353 this](llvm::Expected<InputsAndPreamble> IP) mutable { 354 if (!IP) 355 return CB(IP.takeError()); 356 if (auto Reason = isCancelled()) 357 return CB(llvm::make_error<CancelledError>(Reason)); 358 359 llvm::Optional<SpeculativeFuzzyFind> SpecFuzzyFind; 360 if (!IP->Preamble) { 361 // No speculation in Fallback mode, as it's supposed to be much faster 362 // without compiling. 363 vlog("Build for file {0} is not ready. Enter fallback mode.", File); 364 } else if (CodeCompleteOpts.Index) { 365 SpecFuzzyFind.emplace(); 366 { 367 std::lock_guard<std::mutex> Lock(CachedCompletionFuzzyFindRequestMutex); 368 SpecFuzzyFind->CachedReq = CachedCompletionFuzzyFindRequestByFile[File]; 369 } 370 } 371 ParseInputs ParseInput{IP->Command, &TFS, IP->Contents.str()}; 372 ParseInput.Index = Index; 373 374 CodeCompleteOpts.MainFileSignals = IP->Signals; 375 CodeCompleteOpts.AllScopes = Config::current().Completion.AllScopes; 376 // FIXME(ibiryukov): even if Preamble is non-null, we may want to check 377 // both the old and the new version in case only one of them matches. 378 CodeCompleteResult Result = clangd::codeComplete( 379 File, Pos, IP->Preamble, ParseInput, CodeCompleteOpts, 380 SpecFuzzyFind ? SpecFuzzyFind.getPointer() : nullptr); 381 { 382 clang::clangd::trace::Span Tracer("Completion results callback"); 383 CB(std::move(Result)); 384 } 385 if (SpecFuzzyFind && SpecFuzzyFind->NewReq.hasValue()) { 386 std::lock_guard<std::mutex> Lock(CachedCompletionFuzzyFindRequestMutex); 387 CachedCompletionFuzzyFindRequestByFile[File] = 388 SpecFuzzyFind->NewReq.getValue(); 389 } 390 // SpecFuzzyFind is only destroyed after speculative fuzzy find finishes. 391 // We don't want `codeComplete` to wait for the async call if it doesn't use 392 // the result (e.g. non-index completion, speculation fails), so that `CB` 393 // is called as soon as results are available. 394 }; 395 396 // We use a potentially-stale preamble because latency is critical here. 397 WorkScheduler->runWithPreamble( 398 "CodeComplete", File, 399 (Opts.RunParser == CodeCompleteOptions::AlwaysParse) 400 ? TUScheduler::Stale 401 : TUScheduler::StaleOrAbsent, 402 std::move(Task)); 403 } 404 405 void ClangdServer::signatureHelp(PathRef File, Position Pos, 406 Callback<SignatureHelp> CB) { 407 408 auto Action = [Pos, File = File.str(), CB = std::move(CB), 409 this](llvm::Expected<InputsAndPreamble> IP) mutable { 410 if (!IP) 411 return CB(IP.takeError()); 412 413 const auto *PreambleData = IP->Preamble; 414 if (!PreambleData) 415 return CB(error("Failed to parse includes")); 416 417 ParseInputs ParseInput{IP->Command, &TFS, IP->Contents.str()}; 418 ParseInput.Index = Index; 419 CB(clangd::signatureHelp(File, Pos, *PreambleData, ParseInput)); 420 }; 421 422 // Unlike code completion, we wait for a preamble here. 423 WorkScheduler->runWithPreamble("SignatureHelp", File, TUScheduler::Stale, 424 std::move(Action)); 425 } 426 427 void ClangdServer::formatFile(PathRef File, llvm::Optional<Range> Rng, 428 Callback<tooling::Replacements> CB) { 429 auto Code = getDraft(File); 430 if (!Code) 431 return CB(llvm::make_error<LSPError>("trying to format non-added document", 432 ErrorCode::InvalidParams)); 433 tooling::Range RequestedRange; 434 if (Rng) { 435 llvm::Expected<size_t> Begin = positionToOffset(*Code, Rng->start); 436 if (!Begin) 437 return CB(Begin.takeError()); 438 llvm::Expected<size_t> End = positionToOffset(*Code, Rng->end); 439 if (!End) 440 return CB(End.takeError()); 441 RequestedRange = tooling::Range(*Begin, *End - *Begin); 442 } else { 443 RequestedRange = tooling::Range(0, Code->size()); 444 } 445 446 // Call clang-format. 447 auto Action = [File = File.str(), Code = std::move(*Code), 448 Ranges = std::vector<tooling::Range>{RequestedRange}, 449 CB = std::move(CB), this]() mutable { 450 format::FormatStyle Style = getFormatStyleForFile(File, Code, TFS); 451 tooling::Replacements IncludeReplaces = 452 format::sortIncludes(Style, Code, Ranges, File); 453 auto Changed = tooling::applyAllReplacements(Code, IncludeReplaces); 454 if (!Changed) 455 return CB(Changed.takeError()); 456 457 CB(IncludeReplaces.merge(format::reformat( 458 Style, *Changed, 459 tooling::calculateRangesAfterReplacements(IncludeReplaces, Ranges), 460 File))); 461 }; 462 WorkScheduler->runQuick("Format", File, std::move(Action)); 463 } 464 465 void ClangdServer::formatOnType(PathRef File, Position Pos, 466 StringRef TriggerText, 467 Callback<std::vector<TextEdit>> CB) { 468 auto Code = getDraft(File); 469 if (!Code) 470 return CB(llvm::make_error<LSPError>("trying to format non-added document", 471 ErrorCode::InvalidParams)); 472 llvm::Expected<size_t> CursorPos = positionToOffset(*Code, Pos); 473 if (!CursorPos) 474 return CB(CursorPos.takeError()); 475 auto Action = [File = File.str(), Code = std::move(*Code), 476 TriggerText = TriggerText.str(), CursorPos = *CursorPos, 477 CB = std::move(CB), this]() mutable { 478 auto Style = format::getStyle(format::DefaultFormatStyle, File, 479 format::DefaultFallbackStyle, Code, 480 TFS.view(/*CWD=*/llvm::None).get()); 481 if (!Style) 482 return CB(Style.takeError()); 483 484 std::vector<TextEdit> Result; 485 for (const tooling::Replacement &R : 486 formatIncremental(Code, CursorPos, TriggerText, *Style)) 487 Result.push_back(replacementToEdit(Code, R)); 488 return CB(Result); 489 }; 490 WorkScheduler->runQuick("FormatOnType", File, std::move(Action)); 491 } 492 493 void ClangdServer::prepareRename(PathRef File, Position Pos, 494 llvm::Optional<std::string> NewName, 495 const RenameOptions &RenameOpts, 496 Callback<RenameResult> CB) { 497 auto Action = [Pos, File = File.str(), CB = std::move(CB), 498 NewName = std::move(NewName), 499 RenameOpts](llvm::Expected<InputsAndAST> InpAST) mutable { 500 if (!InpAST) 501 return CB(InpAST.takeError()); 502 // prepareRename is latency-sensitive: we don't query the index, as we 503 // only need main-file references 504 auto Results = 505 clangd::rename({Pos, NewName.getValueOr("__clangd_rename_placeholder"), 506 InpAST->AST, File, /*FS=*/nullptr, 507 /*Index=*/nullptr, RenameOpts}); 508 if (!Results) { 509 // LSP says to return null on failure, but that will result in a generic 510 // failure message. If we send an LSP error response, clients can surface 511 // the message to users (VSCode does). 512 return CB(Results.takeError()); 513 } 514 return CB(*Results); 515 }; 516 WorkScheduler->runWithAST("PrepareRename", File, std::move(Action)); 517 } 518 519 void ClangdServer::rename(PathRef File, Position Pos, llvm::StringRef NewName, 520 const RenameOptions &Opts, 521 Callback<RenameResult> CB) { 522 auto Action = [File = File.str(), NewName = NewName.str(), Pos, Opts, 523 CB = std::move(CB), 524 this](llvm::Expected<InputsAndAST> InpAST) mutable { 525 // Tracks number of files edited per invocation. 526 static constexpr trace::Metric RenameFiles("rename_files", 527 trace::Metric::Distribution); 528 if (!InpAST) 529 return CB(InpAST.takeError()); 530 auto R = clangd::rename({Pos, NewName, InpAST->AST, File, 531 DirtyFS->view(llvm::None), Index, Opts}); 532 if (!R) 533 return CB(R.takeError()); 534 535 if (Opts.WantFormat) { 536 auto Style = getFormatStyleForFile(File, InpAST->Inputs.Contents, 537 *InpAST->Inputs.TFS); 538 llvm::Error Err = llvm::Error::success(); 539 for (auto &E : R->GlobalChanges) 540 Err = 541 llvm::joinErrors(reformatEdit(E.getValue(), Style), std::move(Err)); 542 543 if (Err) 544 return CB(std::move(Err)); 545 } 546 RenameFiles.record(R->GlobalChanges.size()); 547 return CB(*R); 548 }; 549 WorkScheduler->runWithAST("Rename", File, std::move(Action)); 550 } 551 552 // May generate several candidate selections, due to SelectionTree ambiguity. 553 // vector of pointers because GCC doesn't like non-copyable Selection. 554 static llvm::Expected<std::vector<std::unique_ptr<Tweak::Selection>>> 555 tweakSelection(const Range &Sel, const InputsAndAST &AST, 556 llvm::vfs::FileSystem *FS) { 557 auto Begin = positionToOffset(AST.Inputs.Contents, Sel.start); 558 if (!Begin) 559 return Begin.takeError(); 560 auto End = positionToOffset(AST.Inputs.Contents, Sel.end); 561 if (!End) 562 return End.takeError(); 563 std::vector<std::unique_ptr<Tweak::Selection>> Result; 564 SelectionTree::createEach( 565 AST.AST.getASTContext(), AST.AST.getTokens(), *Begin, *End, 566 [&](SelectionTree T) { 567 Result.push_back(std::make_unique<Tweak::Selection>( 568 AST.Inputs.Index, AST.AST, *Begin, *End, std::move(T), FS)); 569 return false; 570 }); 571 assert(!Result.empty() && "Expected at least one SelectionTree"); 572 return std::move(Result); 573 } 574 575 void ClangdServer::enumerateTweaks( 576 PathRef File, Range Sel, llvm::unique_function<bool(const Tweak &)> Filter, 577 Callback<std::vector<TweakRef>> CB) { 578 // Tracks number of times a tweak has been offered. 579 static constexpr trace::Metric TweakAvailable( 580 "tweak_available", trace::Metric::Counter, "tweak_id"); 581 auto Action = [Sel, CB = std::move(CB), Filter = std::move(Filter), 582 FeatureModules(this->FeatureModules)]( 583 Expected<InputsAndAST> InpAST) mutable { 584 if (!InpAST) 585 return CB(InpAST.takeError()); 586 auto Selections = tweakSelection(Sel, *InpAST, /*FS=*/nullptr); 587 if (!Selections) 588 return CB(Selections.takeError()); 589 std::vector<TweakRef> Res; 590 // Don't allow a tweak to fire more than once across ambiguous selections. 591 llvm::DenseSet<llvm::StringRef> PreparedTweaks; 592 auto DeduplicatingFilter = [&](const Tweak &T) { 593 return Filter(T) && !PreparedTweaks.count(T.id()); 594 }; 595 for (const auto &Sel : *Selections) { 596 for (auto &T : prepareTweaks(*Sel, DeduplicatingFilter, FeatureModules)) { 597 Res.push_back({T->id(), T->title(), T->kind()}); 598 PreparedTweaks.insert(T->id()); 599 TweakAvailable.record(1, T->id()); 600 } 601 } 602 603 CB(std::move(Res)); 604 }; 605 606 WorkScheduler->runWithAST("EnumerateTweaks", File, std::move(Action), 607 Transient); 608 } 609 610 void ClangdServer::applyTweak(PathRef File, Range Sel, StringRef TweakID, 611 Callback<Tweak::Effect> CB) { 612 // Tracks number of times a tweak has been attempted. 613 static constexpr trace::Metric TweakAttempt( 614 "tweak_attempt", trace::Metric::Counter, "tweak_id"); 615 // Tracks number of times a tweak has failed to produce edits. 616 static constexpr trace::Metric TweakFailed( 617 "tweak_failed", trace::Metric::Counter, "tweak_id"); 618 TweakAttempt.record(1, TweakID); 619 auto Action = [File = File.str(), Sel, TweakID = TweakID.str(), 620 CB = std::move(CB), 621 this](Expected<InputsAndAST> InpAST) mutable { 622 if (!InpAST) 623 return CB(InpAST.takeError()); 624 auto FS = DirtyFS->view(llvm::None); 625 auto Selections = tweakSelection(Sel, *InpAST, FS.get()); 626 if (!Selections) 627 return CB(Selections.takeError()); 628 llvm::Optional<llvm::Expected<Tweak::Effect>> Effect; 629 // Try each selection, take the first one that prepare()s. 630 // If they all fail, Effect will hold get the last error. 631 for (const auto &Selection : *Selections) { 632 auto T = prepareTweak(TweakID, *Selection, FeatureModules); 633 if (T) { 634 Effect = (*T)->apply(*Selection); 635 break; 636 } 637 Effect = T.takeError(); 638 } 639 assert(Effect.hasValue() && "Expected at least one selection"); 640 if (*Effect) { 641 // Tweaks don't apply clang-format, do that centrally here. 642 for (auto &It : (*Effect)->ApplyEdits) { 643 Edit &E = It.second; 644 format::FormatStyle Style = 645 getFormatStyleForFile(File, E.InitialCode, TFS); 646 if (llvm::Error Err = reformatEdit(E, Style)) 647 elog("Failed to format {0}: {1}", It.first(), std::move(Err)); 648 } 649 } else { 650 TweakFailed.record(1, TweakID); 651 } 652 return CB(std::move(*Effect)); 653 }; 654 WorkScheduler->runWithAST("ApplyTweak", File, std::move(Action)); 655 } 656 657 void ClangdServer::locateSymbolAt(PathRef File, Position Pos, 658 Callback<std::vector<LocatedSymbol>> CB) { 659 auto Action = [Pos, CB = std::move(CB), 660 this](llvm::Expected<InputsAndAST> InpAST) mutable { 661 if (!InpAST) 662 return CB(InpAST.takeError()); 663 CB(clangd::locateSymbolAt(InpAST->AST, Pos, Index)); 664 }; 665 666 WorkScheduler->runWithAST("Definitions", File, std::move(Action)); 667 } 668 669 void ClangdServer::switchSourceHeader( 670 PathRef Path, Callback<llvm::Optional<clangd::Path>> CB) { 671 // We want to return the result as fast as possible, strategy is: 672 // 1) use the file-only heuristic, it requires some IO but it is much 673 // faster than building AST, but it only works when .h/.cc files are in 674 // the same directory. 675 // 2) if 1) fails, we use the AST&Index approach, it is slower but supports 676 // different code layout. 677 if (auto CorrespondingFile = 678 getCorrespondingHeaderOrSource(Path, TFS.view(llvm::None))) 679 return CB(std::move(CorrespondingFile)); 680 auto Action = [Path = Path.str(), CB = std::move(CB), 681 this](llvm::Expected<InputsAndAST> InpAST) mutable { 682 if (!InpAST) 683 return CB(InpAST.takeError()); 684 CB(getCorrespondingHeaderOrSource(Path, InpAST->AST, Index)); 685 }; 686 WorkScheduler->runWithAST("SwitchHeaderSource", Path, std::move(Action)); 687 } 688 689 void ClangdServer::findDocumentHighlights( 690 PathRef File, Position Pos, Callback<std::vector<DocumentHighlight>> CB) { 691 auto Action = 692 [Pos, CB = std::move(CB)](llvm::Expected<InputsAndAST> InpAST) mutable { 693 if (!InpAST) 694 return CB(InpAST.takeError()); 695 CB(clangd::findDocumentHighlights(InpAST->AST, Pos)); 696 }; 697 698 WorkScheduler->runWithAST("Highlights", File, std::move(Action), Transient); 699 } 700 701 void ClangdServer::findHover(PathRef File, Position Pos, 702 Callback<llvm::Optional<HoverInfo>> CB) { 703 auto Action = [File = File.str(), Pos, CB = std::move(CB), 704 this](llvm::Expected<InputsAndAST> InpAST) mutable { 705 if (!InpAST) 706 return CB(InpAST.takeError()); 707 format::FormatStyle Style = getFormatStyleForFile( 708 File, InpAST->Inputs.Contents, *InpAST->Inputs.TFS); 709 CB(clangd::getHover(InpAST->AST, Pos, std::move(Style), Index)); 710 }; 711 712 WorkScheduler->runWithAST("Hover", File, std::move(Action), Transient); 713 } 714 715 void ClangdServer::typeHierarchy(PathRef File, Position Pos, int Resolve, 716 TypeHierarchyDirection Direction, 717 Callback<Optional<TypeHierarchyItem>> CB) { 718 auto Action = [File = File.str(), Pos, Resolve, Direction, CB = std::move(CB), 719 this](Expected<InputsAndAST> InpAST) mutable { 720 if (!InpAST) 721 return CB(InpAST.takeError()); 722 CB(clangd::getTypeHierarchy(InpAST->AST, Pos, Resolve, Direction, Index, 723 File)); 724 }; 725 726 WorkScheduler->runWithAST("TypeHierarchy", File, std::move(Action)); 727 } 728 729 void ClangdServer::resolveTypeHierarchy( 730 TypeHierarchyItem Item, int Resolve, TypeHierarchyDirection Direction, 731 Callback<llvm::Optional<TypeHierarchyItem>> CB) { 732 WorkScheduler->run( 733 "Resolve Type Hierarchy", "", [=, CB = std::move(CB)]() mutable { 734 clangd::resolveTypeHierarchy(Item, Resolve, Direction, Index); 735 CB(Item); 736 }); 737 } 738 739 void ClangdServer::prepareCallHierarchy( 740 PathRef File, Position Pos, Callback<std::vector<CallHierarchyItem>> CB) { 741 auto Action = [File = File.str(), Pos, 742 CB = std::move(CB)](Expected<InputsAndAST> InpAST) mutable { 743 if (!InpAST) 744 return CB(InpAST.takeError()); 745 CB(clangd::prepareCallHierarchy(InpAST->AST, Pos, File)); 746 }; 747 WorkScheduler->runWithAST("CallHierarchy", File, std::move(Action)); 748 } 749 750 void ClangdServer::incomingCalls( 751 const CallHierarchyItem &Item, 752 Callback<std::vector<CallHierarchyIncomingCall>> CB) { 753 WorkScheduler->run("Incoming Calls", "", 754 [CB = std::move(CB), Item, this]() mutable { 755 CB(clangd::incomingCalls(Item, Index)); 756 }); 757 } 758 759 void ClangdServer::inlayHints(PathRef File, 760 Callback<std::vector<InlayHint>> CB) { 761 auto Action = [CB = std::move(CB)](Expected<InputsAndAST> InpAST) mutable { 762 if (!InpAST) 763 return CB(InpAST.takeError()); 764 CB(clangd::inlayHints(InpAST->AST)); 765 }; 766 WorkScheduler->runWithAST("InlayHints", File, std::move(Action)); 767 } 768 769 void ClangdServer::onFileEvent(const DidChangeWatchedFilesParams &Params) { 770 // FIXME: Do nothing for now. This will be used for indexing and potentially 771 // invalidating other caches. 772 } 773 774 void ClangdServer::workspaceSymbols( 775 llvm::StringRef Query, int Limit, 776 Callback<std::vector<SymbolInformation>> CB) { 777 WorkScheduler->run( 778 "getWorkspaceSymbols", /*Path=*/"", 779 [Query = Query.str(), Limit, CB = std::move(CB), this]() mutable { 780 CB(clangd::getWorkspaceSymbols(Query, Limit, Index, 781 WorkspaceRoot.getValueOr(""))); 782 }); 783 } 784 785 void ClangdServer::documentSymbols(llvm::StringRef File, 786 Callback<std::vector<DocumentSymbol>> CB) { 787 auto Action = 788 [CB = std::move(CB)](llvm::Expected<InputsAndAST> InpAST) mutable { 789 if (!InpAST) 790 return CB(InpAST.takeError()); 791 CB(clangd::getDocumentSymbols(InpAST->AST)); 792 }; 793 WorkScheduler->runWithAST("DocumentSymbols", File, std::move(Action), 794 Transient); 795 } 796 797 void ClangdServer::foldingRanges(llvm::StringRef File, 798 Callback<std::vector<FoldingRange>> CB) { 799 auto Action = 800 [CB = std::move(CB)](llvm::Expected<InputsAndAST> InpAST) mutable { 801 if (!InpAST) 802 return CB(InpAST.takeError()); 803 CB(clangd::getFoldingRanges(InpAST->AST)); 804 }; 805 WorkScheduler->runWithAST("FoldingRanges", File, std::move(Action), 806 Transient); 807 } 808 809 void ClangdServer::findImplementations( 810 PathRef File, Position Pos, Callback<std::vector<LocatedSymbol>> CB) { 811 auto Action = [Pos, CB = std::move(CB), 812 this](llvm::Expected<InputsAndAST> InpAST) mutable { 813 if (!InpAST) 814 return CB(InpAST.takeError()); 815 CB(clangd::findImplementations(InpAST->AST, Pos, Index)); 816 }; 817 818 WorkScheduler->runWithAST("Implementations", File, std::move(Action)); 819 } 820 821 void ClangdServer::findReferences(PathRef File, Position Pos, uint32_t Limit, 822 Callback<ReferencesResult> CB) { 823 auto Action = [Pos, Limit, CB = std::move(CB), 824 this](llvm::Expected<InputsAndAST> InpAST) mutable { 825 if (!InpAST) 826 return CB(InpAST.takeError()); 827 CB(clangd::findReferences(InpAST->AST, Pos, Limit, Index)); 828 }; 829 830 WorkScheduler->runWithAST("References", File, std::move(Action)); 831 } 832 833 void ClangdServer::symbolInfo(PathRef File, Position Pos, 834 Callback<std::vector<SymbolDetails>> CB) { 835 auto Action = 836 [Pos, CB = std::move(CB)](llvm::Expected<InputsAndAST> InpAST) mutable { 837 if (!InpAST) 838 return CB(InpAST.takeError()); 839 CB(clangd::getSymbolInfo(InpAST->AST, Pos)); 840 }; 841 842 WorkScheduler->runWithAST("SymbolInfo", File, std::move(Action)); 843 } 844 845 void ClangdServer::semanticRanges(PathRef File, 846 const std::vector<Position> &Positions, 847 Callback<std::vector<SelectionRange>> CB) { 848 auto Action = [Positions, CB = std::move(CB)]( 849 llvm::Expected<InputsAndAST> InpAST) mutable { 850 if (!InpAST) 851 return CB(InpAST.takeError()); 852 std::vector<SelectionRange> Result; 853 for (const auto &Pos : Positions) { 854 if (auto Range = clangd::getSemanticRanges(InpAST->AST, Pos)) 855 Result.push_back(std::move(*Range)); 856 else 857 return CB(Range.takeError()); 858 } 859 CB(std::move(Result)); 860 }; 861 WorkScheduler->runWithAST("SemanticRanges", File, std::move(Action)); 862 } 863 864 void ClangdServer::documentLinks(PathRef File, 865 Callback<std::vector<DocumentLink>> CB) { 866 auto Action = 867 [CB = std::move(CB)](llvm::Expected<InputsAndAST> InpAST) mutable { 868 if (!InpAST) 869 return CB(InpAST.takeError()); 870 CB(clangd::getDocumentLinks(InpAST->AST)); 871 }; 872 WorkScheduler->runWithAST("DocumentLinks", File, std::move(Action), 873 Transient); 874 } 875 876 void ClangdServer::semanticHighlights( 877 PathRef File, Callback<std::vector<HighlightingToken>> CB) { 878 auto Action = 879 [CB = std::move(CB)](llvm::Expected<InputsAndAST> InpAST) mutable { 880 if (!InpAST) 881 return CB(InpAST.takeError()); 882 CB(clangd::getSemanticHighlightings(InpAST->AST)); 883 }; 884 WorkScheduler->runWithAST("SemanticHighlights", File, std::move(Action), 885 Transient); 886 } 887 888 void ClangdServer::getAST(PathRef File, llvm::Optional<Range> R, 889 Callback<llvm::Optional<ASTNode>> CB) { 890 auto Action = 891 [R, CB(std::move(CB))](llvm::Expected<InputsAndAST> Inputs) mutable { 892 if (!Inputs) 893 return CB(Inputs.takeError()); 894 if (!R) { 895 // It's safe to pass in the TU, as dumpAST() does not 896 // deserialize the preamble. 897 auto Node = DynTypedNode::create( 898 *Inputs->AST.getASTContext().getTranslationUnitDecl()); 899 return CB(dumpAST(Node, Inputs->AST.getTokens(), 900 Inputs->AST.getASTContext())); 901 } 902 unsigned Start, End; 903 if (auto Offset = positionToOffset(Inputs->Inputs.Contents, R->start)) 904 Start = *Offset; 905 else 906 return CB(Offset.takeError()); 907 if (auto Offset = positionToOffset(Inputs->Inputs.Contents, R->end)) 908 End = *Offset; 909 else 910 return CB(Offset.takeError()); 911 bool Success = SelectionTree::createEach( 912 Inputs->AST.getASTContext(), Inputs->AST.getTokens(), Start, End, 913 [&](SelectionTree T) { 914 if (const SelectionTree::Node *N = T.commonAncestor()) { 915 CB(dumpAST(N->ASTNode, Inputs->AST.getTokens(), 916 Inputs->AST.getASTContext())); 917 return true; 918 } 919 return false; 920 }); 921 if (!Success) 922 CB(llvm::None); 923 }; 924 WorkScheduler->runWithAST("GetAST", File, std::move(Action)); 925 } 926 927 void ClangdServer::customAction(PathRef File, llvm::StringRef Name, 928 Callback<InputsAndAST> Action) { 929 WorkScheduler->runWithAST(Name, File, std::move(Action)); 930 } 931 932 void ClangdServer::diagnostics(PathRef File, Callback<std::vector<Diag>> CB) { 933 auto Action = 934 [CB = std::move(CB)](llvm::Expected<InputsAndAST> InpAST) mutable { 935 if (!InpAST) 936 return CB(InpAST.takeError()); 937 if (auto Diags = InpAST->AST.getDiagnostics()) 938 return CB(*Diags); 939 // FIXME: Use ServerCancelled error once it is settled in LSP-3.17. 940 return CB(llvm::make_error<LSPError>("server is busy parsing includes", 941 ErrorCode::InternalError)); 942 }; 943 944 WorkScheduler->runWithAST("Diagnostics", File, std::move(Action)); 945 } 946 947 llvm::StringMap<TUScheduler::FileStats> ClangdServer::fileStats() const { 948 return WorkScheduler->fileStats(); 949 } 950 951 LLVM_NODISCARD bool 952 ClangdServer::blockUntilIdleForTest(llvm::Optional<double> TimeoutSeconds) { 953 // Order is important here: we don't want to block on A and then B, 954 // if B might schedule work on A. 955 956 // Nothing else can schedule work on TUScheduler, because it's not threadsafe 957 // and we're blocking the main thread. 958 if (!WorkScheduler->blockUntilIdle(timeoutSeconds(TimeoutSeconds))) 959 return false; 960 961 // Unfortunately we don't have strict topological order between the rest of 962 // the components. E.g. CDB broadcast triggers backrgound indexing. 963 // This queries the CDB which may discover new work if disk has changed. 964 // 965 // So try each one a few times in a loop. 966 // If there are no tricky interactions then all after the first are no-ops. 967 // Then on the last iteration, verify they're idle without waiting. 968 // 969 // There's a small chance they're juggling work and we didn't catch them :-( 970 for (llvm::Optional<double> Timeout : 971 {TimeoutSeconds, TimeoutSeconds, llvm::Optional<double>(0)}) { 972 if (!CDB.blockUntilIdle(timeoutSeconds(Timeout))) 973 return false; 974 if (BackgroundIdx && !BackgroundIdx->blockUntilIdleForTest(Timeout)) 975 return false; 976 if (FeatureModules && llvm::any_of(*FeatureModules, [&](FeatureModule &M) { 977 return !M.blockUntilIdle(timeoutSeconds(Timeout)); 978 })) 979 return false; 980 } 981 982 assert(WorkScheduler->blockUntilIdle(Deadline::zero()) && 983 "Something scheduled work while we're blocking the main thread!"); 984 return true; 985 } 986 987 void ClangdServer::profile(MemoryTree &MT) const { 988 if (DynamicIdx) 989 DynamicIdx->profile(MT.child("dynamic_index")); 990 if (BackgroundIdx) 991 BackgroundIdx->profile(MT.child("background_index")); 992 WorkScheduler->profile(MT.child("tuscheduler")); 993 } 994 } // namespace clangd 995 } // namespace clang 996