clang-tools  14.0.0git
ClangdServer.cpp
Go to the documentation of this file.
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"
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 
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 {
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 
154  const ThreadsafeFS &TFS, const Options &Opts,
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) {
182  BGOpts.ThreadPoolSize = std::max(Opts.AsyncThreadsCount, 1u);
184  if (Callbacks)
186  };
187  BGOpts.ContextProvider = Opts.ContextProvider;
188  BackgroundIdx = std::make_unique<BackgroundIndex>(
189  TFS, CDB,
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) {
200  *this->WorkScheduler,
201  this->Index,
202  this->TFS,
203  };
204  for (auto &Mod : *Opts.FeatureModules)
205  Mod.initialize(F);
206  }
207 }
208 
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.
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 
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,
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)>
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 
340  DraftMgr.removeDraft(File);
341  WorkScheduler->remove(File);
342 }
343 
345  const clangd::CodeCompleteOptions &Opts,
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.
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)
402  std::move(Task));
403 }
404 
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;
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,
429  auto Code = getDraft(File);
430  if (!Code)
431  return CB(llvm::make_error<LSPError>("trying to format non-added document",
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 
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",
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 
494  llvm::Optional<std::string> NewName,
495  const RenameOptions &RenameOpts,
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,
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",
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;
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 
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,
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 && (*Effect)->FormatEdits) {
641  // Format tweaks that require it 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 
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 
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 
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 
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());
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 
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 
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 
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 
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 
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 
770  // FIXME: Do nothing for now. This will be used for indexing and potentially
771  // invalidating other caches.
772 }
773 
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 
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 
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 
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 
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 
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 
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,
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
clang::clangd::ClangdServer::rename
void rename(PathRef File, Position Pos, llvm::StringRef NewName, const RenameOptions &Opts, Callback< RenameResult > CB)
Rename all occurrences of the symbol at the Pos in File to NewName.
Definition: ClangdServer.cpp:519
Range
CharSourceRange Range
SourceRange for the file name.
Definition: IncludeOrderCheck.cpp:38
WantDiags
WantDiagnostics WantDiags
Definition: TUScheduler.cpp:453
clang::clangd::BackgroundQueue::Stats
Definition: Background.h:86
XRefs.h
clang::clangd::incomingCalls
std::vector< CallHierarchyIncomingCall > incomingCalls(const CallHierarchyItem &Item, const SymbolIndex *Index)
Definition: XRefs.cpp:1915
Base
std::unique_ptr< GlobalCompilationDatabase > Base
Definition: GlobalCompilationDatabaseTests.cpp:90
clang::clangd::MemoryTree::child
MemoryTree & child(llvm::StringLiteral Name)
No copy of the Name.
Definition: MemoryTree.h:41
clang::clangd::BackgroundIndexStorage::createDiskBackedStorageFactory
static Factory createDiskBackedStorageFactory(std::function< llvm::Optional< ProjectInfo >(PathRef)> GetProjectInfo)
Definition: BackgroundIndexStorage.cpp:146
Headers.h
clang::clangd::timeoutSeconds
Deadline timeoutSeconds(llvm::Optional< double > Seconds)
Makes a deadline from a timeout in seconds. None means wait forever.
Definition: Threading.cpp:105
clang::clangd::getFoldingRanges
llvm::Expected< std::vector< FoldingRange > > getFoldingRanges(ParsedAST &AST)
Returns a list of ranges whose contents might be collapsible in an editor.
Definition: SemanticSelection.cpp:161
clang::clangd::Deadline::infinity
static Deadline infinity()
Definition: Threading.h:64
clang::clangd::Config::AllScopes
bool AllScopes
Whether code completion includes results that are not visible in current scopes.
Definition: Config.h:114
clang::clangd::signatureHelp
SignatureHelp signatureHelp(PathRef FileName, Position Pos, const PreambleData &Preamble, const ParseInputs &ParseInput)
Get signature help at a specified Pos in FileName.
Definition: CodeComplete.cpp:1883
clang::clangd::findReferences
ReferencesResult findReferences(ParsedAST &AST, Position Pos, uint32_t Limit, const SymbolIndex *Index)
Returns references of the symbol at a specified Pos.
Definition: XRefs.cpp:1329
clang::clangd::Edit
A set of edits generated for a single file.
Definition: SourceCode.h:180
clang::clangd::rename
llvm::Expected< RenameResult > rename(const RenameInputs &RInputs)
Renames all occurrences of the symbol.
Definition: Rename.cpp:697
E
const Expr * E
Definition: AvoidBindCheck.cpp:88
CodeComplete.h
clang::clangd::FeatureModule
A FeatureModule contributes a vertical feature to clangd.
Definition: FeatureModule.h:55
clang::clangd::Path
std::string Path
A typedef to represent a file path.
Definition: Path.h:26
clang::clangd::resolveTypeHierarchy
void resolveTypeHierarchy(TypeHierarchyItem &Item, int ResolveLevels, TypeHierarchyDirection Direction, const SymbolIndex *Index)
Definition: XRefs.cpp:1875
Tracer
std::unique_ptr< trace::EventTracer > Tracer
Definition: TraceTests.cpp:164
clang::clangd::error
llvm::Error error(std::error_code EC, const char *Fmt, Ts &&... Vals)
Definition: Logger.h:80
clang::clangd::config::Params::FreshTime
std::chrono::steady_clock::time_point FreshTime
Hint that stale data is OK to improve performance (e.g.
Definition: ConfigProvider.h:42
clang::clangd::Context::current
static const Context & current()
Returns the context for the current thread, creating it if needed.
Definition: Context.cpp:27
FormatStyle
static cl::opt< std::string > FormatStyle("format-style", cl::desc(R"( Style for formatting code around applied fixes: - 'none' (default) turns off formatting - 'file' (literally 'file', not a placeholder) uses .clang-format file in the closest parent directory - '{ <json> }' specifies options inline, e.g. -format-style='{BasedOnStyle: llvm, IndentWidth: 8}' - 'llvm', 'google', 'webkit', 'mozilla' See clang-format documentation for the up-to-date information about formatting styles and options. This option overrides the 'FormatStyle` option in .clang-tidy file, if any. )"), cl::init("none"), cl::cat(ClangTidyCategory))
clang::clangd::InputsAndAST
Definition: TUScheduler.h:38
clang::clangd::findImplementations
std::vector< LocatedSymbol > findImplementations(ParsedAST &AST, Position Pos, const SymbolIndex *Index)
Returns implementations at a specified Pos:
Definition: XRefs.cpp:1276
clang::clangd::Context::clone
Context clone() const
Clone this context object.
Definition: Context.cpp:20
clang::clangd::BackgroundIndex::Options::ContextProvider
std::function< Context(PathRef)> ContextProvider
Definition: Background.h:145
Diagnostics
WantDiagnostics Diagnostics
Definition: TUScheduler.cpp:561
ParseInput
const ParseInputs & ParseInput
Definition: CodeComplete.cpp:1106
clang::clangd::ParsedAST::getASTContext
ASTContext & getASTContext()
Note that the returned ast will not contain decls from the preamble that were not deserialized during...
Definition: ParsedAST.cpp:532
DumpAST.h
clang::clangd::WantDiagnostics::Auto
@ Auto
Diagnostics must not be generated for this snapshot.
clang::clangd::SelectionTree::createEach
static bool createEach(ASTContext &AST, const syntax::TokenBuffer &Tokens, unsigned Begin, unsigned End, llvm::function_ref< bool(SelectionTree)> Func)
Definition: Selection.cpp:832
clang::clangd::PreambleData::Preamble
PrecompiledPreamble Preamble
Definition: Preamble.h:55
clang::clangd::DraftStore::addDraft
std::string addDraft(PathRef File, llvm::StringRef Version, StringRef Contents)
Replace contents of the draft for File with Contents.
Definition: DraftStore.cpp:76
clang::clangd::Range::start
Position start
The range's start position.
Definition: Protocol.h:179
clang::clangd::reformatEdit
llvm::Error reformatEdit(Edit &E, const format::FormatStyle &Style)
Formats the edits and code around it according to Style.
Definition: SourceCode.cpp:1048
Preamble.h
clang::clangd::ClangdServer::getAST
void getAST(PathRef File, llvm::Optional< Range > R, Callback< llvm::Optional< ASTNode >> CB)
Describe the AST subtree for a piece of code.
Definition: ClangdServer.cpp:888
clang::clangd::ClangdServer::switchSourceHeader
void switchSourceHeader(PathRef Path, Callback< llvm::Optional< clangd::Path >> CB)
Switch to a corresponding source file when given a header file, and vice versa.
Definition: ClangdServer.cpp:669
Ctx
Context Ctx
Definition: TUScheduler.cpp:454
clang::clangd::ClangdServer::findReferences
void findReferences(PathRef File, Position Pos, uint32_t Limit, Callback< ReferencesResult > CB)
Retrieve locations for symbol references.
Definition: ClangdServer.cpp:821
clang::clangd::getHover
llvm::Optional< HoverInfo > getHover(ParsedAST &AST, Position Pos, format::FormatStyle Style, const SymbolIndex *Index)
Get the hover information when hovering at Pos.
Definition: Hover.cpp:913
Trace.h
clang::clangd::Config
Settings that express user/project preferences and control clangd behavior.
Definition: Config.h:43
clang::clangd::config::Provider
A source of configuration fragments.
Definition: ConfigProvider.h:64
clang::clangd::ClangdServer::optsForTest
static Options optsForTest()
Definition: ClangdServer.cpp:135
HeaderSourceSwitch.h
Format.h
FindSymbols.h
clang::clangd::getSemanticRanges
llvm::Expected< SelectionRange > getSemanticRanges(ParsedAST &AST, Position Pos)
Returns the list of all interesting ranges around the Position Pos.
Definition: SemanticSelection.cpp:103
clang::clangd::FileIndex
This manages symbols from files and an in-memory index on all symbols.
Definition: FileIndex.h:111
clang::clangd::GlobalCompilationDatabase
Provides compilation arguments used for parsing C and C++ files.
Definition: GlobalCompilationDatabase.h:36
Action
llvm::unique_function< void()> Action
Definition: TUScheduler.cpp:596
clang::clangd::FeatureModule::Facilities
Shared server facilities needed by the module to get its work done.
Definition: FeatureModule.h:75
clang::clangd::ClangdServer::documentSymbols
void documentSymbols(StringRef File, Callback< std::vector< DocumentSymbol >> CB)
Retrieve the symbols within the specified file.
Definition: ClangdServer.cpp:785
clang::clangd::ClangdServer::foldingRanges
void foldingRanges(StringRef File, Callback< std::vector< FoldingRange >> CB)
Retrieve ranges that can be used to fold code within the specified file.
Definition: ClangdServer.cpp:797
clang::clangd::replacementToEdit
TextEdit replacementToEdit(llvm::StringRef Code, const tooling::Replacement &R)
Definition: SourceCode.cpp:491
clang::clangd::ClangdServer::findImplementations
void findImplementations(PathRef File, Position Pos, Callback< std::vector< LocatedSymbol >> CB)
Retrieve implementations for virtual method.
Definition: ClangdServer.cpp:809
clang::clangd::TUScheduler::Stale
@ Stale
The preamble may be generated from an older version of the file.
Definition: TUScheduler.h:288
clang::clangd::ClangdServer::addDocument
void addDocument(PathRef File, StringRef Contents, llvm::StringRef Version="null", WantDiagnostics WD=WantDiagnostics::Auto, bool ForceRebuild=false)
Add a File to the list of tracked C++ files or update the contents if File is already tracked.
Definition: ClangdServer.cpp:223
clang::clangd::ClangdServer::inlayHints
void inlayHints(PathRef File, Callback< std::vector< InlayHint >>)
Resolve inlay hints for a given document.
Definition: ClangdServer.cpp:759
clang::clangd::DraftStore::removeDraft
void removeDraft(PathRef File)
Remove the draft from the store.
Definition: DraftStore.cpp:87
clang::clangd::TUScheduler::StaleOrAbsent
@ StaleOrAbsent
Besides accepting stale preamble, this also allow preamble to be absent (not ready or failed to build...
Definition: TUScheduler.h:291
InlayHints.h
clang::clangd::ClangdServer::prepareRename
void prepareRename(PathRef File, Position Pos, llvm::Optional< std::string > NewName, const RenameOptions &RenameOpts, Callback< RenameResult > CB)
Test the validity of a rename operation.
Definition: ClangdServer.cpp:493
clang::clangd::WantDiagnostics
WantDiagnostics
Determines whether diagnostics should be generated for a file snapshot.
Definition: TUScheduler.h:53
Protocol.h
M
const google::protobuf::Message & M
Definition: Server.cpp:309
ThreadsafeFS.h
Inputs
ParseInputs Inputs
Definition: TUScheduler.cpp:451
clang::clangd::isCancelled
int isCancelled(const Context &Ctx)
If the current context is within a cancelled task, returns the reason.
Definition: Cancellation.cpp:35
clang::clangd::prepareTweaks
std::vector< std::unique_ptr< Tweak > > prepareTweaks(const Tweak::Selection &S, llvm::function_ref< bool(const Tweak &)> Filter, const FeatureModuleSet *Modules)
Calls prepare() on all tweaks that satisfy the filter, returning those that can run on the selection.
Definition: Tweak.cpp:74
Offset
size_t Offset
Definition: CodeComplete.cpp:1103
clang::clangd::ClangdServer::Options
Definition: ClangdServer.h:99
Rename.h
clang::clangd::Position
Definition: Protocol.h:148
Code
std::string Code
Definition: FindTargetTests.cpp:67
clang::clangd::ParseInputs
Information required to run clang, e.g. to parse AST or do code completion.
Definition: Compiler.h:47
clang::clangd::dumpAST
ASTNode dumpAST(const DynTypedNode &N, const syntax::TokenBuffer &Tokens, const ASTContext &Ctx)
Definition: DumpAST.cpp:401
CanonicalIncludes.h
ns1::ns2::D
@ D
Definition: CategoricalFeature.h:3
clang::clangd::ClangdServer::getDraft
std::shared_ptr< const std::string > getDraft(PathRef File) const
Gets the contents of a currently tracked file.
Definition: ClangdServer.cpp:255
clang::clangd::locateSymbolAt
std::vector< LocatedSymbol > locateSymbolAt(ParsedAST &AST, Position Pos, const SymbolIndex *Index)
Get definition of symbol at a specified Pos.
Definition: XRefs.cpp:756
clang::clangd::ClangdServer::removeDocument
void removeDocument(PathRef File)
Remove File from list of tracked files, schedule a request to free resources associated with it.
Definition: ClangdServer.cpp:339
clang::clangd::ClangdServer::codeComplete
void codeComplete(PathRef File, Position Pos, const clangd::CodeCompleteOptions &Opts, Callback< CodeCompleteResult > CB)
Run code completion for File at Pos.
Definition: ClangdServer.cpp:344
clang::clangd::ErrorCode::InvalidParams
@ InvalidParams
clang::clangd::PreambleData
The parsed preamble and associated data.
Definition: Preamble.h:49
Tweak.h
clang::clangd::MemoryTree
A tree that can be used to represent memory usage of nested components while preserving the hierarchy...
Definition: MemoryTree.h:32
SemanticSelection.h
clang::clangd::DidChangeWatchedFilesParams
Definition: Protocol.h:746
Logger.h
clang::clangd::DraftStore::getActiveFiles
std::vector< Path > getActiveFiles() const
Definition: DraftStore.cpp:30
Markup.h
clang::clangd::getSymbolInfo
std::vector< SymbolDetails > getSymbolInfo(ParsedAST &AST, Position Pos)
Get info about symbols at Pos.
Definition: XRefs.cpp:1509
clang::clangd::codeComplete
CodeCompleteResult codeComplete(PathRef FileName, Position Pos, const PreambleData *Preamble, const ParseInputs &ParseInput, CodeCompleteOptions Opts, SpeculativeFuzzyFind *SpecFuzzyFind)
Gets code completions at a specified Pos in FileName.
Definition: CodeComplete.cpp:1860
clang::clangd::positionToOffset
llvm::Expected< size_t > positionToOffset(llvm::StringRef Code, Position P, bool AllowColumnsBeyondLineLength)
Turn a [line, column] pair into an offset in Code.
Definition: SourceCode.cpp:175
clang::clangd::ClangdServer::onFileEvent
void onFileEvent(const DidChangeWatchedFilesParams &Params)
Called when an event occurs for a watched file in the workspace.
Definition: ClangdServer.cpp:769
Name
static constexpr llvm::StringLiteral Name
Definition: UppercaseLiteralSuffixCheck.cpp:27
clang::clangd::DraftStore::getDraft
llvm::Optional< Draft > getDraft(PathRef File) const
Definition: DraftStore.cpp:20
clang::clangd::BackgroundIndex::Options::ThreadPoolSize
size_t ThreadPoolSize
Definition: Background.h:139
clang::clangd::config::Provider::getConfig
Config getConfig(const Params &, DiagnosticCallback) const
Build a config based on this provider.
Definition: ConfigProvider.cpp:169
clang::clangd::toDiag
Diag toDiag(const llvm::SMDiagnostic &D, Diag::DiagSource Source)
Definition: Diagnostics.cpp:435
clang::clangd::ClangdServer::semanticHighlights
void semanticHighlights(PathRef File, Callback< std::vector< HighlightingToken >>)
Definition: ClangdServer.cpp:876
clang::clangd::RenameOptions
Definition: Rename.h:24
clang::clangd::vlog
void vlog(const char *Fmt, Ts &&... Vals)
Definition: Logger.h:73
clang::clangd::ClangdServer::findDocumentHighlights
void findDocumentHighlights(PathRef File, Position Pos, Callback< std::vector< DocumentHighlight >> CB)
Get document highlights for a given position.
Definition: ClangdServer.cpp:689
clang::clangd::trace::Metric::Distribution
@ Distribution
A distribution of values with a meaningful mean and count.
Definition: Trace.h:52
clang::clangd::ClangdServer::incomingCalls
void incomingCalls(const CallHierarchyItem &Item, Callback< std::vector< CallHierarchyIncomingCall >>)
Resolve incoming calls for a given call hierarchy item.
Definition: ClangdServer.cpp:750
Diagnostics.h
Results
std::vector< CodeCompletionResult > Results
Definition: CodeComplete.cpp:771
clang::clangd::Range::end
Position end
The range's end position.
Definition: Protocol.h:182
clang::clangd::SelectionTree
Definition: Selection.h:76
clang::clangd::ClangdServer::formatOnType
void formatOnType(PathRef File, Position Pos, StringRef TriggerText, Callback< std::vector< TextEdit >> CB)
Run formatting after TriggerText was typed at Pos in File with content Code.
Definition: ClangdServer.cpp:465
FeatureModules
FeatureModuleSet FeatureModules
Definition: ClangdLSPServerTests.cpp:73
FileIndex.h
clang::clangd::BackgroundIndex::Options::OnProgress
std::function< void(BackgroundQueue::Stats)> OnProgress
Definition: Background.h:141
clang::clangd::getSemanticHighlightings
std::vector< HighlightingToken > getSemanticHighlightings(ParsedAST &AST)
Definition: SemanticHighlighting.cpp:779
clang::clangd::getDocumentSymbols
llvm::Expected< std::vector< DocumentSymbol > > getDocumentSymbols(ParsedAST &AST)
Retrieves the symbols contained in the "main file" section of an AST in the same order that they appe...
Definition: FindSymbols.cpp:531
clang::clangd::ClangdServer::formatFile
void formatFile(PathRef File, llvm::Optional< Range > Rng, Callback< tooling::Replacements > CB)
Run formatting for the File with content Code.
Definition: ClangdServer.cpp:427
clang::clangd::Config::Completion
struct clang::clangd::Config::@6 Completion
Configures code completion feature.
clang::clangd::getFormatStyleForFile
format::FormatStyle getFormatStyleForFile(llvm::StringRef File, llvm::StringRef Content, const ThreadsafeFS &TFS)
Choose the clang-format style we should apply to a certain file.
Definition: SourceCode.cpp:573
clang::clangd::CodeCompleteOptions
Definition: CodeComplete.h:45
clang::tidy::bugprone::PP
static Preprocessor * PP
Definition: BadSignalToKillThreadCheck.cpp:29
clang::clangd::log
void log(const char *Fmt, Ts &&... Vals)
Definition: Logger.h:68
clang::clangd::ClangdServer::workspaceSymbols
void workspaceSymbols(StringRef Query, int Limit, Callback< std::vector< SymbolInformation >> CB)
Retrieve the top symbols from the workspace matching a query.
Definition: ClangdServer.cpp:774
Entry
Definition: Modularize.cpp:428
clang::clangd::BackgroundIndex::Options
Definition: Background.h:136
SourceCode.h
clang::clangd::ClangdServer::documentLinks
void documentLinks(PathRef File, Callback< std::vector< DocumentLink >> CB)
Get all document links in a file.
Definition: ClangdServer.cpp:864
clang::clangd::SymbolIndex
Interface for symbol indexes that can be used for searching or matching symbols among a set of symbol...
Definition: Index.h:111
clang::clangd::trace::Metric::Counter
@ Counter
An aggregate number whose rate of change over time is meaningful.
Definition: Trace.h:46
Config.h
clang::clangd::ClangdServer::signatureHelp
void signatureHelp(PathRef File, Position Pos, Callback< SignatureHelp > CB)
Provide signature help for File at Pos.
Definition: ClangdServer.cpp:405
clang::clangd::ClangdServer::locateSymbolAt
void locateSymbolAt(PathRef File, Position Pos, Callback< std::vector< LocatedSymbol >> CB)
Find declaration/definition locations of symbol at a specified position.
Definition: ClangdServer.cpp:657
clang::clangd::TypeHierarchyDirection
TypeHierarchyDirection
Definition: Protocol.h:1351
clang::clangd::TypeHierarchyItem
Definition: Protocol.h:1368
clang::clangd::Context::derive
Context derive(const Key< Type > &Key, typename std::decay< Type >::type Value) const &
Derives a child context It is safe to move or destroy a parent context after calling derive().
Definition: Context.h:119
clang::clangd::ClangdServer::Callbacks::onBackgroundIndexProgress
virtual void onBackgroundIndexProgress(const BackgroundQueue::Stats &Stats)
Called when background indexing tasks are enqueued/started/completed.
Definition: ClangdServer.h:82
clang::clangd::ClangdServer::Callbacks
Interface with hooks for users of ClangdServer to be notified of events.
Definition: ClangdServer.h:65
clang::clangd::PathRef
llvm::StringRef PathRef
A typedef to represent a ref to file path.
Definition: Path.h:29
clang::clangd::ThreadsafeFS
Wrapper for vfs::FileSystem for use in multithreaded programs like clangd.
Definition: ThreadsafeFS.h:28
clang::clangd::trace::Metric
Represents measurements of clangd events, e.g.
Definition: Trace.h:38
clang::clangd::ParseOptions
Definition: Compiler.h:42
clang::clangd::ThreadsafeFS::view
llvm::IntrusiveRefCntPtr< llvm::vfs::FileSystem > view(llvm::NoneType CWD) const
Obtain a vfs::FileSystem with an arbitrary initial working directory.
Definition: ThreadsafeFS.h:34
clang::clangd::TUScheduler::Options
Definition: TUScheduler.h:188
clang::clangd::ClangdServer::applyTweak
void applyTweak(PathRef File, Range Sel, StringRef ID, Callback< Tweak::Effect > CB)
Apply the code tweak with a specified ID.
Definition: ClangdServer.cpp:610
clang::clangd::Range
Definition: Protocol.h:177
C
const Criteria C
Definition: FunctionCognitiveComplexityCheck.cpp:93
SemanticHighlighting.h
MemoryTree.h
clang::clangd::CodeCompleteResult
Definition: CodeComplete.h:238
clang::clangd::CodeCompleteOptions::AlwaysParse
@ AlwaysParse
Block until we can run the parser (e.g.
Definition: CodeComplete.h:114
clang::clangd::config::Params
Describes the context used to evaluate configuration fragments.
Definition: ConfigProvider.h:35
clang
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
Definition: ApplyReplacements.h:27
clang::clangd::ClangdServer::symbolInfo
void symbolInfo(PathRef File, Position Pos, Callback< std::vector< SymbolDetails >> CB)
Get symbol info for given position.
Definition: ClangdServer.cpp:833
clang::clangd::ParsedAST::getTokens
const syntax::TokenBuffer & getTokens() const
Tokens recorded while parsing the main file.
Definition: ParsedAST.h:106
ClangdServer.h
clang::clangd::config::Params::Path
llvm::StringRef Path
Absolute path to a source file we're applying the config to.
Definition: ConfigProvider.h:38
clang::clangd::formatIncremental
std::vector< tooling::Replacement > formatIncremental(llvm::StringRef OriginalCode, unsigned OriginalCursor, llvm::StringRef InsertedText, format::FormatStyle Style)
Applies limited formatting around new InsertedText.
Definition: Format.cpp:248
clang::clangd::Diag::ClangdConfig
@ ClangdConfig
Definition: Diagnostics.h:104
TUScheduler.h
clang::clangd::prepareTweak
llvm::Expected< std::unique_ptr< Tweak > > prepareTweak(StringRef ID, const Tweak::Selection &S, const FeatureModuleSet *Modules)
Definition: Tweak.cpp:93
clang::clangd::ClangdServer::reparseOpenFilesIfNeeded
void reparseOpenFilesIfNeeded(llvm::function_ref< bool(llvm::StringRef File)> Filter)
Requests a reparse of currently opened files using their latest source.
Definition: ClangdServer.cpp:245
Diags
CapturedDiags Diags
Definition: ConfigCompileTests.cpp:38
clang::clangd::Tweak
An interface base for small context-sensitive refactoring actions.
Definition: Tweak.h:49
clang::clangd::ClangdServer::semanticRanges
void semanticRanges(PathRef File, const std::vector< Position > &Pos, Callback< std::vector< SelectionRange >> CB)
Get semantic ranges around a specified position in a file.
Definition: ClangdServer.cpp:845
clang::clangd::ClangdServer::resolveTypeHierarchy
void resolveTypeHierarchy(TypeHierarchyItem Item, int Resolve, TypeHierarchyDirection Direction, Callback< llvm::Optional< TypeHierarchyItem >> CB)
Resolve type hierarchy item in the given direction.
Definition: ClangdServer.cpp:729
clang::clangd::CallHierarchyItem
Represents programming constructs like functions or constructors in the context of call hierarchy.
Definition: Protocol.h:1436
clang::clangd::Config::current
static const Config & current()
Returns the Config of the current Context, or an empty configuration.
Definition: Config.cpp:17
clang::clangd::ClangdServer::findHover
void findHover(PathRef File, Position Pos, Callback< llvm::Optional< HoverInfo >> CB)
Get code hover for a given position.
Definition: ClangdServer.cpp:701
clang::clangd::getCorrespondingHeaderOrSource
llvm::Optional< Path > getCorrespondingHeaderOrSource(PathRef OriginalFile, llvm::IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS)
Given a header file, returns the best matching source file, and vice visa.
Definition: HeaderSourceSwitch.cpp:19
clang::clangd::getTypeHierarchy
llvm::Optional< TypeHierarchyItem > getTypeHierarchy(ParsedAST &AST, Position Pos, int ResolveLevels, TypeHierarchyDirection Direction, const SymbolIndex *Index, PathRef TUPath)
Get type hierarchy information at Pos.
Definition: XRefs.cpp:1828
clang::clangd::TUScheduler
Handles running tasks for ClangdServer and managing the resources (e.g., preambles and ASTs) for open...
Definition: TUScheduler.h:186
clang::clangd::Callback
llvm::unique_function< void(llvm::Expected< T >)> Callback
A Callback<T> is a void function that accepts Expected<T>.
Definition: Function.h:28
clang::clangd::DebouncePolicy::fixed
static DebouncePolicy fixed(clock::duration)
A policy that always returns the same duration, useful for tests.
Definition: TUScheduler.cpp:1671
clang::clangd::Config::Key
static clangd::Key< Config > Key
Context key which can be used to set the current Config.
Definition: Config.h:47
Pos
Position Pos
Definition: SourceCode.cpp:650
Merge.h
clang::clangd::ClangdServer::enumerateTweaks
void enumerateTweaks(PathRef File, Range Sel, llvm::unique_function< bool(const Tweak &)> Filter, Callback< std::vector< TweakRef >> CB)
Enumerate the code tweaks available to the user at a specified point.
Definition: ClangdServer.cpp:575
clang::clangd::ClangdServer::Callbacks::onDiagnosticsReady
virtual void onDiagnosticsReady(PathRef File, llvm::StringRef Version, std::vector< Diag > Diagnostics)
Called by ClangdServer when Diagnostics for File are ready.
Definition: ClangdServer.h:73
clang::clangd::inlayHints
std::vector< InlayHint > inlayHints(ParsedAST &AST)
Definition: InlayHints.cpp:365
clang::clangd::elog
void elog(const char *Fmt, Ts &&... Vals)
Definition: Logger.h:62
clang::clangd::ClangdServer::~ClangdServer
~ClangdServer()
Definition: ClangdServer.cpp:209
clang::clangd::getDocumentLinks
std::vector< DocumentLink > getDocumentLinks(ParsedAST &AST)
Get all document links.
Definition: XRefs.cpp:841
clang::clangd::ClangdServer::prepareCallHierarchy
void prepareCallHierarchy(PathRef File, Position Pos, Callback< std::vector< CallHierarchyItem >> CB)
Get information about call hierarchy for a given position.
Definition: ClangdServer.cpp:739
clang::clangd::ClangdServer::ClangdServer
ClangdServer(const GlobalCompilationDatabase &CDB, const ThreadsafeFS &TFS, const Options &Opts, Callbacks *Callbacks=nullptr)
Creates a new ClangdServer instance.
Definition: ClangdServer.cpp:153
clang::clangd::Context
A context is an immutable container for per-request data that must be propagated through layers that ...
Definition: Context.h:69
clang::clangd::prepareCallHierarchy
std::vector< CallHierarchyItem > prepareCallHierarchy(ParsedAST &AST, Position Pos, PathRef TUPath)
Get call hierarchy information at Pos.
Definition: XRefs.cpp:1895
clang::clangd::ClangdServer::typeHierarchy
void typeHierarchy(PathRef File, Position Pos, int Resolve, TypeHierarchyDirection Direction, Callback< llvm::Optional< TypeHierarchyItem >> CB)
Get information about type hierarchy for a given position.
Definition: ClangdServer.cpp:715
clang::clangd::FileChangeType::Changed
@ Changed
The file got changed.
clang::clangd::tweakSelection
static llvm::Expected< std::vector< std::unique_ptr< Tweak::Selection > > > tweakSelection(const Range &Sel, const InputsAndAST &AST, llvm::vfs::FileSystem *FS)
Definition: ClangdServer.cpp:555
ParsedAST.h
clang::clangd::findDocumentHighlights
std::vector< DocumentHighlight > findDocumentHighlights(ParsedAST &AST, Position Pos)
Returns highlights for all usages of a symbol at Pos.
Definition: XRefs.cpp:1231
clang::clangd::ClangdServer::createConfiguredContextProvider
static std::function< Context(PathRef)> createConfiguredContextProvider(const config::Provider *Provider, ClangdServer::Callbacks *)
Creates a context provider that loads and installs config.
Definition: ClangdServer.cpp:263
clang::clangd::trace::Span
Records an event whose duration is the lifetime of the Span object.
Definition: Trace.h:143