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 "FindSymbols.h" 12 #include "Format.h" 13 #include "FormattedString.h" 14 #include "HeaderSourceSwitch.h" 15 #include "Headers.h" 16 #include "ParsedAST.h" 17 #include "Preamble.h" 18 #include "Protocol.h" 19 #include "SemanticHighlighting.h" 20 #include "SemanticSelection.h" 21 #include "SourceCode.h" 22 #include "TUScheduler.h" 23 #include "XRefs.h" 24 #include "index/CanonicalIncludes.h" 25 #include "index/FileIndex.h" 26 #include "index/Merge.h" 27 #include "refactor/Rename.h" 28 #include "refactor/Tweak.h" 29 #include "support/Logger.h" 30 #include "support/Trace.h" 31 #include "clang/Format/Format.h" 32 #include "clang/Frontend/CompilerInstance.h" 33 #include "clang/Frontend/CompilerInvocation.h" 34 #include "clang/Lex/Preprocessor.h" 35 #include "clang/Tooling/CompilationDatabase.h" 36 #include "clang/Tooling/Core/Replacement.h" 37 #include "llvm/ADT/ArrayRef.h" 38 #include "llvm/ADT/Optional.h" 39 #include "llvm/ADT/STLExtras.h" 40 #include "llvm/ADT/ScopeExit.h" 41 #include "llvm/ADT/StringRef.h" 42 #include "llvm/Support/Errc.h" 43 #include "llvm/Support/Error.h" 44 #include "llvm/Support/FileSystem.h" 45 #include "llvm/Support/Path.h" 46 #include "llvm/Support/raw_ostream.h" 47 #include <algorithm> 48 #include <future> 49 #include <memory> 50 #include <mutex> 51 #include <type_traits> 52 53 namespace clang { 54 namespace clangd { 55 namespace { 56 57 // Update the FileIndex with new ASTs and plumb the diagnostics responses. 58 struct UpdateIndexCallbacks : public ParsingCallbacks { 59 UpdateIndexCallbacks(FileIndex *FIndex, 60 ClangdServer::Callbacks *ServerCallbacks, 61 bool TheiaSemanticHighlighting) 62 : FIndex(FIndex), ServerCallbacks(ServerCallbacks), 63 TheiaSemanticHighlighting(TheiaSemanticHighlighting) {} 64 65 void onPreambleAST(PathRef Path, llvm::StringRef Version, ASTContext &Ctx, 66 std::shared_ptr<clang::Preprocessor> PP, 67 const CanonicalIncludes &CanonIncludes) override { 68 if (FIndex) 69 FIndex->updatePreamble(Path, Version, Ctx, std::move(PP), CanonIncludes); 70 } 71 72 void onMainAST(PathRef Path, ParsedAST &AST, PublishFn Publish) override { 73 if (FIndex) 74 FIndex->updateMain(Path, AST); 75 76 std::vector<Diag> Diagnostics = AST.getDiagnostics(); 77 std::vector<HighlightingToken> Highlightings; 78 if (TheiaSemanticHighlighting) 79 Highlightings = getSemanticHighlightings(AST); 80 81 if (ServerCallbacks) 82 Publish([&]() { 83 ServerCallbacks->onDiagnosticsReady(Path, AST.version(), 84 std::move(Diagnostics)); 85 if (TheiaSemanticHighlighting) 86 ServerCallbacks->onHighlightingsReady(Path, AST.version(), 87 std::move(Highlightings)); 88 }); 89 } 90 91 void onFailedAST(PathRef Path, llvm::StringRef Version, 92 std::vector<Diag> Diags, PublishFn Publish) override { 93 if (ServerCallbacks) 94 Publish( 95 [&]() { ServerCallbacks->onDiagnosticsReady(Path, Version, Diags); }); 96 } 97 98 void onFileUpdated(PathRef File, const TUStatus &Status) override { 99 if (ServerCallbacks) 100 ServerCallbacks->onFileUpdated(File, Status); 101 } 102 103 private: 104 FileIndex *FIndex; 105 ClangdServer::Callbacks *ServerCallbacks; 106 bool TheiaSemanticHighlighting; 107 }; 108 } // namespace 109 110 ClangdServer::Options ClangdServer::optsForTest() { 111 ClangdServer::Options Opts; 112 Opts.UpdateDebounce = DebouncePolicy::fixed(/*zero*/ {}); 113 Opts.StorePreamblesInMemory = true; 114 Opts.AsyncThreadsCount = 4; // Consistent! 115 Opts.TheiaSemanticHighlighting = true; 116 return Opts; 117 } 118 119 ClangdServer::Options::operator TUScheduler::Options() const { 120 TUScheduler::Options Opts; 121 Opts.AsyncThreadsCount = AsyncThreadsCount; 122 Opts.RetentionPolicy = RetentionPolicy; 123 Opts.StorePreamblesInMemory = StorePreamblesInMemory; 124 Opts.UpdateDebounce = UpdateDebounce; 125 return Opts; 126 } 127 128 ClangdServer::ClangdServer(const GlobalCompilationDatabase &CDB, 129 const FileSystemProvider &FSProvider, 130 const Options &Opts, Callbacks *Callbacks) 131 : FSProvider(FSProvider), 132 DynamicIdx(Opts.BuildDynamicSymbolIndex 133 ? new FileIndex(Opts.HeavyweightDynamicSymbolIndex) 134 : nullptr), 135 GetClangTidyOptions(Opts.GetClangTidyOptions), 136 SuggestMissingIncludes(Opts.SuggestMissingIncludes), 137 BuildRecoveryAST(Opts.BuildRecoveryAST), TweakFilter(Opts.TweakFilter), 138 WorkspaceRoot(Opts.WorkspaceRoot), 139 // Pass a callback into `WorkScheduler` to extract symbols from a newly 140 // parsed file and rebuild the file index synchronously each time an AST 141 // is parsed. 142 // FIXME(ioeric): this can be slow and we may be able to index on less 143 // critical paths. 144 WorkScheduler( 145 CDB, TUScheduler::Options(Opts), 146 std::make_unique<UpdateIndexCallbacks>( 147 DynamicIdx.get(), Callbacks, Opts.TheiaSemanticHighlighting)) { 148 // Adds an index to the stack, at higher priority than existing indexes. 149 auto AddIndex = [&](SymbolIndex *Idx) { 150 if (this->Index != nullptr) { 151 MergedIdx.push_back(std::make_unique<MergedIndex>(Idx, this->Index)); 152 this->Index = MergedIdx.back().get(); 153 } else { 154 this->Index = Idx; 155 } 156 }; 157 if (Opts.StaticIndex) 158 AddIndex(Opts.StaticIndex); 159 if (Opts.BackgroundIndex) { 160 BackgroundIdx = std::make_unique<BackgroundIndex>( 161 Context::current().clone(), FSProvider, CDB, 162 BackgroundIndexStorage::createDiskBackedStorageFactory( 163 [&CDB](llvm::StringRef File) { return CDB.getProjectInfo(File); }), 164 std::max(Opts.AsyncThreadsCount, 1u), 165 [Callbacks](BackgroundQueue::Stats S) { 166 if (Callbacks) 167 Callbacks->onBackgroundIndexProgress(S); 168 }); 169 AddIndex(BackgroundIdx.get()); 170 } 171 if (DynamicIdx) 172 AddIndex(DynamicIdx.get()); 173 } 174 175 void ClangdServer::addDocument(PathRef File, llvm::StringRef Contents, 176 llvm::StringRef Version, 177 WantDiagnostics WantDiags, bool ForceRebuild) { 178 auto FS = FSProvider.getFileSystem(); 179 180 ParseOptions Opts; 181 Opts.ClangTidyOpts = tidy::ClangTidyOptions::getDefaults(); 182 // FIXME: call tidy options builder on the worker thread, it can do IO. 183 if (GetClangTidyOptions) 184 Opts.ClangTidyOpts = GetClangTidyOptions(*FS, File); 185 Opts.SuggestMissingIncludes = SuggestMissingIncludes; 186 187 // Compile command is set asynchronously during update, as it can be slow. 188 ParseInputs Inputs; 189 Inputs.FS = FS; 190 Inputs.Contents = std::string(Contents); 191 Inputs.Version = Version.str(); 192 Inputs.ForceRebuild = ForceRebuild; 193 Inputs.Opts = std::move(Opts); 194 Inputs.Index = Index; 195 Inputs.Opts.BuildRecoveryAST = BuildRecoveryAST; 196 bool NewFile = WorkScheduler.update(File, Inputs, WantDiags); 197 // If we loaded Foo.h, we want to make sure Foo.cpp is indexed. 198 if (NewFile && BackgroundIdx) 199 BackgroundIdx->boostRelated(File); 200 } 201 202 void ClangdServer::removeDocument(PathRef File) { WorkScheduler.remove(File); } 203 204 void ClangdServer::codeComplete(PathRef File, Position Pos, 205 const clangd::CodeCompleteOptions &Opts, 206 Callback<CodeCompleteResult> CB) { 207 // Copy completion options for passing them to async task handler. 208 auto CodeCompleteOpts = Opts; 209 if (!CodeCompleteOpts.Index) // Respect overridden index. 210 CodeCompleteOpts.Index = Index; 211 212 auto Task = [Pos, FS = FSProvider.getFileSystem(), CodeCompleteOpts, 213 File = File.str(), CB = std::move(CB), 214 this](llvm::Expected<InputsAndPreamble> IP) mutable { 215 if (!IP) 216 return CB(IP.takeError()); 217 if (auto Reason = isCancelled()) 218 return CB(llvm::make_error<CancelledError>(Reason)); 219 220 llvm::Optional<SpeculativeFuzzyFind> SpecFuzzyFind; 221 if (!IP->Preamble) { 222 // No speculation in Fallback mode, as it's supposed to be much faster 223 // without compiling. 224 vlog("Build for file {0} is not ready. Enter fallback mode.", File); 225 } else { 226 if (CodeCompleteOpts.Index && CodeCompleteOpts.SpeculativeIndexRequest) { 227 SpecFuzzyFind.emplace(); 228 { 229 std::lock_guard<std::mutex> Lock( 230 CachedCompletionFuzzyFindRequestMutex); 231 SpecFuzzyFind->CachedReq = 232 CachedCompletionFuzzyFindRequestByFile[File]; 233 } 234 } 235 } 236 // FIXME(ibiryukov): even if Preamble is non-null, we may want to check 237 // both the old and the new version in case only one of them matches. 238 CodeCompleteResult Result = clangd::codeComplete( 239 File, IP->Command, IP->Preamble, IP->Contents, Pos, FS, 240 CodeCompleteOpts, SpecFuzzyFind ? SpecFuzzyFind.getPointer() : nullptr); 241 { 242 clang::clangd::trace::Span Tracer("Completion results callback"); 243 CB(std::move(Result)); 244 } 245 if (SpecFuzzyFind && SpecFuzzyFind->NewReq.hasValue()) { 246 std::lock_guard<std::mutex> Lock(CachedCompletionFuzzyFindRequestMutex); 247 CachedCompletionFuzzyFindRequestByFile[File] = 248 SpecFuzzyFind->NewReq.getValue(); 249 } 250 // SpecFuzzyFind is only destroyed after speculative fuzzy find finishes. 251 // We don't want `codeComplete` to wait for the async call if it doesn't use 252 // the result (e.g. non-index completion, speculation fails), so that `CB` 253 // is called as soon as results are available. 254 }; 255 256 // We use a potentially-stale preamble because latency is critical here. 257 WorkScheduler.runWithPreamble( 258 "CodeComplete", File, 259 (Opts.RunParser == CodeCompleteOptions::AlwaysParse) 260 ? TUScheduler::Stale 261 : TUScheduler::StaleOrAbsent, 262 std::move(Task)); 263 } 264 265 void ClangdServer::signatureHelp(PathRef File, Position Pos, 266 Callback<SignatureHelp> CB) { 267 268 auto Action = [Pos, FS = FSProvider.getFileSystem(), File = File.str(), 269 CB = std::move(CB), 270 this](llvm::Expected<InputsAndPreamble> IP) mutable { 271 if (!IP) 272 return CB(IP.takeError()); 273 274 const auto *PreambleData = IP->Preamble; 275 if (!PreambleData) 276 return CB(llvm::createStringError(llvm::inconvertibleErrorCode(), 277 "Failed to parse includes")); 278 279 CB(clangd::signatureHelp(File, IP->Command, *PreambleData, IP->Contents, 280 Pos, FS, Index)); 281 }; 282 283 // Unlike code completion, we wait for a preamble here. 284 WorkScheduler.runWithPreamble("SignatureHelp", File, TUScheduler::Stale, 285 std::move(Action)); 286 } 287 288 llvm::Expected<tooling::Replacements> 289 ClangdServer::formatRange(llvm::StringRef Code, PathRef File, Range Rng) { 290 llvm::Expected<size_t> Begin = positionToOffset(Code, Rng.start); 291 if (!Begin) 292 return Begin.takeError(); 293 llvm::Expected<size_t> End = positionToOffset(Code, Rng.end); 294 if (!End) 295 return End.takeError(); 296 return formatCode(Code, File, {tooling::Range(*Begin, *End - *Begin)}); 297 } 298 299 llvm::Expected<tooling::Replacements> 300 ClangdServer::formatFile(llvm::StringRef Code, PathRef File) { 301 // Format everything. 302 return formatCode(Code, File, {tooling::Range(0, Code.size())}); 303 } 304 305 llvm::Expected<std::vector<TextEdit>> 306 ClangdServer::formatOnType(llvm::StringRef Code, PathRef File, Position Pos, 307 StringRef TriggerText) { 308 llvm::Expected<size_t> CursorPos = positionToOffset(Code, Pos); 309 if (!CursorPos) 310 return CursorPos.takeError(); 311 auto FS = FSProvider.getFileSystem(); 312 auto Style = format::getStyle(format::DefaultFormatStyle, File, 313 format::DefaultFallbackStyle, Code, FS.get()); 314 if (!Style) 315 return Style.takeError(); 316 317 std::vector<TextEdit> Result; 318 for (const tooling::Replacement &R : 319 formatIncremental(Code, *CursorPos, TriggerText, *Style)) 320 Result.push_back(replacementToEdit(Code, R)); 321 return Result; 322 } 323 324 void ClangdServer::prepareRename(PathRef File, Position Pos, 325 const RenameOptions &RenameOpts, 326 Callback<llvm::Optional<Range>> CB) { 327 auto Action = [Pos, File = File.str(), CB = std::move(CB), RenameOpts, 328 this](llvm::Expected<InputsAndAST> InpAST) mutable { 329 if (!InpAST) 330 return CB(InpAST.takeError()); 331 auto &AST = InpAST->AST; 332 const auto &SM = AST.getSourceManager(); 333 auto Loc = sourceLocationInMainFile(SM, Pos); 334 if (!Loc) 335 return CB(Loc.takeError()); 336 const auto *TouchingIdentifier = 337 spelledIdentifierTouching(*Loc, AST.getTokens()); 338 if (!TouchingIdentifier) 339 return CB(llvm::None); // no rename on non-identifiers. 340 341 auto Range = halfOpenToRange( 342 SM, CharSourceRange::getCharRange(TouchingIdentifier->location(), 343 TouchingIdentifier->endLocation())); 344 345 if (RenameOpts.AllowCrossFile) 346 // FIXME: we now assume cross-file rename always succeeds, revisit this. 347 return CB(Range); 348 349 // Performing the local rename isn't substantially more expensive than 350 // doing an AST-based check, so we just rename and throw away the results. 351 auto Changes = clangd::rename({Pos, "dummy", AST, File, Index, RenameOpts, 352 /*GetDirtyBuffer=*/nullptr}); 353 if (!Changes) { 354 // LSP says to return null on failure, but that will result in a generic 355 // failure message. If we send an LSP error response, clients can surface 356 // the message to users (VSCode does). 357 return CB(Changes.takeError()); 358 } 359 return CB(Range); 360 }; 361 WorkScheduler.runWithAST("PrepareRename", File, std::move(Action)); 362 } 363 364 void ClangdServer::rename(PathRef File, Position Pos, llvm::StringRef NewName, 365 const RenameOptions &Opts, Callback<FileEdits> CB) { 366 // A snapshot of all file dirty buffers. 367 llvm::StringMap<std::string> Snapshot = WorkScheduler.getAllFileContents(); 368 auto Action = [File = File.str(), NewName = NewName.str(), Pos, Opts, 369 CB = std::move(CB), Snapshot = std::move(Snapshot), 370 this](llvm::Expected<InputsAndAST> InpAST) mutable { 371 if (!InpAST) 372 return CB(InpAST.takeError()); 373 auto GetDirtyBuffer = 374 [&Snapshot](PathRef AbsPath) -> llvm::Optional<std::string> { 375 auto It = Snapshot.find(AbsPath); 376 if (It == Snapshot.end()) 377 return llvm::None; 378 return It->second; 379 }; 380 auto Edits = clangd::rename( 381 {Pos, NewName, InpAST->AST, File, Index, Opts, GetDirtyBuffer}); 382 if (!Edits) 383 return CB(Edits.takeError()); 384 385 if (Opts.WantFormat) { 386 auto Style = getFormatStyleForFile(File, InpAST->Inputs.Contents, 387 InpAST->Inputs.FS.get()); 388 llvm::Error Err = llvm::Error::success(); 389 for (auto &E : *Edits) 390 Err = 391 llvm::joinErrors(reformatEdit(E.getValue(), Style), std::move(Err)); 392 393 if (Err) 394 return CB(std::move(Err)); 395 } 396 return CB(std::move(*Edits)); 397 }; 398 WorkScheduler.runWithAST("Rename", File, std::move(Action)); 399 } 400 401 // May generate several candidate selections, due to SelectionTree ambiguity. 402 // vector of pointers because GCC doesn't like non-copyable Selection. 403 static llvm::Expected<std::vector<std::unique_ptr<Tweak::Selection>>> 404 tweakSelection(const Range &Sel, const InputsAndAST &AST) { 405 auto Begin = positionToOffset(AST.Inputs.Contents, Sel.start); 406 if (!Begin) 407 return Begin.takeError(); 408 auto End = positionToOffset(AST.Inputs.Contents, Sel.end); 409 if (!End) 410 return End.takeError(); 411 std::vector<std::unique_ptr<Tweak::Selection>> Result; 412 SelectionTree::createEach( 413 AST.AST.getASTContext(), AST.AST.getTokens(), *Begin, *End, 414 [&](SelectionTree T) { 415 Result.push_back(std::make_unique<Tweak::Selection>( 416 AST.Inputs.Index, AST.AST, *Begin, *End, std::move(T))); 417 return false; 418 }); 419 assert(!Result.empty() && "Expected at least one SelectionTree"); 420 return std::move(Result); 421 } 422 423 void ClangdServer::enumerateTweaks(PathRef File, Range Sel, 424 Callback<std::vector<TweakRef>> CB) { 425 auto Action = [File = File.str(), Sel, CB = std::move(CB), 426 this](Expected<InputsAndAST> InpAST) mutable { 427 if (!InpAST) 428 return CB(InpAST.takeError()); 429 auto Selections = tweakSelection(Sel, *InpAST); 430 if (!Selections) 431 return CB(Selections.takeError()); 432 std::vector<TweakRef> Res; 433 // Don't allow a tweak to fire more than once across ambiguous selections. 434 llvm::DenseSet<llvm::StringRef> PreparedTweaks; 435 auto Filter = [&](const Tweak &T) { 436 return TweakFilter(T) && !PreparedTweaks.count(T.id()); 437 }; 438 for (const auto &Sel : *Selections) { 439 for (auto &T : prepareTweaks(*Sel, Filter)) { 440 Res.push_back({T->id(), T->title(), T->intent()}); 441 PreparedTweaks.insert(T->id()); 442 } 443 } 444 445 CB(std::move(Res)); 446 }; 447 448 WorkScheduler.runWithAST("EnumerateTweaks", File, std::move(Action), 449 TUScheduler::InvalidateOnUpdate); 450 } 451 452 void ClangdServer::applyTweak(PathRef File, Range Sel, StringRef TweakID, 453 Callback<Tweak::Effect> CB) { 454 auto Action = 455 [File = File.str(), Sel, TweakID = TweakID.str(), CB = std::move(CB), 456 FS = FSProvider.getFileSystem()](Expected<InputsAndAST> InpAST) mutable { 457 if (!InpAST) 458 return CB(InpAST.takeError()); 459 auto Selections = tweakSelection(Sel, *InpAST); 460 if (!Selections) 461 return CB(Selections.takeError()); 462 llvm::Optional<llvm::Expected<Tweak::Effect>> Effect; 463 // Try each selection, take the first one that prepare()s. 464 // If they all fail, Effect will hold get the last error. 465 for (const auto &Selection : *Selections) { 466 auto T = prepareTweak(TweakID, *Selection); 467 if (T) { 468 Effect = (*T)->apply(*Selection); 469 break; 470 } 471 Effect = T.takeError(); 472 } 473 assert(Effect.hasValue() && "Expected at least one selection"); 474 if (*Effect) { 475 // Tweaks don't apply clang-format, do that centrally here. 476 for (auto &It : (*Effect)->ApplyEdits) { 477 Edit &E = It.second; 478 format::FormatStyle Style = 479 getFormatStyleForFile(File, E.InitialCode, FS.get()); 480 if (llvm::Error Err = reformatEdit(E, Style)) 481 elog("Failed to format {0}: {1}", It.first(), std::move(Err)); 482 } 483 } 484 return CB(std::move(*Effect)); 485 }; 486 WorkScheduler.runWithAST("ApplyTweak", File, std::move(Action)); 487 } 488 489 void ClangdServer::dumpAST(PathRef File, 490 llvm::unique_function<void(std::string)> Callback) { 491 auto Action = [Callback = std::move(Callback)]( 492 llvm::Expected<InputsAndAST> InpAST) mutable { 493 if (!InpAST) { 494 llvm::consumeError(InpAST.takeError()); 495 return Callback("<no-ast>"); 496 } 497 std::string Result; 498 499 llvm::raw_string_ostream ResultOS(Result); 500 clangd::dumpAST(InpAST->AST, ResultOS); 501 ResultOS.flush(); 502 503 Callback(Result); 504 }; 505 506 WorkScheduler.runWithAST("DumpAST", File, std::move(Action)); 507 } 508 509 void ClangdServer::locateSymbolAt(PathRef File, Position Pos, 510 Callback<std::vector<LocatedSymbol>> CB) { 511 auto Action = [Pos, CB = std::move(CB), 512 this](llvm::Expected<InputsAndAST> InpAST) mutable { 513 if (!InpAST) 514 return CB(InpAST.takeError()); 515 CB(clangd::locateSymbolAt(InpAST->AST, Pos, Index)); 516 }; 517 518 WorkScheduler.runWithAST("Definitions", File, std::move(Action)); 519 } 520 521 void ClangdServer::switchSourceHeader( 522 PathRef Path, Callback<llvm::Optional<clangd::Path>> CB) { 523 // We want to return the result as fast as possible, strategy is: 524 // 1) use the file-only heuristic, it requires some IO but it is much 525 // faster than building AST, but it only works when .h/.cc files are in 526 // the same directory. 527 // 2) if 1) fails, we use the AST&Index approach, it is slower but supports 528 // different code layout. 529 if (auto CorrespondingFile = getCorrespondingHeaderOrSource( 530 std::string(Path), FSProvider.getFileSystem())) 531 return CB(std::move(CorrespondingFile)); 532 auto Action = [Path = Path.str(), CB = std::move(CB), 533 this](llvm::Expected<InputsAndAST> InpAST) mutable { 534 if (!InpAST) 535 return CB(InpAST.takeError()); 536 CB(getCorrespondingHeaderOrSource(Path, InpAST->AST, Index)); 537 }; 538 WorkScheduler.runWithAST("SwitchHeaderSource", Path, std::move(Action)); 539 } 540 541 llvm::Expected<tooling::Replacements> 542 ClangdServer::formatCode(llvm::StringRef Code, PathRef File, 543 llvm::ArrayRef<tooling::Range> Ranges) { 544 // Call clang-format. 545 format::FormatStyle Style = 546 getFormatStyleForFile(File, Code, FSProvider.getFileSystem().get()); 547 tooling::Replacements IncludeReplaces = 548 format::sortIncludes(Style, Code, Ranges, File); 549 auto Changed = tooling::applyAllReplacements(Code, IncludeReplaces); 550 if (!Changed) 551 return Changed.takeError(); 552 553 return IncludeReplaces.merge(format::reformat( 554 Style, *Changed, 555 tooling::calculateRangesAfterReplacements(IncludeReplaces, Ranges), 556 File)); 557 } 558 559 void ClangdServer::findDocumentHighlights( 560 PathRef File, Position Pos, Callback<std::vector<DocumentHighlight>> CB) { 561 auto Action = 562 [Pos, CB = std::move(CB)](llvm::Expected<InputsAndAST> InpAST) mutable { 563 if (!InpAST) 564 return CB(InpAST.takeError()); 565 CB(clangd::findDocumentHighlights(InpAST->AST, Pos)); 566 }; 567 568 WorkScheduler.runWithAST("Highlights", File, std::move(Action), 569 TUScheduler::InvalidateOnUpdate); 570 } 571 572 void ClangdServer::findHover(PathRef File, Position Pos, 573 Callback<llvm::Optional<HoverInfo>> CB) { 574 auto Action = [File = File.str(), Pos, CB = std::move(CB), 575 this](llvm::Expected<InputsAndAST> InpAST) mutable { 576 if (!InpAST) 577 return CB(InpAST.takeError()); 578 format::FormatStyle Style = getFormatStyleForFile( 579 File, InpAST->Inputs.Contents, InpAST->Inputs.FS.get()); 580 CB(clangd::getHover(InpAST->AST, Pos, std::move(Style), Index)); 581 }; 582 583 WorkScheduler.runWithAST("Hover", File, std::move(Action), 584 TUScheduler::InvalidateOnUpdate); 585 } 586 587 void ClangdServer::typeHierarchy(PathRef File, Position Pos, int Resolve, 588 TypeHierarchyDirection Direction, 589 Callback<Optional<TypeHierarchyItem>> CB) { 590 auto Action = [File = File.str(), Pos, Resolve, Direction, CB = std::move(CB), 591 this](Expected<InputsAndAST> InpAST) mutable { 592 if (!InpAST) 593 return CB(InpAST.takeError()); 594 CB(clangd::getTypeHierarchy(InpAST->AST, Pos, Resolve, Direction, Index, 595 File)); 596 }; 597 598 WorkScheduler.runWithAST("Type Hierarchy", File, std::move(Action)); 599 } 600 601 void ClangdServer::resolveTypeHierarchy( 602 TypeHierarchyItem Item, int Resolve, TypeHierarchyDirection Direction, 603 Callback<llvm::Optional<TypeHierarchyItem>> CB) { 604 clangd::resolveTypeHierarchy(Item, Resolve, Direction, Index); 605 CB(Item); 606 } 607 608 void ClangdServer::onFileEvent(const DidChangeWatchedFilesParams &Params) { 609 // FIXME: Do nothing for now. This will be used for indexing and potentially 610 // invalidating other caches. 611 } 612 613 void ClangdServer::workspaceSymbols( 614 llvm::StringRef Query, int Limit, 615 Callback<std::vector<SymbolInformation>> CB) { 616 WorkScheduler.run( 617 "getWorkspaceSymbols", 618 [Query = Query.str(), Limit, CB = std::move(CB), this]() mutable { 619 CB(clangd::getWorkspaceSymbols(Query, Limit, Index, 620 WorkspaceRoot.getValueOr(""))); 621 }); 622 } 623 624 void ClangdServer::documentSymbols(llvm::StringRef File, 625 Callback<std::vector<DocumentSymbol>> CB) { 626 auto Action = 627 [CB = std::move(CB)](llvm::Expected<InputsAndAST> InpAST) mutable { 628 if (!InpAST) 629 return CB(InpAST.takeError()); 630 CB(clangd::getDocumentSymbols(InpAST->AST)); 631 }; 632 WorkScheduler.runWithAST("documentSymbols", File, std::move(Action), 633 TUScheduler::InvalidateOnUpdate); 634 } 635 636 void ClangdServer::findReferences(PathRef File, Position Pos, uint32_t Limit, 637 Callback<ReferencesResult> CB) { 638 auto Action = [Pos, Limit, CB = std::move(CB), 639 this](llvm::Expected<InputsAndAST> InpAST) mutable { 640 if (!InpAST) 641 return CB(InpAST.takeError()); 642 CB(clangd::findReferences(InpAST->AST, Pos, Limit, Index)); 643 }; 644 645 WorkScheduler.runWithAST("References", File, std::move(Action)); 646 } 647 648 void ClangdServer::symbolInfo(PathRef File, Position Pos, 649 Callback<std::vector<SymbolDetails>> CB) { 650 auto Action = 651 [Pos, CB = std::move(CB)](llvm::Expected<InputsAndAST> InpAST) mutable { 652 if (!InpAST) 653 return CB(InpAST.takeError()); 654 CB(clangd::getSymbolInfo(InpAST->AST, Pos)); 655 }; 656 657 WorkScheduler.runWithAST("SymbolInfo", File, std::move(Action)); 658 } 659 660 void ClangdServer::semanticRanges(PathRef File, 661 const std::vector<Position> &Positions, 662 Callback<std::vector<SelectionRange>> CB) { 663 auto Action = [Positions, CB = std::move(CB)]( 664 llvm::Expected<InputsAndAST> InpAST) mutable { 665 if (!InpAST) 666 return CB(InpAST.takeError()); 667 std::vector<SelectionRange> Result; 668 for (const auto &Pos : Positions) { 669 if (auto Range = clangd::getSemanticRanges(InpAST->AST, Pos)) 670 Result.push_back(std::move(*Range)); 671 else 672 return CB(Range.takeError()); 673 } 674 CB(std::move(Result)); 675 }; 676 WorkScheduler.runWithAST("SemanticRanges", File, std::move(Action)); 677 } 678 679 void ClangdServer::documentLinks(PathRef File, 680 Callback<std::vector<DocumentLink>> CB) { 681 auto Action = 682 [CB = std::move(CB)](llvm::Expected<InputsAndAST> InpAST) mutable { 683 if (!InpAST) 684 return CB(InpAST.takeError()); 685 CB(clangd::getDocumentLinks(InpAST->AST)); 686 }; 687 WorkScheduler.runWithAST("DocumentLinks", File, std::move(Action), 688 TUScheduler::InvalidateOnUpdate); 689 } 690 691 void ClangdServer::semanticHighlights( 692 PathRef File, Callback<std::vector<HighlightingToken>> CB) { 693 auto Action = 694 [CB = std::move(CB)](llvm::Expected<InputsAndAST> InpAST) mutable { 695 if (!InpAST) 696 return CB(InpAST.takeError()); 697 CB(clangd::getSemanticHighlightings(InpAST->AST)); 698 }; 699 WorkScheduler.runWithAST("SemanticHighlights", File, std::move(Action), 700 TUScheduler::InvalidateOnUpdate); 701 } 702 703 llvm::StringMap<TUScheduler::FileStats> ClangdServer::fileStats() const { 704 return WorkScheduler.fileStats(); 705 } 706 707 LLVM_NODISCARD bool 708 ClangdServer::blockUntilIdleForTest(llvm::Optional<double> TimeoutSeconds) { 709 return WorkScheduler.blockUntilIdle(timeoutSeconds(TimeoutSeconds)) && 710 (!BackgroundIdx || 711 BackgroundIdx->blockUntilIdleForTest(TimeoutSeconds)); 712 } 713 714 } // namespace clangd 715 } // namespace clang 716