[clang-tools-extra] Fix a link in ReleaseNotes.rst
[llvm-project.git] / clang-tools-extra / clangd / ClangdServer.h
blobe73454901cff0d6f8d1aea1ded5b2e9caface96e
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 //===----------------------------------------------------------------------===//
9 #ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_CLANGDSERVER_H
10 #define LLVM_CLANG_TOOLS_EXTRA_CLANGD_CLANGDSERVER_H
12 #include "CodeComplete.h"
13 #include "ConfigProvider.h"
14 #include "Diagnostics.h"
15 #include "DraftStore.h"
16 #include "FeatureModule.h"
17 #include "GlobalCompilationDatabase.h"
18 #include "Hover.h"
19 #include "Protocol.h"
20 #include "SemanticHighlighting.h"
21 #include "TUScheduler.h"
22 #include "XRefs.h"
23 #include "index/Background.h"
24 #include "index/FileIndex.h"
25 #include "index/Index.h"
26 #include "refactor/Rename.h"
27 #include "refactor/Tweak.h"
28 #include "support/Function.h"
29 #include "support/MemoryTree.h"
30 #include "support/Path.h"
31 #include "support/ThreadsafeFS.h"
32 #include "clang/Tooling/Core/Replacement.h"
33 #include "llvm/ADT/FunctionExtras.h"
34 #include "llvm/ADT/Optional.h"
35 #include "llvm/ADT/StringRef.h"
36 #include <functional>
37 #include <memory>
38 #include <string>
39 #include <type_traits>
40 #include <utility>
41 #include <vector>
43 namespace clang {
44 namespace clangd {
45 /// Manages a collection of source files and derived data (ASTs, indexes),
46 /// and provides language-aware features such as code completion.
47 ///
48 /// The primary client is ClangdLSPServer which exposes these features via
49 /// the Language Server protocol. ClangdServer may also be embedded directly,
50 /// though its API is not stable over time.
51 ///
52 /// ClangdServer should be used from a single thread. Many potentially-slow
53 /// operations have asynchronous APIs and deliver their results on another
54 /// thread.
55 /// Such operations support cancellation: if the caller sets up a cancelable
56 /// context, many operations will notice cancellation and fail early.
57 /// (ClangdLSPServer uses this to implement $/cancelRequest).
58 class ClangdServer {
59 public:
60 /// Interface with hooks for users of ClangdServer to be notified of events.
61 class Callbacks {
62 public:
63 virtual ~Callbacks() = default;
65 /// Called by ClangdServer when \p Diagnostics for \p File are ready.
66 /// These pushed diagnostics might correspond to an older version of the
67 /// file, they do not interfere with "pull-based" ClangdServer::diagnostics.
68 /// May be called concurrently for separate files, not for a single file.
69 virtual void onDiagnosticsReady(PathRef File, llvm::StringRef Version,
70 std::vector<Diag> Diagnostics) {}
71 /// Called whenever the file status is updated.
72 /// May be called concurrently for separate files, not for a single file.
73 virtual void onFileUpdated(PathRef File, const TUStatus &Status) {}
75 /// Called when background indexing tasks are enqueued/started/completed.
76 /// Not called concurrently.
77 virtual void
78 onBackgroundIndexProgress(const BackgroundQueue::Stats &Stats) {}
80 /// Called when the meaning of a source code may have changed without an
81 /// edit. Usually clients assume that responses to requests are valid until
82 /// they next edit the file. If they're invalidated at other times, we
83 /// should tell the client. In particular, when an asynchronous preamble
84 /// build finishes, we can provide more accurate semantic tokens, so we
85 /// should tell the client to refresh.
86 virtual void onSemanticsMaybeChanged(PathRef File) {}
88 /// Creates a context provider that loads and installs config.
89 /// Errors in loading config are reported as diagnostics via Callbacks.
90 /// (This is typically used as ClangdServer::Options::ContextProvider).
91 static std::function<Context(PathRef)>
92 createConfiguredContextProvider(const config::Provider *Provider,
93 ClangdServer::Callbacks *);
95 struct Options {
96 /// To process requests asynchronously, ClangdServer spawns worker threads.
97 /// If this is zero, no threads are spawned. All work is done on the calling
98 /// thread, and callbacks are invoked before "async" functions return.
99 unsigned AsyncThreadsCount = getDefaultAsyncThreadsCount();
101 /// AST caching policy. The default is to keep up to 3 ASTs in memory.
102 ASTRetentionPolicy RetentionPolicy;
104 /// Cached preambles are potentially large. If false, store them on disk.
105 bool StorePreamblesInMemory = true;
107 /// If true, ClangdServer builds a dynamic in-memory index for symbols in
108 /// opened files and uses the index to augment code completion results.
109 bool BuildDynamicSymbolIndex = false;
110 /// If true, ClangdServer automatically indexes files in the current project
111 /// on background threads. The index is stored in the project root.
112 bool BackgroundIndex = false;
113 llvm::ThreadPriority BackgroundIndexPriority = llvm::ThreadPriority::Low;
115 /// If set, use this index to augment code completion results.
116 SymbolIndex *StaticIndex = nullptr;
118 /// If set, queried to derive a processing context for some work.
119 /// Usually used to inject Config (see createConfiguredContextProvider).
121 /// When the provider is called, the active context will be that inherited
122 /// from the request (e.g. addDocument()), or from the ClangdServer
123 /// constructor if there is no such request (e.g. background indexing).
125 /// The path is an absolute path of the file being processed.
126 /// If there is no particular file (e.g. project loading) then it is empty.
127 std::function<Context(PathRef)> ContextProvider;
129 /// The Options provider to use when running clang-tidy. If null, clang-tidy
130 /// checks will be disabled.
131 TidyProviderRef ClangTidyProvider;
133 /// Clangd's workspace root. Relevant for "workspace" operations not bound
134 /// to a particular file.
135 /// FIXME: If not set, should use the current working directory.
136 llvm::Optional<std::string> WorkspaceRoot;
138 /// The resource directory is used to find internal headers, overriding
139 /// defaults and -resource-dir compiler flag).
140 /// If None, ClangdServer calls CompilerInvocation::GetResourcePath() to
141 /// obtain the standard resource directory.
142 llvm::Optional<std::string> ResourceDir = llvm::None;
144 /// Time to wait after a new file version before computing diagnostics.
145 DebouncePolicy UpdateDebounce = DebouncePolicy{
146 /*Min=*/std::chrono::milliseconds(50),
147 /*Max=*/std::chrono::milliseconds(500),
148 /*RebuildRatio=*/1,
151 /// Cancel certain requests if the file changes before they begin running.
152 /// This is useful for "transient" actions like enumerateTweaks that were
153 /// likely implicitly generated, and avoids redundant work if clients forget
154 /// to cancel. Clients that always cancel stale requests should clear this.
155 bool ImplicitCancellation = true;
157 /// Clangd will execute compiler drivers matching one of these globs to
158 /// fetch system include path.
159 std::vector<std::string> QueryDriverGlobs;
161 /// Enable preview of FoldingRanges feature.
162 bool FoldingRanges = false;
164 FeatureModuleSet *FeatureModules = nullptr;
165 /// If true, use the dirty buffer contents when building Preambles.
166 bool UseDirtyHeaders = false;
168 // If true, parse emplace-like functions in the preamble.
169 bool PreambleParseForwardingFunctions = false;
171 explicit operator TUScheduler::Options() const;
173 // Sensible default options for use in tests.
174 // Features like indexing must be enabled if desired.
175 static Options optsForTest();
177 /// Creates a new ClangdServer instance.
179 /// ClangdServer uses \p CDB to obtain compilation arguments for parsing. Note
180 /// that ClangdServer only obtains compilation arguments once for each newly
181 /// added file (i.e., when processing a first call to addDocument) and reuses
182 /// those arguments for subsequent reparses. However, ClangdServer will check
183 /// if compilation arguments changed on calls to forceReparse().
184 ClangdServer(const GlobalCompilationDatabase &CDB, const ThreadsafeFS &TFS,
185 const Options &Opts, Callbacks *Callbacks = nullptr);
186 ~ClangdServer();
188 /// Gets the installed feature module of a given type, if any.
189 /// This exposes access the public interface of feature modules that have one.
190 template <typename Mod> Mod *featureModule() {
191 return FeatureModules ? FeatureModules->get<Mod>() : nullptr;
193 template <typename Mod> const Mod *featureModule() const {
194 return FeatureModules ? FeatureModules->get<Mod>() : nullptr;
197 /// Add a \p File to the list of tracked C++ files or update the contents if
198 /// \p File is already tracked. Also schedules parsing of the AST for it on a
199 /// separate thread. When the parsing is complete, DiagConsumer passed in
200 /// constructor will receive onDiagnosticsReady callback.
201 /// Version identifies this snapshot and is propagated to ASTs, preambles,
202 /// diagnostics etc built from it. If empty, a version number is generated.
203 void addDocument(PathRef File, StringRef Contents,
204 llvm::StringRef Version = "null",
205 WantDiagnostics WD = WantDiagnostics::Auto,
206 bool ForceRebuild = false);
208 /// Remove \p File from list of tracked files, schedule a request to free
209 /// resources associated with it. Pending diagnostics for closed files may not
210 /// be delivered, even if requested with WantDiags::Auto or WantDiags::Yes.
211 /// An empty set of diagnostics will be delivered, with Version = "".
212 void removeDocument(PathRef File);
214 /// Requests a reparse of currently opened files using their latest source.
215 /// This will typically only rebuild if something other than the source has
216 /// changed (e.g. the CDB yields different flags, or files included in the
217 /// preamble have been modified).
218 void reparseOpenFilesIfNeeded(
219 llvm::function_ref<bool(llvm::StringRef File)> Filter);
221 /// Run code completion for \p File at \p Pos.
223 /// This method should only be called for currently tracked files.
224 void codeComplete(PathRef File, Position Pos,
225 const clangd::CodeCompleteOptions &Opts,
226 Callback<CodeCompleteResult> CB);
228 /// Provide signature help for \p File at \p Pos. This method should only be
229 /// called for tracked files.
230 void signatureHelp(PathRef File, Position Pos, MarkupKind DocumentationFormat,
231 Callback<SignatureHelp> CB);
233 /// Find declaration/definition locations of symbol at a specified position.
234 void locateSymbolAt(PathRef File, Position Pos,
235 Callback<std::vector<LocatedSymbol>> CB);
237 /// Switch to a corresponding source file when given a header file, and vice
238 /// versa.
239 void switchSourceHeader(PathRef Path,
240 Callback<llvm::Optional<clangd::Path>> CB);
242 /// Get document highlights for a given position.
243 void findDocumentHighlights(PathRef File, Position Pos,
244 Callback<std::vector<DocumentHighlight>> CB);
246 /// Get code hover for a given position.
247 void findHover(PathRef File, Position Pos,
248 Callback<llvm::Optional<HoverInfo>> CB);
250 /// Get information about type hierarchy for a given position.
251 void typeHierarchy(PathRef File, Position Pos, int Resolve,
252 TypeHierarchyDirection Direction,
253 Callback<llvm::Optional<TypeHierarchyItem>> CB);
255 /// Resolve type hierarchy item in the given direction.
256 void resolveTypeHierarchy(TypeHierarchyItem Item, int Resolve,
257 TypeHierarchyDirection Direction,
258 Callback<llvm::Optional<TypeHierarchyItem>> CB);
260 /// Get information about call hierarchy for a given position.
261 void prepareCallHierarchy(PathRef File, Position Pos,
262 Callback<std::vector<CallHierarchyItem>> CB);
264 /// Resolve incoming calls for a given call hierarchy item.
265 void incomingCalls(const CallHierarchyItem &Item,
266 Callback<std::vector<CallHierarchyIncomingCall>>);
268 /// Resolve inlay hints for a given document.
269 void inlayHints(PathRef File, llvm::Optional<Range> RestrictRange,
270 Callback<std::vector<InlayHint>>);
272 /// Retrieve the top symbols from the workspace matching a query.
273 void workspaceSymbols(StringRef Query, int Limit,
274 Callback<std::vector<SymbolInformation>> CB);
276 /// Retrieve the symbols within the specified file.
277 void documentSymbols(StringRef File,
278 Callback<std::vector<DocumentSymbol>> CB);
280 /// Retrieve ranges that can be used to fold code within the specified file.
281 void foldingRanges(StringRef File, Callback<std::vector<FoldingRange>> CB);
283 /// Retrieve implementations for virtual method.
284 void findImplementations(PathRef File, Position Pos,
285 Callback<std::vector<LocatedSymbol>> CB);
287 /// Retrieve symbols for types referenced at \p Pos.
288 void findType(PathRef File, Position Pos,
289 Callback<std::vector<LocatedSymbol>> CB);
291 /// Retrieve locations for symbol references.
292 void findReferences(PathRef File, Position Pos, uint32_t Limit,
293 Callback<ReferencesResult> CB);
295 /// Run formatting for the \p File with content \p Code.
296 /// If \p Rng is non-null, formats only that region.
297 void formatFile(PathRef File, llvm::Optional<Range> Rng,
298 Callback<tooling::Replacements> CB);
300 /// Run formatting after \p TriggerText was typed at \p Pos in \p File with
301 /// content \p Code.
302 void formatOnType(PathRef File, Position Pos, StringRef TriggerText,
303 Callback<std::vector<TextEdit>> CB);
305 /// Test the validity of a rename operation.
307 /// If NewName is provided, it performs a name validation.
308 void prepareRename(PathRef File, Position Pos,
309 llvm::Optional<std::string> NewName,
310 const RenameOptions &RenameOpts,
311 Callback<RenameResult> CB);
313 /// Rename all occurrences of the symbol at the \p Pos in \p File to
314 /// \p NewName.
315 /// If WantFormat is false, the final TextEdit will be not formatted,
316 /// embedders could use this method to get all occurrences of the symbol (e.g.
317 /// highlighting them in prepare stage).
318 void rename(PathRef File, Position Pos, llvm::StringRef NewName,
319 const RenameOptions &Opts, Callback<RenameResult> CB);
321 struct TweakRef {
322 std::string ID; /// ID to pass for applyTweak.
323 std::string Title; /// A single-line message to show in the UI.
324 llvm::StringLiteral Kind;
326 /// Enumerate the code tweaks available to the user at a specified point.
327 /// Tweaks where Filter returns false will not be checked or included.
328 void enumerateTweaks(PathRef File, Range Sel,
329 llvm::unique_function<bool(const Tweak &)> Filter,
330 Callback<std::vector<TweakRef>> CB);
332 /// Apply the code tweak with a specified \p ID.
333 void applyTweak(PathRef File, Range Sel, StringRef ID,
334 Callback<Tweak::Effect> CB);
336 /// Called when an event occurs for a watched file in the workspace.
337 void onFileEvent(const DidChangeWatchedFilesParams &Params);
339 /// Get symbol info for given position.
340 /// Clangd extension - not part of official LSP.
341 void symbolInfo(PathRef File, Position Pos,
342 Callback<std::vector<SymbolDetails>> CB);
344 /// Get semantic ranges around a specified position in a file.
345 void semanticRanges(PathRef File, const std::vector<Position> &Pos,
346 Callback<std::vector<SelectionRange>> CB);
348 /// Get all document links in a file.
349 void documentLinks(PathRef File, Callback<std::vector<DocumentLink>> CB);
351 void semanticHighlights(PathRef File,
352 Callback<std::vector<HighlightingToken>>);
354 /// Describe the AST subtree for a piece of code.
355 void getAST(PathRef File, llvm::Optional<Range> R,
356 Callback<llvm::Optional<ASTNode>> CB);
358 /// Runs an arbitrary action that has access to the AST of the specified file.
359 /// The action will execute on one of ClangdServer's internal threads.
360 /// The AST is only valid for the duration of the callback.
361 /// As with other actions, the file must have been opened.
362 void customAction(PathRef File, llvm::StringRef Name,
363 Callback<InputsAndAST> Action);
365 /// Fetches diagnostics for current version of the \p File. This might fail if
366 /// server is busy (building a preamble) and would require a long time to
367 /// prepare diagnostics. If it fails, clients should wait for
368 /// onSemanticsMaybeChanged and then retry.
369 /// These 'pulled' diagnostics do not interfere with the diagnostics 'pushed'
370 /// to Callbacks::onDiagnosticsReady, and clients may use either or both.
371 void diagnostics(PathRef File, Callback<std::vector<Diag>> CB);
373 /// Returns estimated memory usage and other statistics for each of the
374 /// currently open files.
375 /// Overall memory usage of clangd may be significantly more than reported
376 /// here, as this metric does not account (at least) for:
377 /// - memory occupied by static and dynamic index,
378 /// - memory required for in-flight requests,
379 /// FIXME: those metrics might be useful too, we should add them.
380 llvm::StringMap<TUScheduler::FileStats> fileStats() const;
382 /// Gets the contents of a currently tracked file. Returns nullptr if the file
383 /// isn't being tracked.
384 std::shared_ptr<const std::string> getDraft(PathRef File) const;
386 // Blocks the main thread until the server is idle. Only for use in tests.
387 // Returns false if the timeout expires.
388 // FIXME: various subcomponents each get the full timeout, so it's more of
389 // an order of magnitude than a hard deadline.
390 LLVM_NODISCARD bool
391 blockUntilIdleForTest(llvm::Optional<double> TimeoutSeconds = 10);
393 /// Builds a nested representation of memory used by components.
394 void profile(MemoryTree &MT) const;
396 private:
397 FeatureModuleSet *FeatureModules;
398 const GlobalCompilationDatabase &CDB;
399 const ThreadsafeFS &getHeaderFS() const {
400 return UseDirtyHeaders ? *DirtyFS : TFS;
402 const ThreadsafeFS &TFS;
404 Path ResourceDir;
405 // The index used to look up symbols. This could be:
406 // - null (all index functionality is optional)
407 // - the dynamic index owned by ClangdServer (DynamicIdx)
408 // - the static index passed to the constructor
409 // - a merged view of a static and dynamic index (MergedIndex)
410 const SymbolIndex *Index = nullptr;
411 // If present, an index of symbols in open files. Read via *Index.
412 std::unique_ptr<FileIndex> DynamicIdx;
413 // If present, the new "auto-index" maintained in background threads.
414 std::unique_ptr<BackgroundIndex> BackgroundIdx;
415 // Storage for merged views of the various indexes.
416 std::vector<std::unique_ptr<SymbolIndex>> MergedIdx;
418 // When set, provides clang-tidy options for a specific file.
419 TidyProviderRef ClangTidyProvider;
421 bool UseDirtyHeaders = false;
423 bool PreambleParseForwardingFunctions = false;
425 // GUARDED_BY(CachedCompletionFuzzyFindRequestMutex)
426 llvm::StringMap<llvm::Optional<FuzzyFindRequest>>
427 CachedCompletionFuzzyFindRequestByFile;
428 mutable std::mutex CachedCompletionFuzzyFindRequestMutex;
430 llvm::Optional<std::string> WorkspaceRoot;
431 llvm::Optional<AsyncTaskRunner> IndexTasks; // for stdlib indexing.
432 llvm::Optional<TUScheduler> WorkScheduler;
433 // Invalidation policy used for actions that we assume are "transient".
434 TUScheduler::ASTActionInvalidation Transient;
436 // Store of the current versions of the open documents.
437 // Only written from the main thread (despite being threadsafe).
438 DraftStore DraftMgr;
440 std::unique_ptr<ThreadsafeFS> DirtyFS;
443 } // namespace clangd
444 } // namespace clang
446 #endif