clang-tools  11.0.0
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 "FindSymbols.h"
13 #include "Format.h"
14 #include "HeaderSourceSwitch.h"
15 #include "Headers.h"
16 #include "ParsedAST.h"
17 #include "Preamble.h"
18 #include "Protocol.h"
19 #include "SemanticHighlighting.h"
20 #include "SemanticSelection.h"
21 #include "SourceCode.h"
22 #include "TUScheduler.h"
23 #include "XRefs.h"
25 #include "index/FileIndex.h"
26 #include "index/Merge.h"
27 #include "refactor/Rename.h"
28 #include "refactor/Tweak.h"
29 #include "support/Logger.h"
30 #include "support/Markup.h"
31 #include "support/ThreadsafeFS.h"
32 #include "support/Trace.h"
33 #include "clang/Format/Format.h"
34 #include "clang/Frontend/CompilerInstance.h"
35 #include "clang/Frontend/CompilerInvocation.h"
36 #include "clang/Lex/Preprocessor.h"
37 #include "clang/Tooling/CompilationDatabase.h"
38 #include "clang/Tooling/Core/Replacement.h"
39 #include "llvm/ADT/ArrayRef.h"
40 #include "llvm/ADT/Optional.h"
41 #include "llvm/ADT/STLExtras.h"
42 #include "llvm/ADT/ScopeExit.h"
43 #include "llvm/ADT/StringRef.h"
44 #include "llvm/Support/Errc.h"
45 #include "llvm/Support/Error.h"
46 #include "llvm/Support/FileSystem.h"
47 #include "llvm/Support/Path.h"
48 #include "llvm/Support/ScopedPrinter.h"
49 #include "llvm/Support/raw_ostream.h"
50 #include <algorithm>
51 #include <chrono>
52 #include <future>
53 #include <memory>
54 #include <mutex>
55 #include <type_traits>
56 
57 namespace clang {
58 namespace clangd {
59 namespace {
60 
61 // Update the FileIndex with new ASTs and plumb the diagnostics responses.
62 struct UpdateIndexCallbacks : public ParsingCallbacks {
63  UpdateIndexCallbacks(FileIndex *FIndex,
64  ClangdServer::Callbacks *ServerCallbacks,
65  bool TheiaSemanticHighlighting)
66  : FIndex(FIndex), ServerCallbacks(ServerCallbacks),
67  TheiaSemanticHighlighting(TheiaSemanticHighlighting) {}
68 
69  void onPreambleAST(PathRef Path, llvm::StringRef Version, ASTContext &Ctx,
70  std::shared_ptr<clang::Preprocessor> PP,
71  const CanonicalIncludes &CanonIncludes) override {
72  if (FIndex)
73  FIndex->updatePreamble(Path, Version, Ctx, std::move(PP), CanonIncludes);
74  }
75 
76  void onMainAST(PathRef Path, ParsedAST &AST, PublishFn Publish) override {
77  if (FIndex)
78  FIndex->updateMain(Path, AST);
79 
80  std::vector<Diag> Diagnostics = AST.getDiagnostics();
81  std::vector<HighlightingToken> Highlightings;
82  if (TheiaSemanticHighlighting)
83  Highlightings = getSemanticHighlightings(AST);
84 
85  if (ServerCallbacks)
86  Publish([&]() {
87  ServerCallbacks->onDiagnosticsReady(Path, AST.version(),
88  std::move(Diagnostics));
89  if (TheiaSemanticHighlighting)
90  ServerCallbacks->onHighlightingsReady(Path, AST.version(),
91  std::move(Highlightings));
92  });
93  }
94 
95  void onFailedAST(PathRef Path, llvm::StringRef Version,
96  std::vector<Diag> Diags, PublishFn Publish) override {
97  if (ServerCallbacks)
98  Publish(
99  [&]() { ServerCallbacks->onDiagnosticsReady(Path, Version, Diags); });
100  }
101 
102  void onFileUpdated(PathRef File, const TUStatus &Status) override {
103  if (ServerCallbacks)
104  ServerCallbacks->onFileUpdated(File, Status);
105  }
106 
107 private:
108  FileIndex *FIndex;
109  ClangdServer::Callbacks *ServerCallbacks;
110  bool TheiaSemanticHighlighting;
111 };
112 } // namespace
113 
116  Opts.UpdateDebounce = DebouncePolicy::fixed(/*zero*/ {});
117  Opts.StorePreamblesInMemory = true;
118  Opts.AsyncThreadsCount = 4; // Consistent!
119  Opts.TheiaSemanticHighlighting = true;
120  Opts.AsyncPreambleBuilds = true;
121  return Opts;
122 }
123 
124 ClangdServer::Options::operator TUScheduler::Options() const {
126  Opts.AsyncThreadsCount = AsyncThreadsCount;
127  Opts.RetentionPolicy = RetentionPolicy;
128  Opts.StorePreamblesInMemory = StorePreamblesInMemory;
129  Opts.UpdateDebounce = UpdateDebounce;
130  Opts.AsyncPreambleBuilds = AsyncPreambleBuilds;
131  return Opts;
132 }
133 
135  const ThreadsafeFS &TFS, const Options &Opts,
137  : ConfigProvider(Opts.ConfigProvider), TFS(TFS),
138  DynamicIdx(Opts.BuildDynamicSymbolIndex
139  ? new FileIndex(Opts.HeavyweightDynamicSymbolIndex)
140  : nullptr),
141  GetClangTidyOptions(Opts.GetClangTidyOptions),
142  SuggestMissingIncludes(Opts.SuggestMissingIncludes),
143  BuildRecoveryAST(Opts.BuildRecoveryAST),
144  PreserveRecoveryASTType(Opts.PreserveRecoveryASTType),
145  TweakFilter(Opts.TweakFilter), WorkspaceRoot(Opts.WorkspaceRoot),
146  // Pass a callback into `WorkScheduler` to extract symbols from a newly
147  // parsed file and rebuild the file index synchronously each time an AST
148  // is parsed.
149  // FIXME(ioeric): this can be slow and we may be able to index on less
150  // critical paths.
151  WorkScheduler(
152  CDB,
153  [&, this] {
154  TUScheduler::Options O(Opts);
155  O.ContextProvider = [this](PathRef P) {
156  return createProcessingContext(P);
157  };
158  return O;
159  }(),
160  std::make_unique<UpdateIndexCallbacks>(
161  DynamicIdx.get(), Callbacks, Opts.TheiaSemanticHighlighting)) {
162  // Adds an index to the stack, at higher priority than existing indexes.
163  auto AddIndex = [&](SymbolIndex *Idx) {
164  if (this->Index != nullptr) {
165  MergedIdx.push_back(std::make_unique<MergedIndex>(Idx, this->Index));
166  this->Index = MergedIdx.back().get();
167  } else {
168  this->Index = Idx;
169  }
170  };
171  if (Opts.StaticIndex)
172  AddIndex(Opts.StaticIndex);
173  if (Opts.BackgroundIndex) {
174  BackgroundIdx = std::make_unique<BackgroundIndex>(
175  Context::current().clone(), TFS, CDB,
177  [&CDB](llvm::StringRef File) { return CDB.getProjectInfo(File); }),
178  std::max(Opts.AsyncThreadsCount, 1u),
179  [Callbacks](BackgroundQueue::Stats S) {
180  if (Callbacks)
181  Callbacks->onBackgroundIndexProgress(S);
182  },
183  [this](PathRef P) { return createProcessingContext(P); });
184  AddIndex(BackgroundIdx.get());
185  }
186  if (DynamicIdx)
187  AddIndex(DynamicIdx.get());
188 }
189 
190 void ClangdServer::addDocument(PathRef File, llvm::StringRef Contents,
191  llvm::StringRef Version,
192  WantDiagnostics WantDiags, bool ForceRebuild) {
193  ParseOptions Opts;
194  Opts.ClangTidyOpts = tidy::ClangTidyOptions::getDefaults();
195  // FIXME: call tidy options builder on the worker thread, it can do IO.
196  if (GetClangTidyOptions)
197  Opts.ClangTidyOpts =
198  GetClangTidyOptions(*TFS.view(/*CWD=*/llvm::None), File);
199  Opts.SuggestMissingIncludes = SuggestMissingIncludes;
200 
201  // Compile command is set asynchronously during update, as it can be slow.
203  Inputs.TFS = &TFS;
204  Inputs.Contents = std::string(Contents);
205  Inputs.Version = Version.str();
206  Inputs.ForceRebuild = ForceRebuild;
207  Inputs.Opts = std::move(Opts);
208  Inputs.Index = Index;
209  Inputs.Opts.BuildRecoveryAST = BuildRecoveryAST;
210  Inputs.Opts.PreserveRecoveryASTType = PreserveRecoveryASTType;
211  bool NewFile = WorkScheduler.update(File, Inputs, WantDiags);
212  // If we loaded Foo.h, we want to make sure Foo.cpp is indexed.
213  if (NewFile && BackgroundIdx)
214  BackgroundIdx->boostRelated(File);
215 }
216 
217 void ClangdServer::removeDocument(PathRef File) { WorkScheduler.remove(File); }
218 
220  const clangd::CodeCompleteOptions &Opts,
222  // Copy completion options for passing them to async task handler.
223  auto CodeCompleteOpts = Opts;
224  if (!CodeCompleteOpts.Index) // Respect overridden index.
225  CodeCompleteOpts.Index = Index;
226 
227  auto Task = [Pos, CodeCompleteOpts, File = File.str(), CB = std::move(CB),
228  this](llvm::Expected<InputsAndPreamble> IP) mutable {
229  if (!IP)
230  return CB(IP.takeError());
231  if (auto Reason = isCancelled())
232  return CB(llvm::make_error<CancelledError>(Reason));
233 
234  llvm::Optional<SpeculativeFuzzyFind> SpecFuzzyFind;
235  if (!IP->Preamble) {
236  // No speculation in Fallback mode, as it's supposed to be much faster
237  // without compiling.
238  vlog("Build for file {0} is not ready. Enter fallback mode.", File);
239  } else {
240  if (CodeCompleteOpts.Index && CodeCompleteOpts.SpeculativeIndexRequest) {
241  SpecFuzzyFind.emplace();
242  {
243  std::lock_guard<std::mutex> Lock(
244  CachedCompletionFuzzyFindRequestMutex);
245  SpecFuzzyFind->CachedReq =
246  CachedCompletionFuzzyFindRequestByFile[File];
247  }
248  }
249  }
250  ParseInputs ParseInput{IP->Command, &TFS, IP->Contents.str()};
251  ParseInput.Index = Index;
252  ParseInput.Opts.BuildRecoveryAST = BuildRecoveryAST;
253  ParseInput.Opts.PreserveRecoveryASTType = PreserveRecoveryASTType;
254 
255  // FIXME(ibiryukov): even if Preamble is non-null, we may want to check
256  // both the old and the new version in case only one of them matches.
258  File, Pos, IP->Preamble, ParseInput, CodeCompleteOpts,
259  SpecFuzzyFind ? SpecFuzzyFind.getPointer() : nullptr);
260  {
261  clang::clangd::trace::Span Tracer("Completion results callback");
262  CB(std::move(Result));
263  }
264  if (SpecFuzzyFind && SpecFuzzyFind->NewReq.hasValue()) {
265  std::lock_guard<std::mutex> Lock(CachedCompletionFuzzyFindRequestMutex);
266  CachedCompletionFuzzyFindRequestByFile[File] =
267  SpecFuzzyFind->NewReq.getValue();
268  }
269  // SpecFuzzyFind is only destroyed after speculative fuzzy find finishes.
270  // We don't want `codeComplete` to wait for the async call if it doesn't use
271  // the result (e.g. non-index completion, speculation fails), so that `CB`
272  // is called as soon as results are available.
273  };
274 
275  // We use a potentially-stale preamble because latency is critical here.
276  WorkScheduler.runWithPreamble(
277  "CodeComplete", File,
278  (Opts.RunParser == CodeCompleteOptions::AlwaysParse)
281  std::move(Task));
282 }
283 
286 
287  auto Action = [Pos, File = File.str(), CB = std::move(CB),
288  this](llvm::Expected<InputsAndPreamble> IP) mutable {
289  if (!IP)
290  return CB(IP.takeError());
291 
292  const auto *PreambleData = IP->Preamble;
293  if (!PreambleData)
294  return CB(llvm::createStringError(llvm::inconvertibleErrorCode(),
295  "Failed to parse includes"));
296 
297  ParseInputs ParseInput{IP->Command, &TFS, IP->Contents.str()};
298  ParseInput.Index = Index;
299  ParseInput.Opts.BuildRecoveryAST = BuildRecoveryAST;
300  ParseInput.Opts.PreserveRecoveryASTType = PreserveRecoveryASTType;
302  };
303 
304  // Unlike code completion, we wait for a preamble here.
305  WorkScheduler.runWithPreamble("SignatureHelp", File, TUScheduler::Stale,
306  std::move(Action));
307 }
308 
309 void ClangdServer::formatRange(PathRef File, llvm::StringRef Code, Range Rng,
311  llvm::Expected<size_t> Begin = positionToOffset(Code, Rng.start);
312  if (!Begin)
313  return CB(Begin.takeError());
314  llvm::Expected<size_t> End = positionToOffset(Code, Rng.end);
315  if (!End)
316  return CB(End.takeError());
317  formatCode(File, Code, {tooling::Range(*Begin, *End - *Begin)},
318  std::move(CB));
319 }
320 
321 void ClangdServer::formatFile(PathRef File, llvm::StringRef Code,
323  // Format everything.
324  formatCode(File, Code, {tooling::Range(0, Code.size())}, std::move(CB));
325 }
326 
327 void ClangdServer::formatOnType(PathRef File, llvm::StringRef Code,
328  Position Pos, StringRef TriggerText,
329  Callback<std::vector<TextEdit>> CB) {
330  llvm::Expected<size_t> CursorPos = positionToOffset(Code, Pos);
331  if (!CursorPos)
332  return CB(CursorPos.takeError());
333  auto Action = [File = File.str(), Code = Code.str(),
334  TriggerText = TriggerText.str(), CursorPos = *CursorPos,
335  CB = std::move(CB), this]() mutable {
336  auto Style = format::getStyle(format::DefaultFormatStyle, File,
337  format::DefaultFallbackStyle, Code,
338  TFS.view(/*CWD=*/llvm::None).get());
339  if (!Style)
340  return CB(Style.takeError());
341 
342  std::vector<TextEdit> Result;
343  for (const tooling::Replacement &R :
344  formatIncremental(Code, CursorPos, TriggerText, *Style))
345  Result.push_back(replacementToEdit(Code, R));
346  return CB(Result);
347  };
348  WorkScheduler.run("FormatOnType", File, std::move(Action));
349 }
350 
352  const RenameOptions &RenameOpts,
353  Callback<llvm::Optional<Range>> CB) {
354  auto Action = [Pos, File = File.str(), CB = std::move(CB), RenameOpts,
355  this](llvm::Expected<InputsAndAST> InpAST) mutable {
356  if (!InpAST)
357  return CB(InpAST.takeError());
358  auto &AST = InpAST->AST;
359  const auto &SM = AST.getSourceManager();
360  auto Loc = sourceLocationInMainFile(SM, Pos);
361  if (!Loc)
362  return CB(Loc.takeError());
363  const auto *TouchingIdentifier =
364  spelledIdentifierTouching(*Loc, AST.getTokens());
365  if (!TouchingIdentifier)
366  return CB(llvm::None); // no rename on non-identifiers.
367 
368  auto Range = halfOpenToRange(
369  SM, CharSourceRange::getCharRange(TouchingIdentifier->location(),
370  TouchingIdentifier->endLocation()));
371 
372  if (RenameOpts.AllowCrossFile)
373  // FIXME: we now assume cross-file rename always succeeds, revisit this.
374  return CB(Range);
375 
376  // Performing the local rename isn't substantially more expensive than
377  // doing an AST-based check, so we just rename and throw away the results.
378  auto Changes = clangd::rename({Pos, "dummy", AST, File, Index, RenameOpts,
379  /*GetDirtyBuffer=*/nullptr});
380  if (!Changes) {
381  // LSP says to return null on failure, but that will result in a generic
382  // failure message. If we send an LSP error response, clients can surface
383  // the message to users (VSCode does).
384  return CB(Changes.takeError());
385  }
386  return CB(Range);
387  };
388  WorkScheduler.runWithAST("PrepareRename", File, std::move(Action));
389 }
390 
391 void ClangdServer::rename(PathRef File, Position Pos, llvm::StringRef NewName,
392  const RenameOptions &Opts, Callback<FileEdits> CB) {
393  // A snapshot of all file dirty buffers.
394  llvm::StringMap<std::string> Snapshot = WorkScheduler.getAllFileContents();
395  auto Action = [File = File.str(), NewName = NewName.str(), Pos, Opts,
396  CB = std::move(CB), Snapshot = std::move(Snapshot),
397  this](llvm::Expected<InputsAndAST> InpAST) mutable {
398  // Tracks number of files edited per invocation.
399  static constexpr trace::Metric RenameFiles("rename_files",
401  if (!InpAST)
402  return CB(InpAST.takeError());
403  auto GetDirtyBuffer =
404  [&Snapshot](PathRef AbsPath) -> llvm::Optional<std::string> {
405  auto It = Snapshot.find(AbsPath);
406  if (It == Snapshot.end())
407  return llvm::None;
408  return It->second;
409  };
410  auto Edits = clangd::rename(
411  {Pos, NewName, InpAST->AST, File, Index, Opts, GetDirtyBuffer});
412  if (!Edits)
413  return CB(Edits.takeError());
414 
415  if (Opts.WantFormat) {
416  auto Style = getFormatStyleForFile(File, InpAST->Inputs.Contents,
417  *InpAST->Inputs.TFS);
418  llvm::Error Err = llvm::Error::success();
419  for (auto &E : *Edits)
420  Err =
421  llvm::joinErrors(reformatEdit(E.getValue(), Style), std::move(Err));
422 
423  if (Err)
424  return CB(std::move(Err));
425  }
426  RenameFiles.record(Edits->size());
427  return CB(std::move(*Edits));
428  };
429  WorkScheduler.runWithAST("Rename", File, std::move(Action));
430 }
431 
432 // May generate several candidate selections, due to SelectionTree ambiguity.
433 // vector of pointers because GCC doesn't like non-copyable Selection.
434 static llvm::Expected<std::vector<std::unique_ptr<Tweak::Selection>>>
435 tweakSelection(const Range &Sel, const InputsAndAST &AST) {
436  auto Begin = positionToOffset(AST.Inputs.Contents, Sel.start);
437  if (!Begin)
438  return Begin.takeError();
439  auto End = positionToOffset(AST.Inputs.Contents, Sel.end);
440  if (!End)
441  return End.takeError();
442  std::vector<std::unique_ptr<Tweak::Selection>> Result;
444  AST.AST.getASTContext(), AST.AST.getTokens(), *Begin, *End,
445  [&](SelectionTree T) {
446  Result.push_back(std::make_unique<Tweak::Selection>(
447  AST.Inputs.Index, AST.AST, *Begin, *End, std::move(T)));
448  return false;
449  });
450  assert(!Result.empty() && "Expected at least one SelectionTree");
451  return std::move(Result);
452 }
453 
455  Callback<std::vector<TweakRef>> CB) {
456  // Tracks number of times a tweak has been offered.
457  static constexpr trace::Metric TweakAvailable(
458  "tweak_available", trace::Metric::Counter, "tweak_id");
459  auto Action = [File = File.str(), Sel, CB = std::move(CB),
460  this](Expected<InputsAndAST> InpAST) mutable {
461  if (!InpAST)
462  return CB(InpAST.takeError());
463  auto Selections = tweakSelection(Sel, *InpAST);
464  if (!Selections)
465  return CB(Selections.takeError());
466  std::vector<TweakRef> Res;
467  // Don't allow a tweak to fire more than once across ambiguous selections.
468  llvm::DenseSet<llvm::StringRef> PreparedTweaks;
469  auto Filter = [&](const Tweak &T) {
470  return TweakFilter(T) && !PreparedTweaks.count(T.id());
471  };
472  for (const auto &Sel : *Selections) {
473  for (auto &T : prepareTweaks(*Sel, Filter)) {
474  Res.push_back({T->id(), T->title(), T->intent()});
475  PreparedTweaks.insert(T->id());
476  TweakAvailable.record(1, T->id());
477  }
478  }
479 
480  CB(std::move(Res));
481  };
482 
483  WorkScheduler.runWithAST("EnumerateTweaks", File, std::move(Action),
485 }
486 
487 void ClangdServer::applyTweak(PathRef File, Range Sel, StringRef TweakID,
489  // Tracks number of times a tweak has been applied.
490  static constexpr trace::Metric TweakAttempt(
491  "tweak_attempt", trace::Metric::Counter, "tweak_id");
492  TweakAttempt.record(1, TweakID);
493  auto Action = [File = File.str(), Sel, TweakID = TweakID.str(),
494  CB = std::move(CB),
495  this](Expected<InputsAndAST> InpAST) mutable {
496  if (!InpAST)
497  return CB(InpAST.takeError());
498  auto Selections = tweakSelection(Sel, *InpAST);
499  if (!Selections)
500  return CB(Selections.takeError());
501  llvm::Optional<llvm::Expected<Tweak::Effect>> Effect;
502  // Try each selection, take the first one that prepare()s.
503  // If they all fail, Effect will hold get the last error.
504  for (const auto &Selection : *Selections) {
505  auto T = prepareTweak(TweakID, *Selection);
506  if (T) {
507  Effect = (*T)->apply(*Selection);
508  break;
509  }
510  Effect = T.takeError();
511  }
512  assert(Effect.hasValue() && "Expected at least one selection");
513  if (*Effect) {
514  // Tweaks don't apply clang-format, do that centrally here.
515  for (auto &It : (*Effect)->ApplyEdits) {
516  Edit &E = It.second;
517  format::FormatStyle Style =
518  getFormatStyleForFile(File, E.InitialCode, TFS);
519  if (llvm::Error Err = reformatEdit(E, Style))
520  elog("Failed to format {0}: {1}", It.first(), std::move(Err));
521  }
522  }
523  return CB(std::move(*Effect));
524  };
525  WorkScheduler.runWithAST("ApplyTweak", File, std::move(Action));
526 }
527 
529  llvm::unique_function<void(std::string)> Callback) {
530  auto Action = [Callback = std::move(Callback)](
531  llvm::Expected<InputsAndAST> InpAST) mutable {
532  if (!InpAST) {
533  llvm::consumeError(InpAST.takeError());
534  return Callback("<no-ast>");
535  }
536  std::string Result;
537 
538  llvm::raw_string_ostream ResultOS(Result);
539  clangd::dumpAST(InpAST->AST, ResultOS);
540  ResultOS.flush();
541 
542  Callback(Result);
543  };
544 
545  WorkScheduler.runWithAST("DumpAST", File, std::move(Action));
546 }
547 
549  Callback<std::vector<LocatedSymbol>> CB) {
550  auto Action = [Pos, CB = std::move(CB),
551  this](llvm::Expected<InputsAndAST> InpAST) mutable {
552  if (!InpAST)
553  return CB(InpAST.takeError());
554  CB(clangd::locateSymbolAt(InpAST->AST, Pos, Index));
555  };
556 
557  WorkScheduler.runWithAST("Definitions", File, std::move(Action));
558 }
559 
561  PathRef Path, Callback<llvm::Optional<clangd::Path>> CB) {
562  // We want to return the result as fast as possible, strategy is:
563  // 1) use the file-only heuristic, it requires some IO but it is much
564  // faster than building AST, but it only works when .h/.cc files are in
565  // the same directory.
566  // 2) if 1) fails, we use the AST&Index approach, it is slower but supports
567  // different code layout.
568  if (auto CorrespondingFile = getCorrespondingHeaderOrSource(
569  std::string(Path), TFS.view(llvm::None)))
570  return CB(std::move(CorrespondingFile));
571  auto Action = [Path = Path.str(), CB = std::move(CB),
572  this](llvm::Expected<InputsAndAST> InpAST) mutable {
573  if (!InpAST)
574  return CB(InpAST.takeError());
575  CB(getCorrespondingHeaderOrSource(Path, InpAST->AST, Index));
576  };
577  WorkScheduler.runWithAST("SwitchHeaderSource", Path, std::move(Action));
578 }
579 
580 void ClangdServer::formatCode(PathRef File, llvm::StringRef Code,
581  llvm::ArrayRef<tooling::Range> Ranges,
583  // Call clang-format.
584  auto Action = [File = File.str(), Code = Code.str(), Ranges = Ranges.vec(),
585  CB = std::move(CB), this]() mutable {
587  tooling::Replacements IncludeReplaces =
588  format::sortIncludes(Style, Code, Ranges, File);
589  auto Changed = tooling::applyAllReplacements(Code, IncludeReplaces);
590  if (!Changed)
591  return CB(Changed.takeError());
592 
593  CB(IncludeReplaces.merge(format::reformat(
594  Style, *Changed,
595  tooling::calculateRangesAfterReplacements(IncludeReplaces, Ranges),
596  File)));
597  };
598  WorkScheduler.run("Format", File, std::move(Action));
599 }
600 
602  PathRef File, Position Pos, Callback<std::vector<DocumentHighlight>> CB) {
603  auto Action =
604  [Pos, CB = std::move(CB)](llvm::Expected<InputsAndAST> InpAST) mutable {
605  if (!InpAST)
606  return CB(InpAST.takeError());
607  CB(clangd::findDocumentHighlights(InpAST->AST, Pos));
608  };
609 
610  WorkScheduler.runWithAST("Highlights", File, std::move(Action),
612 }
613 
615  Callback<llvm::Optional<HoverInfo>> CB) {
616  auto Action = [File = File.str(), Pos, CB = std::move(CB),
617  this](llvm::Expected<InputsAndAST> InpAST) mutable {
618  if (!InpAST)
619  return CB(InpAST.takeError());
621  File, InpAST->Inputs.Contents, *InpAST->Inputs.TFS);
622  CB(clangd::getHover(InpAST->AST, Pos, std::move(Style), Index));
623  };
624 
625  WorkScheduler.runWithAST("Hover", File, std::move(Action),
627 }
628 
630  TypeHierarchyDirection Direction,
631  Callback<Optional<TypeHierarchyItem>> CB) {
632  auto Action = [File = File.str(), Pos, Resolve, Direction, CB = std::move(CB),
633  this](Expected<InputsAndAST> InpAST) mutable {
634  if (!InpAST)
635  return CB(InpAST.takeError());
636  CB(clangd::getTypeHierarchy(InpAST->AST, Pos, Resolve, Direction, Index,
637  File));
638  };
639 
640  WorkScheduler.runWithAST("Type Hierarchy", File, std::move(Action));
641 }
642 
644  TypeHierarchyItem Item, int Resolve, TypeHierarchyDirection Direction,
645  Callback<llvm::Optional<TypeHierarchyItem>> CB) {
646  clangd::resolveTypeHierarchy(Item, Resolve, Direction, Index);
647  CB(Item);
648 }
649 
651  // FIXME: Do nothing for now. This will be used for indexing and potentially
652  // invalidating other caches.
653 }
654 
656  llvm::StringRef Query, int Limit,
657  Callback<std::vector<SymbolInformation>> CB) {
658  WorkScheduler.run(
659  "getWorkspaceSymbols", /*Path=*/"",
660  [Query = Query.str(), Limit, CB = std::move(CB), this]() mutable {
661  CB(clangd::getWorkspaceSymbols(Query, Limit, Index,
662  WorkspaceRoot.getValueOr("")));
663  });
664 }
665 
666 void ClangdServer::documentSymbols(llvm::StringRef File,
667  Callback<std::vector<DocumentSymbol>> CB) {
668  auto Action =
669  [CB = std::move(CB)](llvm::Expected<InputsAndAST> InpAST) mutable {
670  if (!InpAST)
671  return CB(InpAST.takeError());
672  CB(clangd::getDocumentSymbols(InpAST->AST));
673  };
674  WorkScheduler.runWithAST("documentSymbols", File, std::move(Action),
676 }
677 
678 void ClangdServer::foldingRanges(llvm::StringRef File,
679  Callback<std::vector<FoldingRange>> CB) {
680  auto Action =
681  [CB = std::move(CB)](llvm::Expected<InputsAndAST> InpAST) mutable {
682  if (!InpAST)
683  return CB(InpAST.takeError());
684  CB(clangd::getFoldingRanges(InpAST->AST));
685  };
686  WorkScheduler.runWithAST("foldingRanges", File, std::move(Action),
688 }
689 
692  auto Action = [Pos, Limit, CB = std::move(CB),
693  this](llvm::Expected<InputsAndAST> InpAST) mutable {
694  if (!InpAST)
695  return CB(InpAST.takeError());
696  CB(clangd::findReferences(InpAST->AST, Pos, Limit, Index));
697  };
698 
699  WorkScheduler.runWithAST("References", File, std::move(Action));
700 }
701 
703  Callback<std::vector<SymbolDetails>> CB) {
704  auto Action =
705  [Pos, CB = std::move(CB)](llvm::Expected<InputsAndAST> InpAST) mutable {
706  if (!InpAST)
707  return CB(InpAST.takeError());
708  CB(clangd::getSymbolInfo(InpAST->AST, Pos));
709  };
710 
711  WorkScheduler.runWithAST("SymbolInfo", File, std::move(Action));
712 }
713 
715  const std::vector<Position> &Positions,
716  Callback<std::vector<SelectionRange>> CB) {
717  auto Action = [Positions, CB = std::move(CB)](
718  llvm::Expected<InputsAndAST> InpAST) mutable {
719  if (!InpAST)
720  return CB(InpAST.takeError());
721  std::vector<SelectionRange> Result;
722  for (const auto &Pos : Positions) {
723  if (auto Range = clangd::getSemanticRanges(InpAST->AST, Pos))
724  Result.push_back(std::move(*Range));
725  else
726  return CB(Range.takeError());
727  }
728  CB(std::move(Result));
729  };
730  WorkScheduler.runWithAST("SemanticRanges", File, std::move(Action));
731 }
732 
734  Callback<std::vector<DocumentLink>> CB) {
735  auto Action =
736  [CB = std::move(CB)](llvm::Expected<InputsAndAST> InpAST) mutable {
737  if (!InpAST)
738  return CB(InpAST.takeError());
739  CB(clangd::getDocumentLinks(InpAST->AST));
740  };
741  WorkScheduler.runWithAST("DocumentLinks", File, std::move(Action),
743 }
744 
746  PathRef File, Callback<std::vector<HighlightingToken>> CB) {
747  auto Action =
748  [CB = std::move(CB)](llvm::Expected<InputsAndAST> InpAST) mutable {
749  if (!InpAST)
750  return CB(InpAST.takeError());
751  CB(clangd::getSemanticHighlightings(InpAST->AST));
752  };
753  WorkScheduler.runWithAST("SemanticHighlights", File, std::move(Action),
755 }
756 
757 llvm::StringMap<TUScheduler::FileStats> ClangdServer::fileStats() const {
758  return WorkScheduler.fileStats();
759 }
760 
761 Context ClangdServer::createProcessingContext(PathRef File) const {
762  if (!ConfigProvider)
763  return Context::current().clone();
764 
765  config::Params Params;
766  // Don't reread config files excessively often.
767  // FIXME: when we see a config file change event, use the event timestamp.
768  Params.FreshTime = std::chrono::steady_clock::now() - std::chrono::seconds(5);
769  llvm::SmallString<256> PosixPath;
770  if (!File.empty()) {
771  assert(llvm::sys::path::is_absolute(File));
772  llvm::sys::path::native(File, PosixPath, llvm::sys::path::Style::posix);
773  Params.Path = PosixPath.str();
774  }
775 
776  auto DiagnosticHandler = [](const llvm::SMDiagnostic &Diag) {
777  if (Diag.getKind() == llvm::SourceMgr::DK_Error) {
778  elog("config error at {0}:{1}:{2}: {3}", Diag.getFilename(),
779  Diag.getLineNo(), Diag.getColumnNo(), Diag.getMessage());
780  } else {
781  log("config warning at {0}:{1}:{2}: {3}", Diag.getFilename(),
782  Diag.getLineNo(), Diag.getColumnNo(), Diag.getMessage());
783  }
784  };
785  Config C = ConfigProvider->getConfig(Params, DiagnosticHandler);
786  return Context::current().derive(Config::Key, std::move(C));
787 }
788 
789 LLVM_NODISCARD bool
790 ClangdServer::blockUntilIdleForTest(llvm::Optional<double> TimeoutSeconds) {
791  return WorkScheduler.blockUntilIdle(timeoutSeconds(TimeoutSeconds)) &&
792  (!BackgroundIdx ||
793  BackgroundIdx->blockUntilIdleForTest(TimeoutSeconds));
794 }
795 
796 } // namespace clangd
797 } // namespace clang
Range
CharSourceRange Range
SourceRange for the file name.
Definition: IncludeOrderCheck.cpp:38
clang::clangd::ClangdServer::fileStats
llvm::StringMap< TUScheduler::FileStats > fileStats() const
Returns estimated memory usage and other statistics for each of the currently open files.
Definition: ClangdServer.cpp:757
WantDiags
WantDiagnostics WantDiags
Definition: TUScheduler.cpp:323
XRefs.h
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:102
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:105
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:1790
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:1020
clang::clangd::Edit
A set of edits generated for a single file.
Definition: SourceCode.h:180
E
const Expr * E
Definition: AvoidBindCheck.cpp:88
clang::clangd::ClangdServer::dumpAST
void dumpAST(PathRef File, llvm::unique_function< void(std::string)> Callback)
Only for testing purposes.
Definition: ClangdServer.cpp:528
clang::clangd::TUScheduler::runWithPreamble
void runWithPreamble(llvm::StringRef Name, PathRef File, PreambleConsistency Consistency, Callback< InputsAndPreamble > Action)
Schedule an async read of the preamble.
Definition: TUScheduler.cpp:1331
CodeComplete.h
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:471
clang::clangd::ClangdServer::prepareRename
void prepareRename(PathRef File, Position Pos, const RenameOptions &RenameOpts, Callback< llvm::Optional< Range >> CB)
Test the validity of a rename operation.
Definition: ClangdServer.cpp:351
clang::clangd::config::Params::FreshTime
llvm::Optional< std::chrono::steady_clock::time_point > FreshTime
Hint that stale data is OK to improve performance (e.g.
Definition: ConfigProvider.h:41
clang::clangd::Path
std::string Path
A typedef to represent a file path.
Definition: Path.h:20
clang::clangd::resolveTypeHierarchy
void resolveTypeHierarchy(TypeHierarchyItem &Item, int ResolveLevels, TypeHierarchyDirection Direction, const SymbolIndex *Index)
Definition: XRefs.cpp:1439
Tracer
std::unique_ptr< trace::EventTracer > Tracer
Definition: TraceTests.cpp:163
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::TUScheduler::blockUntilIdle
bool blockUntilIdle(Deadline D) const
Wait until there are no scheduled or running tasks.
Definition: TUScheduler.cpp:1258
clang::clangd::InputsAndAST
Definition: TUScheduler.h:35
clang::clangd::Context::clone
Context clone() const
Clone this context object.
Definition: Context.cpp:20
ParseInput
const ParseInputs & ParseInput
Definition: CodeComplete.cpp:1047
clang::clangd::ClangdServer::formatFile
void formatFile(PathRef File, StringRef Code, Callback< tooling::Replacements > CB)
Run formatting for the whole File with content Code.
Definition: ClangdServer.cpp:321
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:775
clang::clangd::PreambleData::Preamble
PrecompiledPreamble Preamble
Definition: Preamble.h:59
clang::clangd::rename
llvm::Expected< FileEdits > rename(const RenameInputs &RInputs)
Renames all occurrences of the symbol.
Definition: Rename.cpp:442
Contents
llvm::StringRef Contents
Definition: DraftStoreTests.cpp:22
clang::clangd::Range::start
Position start
The range's start position.
Definition: Protocol.h:175
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:1034
Preamble.h
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:560
Ctx
Context Ctx
Definition: TUScheduler.cpp:324
clang::clangd::ClangdServer::findReferences
void findReferences(PathRef File, Position Pos, uint32_t Limit, Callback< ReferencesResult > CB)
Retrieve locations for symbol references.
Definition: ClangdServer.cpp:690
clang::clangd::TUScheduler::run
void run(llvm::StringRef Name, llvm::StringRef Path, llvm::unique_function< void()> Action)
Schedule an async task with no dependencies.
Definition: TUScheduler.cpp:1301
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:783
Trace.h
clang::clangd::ClangdServer::optsForTest
static Options optsForTest()
Definition: ClangdServer.cpp:114
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:46
clang::clangd::TextDocumentSyncKind::None
Documents should not be synced at all.
clang::clangd::FileIndex
This manages symbols from files and an in-memory index on all symbols.
Definition: FileIndex.h:105
Changes
tooling::Replacements Changes
Definition: Format.cpp:109
clang::clangd::TUScheduler::update
bool update(PathRef File, ParseInputs Inputs, WantDiagnostics WD)
Schedule an update for File.
Definition: TUScheduler.cpp:1268
clang::clangd::ClangdServer::rename
void rename(PathRef File, Position Pos, llvm::StringRef NewName, const RenameOptions &Opts, Callback< FileEdits > CB)
Rename all occurrences of the symbol at the Pos in File to NewName.
Definition: ClangdServer.cpp:391
clang::clangd::prepareTweak
llvm::Expected< std::unique_ptr< Tweak > > prepareTweak(StringRef ID, const Tweak::Selection &S)
Definition: Tweak.cpp:77
clang::clangd::GlobalCompilationDatabase
Provides compilation arguments used for parsing C and C++ files.
Definition: GlobalCompilationDatabase.h:35
Action
llvm::unique_function< void()> Action
Definition: TUScheduler.cpp:447
clang::clangd::ClangdServer::enumerateTweaks
void enumerateTweaks(PathRef File, Range Sel, Callback< std::vector< TweakRef >> CB)
Enumerate the code tweaks available to the user at a specified point.
Definition: ClangdServer.cpp:454
clang::clangd::TUScheduler::Options::ContextProvider
std::function< Context(PathRef)> ContextProvider
Used to create a context that wraps each single operation.
Definition: TUScheduler.h:202
clang::clangd::ClangdServer::documentSymbols
void documentSymbols(StringRef File, Callback< std::vector< DocumentSymbol >> CB)
Retrieve the symbols within the specified file.
Definition: ClangdServer.cpp:666
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:678
clang::clangd::replacementToEdit
TextEdit replacementToEdit(llvm::StringRef Code, const tooling::Replacement &R)
Definition: SourceCode.cpp:496
clang::clangd::TUScheduler::Stale
The preamble may be generated from an older version of the file.
Definition: TUScheduler.h:277
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:190
clang::clangd::TUScheduler::StaleOrAbsent
Besides accepting stale preamble, this also allow preamble to be absent (not ready or failed to build...
Definition: TUScheduler.h:280
clang::clangd::ClangdServer::formatOnType
void formatOnType(PathRef File, StringRef Code, 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:327
clang::clangd::WantDiagnostics
WantDiagnostics
Determines whether diagnostics should be generated for a file snapshot.
Definition: TUScheduler.h:48
Protocol.h
ThreadsafeFS.h
Inputs
ParseInputs Inputs
Definition: TUScheduler.cpp:321
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::ClangdServer::Options
Definition: ClangdServer.h:90
Rename.h
clang::clangd::halfOpenToRange
Range halfOpenToRange(const SourceManager &SM, CharSourceRange R)
Definition: SourceCode.cpp:471
clang::clangd::Position
Definition: Protocol.h:144
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
CanonicalIncludes.h
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:542
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:217
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:219
clang::clangd::PreambleData
The parsed preamble and associated data.
Definition: Preamble.h:49
Tweak.h
SemanticSelection.h
clang::clangd::prepareTweaks
std::vector< std::unique_ptr< Tweak > > prepareTweaks(const Tweak::Selection &S, llvm::function_ref< bool(const Tweak &)> Filter)
Calls prepare() on all tweaks that satisfy the filter, returning those that can run on the selection.
Definition: Tweak.cpp:59
clang::clangd::DidChangeWatchedFilesParams
Definition: Protocol.h:720
Logger.h
Markup.h
clang::clangd::getSymbolInfo
std::vector< SymbolDetails > getSymbolInfo(ParsedAST &AST, Position Pos)
Get info about symbols at Pos.
Definition: XRefs.cpp:1123
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:1768
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:650
clang::clangd::config::Provider::getConfig
Config getConfig(const Params &, DiagnosticCallback) const
Build a config based on this provider.
Definition: ConfigProvider.cpp:215
clang::clangd::ClangdServer::semanticHighlights
void semanticHighlights(PathRef File, Callback< std::vector< HighlightingToken >>)
Definition: ClangdServer.cpp:745
clang::clangd::RenameOptions
Definition: Rename.h:29
clang::clangd::vlog
void vlog(const char *Fmt, Ts &&... Vals)
Definition: Logger.h:67
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:601
clang::clangd::trace::Metric::Distribution
A distribution of values with a meaningful mean and count.
Definition: Trace.h:52
clang::clangd::TUScheduler::remove
void remove(PathRef File)
Remove File from the list of tracked files and schedule removal of its resources.
Definition: TUScheduler.cpp:1287
clang::clangd::Range::end
Position end
The range's end position.
Definition: Protocol.h:178
clang::clangd::TUScheduler::fileStats
llvm::StringMap< FileStats > fileStats() const
Returns resources used for each of the currently open files.
Definition: TUScheduler.cpp:1383
clang::clangd::SelectionTree
Definition: Selection.h:76
FileIndex.h
clang::clangd::SymbolOrigin::AST
clang::clangd::getSemanticHighlightings
std::vector< HighlightingToken > getSemanticHighlightings(ParsedAST &AST)
Definition: SemanticHighlighting.cpp:340
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:270
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:578
clang::clangd::CodeCompleteOptions
Definition: CodeComplete.h:44
clang::tidy::bugprone::PP
static Preprocessor * PP
Definition: BadSignalToKillThreadCheck.cpp:29
clang::clangd::log
void log(const char *Fmt, Ts &&... Vals)
Definition: Logger.h:62
Config
static cl::opt< std::string > Config("config", cl::desc(R"( Specifies a configuration in YAML/JSON format: -config="{Checks:' *', CheckOptions:[{key:x, value:y}]}" When the value is empty, clang-tidy will attempt to find a file named .clang-tidy for each source file in its parent directories. )"), cl::init(""), cl::cat(ClangTidyCategory))
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:655
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:733
clang::clangd::CompletionItemKind::File
clang::clangd::getWorkspaceSymbols
llvm::Expected< std::vector< SymbolInformation > > getWorkspaceSymbols(llvm::StringRef Query, int Limit, const SymbolIndex *const Index, llvm::StringRef HintPath)
Searches for the symbols matching Query.
Definition: FindSymbols.cpp:71
clang::clangd::SymbolIndex
Interface for symbol indexes that can be used for searching or matching symbols among a set of symbol...
Definition: Index.h:85
clang::clangd::trace::Metric::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:284
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:548
clang::clangd::TypeHierarchyDirection
TypeHierarchyDirection
Definition: Protocol.h:1270
clang::clangd::TypeHierarchyItem
Definition: Protocol.h:1285
clang::clangd::tweakSelection
static llvm::Expected< std::vector< std::unique_ptr< Tweak::Selection > > > tweakSelection(const Range &Sel, const InputsAndAST &AST)
Definition: ClangdServer.cpp:435
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:121
clang::clangd::ClangdServer::Callbacks
Interface with hooks for users of ClangdServer to be notified of events.
Definition: ClangdServer.h:66
clang::clangd::PathRef
llvm::StringRef PathRef
A typedef to represent a ref to file path.
Definition: Path.h:23
clang::clangd::ThreadsafeFS
Wrapper for vfs::FileSystem for use in multithreaded programs like clangd.
Definition: ThreadsafeFS.h:28
RenameOpts
RenameOptions RenameOpts
Definition: ClangdLSPServerTests.cpp:68
clang::clangd::trace::Metric
Represents measurements of clangd events, e.g.
Definition: Trace.h:38
clang::clangd::ParseOptions
Definition: Compiler.h:39
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::dumpAST
void dumpAST(ParsedAST &AST, llvm::raw_ostream &OS)
For testing/debugging purposes.
Definition: ParsedAST.cpp:241
clang::clangd::TUScheduler::Options
Definition: TUScheduler.h:178
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:487
clang::clangd::TUScheduler::runWithAST
void runWithAST(llvm::StringRef Name, PathRef File, Callback< InputsAndAST > Action, ASTActionInvalidation=NoInvalidation)
Schedule an async read of the AST.
Definition: TUScheduler.cpp:1317
clang::clangd::Range
Definition: Protocol.h:173
SemanticHighlighting.h
clang::clangd::CodeCompleteResult
Definition: CodeComplete.h:234
clang::clangd::CodeCompleteOptions::AlwaysParse
Block until we can run the parser (e.g.
Definition: CodeComplete.h:133
clang::clangd::config::Params
Describes the context used to evaluate configuration fragments.
Definition: ConfigProvider.h:34
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:702
clang::clangd::ParsedAST::getTokens
const syntax::TokenBuffer & getTokens() const
Tokens recorded while parsing the main file.
Definition: ParsedAST.h:103
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:37
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:247
TUScheduler.h
clang::clangd::TUScheduler::getAllFileContents
llvm::StringMap< std::string > getAllFileContents() const
Returns a snapshot of all file buffer contents, per last update().
Definition: TUScheduler.cpp:1294
Diags
CapturedDiags Diags
Definition: ConfigCompileTests.cpp:26
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:714
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:643
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:614
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:1399
Loc
SourceLocation Loc
'#' location in the include directive
Definition: IncludeOrderCheck.cpp:37
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:1423
clang::clangd::getCorrespondingHeaderOrSource
llvm::Optional< Path > getCorrespondingHeaderOrSource(const Path &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::ClangdServer::formatRange
void formatRange(PathRef File, StringRef Code, Range Rng, Callback< tooling::Replacements > CB)
Run formatting for Rng inside File with content Code.
Definition: ClangdServer.cpp:309
clang::clangd::Config::Key
static clangd::Key< Config > Key
Context key which can be used to set the current Config.
Definition: Config.h:44
Pos
Position Pos
Definition: SourceCode.cpp:649
Merge.h
clang::clangd::elog
void elog(const char *Fmt, Ts &&... Vals)
Definition: Logger.h:56
clang::clangd::getDocumentLinks
std::vector< DocumentLink > getDocumentLinks(ParsedAST &AST)
Get all document links.
Definition: XRefs.cpp:612
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:134
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::tidy::ClangTidyOptions::getDefaults
static ClangTidyOptions getDefaults()
These options are used for all settings that haven't been overridden by the OptionsProvider.
Definition: ClangTidyOptions.cpp:109
clang::clangd::MessageType::Error
An error message.
clang::clangd::sourceLocationInMainFile
llvm::Expected< SourceLocation > sourceLocationInMainFile(const SourceManager &SM, Position P)
Return the file location, corresponding to P.
Definition: SourceCode.cpp:461
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:629
clang::clangd::FileChangeType::Changed
The file got changed.
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:980
clang::clangd::ClangdServer::blockUntilIdleForTest
LLVM_NODISCARD bool blockUntilIdleForTest(llvm::Optional< double > TimeoutSeconds=10)
Definition: ClangdServer.cpp:790
clang::clangd::TUScheduler::InvalidateOnUpdate
The request will be implicitly cancelled by a subsequent update().
Definition: TUScheduler.h:253
clang::clangd::trace::Span
Records an event whose duration is the lifetime of the Span object.
Definition: Trace.h:135