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