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                      Preprocessor &PP,
75                      const CanonicalIncludes &CanonIncludes) override {
76     if (FIndex)
77       FIndex->updatePreamble(Path, Version, Ctx, 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       UseDirtyHeaders(Opts.UseDirtyHeaders), 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 = &getHeaderFS();
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, &getHeaderFS(), IP->Contents.str()};
372     // FIXME: Add traling new line if there is none at eof, workaround a crash,
373     // see https://github.com/clangd/clangd/issues/332
374     if (!IP->Contents.endswith("\n"))
375       ParseInput.Contents.append("\n");
376     ParseInput.Index = Index;
377 
378     CodeCompleteOpts.MainFileSignals = IP->Signals;
379     CodeCompleteOpts.AllScopes = Config::current().Completion.AllScopes;
380     // FIXME(ibiryukov): even if Preamble is non-null, we may want to check
381     // both the old and the new version in case only one of them matches.
382     CodeCompleteResult Result = clangd::codeComplete(
383         File, Pos, IP->Preamble, ParseInput, CodeCompleteOpts,
384         SpecFuzzyFind ? SpecFuzzyFind.getPointer() : nullptr);
385     {
386       clang::clangd::trace::Span Tracer("Completion results callback");
387       CB(std::move(Result));
388     }
389     if (SpecFuzzyFind && SpecFuzzyFind->NewReq.hasValue()) {
390       std::lock_guard<std::mutex> Lock(CachedCompletionFuzzyFindRequestMutex);
391       CachedCompletionFuzzyFindRequestByFile[File] =
392           SpecFuzzyFind->NewReq.getValue();
393     }
394     // SpecFuzzyFind is only destroyed after speculative fuzzy find finishes.
395     // We don't want `codeComplete` to wait for the async call if it doesn't use
396     // the result (e.g. non-index completion, speculation fails), so that `CB`
397     // is called as soon as results are available.
398   };
399 
400   // We use a potentially-stale preamble because latency is critical here.
401   WorkScheduler->runWithPreamble(
402       "CodeComplete", File,
403       (Opts.RunParser == CodeCompleteOptions::AlwaysParse)
404           ? TUScheduler::Stale
405           : TUScheduler::StaleOrAbsent,
406       std::move(Task));
407 }
408 
409 void ClangdServer::signatureHelp(PathRef File, Position Pos,
410                                  MarkupKind DocumentationFormat,
411                                  Callback<SignatureHelp> CB) {
412 
413   auto Action = [Pos, File = File.str(), CB = std::move(CB),
414                  DocumentationFormat,
415                  this](llvm::Expected<InputsAndPreamble> IP) mutable {
416     if (!IP)
417       return CB(IP.takeError());
418 
419     const auto *PreambleData = IP->Preamble;
420     if (!PreambleData)
421       return CB(error("Failed to parse includes"));
422 
423     ParseInputs ParseInput{IP->Command, &getHeaderFS(), IP->Contents.str()};
424     // FIXME: Add traling new line if there is none at eof, workaround a crash,
425     // see https://github.com/clangd/clangd/issues/332
426     if (!IP->Contents.endswith("\n"))
427       ParseInput.Contents.append("\n");
428     ParseInput.Index = Index;
429     CB(clangd::signatureHelp(File, Pos, *PreambleData, ParseInput,
430                              DocumentationFormat));
431   };
432 
433   // Unlike code completion, we wait for a preamble here.
434   WorkScheduler->runWithPreamble("SignatureHelp", File, TUScheduler::Stale,
435                                  std::move(Action));
436 }
437 
438 void ClangdServer::formatFile(PathRef File, llvm::Optional<Range> Rng,
439                               Callback<tooling::Replacements> CB) {
440   auto Code = getDraft(File);
441   if (!Code)
442     return CB(llvm::make_error<LSPError>("trying to format non-added document",
443                                          ErrorCode::InvalidParams));
444   tooling::Range RequestedRange;
445   if (Rng) {
446     llvm::Expected<size_t> Begin = positionToOffset(*Code, Rng->start);
447     if (!Begin)
448       return CB(Begin.takeError());
449     llvm::Expected<size_t> End = positionToOffset(*Code, Rng->end);
450     if (!End)
451       return CB(End.takeError());
452     RequestedRange = tooling::Range(*Begin, *End - *Begin);
453   } else {
454     RequestedRange = tooling::Range(0, Code->size());
455   }
456 
457   // Call clang-format.
458   auto Action = [File = File.str(), Code = std::move(*Code),
459                  Ranges = std::vector<tooling::Range>{RequestedRange},
460                  CB = std::move(CB), this]() mutable {
461     format::FormatStyle Style = getFormatStyleForFile(File, Code, TFS);
462     tooling::Replacements IncludeReplaces =
463         format::sortIncludes(Style, Code, Ranges, File);
464     auto Changed = tooling::applyAllReplacements(Code, IncludeReplaces);
465     if (!Changed)
466       return CB(Changed.takeError());
467 
468     CB(IncludeReplaces.merge(format::reformat(
469         Style, *Changed,
470         tooling::calculateRangesAfterReplacements(IncludeReplaces, Ranges),
471         File)));
472   };
473   WorkScheduler->runQuick("Format", File, std::move(Action));
474 }
475 
476 void ClangdServer::formatOnType(PathRef File, Position Pos,
477                                 StringRef TriggerText,
478                                 Callback<std::vector<TextEdit>> CB) {
479   auto Code = getDraft(File);
480   if (!Code)
481     return CB(llvm::make_error<LSPError>("trying to format non-added document",
482                                          ErrorCode::InvalidParams));
483   llvm::Expected<size_t> CursorPos = positionToOffset(*Code, Pos);
484   if (!CursorPos)
485     return CB(CursorPos.takeError());
486   auto Action = [File = File.str(), Code = std::move(*Code),
487                  TriggerText = TriggerText.str(), CursorPos = *CursorPos,
488                  CB = std::move(CB), this]() mutable {
489     auto Style = format::getStyle(format::DefaultFormatStyle, File,
490                                   format::DefaultFallbackStyle, Code,
491                                   TFS.view(/*CWD=*/llvm::None).get());
492     if (!Style)
493       return CB(Style.takeError());
494 
495     std::vector<TextEdit> Result;
496     for (const tooling::Replacement &R :
497          formatIncremental(Code, CursorPos, TriggerText, *Style))
498       Result.push_back(replacementToEdit(Code, R));
499     return CB(Result);
500   };
501   WorkScheduler->runQuick("FormatOnType", File, std::move(Action));
502 }
503 
504 void ClangdServer::prepareRename(PathRef File, Position Pos,
505                                  llvm::Optional<std::string> NewName,
506                                  const RenameOptions &RenameOpts,
507                                  Callback<RenameResult> CB) {
508   auto Action = [Pos, File = File.str(), CB = std::move(CB),
509                  NewName = std::move(NewName),
510                  RenameOpts](llvm::Expected<InputsAndAST> InpAST) mutable {
511     if (!InpAST)
512       return CB(InpAST.takeError());
513     // prepareRename is latency-sensitive: we don't query the index, as we
514     // only need main-file references
515     auto Results =
516         clangd::rename({Pos, NewName.getValueOr("__clangd_rename_placeholder"),
517                         InpAST->AST, File, /*FS=*/nullptr,
518                         /*Index=*/nullptr, RenameOpts});
519     if (!Results) {
520       // LSP says to return null on failure, but that will result in a generic
521       // failure message. If we send an LSP error response, clients can surface
522       // the message to users (VSCode does).
523       return CB(Results.takeError());
524     }
525     return CB(*Results);
526   };
527   WorkScheduler->runWithAST("PrepareRename", File, std::move(Action));
528 }
529 
530 void ClangdServer::rename(PathRef File, Position Pos, llvm::StringRef NewName,
531                           const RenameOptions &Opts,
532                           Callback<RenameResult> CB) {
533   auto Action = [File = File.str(), NewName = NewName.str(), Pos, Opts,
534                  CB = std::move(CB),
535                  this](llvm::Expected<InputsAndAST> InpAST) mutable {
536     // Tracks number of files edited per invocation.
537     static constexpr trace::Metric RenameFiles("rename_files",
538                                                trace::Metric::Distribution);
539     if (!InpAST)
540       return CB(InpAST.takeError());
541     auto R = clangd::rename({Pos, NewName, InpAST->AST, File,
542                              DirtyFS->view(llvm::None), Index, Opts});
543     if (!R)
544       return CB(R.takeError());
545 
546     if (Opts.WantFormat) {
547       auto Style = getFormatStyleForFile(File, InpAST->Inputs.Contents,
548                                          *InpAST->Inputs.TFS);
549       llvm::Error Err = llvm::Error::success();
550       for (auto &E : R->GlobalChanges)
551         Err =
552             llvm::joinErrors(reformatEdit(E.getValue(), Style), std::move(Err));
553 
554       if (Err)
555         return CB(std::move(Err));
556     }
557     RenameFiles.record(R->GlobalChanges.size());
558     return CB(*R);
559   };
560   WorkScheduler->runWithAST("Rename", File, std::move(Action));
561 }
562 
563 // May generate several candidate selections, due to SelectionTree ambiguity.
564 // vector of pointers because GCC doesn't like non-copyable Selection.
565 static llvm::Expected<std::vector<std::unique_ptr<Tweak::Selection>>>
566 tweakSelection(const Range &Sel, const InputsAndAST &AST,
567                llvm::vfs::FileSystem *FS) {
568   auto Begin = positionToOffset(AST.Inputs.Contents, Sel.start);
569   if (!Begin)
570     return Begin.takeError();
571   auto End = positionToOffset(AST.Inputs.Contents, Sel.end);
572   if (!End)
573     return End.takeError();
574   std::vector<std::unique_ptr<Tweak::Selection>> Result;
575   SelectionTree::createEach(
576       AST.AST.getASTContext(), AST.AST.getTokens(), *Begin, *End,
577       [&](SelectionTree T) {
578         Result.push_back(std::make_unique<Tweak::Selection>(
579             AST.Inputs.Index, AST.AST, *Begin, *End, std::move(T), FS));
580         return false;
581       });
582   assert(!Result.empty() && "Expected at least one SelectionTree");
583   return std::move(Result);
584 }
585 
586 void ClangdServer::enumerateTweaks(
587     PathRef File, Range Sel, llvm::unique_function<bool(const Tweak &)> Filter,
588     Callback<std::vector<TweakRef>> CB) {
589   // Tracks number of times a tweak has been offered.
590   static constexpr trace::Metric TweakAvailable(
591       "tweak_available", trace::Metric::Counter, "tweak_id");
592   auto Action = [Sel, CB = std::move(CB), Filter = std::move(Filter),
593                  FeatureModules(this->FeatureModules)](
594                     Expected<InputsAndAST> InpAST) mutable {
595     if (!InpAST)
596       return CB(InpAST.takeError());
597     auto Selections = tweakSelection(Sel, *InpAST, /*FS=*/nullptr);
598     if (!Selections)
599       return CB(Selections.takeError());
600     std::vector<TweakRef> Res;
601     // Don't allow a tweak to fire more than once across ambiguous selections.
602     llvm::DenseSet<llvm::StringRef> PreparedTweaks;
603     auto DeduplicatingFilter = [&](const Tweak &T) {
604       return Filter(T) && !PreparedTweaks.count(T.id());
605     };
606     for (const auto &Sel : *Selections) {
607       for (auto &T : prepareTweaks(*Sel, DeduplicatingFilter, FeatureModules)) {
608         Res.push_back({T->id(), T->title(), T->kind()});
609         PreparedTweaks.insert(T->id());
610         TweakAvailable.record(1, T->id());
611       }
612     }
613 
614     CB(std::move(Res));
615   };
616 
617   WorkScheduler->runWithAST("EnumerateTweaks", File, std::move(Action),
618                             Transient);
619 }
620 
621 void ClangdServer::applyTweak(PathRef File, Range Sel, StringRef TweakID,
622                               Callback<Tweak::Effect> CB) {
623   // Tracks number of times a tweak has been attempted.
624   static constexpr trace::Metric TweakAttempt(
625       "tweak_attempt", trace::Metric::Counter, "tweak_id");
626   // Tracks number of times a tweak has failed to produce edits.
627   static constexpr trace::Metric TweakFailed(
628       "tweak_failed", trace::Metric::Counter, "tweak_id");
629   TweakAttempt.record(1, TweakID);
630   auto Action = [File = File.str(), Sel, TweakID = TweakID.str(),
631                  CB = std::move(CB),
632                  this](Expected<InputsAndAST> InpAST) mutable {
633     if (!InpAST)
634       return CB(InpAST.takeError());
635     auto FS = DirtyFS->view(llvm::None);
636     auto Selections = tweakSelection(Sel, *InpAST, FS.get());
637     if (!Selections)
638       return CB(Selections.takeError());
639     llvm::Optional<llvm::Expected<Tweak::Effect>> Effect;
640     // Try each selection, take the first one that prepare()s.
641     // If they all fail, Effect will hold get the last error.
642     for (const auto &Selection : *Selections) {
643       auto T = prepareTweak(TweakID, *Selection, FeatureModules);
644       if (T) {
645         Effect = (*T)->apply(*Selection);
646         break;
647       }
648       Effect = T.takeError();
649     }
650     assert(Effect.hasValue() && "Expected at least one selection");
651     if (*Effect && (*Effect)->FormatEdits) {
652       // Format tweaks that require it centrally here.
653       for (auto &It : (*Effect)->ApplyEdits) {
654         Edit &E = It.second;
655         format::FormatStyle Style =
656             getFormatStyleForFile(File, E.InitialCode, TFS);
657         if (llvm::Error Err = reformatEdit(E, Style))
658           elog("Failed to format {0}: {1}", It.first(), std::move(Err));
659       }
660     } else {
661       TweakFailed.record(1, TweakID);
662     }
663     return CB(std::move(*Effect));
664   };
665   WorkScheduler->runWithAST("ApplyTweak", File, std::move(Action));
666 }
667 
668 void ClangdServer::locateSymbolAt(PathRef File, Position Pos,
669                                   Callback<std::vector<LocatedSymbol>> CB) {
670   auto Action = [Pos, CB = std::move(CB),
671                  this](llvm::Expected<InputsAndAST> InpAST) mutable {
672     if (!InpAST)
673       return CB(InpAST.takeError());
674     CB(clangd::locateSymbolAt(InpAST->AST, Pos, Index));
675   };
676 
677   WorkScheduler->runWithAST("Definitions", File, std::move(Action));
678 }
679 
680 void ClangdServer::switchSourceHeader(
681     PathRef Path, Callback<llvm::Optional<clangd::Path>> CB) {
682   // We want to return the result as fast as possible, strategy is:
683   //  1) use the file-only heuristic, it requires some IO but it is much
684   //     faster than building AST, but it only works when .h/.cc files are in
685   //     the same directory.
686   //  2) if 1) fails, we use the AST&Index approach, it is slower but supports
687   //     different code layout.
688   if (auto CorrespondingFile =
689           getCorrespondingHeaderOrSource(Path, TFS.view(llvm::None)))
690     return CB(std::move(CorrespondingFile));
691   auto Action = [Path = Path.str(), CB = std::move(CB),
692                  this](llvm::Expected<InputsAndAST> InpAST) mutable {
693     if (!InpAST)
694       return CB(InpAST.takeError());
695     CB(getCorrespondingHeaderOrSource(Path, InpAST->AST, Index));
696   };
697   WorkScheduler->runWithAST("SwitchHeaderSource", Path, std::move(Action));
698 }
699 
700 void ClangdServer::findDocumentHighlights(
701     PathRef File, Position Pos, Callback<std::vector<DocumentHighlight>> CB) {
702   auto Action =
703       [Pos, CB = std::move(CB)](llvm::Expected<InputsAndAST> InpAST) mutable {
704         if (!InpAST)
705           return CB(InpAST.takeError());
706         CB(clangd::findDocumentHighlights(InpAST->AST, Pos));
707       };
708 
709   WorkScheduler->runWithAST("Highlights", File, std::move(Action), Transient);
710 }
711 
712 void ClangdServer::findHover(PathRef File, Position Pos,
713                              Callback<llvm::Optional<HoverInfo>> CB) {
714   auto Action = [File = File.str(), Pos, CB = std::move(CB),
715                  this](llvm::Expected<InputsAndAST> InpAST) mutable {
716     if (!InpAST)
717       return CB(InpAST.takeError());
718     format::FormatStyle Style = getFormatStyleForFile(
719         File, InpAST->Inputs.Contents, *InpAST->Inputs.TFS);
720     CB(clangd::getHover(InpAST->AST, Pos, std::move(Style), Index));
721   };
722 
723   WorkScheduler->runWithAST("Hover", File, std::move(Action), Transient);
724 }
725 
726 void ClangdServer::typeHierarchy(PathRef File, Position Pos, int Resolve,
727                                  TypeHierarchyDirection Direction,
728                                  Callback<Optional<TypeHierarchyItem>> CB) {
729   auto Action = [File = File.str(), Pos, Resolve, Direction, CB = std::move(CB),
730                  this](Expected<InputsAndAST> InpAST) mutable {
731     if (!InpAST)
732       return CB(InpAST.takeError());
733     CB(clangd::getTypeHierarchy(InpAST->AST, Pos, Resolve, Direction, Index,
734                                 File));
735   };
736 
737   WorkScheduler->runWithAST("TypeHierarchy", File, std::move(Action));
738 }
739 
740 void ClangdServer::resolveTypeHierarchy(
741     TypeHierarchyItem Item, int Resolve, TypeHierarchyDirection Direction,
742     Callback<llvm::Optional<TypeHierarchyItem>> CB) {
743   WorkScheduler->run(
744       "Resolve Type Hierarchy", "", [=, CB = std::move(CB)]() mutable {
745         clangd::resolveTypeHierarchy(Item, Resolve, Direction, Index);
746         CB(Item);
747       });
748 }
749 
750 void ClangdServer::prepareCallHierarchy(
751     PathRef File, Position Pos, Callback<std::vector<CallHierarchyItem>> CB) {
752   auto Action = [File = File.str(), Pos,
753                  CB = std::move(CB)](Expected<InputsAndAST> InpAST) mutable {
754     if (!InpAST)
755       return CB(InpAST.takeError());
756     CB(clangd::prepareCallHierarchy(InpAST->AST, Pos, File));
757   };
758   WorkScheduler->runWithAST("CallHierarchy", File, std::move(Action));
759 }
760 
761 void ClangdServer::incomingCalls(
762     const CallHierarchyItem &Item,
763     Callback<std::vector<CallHierarchyIncomingCall>> CB) {
764   WorkScheduler->run("Incoming Calls", "",
765                      [CB = std::move(CB), Item, this]() mutable {
766                        CB(clangd::incomingCalls(Item, Index));
767                      });
768 }
769 
770 void ClangdServer::inlayHints(PathRef File, llvm::Optional<Range> RestrictRange,
771                               Callback<std::vector<InlayHint>> CB) {
772   auto Action = [RestrictRange(std::move(RestrictRange)),
773                  CB = std::move(CB)](Expected<InputsAndAST> InpAST) mutable {
774     if (!InpAST)
775       return CB(InpAST.takeError());
776     CB(clangd::inlayHints(InpAST->AST, std::move(RestrictRange)));
777   };
778   WorkScheduler->runWithAST("InlayHints", File, std::move(Action), Transient);
779 }
780 
781 void ClangdServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
782   // FIXME: Do nothing for now. This will be used for indexing and potentially
783   // invalidating other caches.
784 }
785 
786 void ClangdServer::workspaceSymbols(
787     llvm::StringRef Query, int Limit,
788     Callback<std::vector<SymbolInformation>> CB) {
789   WorkScheduler->run(
790       "getWorkspaceSymbols", /*Path=*/"",
791       [Query = Query.str(), Limit, CB = std::move(CB), this]() mutable {
792         CB(clangd::getWorkspaceSymbols(Query, Limit, Index,
793                                        WorkspaceRoot.getValueOr("")));
794       });
795 }
796 
797 void ClangdServer::documentSymbols(llvm::StringRef File,
798                                    Callback<std::vector<DocumentSymbol>> 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::getDocumentSymbols(InpAST->AST));
804       };
805   WorkScheduler->runWithAST("DocumentSymbols", File, std::move(Action),
806                             Transient);
807 }
808 
809 void ClangdServer::foldingRanges(llvm::StringRef File,
810                                  Callback<std::vector<FoldingRange>> CB) {
811   auto Action =
812       [CB = std::move(CB)](llvm::Expected<InputsAndAST> InpAST) mutable {
813         if (!InpAST)
814           return CB(InpAST.takeError());
815         CB(clangd::getFoldingRanges(InpAST->AST));
816       };
817   WorkScheduler->runWithAST("FoldingRanges", File, std::move(Action),
818                             Transient);
819 }
820 
821 void ClangdServer::findType(llvm::StringRef File, Position Pos,
822                             Callback<std::vector<LocatedSymbol>> CB) {
823   auto Action =
824       [Pos, CB = std::move(CB)](llvm::Expected<InputsAndAST> InpAST) mutable {
825         if (!InpAST)
826           return CB(InpAST.takeError());
827         CB(clangd::findType(InpAST->AST, Pos));
828       };
829   WorkScheduler->runWithAST("FindType", File, std::move(Action));
830 }
831 
832 void ClangdServer::findImplementations(
833     PathRef File, Position Pos, Callback<std::vector<LocatedSymbol>> CB) {
834   auto Action = [Pos, CB = std::move(CB),
835                  this](llvm::Expected<InputsAndAST> InpAST) mutable {
836     if (!InpAST)
837       return CB(InpAST.takeError());
838     CB(clangd::findImplementations(InpAST->AST, Pos, Index));
839   };
840 
841   WorkScheduler->runWithAST("Implementations", File, std::move(Action));
842 }
843 
844 void ClangdServer::findReferences(PathRef File, Position Pos, uint32_t Limit,
845                                   Callback<ReferencesResult> CB) {
846   auto Action = [Pos, Limit, CB = std::move(CB),
847                  this](llvm::Expected<InputsAndAST> InpAST) mutable {
848     if (!InpAST)
849       return CB(InpAST.takeError());
850     CB(clangd::findReferences(InpAST->AST, Pos, Limit, Index));
851   };
852 
853   WorkScheduler->runWithAST("References", File, std::move(Action));
854 }
855 
856 void ClangdServer::symbolInfo(PathRef File, Position Pos,
857                               Callback<std::vector<SymbolDetails>> CB) {
858   auto Action =
859       [Pos, CB = std::move(CB)](llvm::Expected<InputsAndAST> InpAST) mutable {
860         if (!InpAST)
861           return CB(InpAST.takeError());
862         CB(clangd::getSymbolInfo(InpAST->AST, Pos));
863       };
864 
865   WorkScheduler->runWithAST("SymbolInfo", File, std::move(Action));
866 }
867 
868 void ClangdServer::semanticRanges(PathRef File,
869                                   const std::vector<Position> &Positions,
870                                   Callback<std::vector<SelectionRange>> CB) {
871   auto Action = [Positions, CB = std::move(CB)](
872                     llvm::Expected<InputsAndAST> InpAST) mutable {
873     if (!InpAST)
874       return CB(InpAST.takeError());
875     std::vector<SelectionRange> Result;
876     for (const auto &Pos : Positions) {
877       if (auto Range = clangd::getSemanticRanges(InpAST->AST, Pos))
878         Result.push_back(std::move(*Range));
879       else
880         return CB(Range.takeError());
881     }
882     CB(std::move(Result));
883   };
884   WorkScheduler->runWithAST("SemanticRanges", File, std::move(Action));
885 }
886 
887 void ClangdServer::documentLinks(PathRef File,
888                                  Callback<std::vector<DocumentLink>> CB) {
889   auto Action =
890       [CB = std::move(CB)](llvm::Expected<InputsAndAST> InpAST) mutable {
891         if (!InpAST)
892           return CB(InpAST.takeError());
893         CB(clangd::getDocumentLinks(InpAST->AST));
894       };
895   WorkScheduler->runWithAST("DocumentLinks", File, std::move(Action),
896                             Transient);
897 }
898 
899 void ClangdServer::semanticHighlights(
900     PathRef File, Callback<std::vector<HighlightingToken>> CB) {
901   auto Action =
902       [CB = std::move(CB)](llvm::Expected<InputsAndAST> InpAST) mutable {
903         if (!InpAST)
904           return CB(InpAST.takeError());
905         CB(clangd::getSemanticHighlightings(InpAST->AST));
906       };
907   WorkScheduler->runWithAST("SemanticHighlights", File, std::move(Action),
908                             Transient);
909 }
910 
911 void ClangdServer::getAST(PathRef File, llvm::Optional<Range> R,
912                           Callback<llvm::Optional<ASTNode>> CB) {
913   auto Action =
914       [R, CB(std::move(CB))](llvm::Expected<InputsAndAST> Inputs) mutable {
915         if (!Inputs)
916           return CB(Inputs.takeError());
917         if (!R) {
918           // It's safe to pass in the TU, as dumpAST() does not
919           // deserialize the preamble.
920           auto Node = DynTypedNode::create(
921                 *Inputs->AST.getASTContext().getTranslationUnitDecl());
922           return CB(dumpAST(Node, Inputs->AST.getTokens(),
923                             Inputs->AST.getASTContext()));
924         }
925         unsigned Start, End;
926         if (auto Offset = positionToOffset(Inputs->Inputs.Contents, R->start))
927           Start = *Offset;
928         else
929           return CB(Offset.takeError());
930         if (auto Offset = positionToOffset(Inputs->Inputs.Contents, R->end))
931           End = *Offset;
932         else
933           return CB(Offset.takeError());
934         bool Success = SelectionTree::createEach(
935             Inputs->AST.getASTContext(), Inputs->AST.getTokens(), Start, End,
936             [&](SelectionTree T) {
937               if (const SelectionTree::Node *N = T.commonAncestor()) {
938                 CB(dumpAST(N->ASTNode, Inputs->AST.getTokens(),
939                            Inputs->AST.getASTContext()));
940                 return true;
941               }
942               return false;
943             });
944         if (!Success)
945           CB(llvm::None);
946       };
947   WorkScheduler->runWithAST("GetAST", File, std::move(Action));
948 }
949 
950 void ClangdServer::customAction(PathRef File, llvm::StringRef Name,
951                                 Callback<InputsAndAST> Action) {
952   WorkScheduler->runWithAST(Name, File, std::move(Action));
953 }
954 
955 void ClangdServer::diagnostics(PathRef File, Callback<std::vector<Diag>> CB) {
956   auto Action =
957       [CB = std::move(CB)](llvm::Expected<InputsAndAST> InpAST) mutable {
958         if (!InpAST)
959           return CB(InpAST.takeError());
960         if (auto Diags = InpAST->AST.getDiagnostics())
961           return CB(*Diags);
962         // FIXME: Use ServerCancelled error once it is settled in LSP-3.17.
963         return CB(llvm::make_error<LSPError>("server is busy parsing includes",
964                                              ErrorCode::InternalError));
965       };
966 
967   WorkScheduler->runWithAST("Diagnostics", File, std::move(Action));
968 }
969 
970 llvm::StringMap<TUScheduler::FileStats> ClangdServer::fileStats() const {
971   return WorkScheduler->fileStats();
972 }
973 
974 LLVM_NODISCARD bool
975 ClangdServer::blockUntilIdleForTest(llvm::Optional<double> TimeoutSeconds) {
976   // Order is important here: we don't want to block on A and then B,
977   // if B might schedule work on A.
978 
979   // Nothing else can schedule work on TUScheduler, because it's not threadsafe
980   // and we're blocking the main thread.
981   if (!WorkScheduler->blockUntilIdle(timeoutSeconds(TimeoutSeconds)))
982     return false;
983 
984   // Unfortunately we don't have strict topological order between the rest of
985   // the components. E.g. CDB broadcast triggers backrgound indexing.
986   // This queries the CDB which may discover new work if disk has changed.
987   //
988   // So try each one a few times in a loop.
989   // If there are no tricky interactions then all after the first are no-ops.
990   // Then on the last iteration, verify they're idle without waiting.
991   //
992   // There's a small chance they're juggling work and we didn't catch them :-(
993   for (llvm::Optional<double> Timeout :
994        {TimeoutSeconds, TimeoutSeconds, llvm::Optional<double>(0)}) {
995     if (!CDB.blockUntilIdle(timeoutSeconds(Timeout)))
996       return false;
997     if (BackgroundIdx && !BackgroundIdx->blockUntilIdleForTest(Timeout))
998       return false;
999     if (FeatureModules && llvm::any_of(*FeatureModules, [&](FeatureModule &M) {
1000           return !M.blockUntilIdle(timeoutSeconds(Timeout));
1001         }))
1002       return false;
1003   }
1004 
1005   assert(WorkScheduler->blockUntilIdle(Deadline::zero()) &&
1006          "Something scheduled work while we're blocking the main thread!");
1007   return true;
1008 }
1009 
1010 void ClangdServer::profile(MemoryTree &MT) const {
1011   if (DynamicIdx)
1012     DynamicIdx->profile(MT.child("dynamic_index"));
1013   if (BackgroundIdx)
1014     BackgroundIdx->profile(MT.child("background_index"));
1015   WorkScheduler->profile(MT.child("tuscheduler"));
1016 }
1017 } // namespace clangd
1018 } // namespace clang
1019