clang-tools 23.0.0git
ClangdServer.h
Go to the documentation of this file.
1//===--- ClangdServer.h - 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#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_CLANGDSERVER_H
10#define LLVM_CLANG_TOOLS_EXTRA_CLANGD_CLANGDSERVER_H
11
12#include "CodeComplete.h"
13#include "ConfigProvider.h"
14#include "Diagnostics.h"
15#include "DraftStore.h"
16#include "FeatureModule.h"
18#include "Hover.h"
19#include "ModulesBuilder.h"
20#include "Protocol.h"
22#include "TUScheduler.h"
23#include "XRefs.h"
24#include "index/Background.h"
25#include "index/FileIndex.h"
26#include "index/Index.h"
27#include "refactor/Rename.h"
28#include "refactor/Tweak.h"
29#include "support/Function.h"
30#include "support/MemoryTree.h"
31#include "support/Path.h"
33#include "clang/Tooling/Core/Replacement.h"
34#include "llvm/ADT/ArrayRef.h"
35#include "llvm/ADT/FunctionExtras.h"
36#include "llvm/ADT/StringRef.h"
37#include <functional>
38#include <memory>
39#include <optional>
40#include <string>
41#include <tuple>
42#include <vector>
43
44namespace clang {
45namespace clangd {
46/// Manages a collection of source files and derived data (ASTs, indexes),
47/// and provides language-aware features such as code completion.
48///
49/// The primary client is ClangdLSPServer which exposes these features via
50/// the Language Server protocol. ClangdServer may also be embedded directly,
51/// though its API is not stable over time.
52///
53/// ClangdServer should be used from a single thread. Many potentially-slow
54/// operations have asynchronous APIs and deliver their results on another
55/// thread.
56/// Such operations support cancellation: if the caller sets up a cancelable
57/// context, many operations will notice cancellation and fail early.
58/// (ClangdLSPServer uses this to implement $/cancelRequest).
60public:
61 /// Interface with hooks for users of ClangdServer to be notified of events.
62 class Callbacks {
63 public:
64 virtual ~Callbacks() = default;
65
66 /// Called by ClangdServer when \p Diagnostics for \p File are ready.
67 /// These pushed diagnostics might correspond to an older version of the
68 /// file, they do not interfere with "pull-based" ClangdServer::diagnostics.
69 /// May be called concurrently for separate files, not for a single file.
70 virtual void onDiagnosticsReady(PathRef File, llvm::StringRef Version,
71 llvm::ArrayRef<Diag> Diagnostics) {}
72 /// Called whenever the file status is updated.
73 /// May be called concurrently for separate files, not for a single file.
74 virtual void onFileUpdated(PathRef File, const TUStatus &Status) {}
75
76 /// Called when background indexing tasks are enqueued/started/completed.
77 /// Not called concurrently.
78 virtual void
80
81 /// Called when the meaning of a source code may have changed without an
82 /// edit. Usually clients assume that responses to requests are valid until
83 /// they next edit the file. If they're invalidated at other times, we
84 /// should tell the client. In particular, when an asynchronous preamble
85 /// build finishes, we can provide more accurate semantic tokens, so we
86 /// should tell the client to refresh.
88
89 /// Called by ClangdServer when some \p InactiveRegions for \p File are
90 /// ready.
92 std::vector<Range> InactiveRegions) {}
93 };
94 /// Creates a context provider that loads and installs config.
95 /// Errors in loading config are reported as diagnostics via Callbacks.
96 /// (This is typically used as ClangdServer::Options::ContextProvider).
97 static std::function<Context(PathRef)>
100
101 struct Options {
102 /// To process requests asynchronously, ClangdServer spawns worker threads.
103 /// If this is zero, no threads are spawned. All work is done on the calling
104 /// thread, and callbacks are invoked before "async" functions return.
106
107 /// AST caching policy. The default is to keep up to 3 ASTs in memory.
109
110 /// Cached preambles are potentially large. If false, store them on disk.
112
113 /// Call hierarchy's outgoing calls feature requires additional index
114 /// serving structures which increase memory usage. If false, these are
115 /// not created and the feature is not enabled.
117
118 /// This throttler controls which preambles may be built at a given time.
120
121 /// Manages to build module files.
123
124 /// If true, ClangdServer builds a dynamic in-memory index for symbols in
125 /// opened files and uses the index to augment code completion results.
127 /// If true, ClangdServer automatically indexes files in the current project
128 /// on background threads. The index is stored in the project root.
129 bool BackgroundIndex = false;
130 llvm::ThreadPriority BackgroundIndexPriority = llvm::ThreadPriority::Low;
131
132 /// If set, use this index to augment code completion results.
134
135 /// If set, queried to derive a processing context for some work.
136 /// Usually used to inject Config (see createConfiguredContextProvider).
137 ///
138 /// When the provider is called, the active context will be that inherited
139 /// from the request (e.g. addDocument()), or from the ClangdServer
140 /// constructor if there is no such request (e.g. background indexing).
141 ///
142 /// The path is an absolute path of the file being processed.
143 /// If there is no particular file (e.g. project loading) then it is empty.
145
146 /// The Options provider to use when running clang-tidy. If null, clang-tidy
147 /// checks will be disabled.
149
150 /// Clangd's workspace root. Relevant for "workspace" operations not bound
151 /// to a particular file.
152 /// FIXME: If not set, should use the current working directory.
153 std::optional<std::string> WorkspaceRoot;
154
155 /// Sets an alternate mode of operation. Current effects are:
156 /// - Using the current working directory as the working directory for
157 /// fallback commands
159
160 /// The resource directory is used to find internal headers, overriding
161 /// defaults and -resource-dir compiler flag).
162 /// If std::nullopt, ClangdServer calls
163 /// CompilerInvocation::GetResourcePath() to obtain the standard resource
164 /// directory.
165 std::optional<std::string> ResourceDir;
166
167 /// Time to wait after a new file version before computing diagnostics.
169 /*Min=*/std::chrono::milliseconds(50),
170 /*Max=*/std::chrono::milliseconds(500),
171 /*RebuildRatio=*/1,
172 };
173
174 /// Cancel certain requests if the file changes before they begin running.
175 /// This is useful for "transient" actions like enumerateTweaks that were
176 /// likely implicitly generated, and avoids redundant work if clients forget
177 /// to cancel. Clients that always cancel stale requests should clear this.
179
180 /// Clangd will execute compiler drivers matching one of these globs to
181 /// fetch system include path.
182 std::vector<std::string> QueryDriverGlobs;
183
184 // Whether the client supports folding only complete lines.
185 bool LineFoldingOnly = false;
186
188 /// If true, use the dirty buffer contents when building Preambles.
189 bool UseDirtyHeaders = false;
190
191 // If true, parse emplace-like functions in the preamble.
193
194 // If true, skip preamble build.
195 bool SkipPreambleBuild = false;
196
197 /// Whether include fixer insertions for Objective-C code should use #import
198 /// instead of #include.
199 bool ImportInsertions = false;
200
201 /// Whether to collect and publish information about inactive preprocessor
202 /// regions in the document.
204
205 explicit operator TUScheduler::Options() const;
206 };
207 // Sensible default options for use in tests.
208 // Features like indexing must be enabled if desired.
209 static Options optsForTest();
210
211 /// Creates a new ClangdServer instance.
212 ///
213 /// ClangdServer uses \p CDB to obtain compilation arguments for parsing. Note
214 /// that ClangdServer only obtains compilation arguments once for each newly
215 /// added file (i.e., when processing a first call to addDocument) and reuses
216 /// those arguments for subsequent reparses. However, ClangdServer will check
217 /// if compilation arguments changed on calls to forceReparse().
219 const Options &Opts, Callbacks *Callbacks = nullptr);
221
222 /// Gets the installed feature module of a given type, if any.
223 /// This exposes access the public interface of feature modules that have one.
224 template <typename Mod> Mod *featureModule() {
225 return FeatureModules ? FeatureModules->get<Mod>() : nullptr;
226 }
227 template <typename Mod> const Mod *featureModule() const {
228 return FeatureModules ? FeatureModules->get<Mod>() : nullptr;
229 }
230
231 /// Add a \p File to the list of tracked C++ files or update the contents if
232 /// \p File is already tracked. Also schedules parsing of the AST for it on a
233 /// separate thread. When the parsing is complete, DiagConsumer passed in
234 /// constructor will receive onDiagnosticsReady callback.
235 /// Version identifies this snapshot and is propagated to ASTs, preambles,
236 /// diagnostics etc built from it. If empty, a version number is generated.
237 void addDocument(PathRef File, StringRef Contents,
238 llvm::StringRef Version = "null",
240 bool ForceRebuild = false);
241
242 /// Remove \p File from list of tracked files, schedule a request to free
243 /// resources associated with it. Pending diagnostics for closed files may not
244 /// be delivered, even if requested with WantDiags::Auto or WantDiags::Yes.
245 /// An empty set of diagnostics will be delivered, with Version = "".
247
248 /// Requests a reparse of currently opened files using their latest source.
249 /// This will typically only rebuild if something other than the source has
250 /// changed (e.g. the CDB yields different flags, or files included in the
251 /// preamble have been modified).
253 llvm::function_ref<bool(llvm::StringRef File)> Filter);
254
255 /// Run code completion for \p File at \p Pos.
256 ///
257 /// This method should only be called for currently tracked files.
259 const clangd::CodeCompleteOptions &Opts,
261
262 /// Provide signature help for \p File at \p Pos. This method should only be
263 /// called for tracked files.
264 void signatureHelp(PathRef File, Position Pos, MarkupKind DocumentationFormat,
266
267 /// Find declaration/definition locations of symbol at a specified position.
269 Callback<std::vector<LocatedSymbol>> CB);
270
271 /// Switch to a corresponding source file when given a header file, and vice
272 /// versa.
274 Callback<std::optional<clangd::Path>> CB);
275
276 /// Get document highlights for a given position.
278 Callback<std::vector<DocumentHighlight>> CB);
279
280 /// Get code hover for a given position.
281 void findHover(PathRef File, Position Pos,
282 Callback<std::optional<HoverInfo>> CB);
283
284 /// Get information about type hierarchy for a given position.
285 void typeHierarchy(PathRef File, Position Pos, int Resolve,
286 TypeHierarchyDirection Direction,
287 Callback<std::vector<TypeHierarchyItem>> CB);
288 /// Get direct parents of a type hierarchy item.
289 void superTypes(const TypeHierarchyItem &Item,
290 Callback<std::optional<std::vector<TypeHierarchyItem>>> CB);
291 /// Get direct children of a type hierarchy item.
292 void subTypes(const TypeHierarchyItem &Item,
293 Callback<std::vector<TypeHierarchyItem>> CB);
294
295 /// Resolve type hierarchy item in the given direction.
296 void resolveTypeHierarchy(TypeHierarchyItem Item, int Resolve,
297 TypeHierarchyDirection Direction,
298 Callback<std::optional<TypeHierarchyItem>> CB);
299
300 /// Get information about call hierarchy for a given position.
302 Callback<std::vector<CallHierarchyItem>> CB);
303
304 /// Resolve incoming calls for a given call hierarchy item.
305 void incomingCalls(const CallHierarchyItem &Item,
306 Callback<std::vector<CallHierarchyIncomingCall>>);
307
308 /// Resolve outgoing calls for a given call hierarchy item.
309 void outgoingCalls(const CallHierarchyItem &Item,
310 Callback<std::vector<CallHierarchyOutgoingCall>>);
311
312 /// Resolve inlay hints for a given document.
313 void inlayHints(PathRef File, std::optional<Range> RestrictRange,
314 Callback<std::vector<InlayHint>>);
315
316 /// Retrieve the top symbols from the workspace matching a query.
317 void workspaceSymbols(StringRef Query, int Limit,
318 Callback<std::vector<SymbolInformation>> CB);
319
320 /// Retrieve the symbols within the specified file.
321 void documentSymbols(StringRef File,
322 Callback<std::vector<DocumentSymbol>> CB);
323
324 /// Retrieve ranges that can be used to fold code within the specified file.
325 void foldingRanges(StringRef File, Callback<std::vector<FoldingRange>> CB);
326
327 /// Retrieve implementations for virtual method.
329 Callback<std::vector<LocatedSymbol>> CB);
330
331 /// Retrieve symbols for types referenced at \p Pos.
332 void findType(PathRef File, Position Pos,
333 Callback<std::vector<LocatedSymbol>> CB);
334
335 /// Retrieve locations for symbol references.
336 void findReferences(PathRef File, Position Pos, uint32_t Limit,
337 bool AddContainer, Callback<ReferencesResult> CB);
338
339 /// Run formatting for the \p File with content \p Code.
340 /// If \p Rng is non-empty, formats only those regions.
341 void formatFile(PathRef File, const std::vector<Range> &Rngs,
343
344 /// Run formatting after \p TriggerText was typed at \p Pos in \p File with
345 /// content \p Code.
346 void formatOnType(PathRef File, Position Pos, StringRef TriggerText,
347 Callback<std::vector<TextEdit>> CB);
348
349 /// Test the validity of a rename operation.
350 ///
351 /// If NewName is provided, it performs a name validation.
353 std::optional<std::string> NewName,
354 const RenameOptions &RenameOpts,
356
357 /// Rename all occurrences of the symbol at the \p Pos in \p File to
358 /// \p NewName.
359 /// If WantFormat is false, the final TextEdit will be not formatted,
360 /// embedders could use this method to get all occurrences of the symbol (e.g.
361 /// highlighting them in prepare stage).
362 void rename(PathRef File, Position Pos, llvm::StringRef NewName,
363 const RenameOptions &Opts, Callback<RenameResult> CB);
364
365 struct TweakRef {
366 std::string ID; /// ID to pass for applyTweak.
367 std::string Title; /// A single-line message to show in the UI.
368 llvm::StringLiteral Kind;
369 };
370
371 // Ref to the clangd::Diag.
372 struct DiagRef {
374 std::string Message;
375 bool operator==(const DiagRef &Other) const {
376 return std::tie(Range, Message) == std::tie(Other.Range, Other.Message);
377 }
378 bool operator<(const DiagRef &Other) const {
379 return std::tie(Range, Message) < std::tie(Other.Range, Other.Message);
380 }
381 };
382
384 std::string File;
386
387 /// Requested kind of actions to return.
388 std::vector<std::string> RequestedActionKinds;
389
390 /// Diagnostics attached to the code action request.
391 std::vector<DiagRef> Diagnostics;
392
393 /// Tweaks where Filter returns false will not be checked or included.
394 std::function<bool(const Tweak &)> TweakFilter;
395 };
397 std::string Version;
398 struct QuickFix {
401 };
402 std::vector<QuickFix> QuickFixes;
403 std::vector<TweakRef> TweakRefs;
404 struct Rename {
406 std::string FixMessage;
407 std::string NewName;
408 };
409 std::vector<Rename> Renames;
410 };
411 /// Surface code actions (quick-fixes for diagnostics, or available code
412 /// tweaks) for a given range in a file.
413 void codeAction(const CodeActionInputs &Inputs,
415
416 /// Apply the code tweak with a specified \p ID.
417 void applyTweak(PathRef File, Range Sel, StringRef ID,
419
420 /// Called when an event occurs for a watched file in the workspace.
421 void onFileEvent(const DidChangeWatchedFilesParams &Params);
422
423 /// Get symbol info for given position.
424 /// Clangd extension - not part of official LSP.
426 Callback<std::vector<SymbolDetails>> CB);
427
428 /// Get semantic ranges around a specified position in a file.
429 void semanticRanges(PathRef File, const std::vector<Position> &Pos,
430 Callback<std::vector<SelectionRange>> CB);
431
432 /// Get all document links in a file.
433 void documentLinks(PathRef File, Callback<std::vector<DocumentLink>> CB);
434
436 Callback<std::vector<HighlightingToken>>);
437
438 /// Describe the AST subtree for a piece of code.
439 void getAST(PathRef File, std::optional<Range> R,
440 Callback<std::optional<ASTNode>> CB);
441
442 /// Runs an arbitrary action that has access to the AST of the specified file.
443 /// The action will execute on one of ClangdServer's internal threads.
444 /// The AST is only valid for the duration of the callback.
445 /// As with other actions, the file must have been opened.
446 void customAction(PathRef File, llvm::StringRef Name,
448
449 /// Fetches diagnostics for current version of the \p File. This might fail if
450 /// server is busy (building a preamble) and would require a long time to
451 /// prepare diagnostics. If it fails, clients should wait for
452 /// onSemanticsMaybeChanged and then retry.
453 /// These 'pulled' diagnostics do not interfere with the diagnostics 'pushed'
454 /// to Callbacks::onDiagnosticsReady, and clients may use either or both.
455 void diagnostics(PathRef File, Callback<std::vector<Diag>> CB);
456
457 /// Returns estimated memory usage and other statistics for each of the
458 /// currently open files.
459 /// Overall memory usage of clangd may be significantly more than reported
460 /// here, as this metric does not account (at least) for:
461 /// - memory occupied by static and dynamic index,
462 /// - memory required for in-flight requests,
463 /// FIXME: those metrics might be useful too, we should add them.
464 llvm::StringMap<TUScheduler::FileStats> fileStats() const;
465
466 /// Gets the contents of a currently tracked file. Returns nullptr if the file
467 /// isn't being tracked.
468 std::shared_ptr<const std::string> getDraft(PathRef File) const;
469
470 // Blocks the main thread until the server is idle. Only for use in tests.
471 // Returns false if the timeout expires.
472 // FIXME: various subcomponents each get the full timeout, so it's more of
473 // an order of magnitude than a hard deadline.
474 [[nodiscard]] bool
475 blockUntilIdleForTest(std::optional<double> TimeoutSeconds = 10);
476
477 /// Builds a nested representation of memory used by components.
478 void profile(MemoryTree &MT) const;
479
480private:
481 FeatureModuleSet *FeatureModules;
482 const GlobalCompilationDatabase &CDB;
483 const ThreadsafeFS &getHeaderFS() const {
484 return UseDirtyHeaders ? *DirtyFS : TFS;
485 }
486 const ThreadsafeFS &TFS;
487
488 void adjustParseInputs(ParseInputs &Inputs, PathRef File) const;
489
490 Path ResourceDir;
491 // The index used to look up symbols. This could be:
492 // - null (all index functionality is optional)
493 // - the dynamic index owned by ClangdServer (DynamicIdx)
494 // - the static index passed to the constructor
495 // - a merged view of a static and dynamic index (MergedIndex)
496 const SymbolIndex *Index = nullptr;
497 // If present, an index of symbols in open files. Read via *Index.
498 std::unique_ptr<FileIndex> DynamicIdx;
499 // If present, the new "auto-index" maintained in background threads.
500 std::unique_ptr<BackgroundIndex> BackgroundIdx;
501 // Storage for merged views of the various indexes.
502 std::vector<std::unique_ptr<SymbolIndex>> MergedIdx;
503 // Manage module files.
504 ModulesBuilder *ModulesManager = nullptr;
505
506 // When set, provides clang-tidy options for a specific file.
507 TidyProviderRef ClangTidyProvider;
508
509 bool UseDirtyHeaders = false;
510
511 // Whether the client supports folding only complete lines.
512 bool LineFoldingOnly = false;
513
514 bool PreambleParseForwardingFunctions = true;
515
516 bool SkipPreambleBuild = false;
517
518 bool ImportInsertions = false;
519
520 bool PublishInactiveRegions = false;
521
522 // GUARDED_BY(CachedCompletionFuzzyFindRequestMutex)
523 llvm::StringMap<std::optional<FuzzyFindRequest>>
524 CachedCompletionFuzzyFindRequestByFile;
525 mutable std::mutex CachedCompletionFuzzyFindRequestMutex;
526
527 std::optional<std::string> WorkspaceRoot;
528 std::optional<AsyncTaskRunner> IndexTasks; // for stdlib indexing.
529 std::optional<TUScheduler> WorkScheduler;
530 // Invalidation policy used for actions that we assume are "transient".
532
533 // Store of the current versions of the open documents.
534 // Only written from the main thread (despite being threadsafe).
535 DraftStore DraftMgr;
536
537 std::unique_ptr<ThreadsafeFS> DirtyFS;
538};
539
540} // namespace clangd
541} // namespace clang
542
543#endif
Interface with hooks for users of ClangdServer to be notified of events.
virtual void onFileUpdated(PathRef File, const TUStatus &Status)
Called whenever the file status is updated.
virtual void onBackgroundIndexProgress(const BackgroundQueue::Stats &Stats)
Called when background indexing tasks are enqueued/started/completed.
virtual void onInactiveRegionsReady(PathRef File, std::vector< Range > InactiveRegions)
Called by ClangdServer when some InactiveRegions for File are ready.
virtual void onSemanticsMaybeChanged(PathRef File)
Called when the meaning of a source code may have changed without an edit.
virtual void onDiagnosticsReady(PathRef File, llvm::StringRef Version, llvm::ArrayRef< Diag > Diagnostics)
Called by ClangdServer when Diagnostics for File are ready.
llvm::StringMap< TUScheduler::FileStats > fileStats() const
Returns estimated memory usage and other statistics for each of the currently open files.
ClangdServer(const GlobalCompilationDatabase &CDB, const ThreadsafeFS &TFS, const Options &Opts, Callbacks *Callbacks=nullptr)
Creates a new ClangdServer instance.
void prepareRename(PathRef File, Position Pos, std::optional< std::string > NewName, const RenameOptions &RenameOpts, Callback< RenameResult > CB)
Test the validity of a rename operation.
void prepareCallHierarchy(PathRef File, Position Pos, Callback< std::vector< CallHierarchyItem > > CB)
Get information about call hierarchy for a given position.
void resolveTypeHierarchy(TypeHierarchyItem Item, int Resolve, TypeHierarchyDirection Direction, Callback< std::optional< TypeHierarchyItem > > CB)
Resolve type hierarchy item in the given direction.
void documentSymbols(StringRef File, Callback< std::vector< DocumentSymbol > > CB)
Retrieve the symbols within the specified file.
void workspaceSymbols(StringRef Query, int Limit, Callback< std::vector< SymbolInformation > > CB)
Retrieve the top symbols from the workspace matching a query.
void diagnostics(PathRef File, Callback< std::vector< Diag > > CB)
Fetches diagnostics for current version of the File.
void typeHierarchy(PathRef File, Position Pos, int Resolve, TypeHierarchyDirection Direction, Callback< std::vector< TypeHierarchyItem > > CB)
Get information about type hierarchy for a given position.
void removeDocument(PathRef File)
Remove File from list of tracked files, schedule a request to free resources associated with it.
void outgoingCalls(const CallHierarchyItem &Item, Callback< std::vector< CallHierarchyOutgoingCall > >)
Resolve outgoing calls for a given call hierarchy item.
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.
void findDocumentHighlights(PathRef File, Position Pos, Callback< std::vector< DocumentHighlight > > CB)
Get document highlights for a given position.
Mod * featureModule()
Gets the installed feature module of a given type, if any.
static std::function< Context(PathRef)> createConfiguredContextProvider(const config::Provider *Provider, ClangdServer::Callbacks *)
Creates a context provider that loads and installs config.
void signatureHelp(PathRef File, Position Pos, MarkupKind DocumentationFormat, Callback< SignatureHelp > CB)
Provide signature help for File at Pos.
void findReferences(PathRef File, Position Pos, uint32_t Limit, bool AddContainer, Callback< ReferencesResult > CB)
Retrieve locations for symbol references.
void switchSourceHeader(PathRef Path, Callback< std::optional< clangd::Path > > CB)
Switch to a corresponding source file when given a header file, and vice versa.
void findType(PathRef File, Position Pos, Callback< std::vector< LocatedSymbol > > CB)
Retrieve symbols for types referenced at Pos.
void findImplementations(PathRef File, Position Pos, Callback< std::vector< LocatedSymbol > > CB)
Retrieve implementations for virtual method.
void subTypes(const TypeHierarchyItem &Item, Callback< std::vector< TypeHierarchyItem > > CB)
Get direct children of a type hierarchy item.
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 formatFile(PathRef File, const std::vector< Range > &Rngs, Callback< tooling::Replacements > CB)
Run formatting for the File with content Code.
void applyTweak(PathRef File, Range Sel, StringRef ID, Callback< Tweak::Effect > CB)
Apply the code tweak with a specified ID.
void semanticHighlights(PathRef File, Callback< std::vector< HighlightingToken > >)
const Mod * featureModule() const
void getAST(PathRef File, std::optional< Range > R, Callback< std::optional< ASTNode > > CB)
Describe the AST subtree for a piece of code.
void symbolInfo(PathRef File, Position Pos, Callback< std::vector< SymbolDetails > > CB)
Get symbol info for given position.
void onFileEvent(const DidChangeWatchedFilesParams &Params)
Called when an event occurs for a watched file in the workspace.
void superTypes(const TypeHierarchyItem &Item, Callback< std::optional< std::vector< TypeHierarchyItem > > > CB)
Get direct parents of a type hierarchy item.
void profile(MemoryTree &MT) const
Builds a nested representation of memory used by components.
void findHover(PathRef File, Position Pos, Callback< std::optional< HoverInfo > > CB)
Get code hover for a given position.
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.
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.
void customAction(PathRef File, llvm::StringRef Name, Callback< InputsAndAST > Action)
Runs an arbitrary action that has access to the AST of the specified file.
void codeAction(const CodeActionInputs &Inputs, Callback< CodeActionResult > CB)
Surface code actions (quick-fixes for diagnostics, or available code tweaks) for a given range in a f...
void locateSymbolAt(PathRef File, Position Pos, Callback< std::vector< LocatedSymbol > > CB)
Find declaration/definition locations of symbol at a specified position.
void incomingCalls(const CallHierarchyItem &Item, Callback< std::vector< CallHierarchyIncomingCall > >)
Resolve incoming calls for a given call hierarchy item.
bool blockUntilIdleForTest(std::optional< double > TimeoutSeconds=10)
void inlayHints(PathRef File, std::optional< Range > RestrictRange, Callback< std::vector< InlayHint > >)
Resolve inlay hints for a given document.
void codeComplete(PathRef File, Position Pos, const clangd::CodeCompleteOptions &Opts, Callback< CodeCompleteResult > CB)
Run code completion for File at Pos.
void reparseOpenFilesIfNeeded(llvm::function_ref< bool(llvm::StringRef File)> Filter)
Requests a reparse of currently opened files using their latest source.
void foldingRanges(StringRef File, Callback< std::vector< FoldingRange > > CB)
Retrieve ranges that can be used to fold code within the specified file.
void documentLinks(PathRef File, Callback< std::vector< DocumentLink > > CB)
Get all document links in a file.
std::shared_ptr< const std::string > getDraft(PathRef File) const
Gets the contents of a currently tracked file.
A context is an immutable container for per-request data that must be propagated through layers that ...
Definition Context.h:69
A thread-safe container for files opened in a workspace, addressed by filenames.
Definition DraftStore.h:28
A FeatureModuleSet is a collection of feature modules installed in clangd.
Provides compilation arguments used for parsing C and C++ files.
This class handles building module files for a given source file.
PreambleThrottler controls which preambles can build at any given time.
Definition TUScheduler.h:98
Interface for symbol indexes that can be used for searching or matching symbols among a set of symbol...
Definition Index.h:134
ASTActionInvalidation
Defines how a runWithAST action is implicitly cancelled by other actions.
Wrapper for vfs::FileSystem for use in multithreaded programs like clangd.
An interface base for small context-sensitive refactoring actions.
Definition Tweak.h:46
A source of configuration fragments.
FIXME: Skip testing on windows temporarily due to the different escaping code mode.
Definition AST.cpp:44
unsigned getDefaultAsyncThreadsCount()
Returns a number of a default async threads to use for TUScheduler.
llvm::function_ref< void(tidy::ClangTidyOptions &, llvm::StringRef)> TidyProviderRef
A factory to modify a tidy::ClangTidyOptions that doesn't hold any state.
llvm::unique_function< void(llvm::Expected< T >)> Callback
A Callback<T> is a void function that accepts Expected<T>.
Definition Function.h:28
llvm::StringRef PathRef
A typedef to represent a ref to file path.
Definition Path.h:29
WantDiagnostics
Determines whether diagnostics should be generated for a file snapshot.
Definition TUScheduler.h:53
@ Auto
Diagnostics must not be generated for this snapshot.
Definition TUScheduler.h:56
std::string Path
A typedef to represent a file path.
Definition Path.h:26
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
Configuration of the AST retention policy.
Definition TUScheduler.h:63
Represents programming constructs like functions or constructors in the context of call hierarchy.
Definition Protocol.h:1615
std::vector< std::string > RequestedActionKinds
Requested kind of actions to return.
std::vector< DiagRef > Diagnostics
Diagnostics attached to the code action request.
std::function< bool(const Tweak &)> TweakFilter
Tweaks where Filter returns false will not be checked or included.
bool operator<(const DiagRef &Other) const
bool operator==(const DiagRef &Other) const
bool BuildDynamicSymbolIndex
If true, ClangdServer builds a dynamic in-memory index for symbols in opened files and uses the index...
std::function< Context(PathRef)> ContextProvider
If set, queried to derive a processing context for some work.
std::vector< std::string > QueryDriverGlobs
Clangd will execute compiler drivers matching one of these globs to fetch system include path.
bool UseDirtyHeaders
If true, use the dirty buffer contents when building Preambles.
clangd::PreambleThrottler * PreambleThrottler
This throttler controls which preambles may be built at a given time.
bool StorePreamblesInMemory
Cached preambles are potentially large. If false, store them on disk.
TidyProviderRef ClangTidyProvider
The Options provider to use when running clang-tidy.
operator TUScheduler::Options() const
SymbolIndex * StaticIndex
If set, use this index to augment code completion results.
std::optional< std::string > WorkspaceRoot
Clangd's workspace root.
bool PublishInactiveRegions
Whether to collect and publish information about inactive preprocessor regions in the document.
llvm::ThreadPriority BackgroundIndexPriority
bool BackgroundIndex
If true, ClangdServer automatically indexes files in the current project on background threads.
ASTRetentionPolicy RetentionPolicy
AST caching policy. The default is to keep up to 3 ASTs in memory.
unsigned AsyncThreadsCount
To process requests asynchronously, ClangdServer spawns worker threads.
bool ImportInsertions
Whether include fixer insertions for Objective-C code should use import instead of include.
DebouncePolicy UpdateDebounce
Time to wait after a new file version before computing diagnostics.
bool StrongWorkspaceMode
Sets an alternate mode of operation.
std::optional< std::string > ResourceDir
The resource directory is used to find internal headers, overriding defaults and -resource-dir compil...
bool EnableOutgoingCalls
Call hierarchy's outgoing calls feature requires additional index serving structures which increase m...
ModulesBuilder * ModulesManager
Manages to build module files.
bool ImplicitCancellation
Cancel certain requests if the file changes before they begin running.
llvm::StringLiteral Kind
A single-line message to show in the UI.
std::string Title
ID to pass for applyTweak.
Clangd may wait after an update to see if another one comes along.
Definition TUScheduler.h:74
Represents a single fix-it that editor can apply to fix the error.
Definition Diagnostics.h:81
A tree that can be used to represent memory usage of nested components while preserving the hierarchy...
Definition MemoryTree.h:30
Information required to run clang, e.g. to parse AST or do code completion.
Definition Compiler.h:51