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