clang-tools 22.0.0git
CodeComplete.h
Go to the documentation of this file.
1//===--- CodeComplete.h ------------------------------------------*- 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// Code completion provides suggestions for what the user might type next.
10// After "std::string S; S." we might suggest members of std::string.
11// Signature help describes the parameters of a function as you type them.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_CODECOMPLETE_H
16#define LLVM_CLANG_TOOLS_EXTRA_CLANGD_CODECOMPLETE_H
17
18#include "ASTSignals.h"
19#include "Compiler.h"
20#include "Config.h"
21#include "Protocol.h"
22#include "Quality.h"
23#include "index/Index.h"
24#include "index/Symbol.h"
25#include "index/SymbolOrigin.h"
26#include "support/Markup.h"
27#include "support/Path.h"
28#include "clang/Sema/CodeCompleteConsumer.h"
29#include "clang/Sema/CodeCompleteOptions.h"
30#include "llvm/ADT/SmallVector.h"
31#include "llvm/ADT/StringRef.h"
32#include <functional>
33#include <future>
34#include <optional>
35#include <utility>
36
37namespace clang {
38class NamedDecl;
39namespace clangd {
40struct PreambleData;
41struct CodeCompletion;
42
44 /// Returns options that can be passed to clang's completion engine.
45 clang::CodeCompleteOptions getClangCompleteOpts() const;
46
47 /// When true, completion items will contain expandable code snippets in
48 /// completion (e.g. `return ${1:expression}` or `foo(${1:int a}, ${2:int
49 /// b})).
50 bool EnableSnippets = false;
51
52 /// Include results that are not legal completions in the current context.
53 /// For example, private members are usually inaccessible.
54 bool IncludeIneligibleResults = false;
55
56 /// Force sema to load decls from preamble even if an index is provided.
57 /// This is helpful for cases the index can't provide symbols, e.g. with
58 /// experimental c++20 modules
59 bool ForceLoadPreamble = false;
60
61 /// Combine overloads into a single completion item where possible.
62 /// If none, the implementation may choose an appropriate behavior.
63 /// (In practice, ClangdLSPServer enables bundling if the client claims
64 /// to supports signature help).
65 std::optional<bool> BundleOverloads;
66
67 /// Limit the number of results returned (0 means no limit).
68 /// If more results are available, we set CompletionList.isIncomplete.
69 size_t Limit = 0;
70
71 /// Whether to present doc comments as plain-text or markdown.
72 MarkupKind DocumentationFormat = MarkupKind::PlainText;
73
74 Config::HeaderInsertionPolicy InsertIncludes =
76
77 /// Whether include insertions for Objective-C code should use #import instead
78 /// of #include.
79 bool ImportInsertions = false;
80
81 /// A visual indicator to prepend to the completion label to indicate whether
82 /// completion result would trigger an #include insertion or not.
83 struct IncludeInsertionIndicator {
84 std::string Insert = "•";
85 std::string NoInsert = " ";
86 } IncludeIndicator;
87
88 /// Expose origins of completion items in the label (for debugging).
89 bool ShowOrigins = false;
90
91 // Populated internally by clangd, do not set.
92 /// If `Index` is set, it is used to augment the code completion
93 /// results.
94 /// FIXME(ioeric): we might want a better way to pass the index around inside
95 /// clangd.
96 const SymbolIndex *Index = nullptr;
97
98 const ASTSignals *MainFileSignals = nullptr;
99 /// Include completions that require small corrections, e.g. change '.' to
100 /// '->' on member access etc.
101 bool IncludeFixIts = false;
102
103 /// Whether to include index symbols that are not defined in the scopes
104 /// visible from the code completion point. This applies in contexts without
105 /// explicit scope qualifiers.
106 ///
107 /// Such completions can insert scope qualifiers.
108 bool AllScopes = false;
109
110 /// The way argument list on calls '()' and generics '<>' are handled.
111 Config::ArgumentListsPolicy ArgumentLists =
113
114 /// Whether to suggest code patterns & snippets or not in completion
116
117 /// Filter macros using an exact prefix, or with a fuzzy match. In both cases,
118 /// macros with leading or trailing underscores are strictly filtered
119 Config::MacroFilterPolicy MacroFilter =
121
122 /// Whether to use the clang parser, or fallback to text-based completion
123 /// (using identifiers in the current file and symbol indexes).
124 enum CodeCompletionParse {
125 /// Block until we can run the parser (e.g. preamble is built).
126 /// Return an error if this fails.
127 AlwaysParse,
128 /// Run the parser if inputs (preamble) are ready.
129 /// Otherwise, use text-based completion.
130 ParseIfReady,
131 /// Always use text-based completion.
132 NeverParse,
133 } RunParser = ParseIfReady;
134
135 /// Callback invoked on all CompletionCandidate after they are scored and
136 /// before they are ranked (by -Score). Thus the results are yielded in
137 /// arbitrary order.
138 ///
139 /// This callbacks allows capturing various internal structures used by clangd
140 /// during code completion. Eg: Symbol quality and relevance signals.
141 std::function<void(const CodeCompletion &, const SymbolQualitySignals &,
142 const SymbolRelevanceSignals &, float Score)>
143 RecordCCResult;
144
145 /// Model to use for ranking code completion candidates.
146 enum CodeCompletionRankingModel {
147 Heuristics,
148 DecisionForest,
149 };
150 static const CodeCompletionRankingModel DefaultRankingModel;
151 CodeCompletionRankingModel RankingModel = DefaultRankingModel;
152
153 /// Callback used to score a CompletionCandidate if DecisionForest ranking
154 /// model is enabled.
155 /// This allows us to inject experimental models and compare them with
156 /// baseline model using A/B testing.
157 std::function<DecisionForestScores(
158 const SymbolQualitySignals &, const SymbolRelevanceSignals &, float Base)>
159 DecisionForestScorer = &evaluateDecisionForest;
160 /// Weight for combining NameMatch and Prediction of DecisionForest.
161 /// CompletionScore is NameMatch * pow(Base, Prediction).
162 /// The optimal value of Base largely depends on the semantics of the model
163 /// and prediction score (e.g. algorithm used during training, number of
164 /// trees, etc.). Usually if the range of Prediction is [-20, 20] then a Base
165 /// in [1.2, 1.7] works fine.
166 /// Semantics: E.g. For Base = 1.3, if the Prediction score reduces by 2.6
167 /// points then completion score reduces by 50% or 1.3^(-2.6).
168 float DecisionForestBase = 1.3f;
169};
170
171// Semi-structured representation of a code-complete suggestion for our C++ API.
172// We don't use the LSP structures here (unlike most features) as we want
173// to expose more data to allow for more precise testing and evaluation.
174struct CodeCompletion {
175 // The unqualified name of the symbol or other completion item.
176 std::string Name;
177 // The name of the symbol for filtering and sorting purposes. Typically the
178 // same as `Name`, but may be different e.g. for ObjC methods, `Name` is the
179 // first selector fragment but the `FilterText` is the entire selector.
180 std::string FilterText;
181 // The scope qualifier for the symbol name. e.g. "ns1::ns2::"
182 // Empty for non-symbol completions. Not inserted, but may be displayed.
183 std::string Scope;
184 // Text that must be inserted before the name, and displayed (e.g. base::).
185 std::string RequiredQualifier;
186 // Details to be displayed following the name. Not inserted.
187 std::string Signature;
188 // Text to be inserted following the name, in snippet format.
189 std::string SnippetSuffix;
190 // Type to be displayed for this completion.
191 std::string ReturnType;
192 // The parsed documentation comment.
193 std::optional<markup::Document> Documentation;
195 // This completion item may represent several symbols that can be inserted in
196 // the same way, such as function overloads. In this case BundleSize > 1, and
197 // the following fields are summaries:
198 // - Signature is e.g. "(...)" for functions.
199 // - SnippetSuffix is similarly e.g. "(${0})".
200 // - ReturnType may be empty
201 // - Documentation may be from one symbol, or a combination of several
202 // Other fields should apply equally to all bundled completions.
203 unsigned BundleSize = 1;
205
206 struct IncludeCandidate {
207 // The header through which this symbol could be included.
208 // Quoted string as expected by an #include directive, e.g. "<memory>".
209 // Empty for non-symbol completions, or when not known.
210 std::string Header;
211 // Present if Header should be inserted to use this item.
212 std::optional<TextEdit> Insertion;
213 };
214 // All possible include headers ranked by preference. By default, the first
215 // include is used.
216 // If we've bundled together overloads that have different sets of includes,
217 // thse includes may not be accurate for all of them.
218 llvm::SmallVector<IncludeCandidate, 1> Includes;
219
220 /// Holds information about small corrections that needs to be done. Like
221 /// converting '->' to '.' on member access.
222 std::vector<TextEdit> FixIts;
223
224 /// Holds the range of the token we are going to replace with this completion.
225 Range CompletionTokenRange;
226
227 // Scores are used to rank completion items.
228 struct Scores {
229 // The score that items are ranked by.
230 float Total = 0.f;
231
232 // The finalScore with the fuzzy name match score excluded.
233 // When filtering client-side, editors should calculate the new fuzzy score,
234 // whose scale is 0-1 (with 1 = prefix match, special case 2 = exact match),
235 // and recompute finalScore = fuzzyScore * symbolScore.
236 float ExcludingName = 0.f;
237
238 // Component scores that contributed to the final score:
239
240 // Quality describes how important we think this candidate is,
241 // independent of the query.
242 // e.g. symbols with lots of incoming references have higher quality.
243 float Quality = 0.f;
244 // Relevance describes how well this candidate matched the query.
245 // e.g. symbols from nearby files have higher relevance.
246 float Relevance = 0.f;
247 };
248 Scores Score;
249
250 /// Indicates if this item is deprecated.
251 bool Deprecated = false;
252
253 // Serialize this to an LSP completion item. This is a lossy operation.
254 CompletionItem render(const CodeCompleteOptions &) const;
255};
256raw_ostream &operator<<(raw_ostream &, const CodeCompletion &);
257struct CodeCompleteResult {
258 std::vector<CodeCompletion> Completions;
259 bool HasMore = false;
260 CodeCompletionContext::Kind Context = CodeCompletionContext::CCC_Other;
261 // The text that is being directly completed.
262 // Example: foo.pb^ -> foo.push_back()
263 // ~~
264 // Typically matches the textEdit.range of Completions, but not guaranteed to.
265 std::optional<Range> CompletionRange;
266 // Usually the source will be parsed with a real C++ parser.
267 // But heuristics may be used instead if e.g. the preamble is not ready.
268 bool RanParser = true;
269};
270raw_ostream &operator<<(raw_ostream &, const CodeCompleteResult &);
271
272/// A speculative and asynchronous fuzzy find index request (based on cached
273/// request) that can be sent before parsing sema. This would reduce completion
274/// latency if the speculation succeeds.
275struct SpeculativeFuzzyFind {
276 /// A cached request from past code completions.
277 /// Set by caller of `codeComplete()`.
278 std::optional<FuzzyFindRequest> CachedReq;
279 /// The actual request used by `codeComplete()`.
280 /// Set by `codeComplete()`. This can be used by callers to update cache.
281 std::optional<FuzzyFindRequest> NewReq;
282 /// The result is consumed by `codeComplete()` if speculation succeeded.
283 std::future<std::pair<bool /*Incomplete*/, SymbolSlab>> Result;
284};
285
286/// Gets code completions at a specified \p Pos in \p FileName.
287///
288/// If \p Preamble is nullptr, this runs code completion without compiling the
289/// code.
290///
291/// If \p SpecFuzzyFind is set, a speculative and asynchronous fuzzy find index
292/// request (based on cached request) will be run before parsing sema. In case
293/// the speculative result is used by code completion (e.g. speculation failed),
294/// the speculative result is not consumed, and `SpecFuzzyFind` is only
295/// destroyed when the async request finishes.
296CodeCompleteResult codeComplete(PathRef FileName, Position Pos,
297 const PreambleData *Preamble,
298 const ParseInputs &ParseInput,
300 SpeculativeFuzzyFind *SpecFuzzyFind = nullptr);
301
302/// Get signature help at a specified \p Pos in \p FileName.
304 const PreambleData &Preamble,
305 const ParseInputs &ParseInput,
306 MarkupKind DocumentationFormat);
307
308// For index-based completion, we only consider:
309// * symbols in namespaces or translation unit scopes (e.g. no class
310// members, no locals)
311// * enum constants (both scoped and unscoped)
312// * primary templates (no specializations)
313// For the other cases, we let Clang do the completion because it does not
314// need any non-local information and it will be much better at following
315// lookup rules. Other symbols still appear in the index for other purposes,
316// like workspace/symbols or textDocument/definition, but are not used for code
317// completion.
318bool isIndexedForCodeCompletion(const NamedDecl &ND, ASTContext &ASTCtx);
319
320// Text immediately before the completion point that should be completed.
321// This is heuristically derived from the source code, and is used when:
322// - semantic analysis fails
323// - semantic analysis may be slow, and we speculatively query the index
325 // The unqualified partial name.
326 // If there is none, begin() == end() == completion position.
327 llvm::StringRef Name;
328 // The spelled scope qualifier, such as Foo::.
329 // If there is none, begin() == end() == Name.begin().
330 llvm::StringRef Qualifier;
331};
332// Heuristically parses before Offset to determine what should be completed.
333CompletionPrefix guessCompletionPrefix(llvm::StringRef Content,
334 unsigned Offset);
335
336// Whether it makes sense to complete at the point based on typed characters.
337// For instance, we implicitly trigger at `a->^` but not at `a>^`.
338bool allowImplicitCompletion(llvm::StringRef Content, unsigned Offset);
339
340} // namespace clangd
341} // namespace clang
342
343#endif // LLVM_CLANG_TOOLS_EXTRA_CLANGD_CODECOMPLETE_H
Interface for symbol indexes that can be used for searching or matching symbols among a set of symbol...
Definition Index.h:134
An immutable symbol container that stores a set of symbols.
Definition Symbol.h:201
FIXME: Skip testing on windows temporarily due to the different escaping code mode.
Definition AST.cpp:45
CompletionPrefix guessCompletionPrefix(llvm::StringRef Content, unsigned Offset)
CompletionItemKind
The kind of a completion entry.
Definition Protocol.h:338
bool allowImplicitCompletion(llvm::StringRef Content, unsigned Offset)
DecisionForestScores evaluateDecisionForest(const SymbolQualitySignals &Quality, const SymbolRelevanceSignals &Relevance, float Base)
llvm::raw_ostream & operator<<(llvm::raw_ostream &OS, const CodeCompletion &C)
llvm::StringRef PathRef
A typedef to represent a ref to file path.
Definition Path.h:29
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.
SignatureHelp signatureHelp(PathRef FileName, Position Pos, const PreambleData &Preamble, const ParseInputs &ParseInput, MarkupKind DocumentationFormat)
Get signature help at a specified Pos in FileName.
bool isIndexedForCodeCompletion(const NamedDecl &ND, ASTContext &ASTCtx)
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
Signals derived from a valid AST of a file.
Definition ASTSignals.h:27
clang::CodeCompleteOptions getClangCompleteOpts() const
Returns options that can be passed to clang's completion engine.
ArgumentListsPolicy
controls the completion options for argument lists.
Definition Config.h:139
@ FullPlaceholders
full name of both type and variable.
Definition Config.h:147
Same semantics as CodeComplete::Score.
Definition Quality.h:179
Information required to run clang, e.g. to parse AST or do code completion.
Definition Compiler.h:49
The parsed preamble and associated data.
Definition Preamble.h:97
Represents the signature of a callable.
Definition Protocol.h:1421
Attributes of a symbol that affect how much we like it.
Definition Quality.h:56
Attributes of a symbol-query pair that affect how much we like it.
Definition Quality.h:86