Go to the documentation of this file.
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"
55 #include <type_traits>
62 struct UpdateIndexCallbacks :
public ParsingCallbacks {
63 UpdateIndexCallbacks(FileIndex *FIndex,
64 ClangdServer::Callbacks *ServerCallbacks,
65 bool TheiaSemanticHighlighting)
66 : FIndex(FIndex), ServerCallbacks(ServerCallbacks),
67 TheiaSemanticHighlighting(TheiaSemanticHighlighting) {}
69 void onPreambleAST(
PathRef Path, llvm::StringRef Version, ASTContext &
Ctx,
70 std::shared_ptr<clang::Preprocessor>
PP,
71 const CanonicalIncludes &CanonIncludes)
override {
73 FIndex->updatePreamble(
Path, Version,
Ctx, std::move(
PP), CanonIncludes);
76 void onMainAST(
PathRef Path, ParsedAST &
AST, PublishFn Publish)
override {
80 std::vector<Diag> Diagnostics =
AST.getDiagnostics();
81 std::vector<HighlightingToken> Highlightings;
82 if (TheiaSemanticHighlighting)
87 ServerCallbacks->onDiagnosticsReady(
Path,
AST.version(),
88 std::move(Diagnostics));
89 if (TheiaSemanticHighlighting)
90 ServerCallbacks->onHighlightingsReady(
Path,
AST.version(),
91 std::move(Highlightings));
95 void onFailedAST(
PathRef Path, llvm::StringRef Version,
96 std::vector<Diag>
Diags, PublishFn Publish)
override {
99 [&]() { ServerCallbacks->onDiagnosticsReady(
Path, Version,
Diags); });
102 void onFileUpdated(
PathRef File,
const TUStatus &Status)
override {
104 ServerCallbacks->onFileUpdated(
File, Status);
109 ClangdServer::Callbacks *ServerCallbacks;
110 bool TheiaSemanticHighlighting;
117 Opts.StorePreamblesInMemory =
true;
118 Opts.AsyncThreadsCount = 4;
119 Opts.TheiaSemanticHighlighting =
true;
120 Opts.AsyncPreambleBuilds =
true;
126 Opts.AsyncThreadsCount = AsyncThreadsCount;
127 Opts.RetentionPolicy = RetentionPolicy;
128 Opts.StorePreamblesInMemory = StorePreamblesInMemory;
129 Opts.UpdateDebounce = UpdateDebounce;
130 Opts.AsyncPreambleBuilds = AsyncPreambleBuilds;
137 : ConfigProvider(Opts.ConfigProvider), TFS(TFS),
138 DynamicIdx(Opts.BuildDynamicSymbolIndex
139 ? new
FileIndex(Opts.HeavyweightDynamicSymbolIndex)
141 GetClangTidyOptions(Opts.GetClangTidyOptions),
142 SuggestMissingIncludes(Opts.SuggestMissingIncludes),
143 BuildRecoveryAST(Opts.BuildRecoveryAST),
144 PreserveRecoveryASTType(Opts.PreserveRecoveryASTType),
145 TweakFilter(Opts.TweakFilter), WorkspaceRoot(Opts.WorkspaceRoot),
156 return createProcessingContext(P);
160 std::make_unique<UpdateIndexCallbacks>(
161 DynamicIdx.get(), Callbacks, Opts.TheiaSemanticHighlighting)) {
164 if (this->Index !=
nullptr) {
165 MergedIdx.push_back(std::make_unique<MergedIndex>(Idx, this->Index));
166 this->Index = MergedIdx.back().get();
171 if (Opts.StaticIndex)
172 AddIndex(Opts.StaticIndex);
173 if (Opts.BackgroundIndex) {
174 BackgroundIdx = std::make_unique<BackgroundIndex>(
177 [&CDB](llvm::StringRef
File) {
return CDB.getProjectInfo(
File); }),
178 std::max(Opts.AsyncThreadsCount, 1u),
179 [Callbacks](BackgroundQueue::Stats S) {
181 Callbacks->onBackgroundIndexProgress(S);
183 [
this](
PathRef P) {
return createProcessingContext(P); });
184 AddIndex(BackgroundIdx.get());
187 AddIndex(DynamicIdx.get());
191 llvm::StringRef Version,
196 if (GetClangTidyOptions)
199 Opts.SuggestMissingIncludes = SuggestMissingIncludes;
205 Inputs.Version = Version.str();
206 Inputs.ForceRebuild = ForceRebuild;
207 Inputs.Opts = std::move(Opts);
209 Inputs.Opts.BuildRecoveryAST = BuildRecoveryAST;
210 Inputs.Opts.PreserveRecoveryASTType = PreserveRecoveryASTType;
213 if (NewFile && BackgroundIdx)
214 BackgroundIdx->boostRelated(
File);
223 auto CodeCompleteOpts = Opts;
224 if (!CodeCompleteOpts.Index)
225 CodeCompleteOpts.Index = Index;
227 auto Task = [
Pos, CodeCompleteOpts,
File =
File.str(), CB = std::move(CB),
228 this](llvm::Expected<InputsAndPreamble> IP)
mutable {
230 return CB(IP.takeError());
232 return CB(llvm::make_error<CancelledError>(Reason));
234 llvm::Optional<SpeculativeFuzzyFind> SpecFuzzyFind;
238 vlog(
"Build for file {0} is not ready. Enter fallback mode.",
File);
240 if (CodeCompleteOpts.Index && CodeCompleteOpts.SpeculativeIndexRequest) {
241 SpecFuzzyFind.emplace();
243 std::lock_guard<std::mutex> Lock(
244 CachedCompletionFuzzyFindRequestMutex);
245 SpecFuzzyFind->CachedReq =
246 CachedCompletionFuzzyFindRequestByFile[
File];
252 ParseInput.Opts.BuildRecoveryAST = BuildRecoveryAST;
253 ParseInput.Opts.PreserveRecoveryASTType = PreserveRecoveryASTType;
259 SpecFuzzyFind ? SpecFuzzyFind.getPointer() :
nullptr);
262 CB(std::move(Result));
264 if (SpecFuzzyFind && SpecFuzzyFind->NewReq.hasValue()) {
265 std::lock_guard<std::mutex> Lock(CachedCompletionFuzzyFindRequestMutex);
266 CachedCompletionFuzzyFindRequestByFile[
File] =
267 SpecFuzzyFind->NewReq.getValue();
277 "CodeComplete",
File,
288 this](llvm::Expected<InputsAndPreamble> IP)
mutable {
290 return CB(IP.takeError());
294 return CB(llvm::createStringError(llvm::inconvertibleErrorCode(),
295 "Failed to parse includes"));
299 ParseInput.Opts.BuildRecoveryAST = BuildRecoveryAST;
300 ParseInput.Opts.PreserveRecoveryASTType = PreserveRecoveryASTType;
313 return CB(Begin.takeError());
316 return CB(End.takeError());
329 Callback<std::vector<TextEdit>> CB) {
332 return CB(CursorPos.takeError());
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,
340 return CB(Style.takeError());
342 std::vector<TextEdit> Result;
343 for (
const tooling::Replacement &R :
353 Callback<llvm::Optional<Range>> CB) {
355 this](llvm::Expected<InputsAndAST> InpAST)
mutable {
357 return CB(InpAST.takeError());
358 auto &
AST = InpAST->AST;
359 const auto &SM =
AST.getSourceManager();
362 return CB(
Loc.takeError());
363 const auto *TouchingIdentifier =
364 spelledIdentifierTouching(*
Loc,
AST.getTokens());
365 if (!TouchingIdentifier)
369 SM, CharSourceRange::getCharRange(TouchingIdentifier->location(),
370 TouchingIdentifier->endLocation()));
384 return CB(
Changes.takeError());
396 CB = std::move(CB), Snapshot = std::move(Snapshot),
397 this](llvm::Expected<InputsAndAST> InpAST)
mutable {
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())
411 {
Pos, NewName, InpAST->AST,
File, Index, Opts, GetDirtyBuffer});
413 return CB(Edits.takeError());
415 if (Opts.WantFormat) {
417 *InpAST->Inputs.TFS);
419 for (
auto &
E : *Edits)
421 llvm::joinErrors(
reformatEdit(
E.getValue(), Style), std::move(Err));
424 return CB(std::move(Err));
426 RenameFiles.record(Edits->size());
427 return CB(std::move(*Edits));
434 static llvm::Expected<std::vector<std::unique_ptr<Tweak::Selection>>>
438 return Begin.takeError();
441 return End.takeError();
442 std::vector<std::unique_ptr<Tweak::Selection>> Result;
446 Result.push_back(std::make_unique<Tweak::Selection>(
447 AST.Inputs.Index, AST.AST, *Begin, *End, std::move(T)));
450 assert(!Result.empty() &&
"Expected at least one SelectionTree");
451 return std::move(Result);
455 Callback<std::vector<TweakRef>> CB) {
460 this](Expected<InputsAndAST> InpAST)
mutable {
462 return CB(InpAST.takeError());
465 return CB(Selections.takeError());
466 std::vector<TweakRef> Res;
468 llvm::DenseSet<llvm::StringRef> PreparedTweaks;
469 auto Filter = [&](
const Tweak &T) {
470 return TweakFilter(T) && !PreparedTweaks.count(T.id());
472 for (
const auto &Sel : *Selections) {
474 Res.push_back({T->id(), T->title(), T->intent()});
475 PreparedTweaks.insert(T->id());
476 TweakAvailable.record(1, T->id());
492 TweakAttempt.record(1, TweakID);
495 this](Expected<InputsAndAST> InpAST)
mutable {
497 return CB(InpAST.takeError());
500 return CB(Selections.takeError());
501 llvm::Optional<llvm::Expected<Tweak::Effect>> Effect;
504 for (
const auto &Selection : *Selections) {
507 Effect = (*T)->apply(*Selection);
510 Effect = T.takeError();
512 assert(Effect.hasValue() &&
"Expected at least one selection");
515 for (
auto &It : (*Effect)->ApplyEdits) {
520 elog(
"Failed to format {0}: {1}", It.first(), std::move(Err));
523 return CB(std::move(*Effect));
529 llvm::unique_function<
void(std::string)>
Callback) {
531 llvm::Expected<InputsAndAST> InpAST)
mutable {
533 llvm::consumeError(InpAST.takeError());
538 llvm::raw_string_ostream ResultOS(Result);
549 Callback<std::vector<LocatedSymbol>> CB) {
551 this](llvm::Expected<InputsAndAST> InpAST)
mutable {
553 return CB(InpAST.takeError());
570 return CB(std::move(CorrespondingFile));
572 this](llvm::Expected<InputsAndAST> InpAST)
mutable {
574 return CB(InpAST.takeError());
580 void ClangdServer::formatCode(
PathRef File, llvm::StringRef
Code,
581 llvm::ArrayRef<tooling::Range> Ranges,
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);
591 return CB(
Changed.takeError());
593 CB(IncludeReplaces.merge(format::reformat(
595 tooling::calculateRangesAfterReplacements(IncludeReplaces, Ranges),
604 [
Pos, CB = std::move(CB)](llvm::Expected<InputsAndAST> InpAST)
mutable {
606 return CB(InpAST.takeError());
615 Callback<llvm::Optional<HoverInfo>> CB) {
617 this](llvm::Expected<InputsAndAST> InpAST)
mutable {
619 return CB(InpAST.takeError());
621 File, InpAST->Inputs.Contents, *InpAST->Inputs.TFS);
631 Callback<Optional<TypeHierarchyItem>> CB) {
633 this](Expected<InputsAndAST> InpAST)
mutable {
635 return CB(InpAST.takeError());
645 Callback<llvm::Optional<TypeHierarchyItem>> CB) {
656 llvm::StringRef Query,
int Limit,
657 Callback<std::vector<SymbolInformation>> CB) {
659 "getWorkspaceSymbols",
"",
660 [Query = Query.str(), Limit, CB = std::move(CB),
this]()
mutable {
662 WorkspaceRoot.getValueOr(
"")));
667 Callback<std::vector<DocumentSymbol>> CB) {
669 [CB = std::move(CB)](llvm::Expected<InputsAndAST> InpAST)
mutable {
671 return CB(InpAST.takeError());
679 Callback<std::vector<FoldingRange>> CB) {
681 [CB = std::move(CB)](llvm::Expected<InputsAndAST> InpAST)
mutable {
683 return CB(InpAST.takeError());
692 auto Action = [
Pos, Limit, CB = std::move(CB),
693 this](llvm::Expected<InputsAndAST> InpAST)
mutable {
695 return CB(InpAST.takeError());
703 Callback<std::vector<SymbolDetails>> CB) {
705 [
Pos, CB = std::move(CB)](llvm::Expected<InputsAndAST> InpAST)
mutable {
707 return CB(InpAST.takeError());
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 {
720 return CB(InpAST.takeError());
721 std::vector<SelectionRange> Result;
722 for (
const auto &
Pos : Positions) {
724 Result.push_back(std::move(*
Range));
726 return CB(
Range.takeError());
728 CB(std::move(Result));
734 Callback<std::vector<DocumentLink>> CB) {
736 [CB = std::move(CB)](llvm::Expected<InputsAndAST> InpAST)
mutable {
738 return CB(InpAST.takeError());
748 [CB = std::move(CB)](llvm::Expected<InputsAndAST> InpAST)
mutable {
750 return CB(InpAST.takeError());
761 Context ClangdServer::createProcessingContext(
PathRef File)
const {
768 Params.
FreshTime = std::chrono::steady_clock::now() - std::chrono::seconds(5);
769 llvm::SmallString<256> PosixPath;
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();
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());
781 log(
"config warning at {0}:{1}:{2}: {3}", Diag.getFilename(),
782 Diag.getLineNo(), Diag.getColumnNo(), Diag.getMessage());
793 BackgroundIdx->blockUntilIdleForTest(TimeoutSeconds));
CharSourceRange Range
SourceRange for the file name.
llvm::StringMap< TUScheduler::FileStats > fileStats() const
Returns estimated memory usage and other statistics for each of the currently open files.
WantDiagnostics WantDiags
static Factory createDiskBackedStorageFactory(std::function< llvm::Optional< ProjectInfo >(PathRef)> GetProjectInfo)
Deadline timeoutSeconds(llvm::Optional< double > Seconds)
Makes a deadline from a timeout in seconds. None means wait forever.
llvm::Expected< std::vector< FoldingRange > > getFoldingRanges(ParsedAST &AST)
Returns a list of ranges whose contents might be collapsible in an editor.
SignatureHelp signatureHelp(PathRef FileName, Position Pos, const PreambleData &Preamble, const ParseInputs &ParseInput)
Get signature help at a specified Pos in FileName.
ReferencesResult findReferences(ParsedAST &AST, Position Pos, uint32_t Limit, const SymbolIndex *Index)
Returns references of the symbol at a specified Pos.
A set of edits generated for a single file.
void dumpAST(PathRef File, llvm::unique_function< void(std::string)> Callback)
Only for testing purposes.
void runWithPreamble(llvm::StringRef Name, PathRef File, PreambleConsistency Consistency, Callback< InputsAndPreamble > Action)
Schedule an async read of the preamble.
ASTContext & getASTContext()
Note that the returned ast will not contain decls from the preamble that were not deserialized during...
void prepareRename(PathRef File, Position Pos, const RenameOptions &RenameOpts, Callback< llvm::Optional< Range >> CB)
Test the validity of a rename operation.
llvm::Optional< std::chrono::steady_clock::time_point > FreshTime
Hint that stale data is OK to improve performance (e.g.
std::string Path
A typedef to represent a file path.
void resolveTypeHierarchy(TypeHierarchyItem &Item, int ResolveLevels, TypeHierarchyDirection Direction, const SymbolIndex *Index)
std::unique_ptr< trace::EventTracer > Tracer
static const Context & current()
Returns the context for the current thread, creating it if needed.
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))
bool blockUntilIdle(Deadline D) const
Wait until there are no scheduled or running tasks.
Context clone() const
Clone this context object.
const ParseInputs & ParseInput
void formatFile(PathRef File, StringRef Code, Callback< tooling::Replacements > CB)
Run formatting for the whole File with content Code.
static bool createEach(ASTContext &AST, const syntax::TokenBuffer &Tokens, unsigned Begin, unsigned End, llvm::function_ref< bool(SelectionTree)> Func)
PrecompiledPreamble Preamble
llvm::Expected< FileEdits > rename(const RenameInputs &RInputs)
Renames all occurrences of the symbol.
Position start
The range's start position.
llvm::Error reformatEdit(Edit &E, const format::FormatStyle &Style)
Formats the edits and code around it according to Style.
void switchSourceHeader(PathRef Path, Callback< llvm::Optional< clangd::Path >> CB)
Switch to a corresponding source file when given a header file, and vice versa.
void findReferences(PathRef File, Position Pos, uint32_t Limit, Callback< ReferencesResult > CB)
Retrieve locations for symbol references.
void run(llvm::StringRef Name, llvm::StringRef Path, llvm::unique_function< void()> Action)
Schedule an async task with no dependencies.
llvm::Optional< HoverInfo > getHover(ParsedAST &AST, Position Pos, format::FormatStyle Style, const SymbolIndex *Index)
Get the hover information when hovering at Pos.
static Options optsForTest()
llvm::Expected< SelectionRange > getSemanticRanges(ParsedAST &AST, Position Pos)
Returns the list of all interesting ranges around the Position Pos.
Documents should not be synced at all.
This manages symbols from files and an in-memory index on all symbols.
bool update(PathRef File, ParseInputs Inputs, WantDiagnostics WD)
Schedule an update for File.
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.
llvm::Expected< std::unique_ptr< Tweak > > prepareTweak(StringRef ID, const Tweak::Selection &S)
Provides compilation arguments used for parsing C and C++ files.
llvm::unique_function< void()> Action
void enumerateTweaks(PathRef File, Range Sel, Callback< std::vector< TweakRef >> CB)
Enumerate the code tweaks available to the user at a specified point.
std::function< Context(PathRef)> ContextProvider
Used to create a context that wraps each single operation.
void documentSymbols(StringRef File, Callback< std::vector< DocumentSymbol >> CB)
Retrieve the symbols within the specified file.
void foldingRanges(StringRef File, Callback< std::vector< FoldingRange >> CB)
Retrieve ranges that can be used to fold code within the specified file.
TextEdit replacementToEdit(llvm::StringRef Code, const tooling::Replacement &R)
The preamble may be generated from an older version of the file.
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.
Besides accepting stale preamble, this also allow preamble to be absent (not ready or failed to build...
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.
WantDiagnostics
Determines whether diagnostics should be generated for a file snapshot.
int isCancelled(const Context &Ctx)
If the current context is within a cancelled task, returns the reason.
Range halfOpenToRange(const SourceManager &SM, CharSourceRange R)
std::vector< LocatedSymbol > locateSymbolAt(ParsedAST &AST, Position Pos, const SymbolIndex *Index)
Get definition of symbol at a specified Pos.
void removeDocument(PathRef File)
Remove File from list of tracked files, schedule a request to free resources associated with it.
void codeComplete(PathRef File, Position Pos, const clangd::CodeCompleteOptions &Opts, Callback< CodeCompleteResult > CB)
Run code completion for File at Pos.
The parsed preamble and associated data.
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.
std::vector< SymbolDetails > getSymbolInfo(ParsedAST &AST, Position Pos)
Get info about symbols at Pos.
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.
llvm::Expected< size_t > positionToOffset(llvm::StringRef Code, Position P, bool AllowColumnsBeyondLineLength)
Turn a [line, column] pair into an offset in Code.
void onFileEvent(const DidChangeWatchedFilesParams &Params)
Called when an event occurs for a watched file in the workspace.
Config getConfig(const Params &, DiagnosticCallback) const
Build a config based on this provider.
void semanticHighlights(PathRef File, Callback< std::vector< HighlightingToken >>)
void vlog(const char *Fmt, Ts &&... Vals)
void findDocumentHighlights(PathRef File, Position Pos, Callback< std::vector< DocumentHighlight >> CB)
Get document highlights for a given position.
A distribution of values with a meaningful mean and count.
void remove(PathRef File)
Remove File from the list of tracked files and schedule removal of its resources.
Position end
The range's end position.
llvm::StringMap< FileStats > fileStats() const
Returns resources used for each of the currently open files.
std::vector< HighlightingToken > getSemanticHighlightings(ParsedAST &AST)
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...
format::FormatStyle getFormatStyleForFile(llvm::StringRef File, llvm::StringRef Content, const ThreadsafeFS &TFS)
Choose the clang-format style we should apply to a certain file.
void log(const char *Fmt, Ts &&... Vals)
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))
void workspaceSymbols(StringRef Query, int Limit, Callback< std::vector< SymbolInformation >> CB)
Retrieve the top symbols from the workspace matching a query.
void documentLinks(PathRef File, Callback< std::vector< DocumentLink >> CB)
Get all document links in a file.
llvm::Expected< std::vector< SymbolInformation > > getWorkspaceSymbols(llvm::StringRef Query, int Limit, const SymbolIndex *const Index, llvm::StringRef HintPath)
Searches for the symbols matching Query.
Interface for symbol indexes that can be used for searching or matching symbols among a set of symbol...
An aggregate number whose rate of change over time is meaningful.
void signatureHelp(PathRef File, Position Pos, Callback< SignatureHelp > CB)
Provide signature help for File at Pos.
void locateSymbolAt(PathRef File, Position Pos, Callback< std::vector< LocatedSymbol >> CB)
Find declaration/definition locations of symbol at a specified position.
static llvm::Expected< std::vector< std::unique_ptr< Tweak::Selection > > > tweakSelection(const Range &Sel, const InputsAndAST &AST)
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().
Interface with hooks for users of ClangdServer to be notified of events.
llvm::StringRef PathRef
A typedef to represent a ref to file path.
Wrapper for vfs::FileSystem for use in multithreaded programs like clangd.
Represents measurements of clangd events, e.g.
llvm::IntrusiveRefCntPtr< llvm::vfs::FileSystem > view(llvm::NoneType CWD) const
Obtain a vfs::FileSystem with an arbitrary initial working directory.
void dumpAST(ParsedAST &AST, llvm::raw_ostream &OS)
For testing/debugging purposes.
void applyTweak(PathRef File, Range Sel, StringRef ID, Callback< Tweak::Effect > CB)
Apply the code tweak with a specified ID.
void runWithAST(llvm::StringRef Name, PathRef File, Callback< InputsAndAST > Action, ASTActionInvalidation=NoInvalidation)
Schedule an async read of the AST.
Block until we can run the parser (e.g.
Describes the context used to evaluate configuration fragments.
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
void symbolInfo(PathRef File, Position Pos, Callback< std::vector< SymbolDetails >> CB)
Get symbol info for given position.
const syntax::TokenBuffer & getTokens() const
Tokens recorded while parsing the main file.
llvm::StringRef Path
Absolute path to a source file we're applying the config to.
std::vector< tooling::Replacement > formatIncremental(llvm::StringRef OriginalCode, unsigned OriginalCursor, llvm::StringRef InsertedText, format::FormatStyle Style)
Applies limited formatting around new InsertedText.
llvm::StringMap< std::string > getAllFileContents() const
Returns a snapshot of all file buffer contents, per last update().
An interface base for small context-sensitive refactoring actions.
void semanticRanges(PathRef File, const std::vector< Position > &Pos, Callback< std::vector< SelectionRange >> CB)
Get semantic ranges around a specified position in a file.
void resolveTypeHierarchy(TypeHierarchyItem Item, int Resolve, TypeHierarchyDirection Direction, Callback< llvm::Optional< TypeHierarchyItem >> CB)
Resolve type hierarchy item in the given direction.
void findHover(PathRef File, Position Pos, Callback< llvm::Optional< HoverInfo >> CB)
Get code hover for a given position.
llvm::Optional< TypeHierarchyItem > getTypeHierarchy(ParsedAST &AST, Position Pos, int ResolveLevels, TypeHierarchyDirection Direction, const SymbolIndex *Index, PathRef TUPath)
Get type hierarchy information at Pos.
SourceLocation Loc
'#' location in the include directive
llvm::unique_function< void(llvm::Expected< T >)> Callback
A Callback<T> is a void function that accepts Expected<T>.
static DebouncePolicy fixed(clock::duration)
A policy that always returns the same duration, useful for tests.
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.
void formatRange(PathRef File, StringRef Code, Range Rng, Callback< tooling::Replacements > CB)
Run formatting for Rng inside File with content Code.
static clangd::Key< Config > Key
Context key which can be used to set the current Config.
void elog(const char *Fmt, Ts &&... Vals)
std::vector< DocumentLink > getDocumentLinks(ParsedAST &AST)
Get all document links.
ClangdServer(const GlobalCompilationDatabase &CDB, const ThreadsafeFS &TFS, const Options &Opts, Callbacks *Callbacks=nullptr)
Creates a new ClangdServer instance.
A context is an immutable container for per-request data that must be propagated through layers that ...
static ClangTidyOptions getDefaults()
These options are used for all settings that haven't been overridden by the OptionsProvider.
llvm::Expected< SourceLocation > sourceLocationInMainFile(const SourceManager &SM, Position P)
Return the file location, corresponding to P.
void typeHierarchy(PathRef File, Position Pos, int Resolve, TypeHierarchyDirection Direction, Callback< llvm::Optional< TypeHierarchyItem >> CB)
Get information about type hierarchy for a given position.
std::vector< DocumentHighlight > findDocumentHighlights(ParsedAST &AST, Position Pos)
Returns highlights for all usages of a symbol at Pos.
LLVM_NODISCARD bool blockUntilIdleForTest(llvm::Optional< double > TimeoutSeconds=10)
The request will be implicitly cancelled by a subsequent update().
Records an event whose duration is the lifetime of the Span object.