150
|
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 "Headers.h"
|
|
19 #include "Protocol.h"
|
173
|
20 #include "Quality.h"
|
150
|
21 #include "index/Index.h"
|
|
22 #include "index/Symbol.h"
|
|
23 #include "index/SymbolOrigin.h"
|
173
|
24 #include "support/Logger.h"
|
|
25 #include "support/Markup.h"
|
|
26 #include "support/Path.h"
|
150
|
27 #include "clang/Sema/CodeCompleteConsumer.h"
|
|
28 #include "clang/Sema/CodeCompleteOptions.h"
|
|
29 #include "clang/Tooling/CompilationDatabase.h"
|
|
30 #include "llvm/ADT/Optional.h"
|
|
31 #include "llvm/ADT/SmallVector.h"
|
|
32 #include "llvm/ADT/StringRef.h"
|
|
33 #include "llvm/Support/Error.h"
|
173
|
34 #include <functional>
|
150
|
35 #include <future>
|
|
36
|
|
37 namespace clang {
|
|
38 class NamedDecl;
|
|
39 namespace clangd {
|
|
40 struct PreambleData;
|
173
|
41 struct CodeCompletion;
|
150
|
42
|
|
43 struct CodeCompleteOptions {
|
|
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 /// Add code patterns to completion results.
|
|
53 /// If EnableSnippets is false, this options is ignored and code patterns will
|
|
54 /// always be omitted.
|
|
55 bool IncludeCodePatterns = true;
|
|
56
|
|
57 /// Add macros to code completion results.
|
|
58 bool IncludeMacros = true;
|
|
59
|
|
60 /// Add comments to code completion results, if available.
|
|
61 bool IncludeComments = true;
|
|
62
|
|
63 /// Include results that are not legal completions in the current context.
|
|
64 /// For example, private members are usually inaccessible.
|
|
65 bool IncludeIneligibleResults = false;
|
|
66
|
|
67 /// Combine overloads into a single completion item where possible.
|
|
68 /// If none, the implementation may choose an appropriate behavior.
|
|
69 /// (In practice, ClangdLSPServer enables bundling if the client claims
|
|
70 /// to supports signature help).
|
|
71 llvm::Optional<bool> BundleOverloads;
|
|
72
|
|
73 /// Limit the number of results returned (0 means no limit).
|
|
74 /// If more results are available, we set CompletionList.isIncomplete.
|
|
75 size_t Limit = 0;
|
|
76
|
173
|
77 /// Whether to present doc comments as plain-text or markdown.
|
|
78 MarkupKind DocumentationFormat = MarkupKind::PlainText;
|
|
79
|
150
|
80 enum IncludeInsertion {
|
|
81 IWYU,
|
|
82 NeverInsert,
|
|
83 } InsertIncludes = IncludeInsertion::IWYU;
|
|
84
|
|
85 /// A visual indicator to prepend to the completion label to indicate whether
|
|
86 /// completion result would trigger an #include insertion or not.
|
|
87 struct IncludeInsertionIndicator {
|
|
88 std::string Insert = "•";
|
|
89 std::string NoInsert = " ";
|
|
90 } IncludeIndicator;
|
|
91
|
|
92 /// Expose origins of completion items in the label (for debugging).
|
|
93 bool ShowOrigins = false;
|
|
94
|
|
95 /// If set to true, this will send an asynchronous speculative index request,
|
|
96 /// based on the index request for the last code completion on the same file
|
|
97 /// and the filter text typed before the cursor, before sema code completion
|
|
98 /// is invoked. This can reduce the code completion latency (by roughly
|
|
99 /// latency of sema code completion) if the speculative request is the same as
|
|
100 /// the one generated for the ongoing code completion from sema. As a sequence
|
|
101 /// of code completions often have the same scopes and proximity paths etc,
|
|
102 /// this should be effective for a number of code completions.
|
|
103 bool SpeculativeIndexRequest = false;
|
|
104
|
|
105 // Populated internally by clangd, do not set.
|
|
106 /// If `Index` is set, it is used to augment the code completion
|
|
107 /// results.
|
|
108 /// FIXME(ioeric): we might want a better way to pass the index around inside
|
|
109 /// clangd.
|
|
110 const SymbolIndex *Index = nullptr;
|
|
111
|
|
112 /// Include completions that require small corrections, e.g. change '.' to
|
|
113 /// '->' on member access etc.
|
|
114 bool IncludeFixIts = false;
|
|
115
|
|
116 /// Whether to generate snippets for function arguments on code-completion.
|
|
117 /// Needs snippets to be enabled as well.
|
|
118 bool EnableFunctionArgSnippets = true;
|
|
119
|
|
120 /// Whether to include index symbols that are not defined in the scopes
|
|
121 /// visible from the code completion point. This applies in contexts without
|
|
122 /// explicit scope qualifiers.
|
|
123 ///
|
|
124 /// Such completions can insert scope qualifiers.
|
|
125 bool AllScopes = false;
|
|
126
|
|
127 /// Whether to use the clang parser, or fallback to text-based completion
|
|
128 /// (using identifiers in the current file and symbol indexes).
|
|
129 enum CodeCompletionParse {
|
|
130 /// Block until we can run the parser (e.g. preamble is built).
|
|
131 /// Return an error if this fails.
|
|
132 AlwaysParse,
|
|
133 /// Run the parser if inputs (preamble) are ready.
|
|
134 /// Otherwise, use text-based completion.
|
|
135 ParseIfReady,
|
|
136 /// Always use text-based completion.
|
|
137 NeverParse,
|
|
138 } RunParser = ParseIfReady;
|
173
|
139
|
|
140 /// Callback invoked on all CompletionCandidate after they are scored and
|
|
141 /// before they are ranked (by -Score). Thus the results are yielded in
|
|
142 /// arbitrary order.
|
|
143 ///
|
|
144 /// This callbacks allows capturing various internal structures used by clangd
|
|
145 /// during code completion. Eg: Symbol quality and relevance signals.
|
|
146 std::function<void(const CodeCompletion &, const SymbolQualitySignals &,
|
|
147 const SymbolRelevanceSignals &, float Score)>
|
|
148 RecordCCResult;
|
150
|
149 };
|
|
150
|
|
151 // Semi-structured representation of a code-complete suggestion for our C++ API.
|
|
152 // We don't use the LSP structures here (unlike most features) as we want
|
|
153 // to expose more data to allow for more precise testing and evaluation.
|
|
154 struct CodeCompletion {
|
|
155 // The unqualified name of the symbol or other completion item.
|
|
156 std::string Name;
|
|
157 // The scope qualifier for the symbol name. e.g. "ns1::ns2::"
|
|
158 // Empty for non-symbol completions. Not inserted, but may be displayed.
|
|
159 std::string Scope;
|
|
160 // Text that must be inserted before the name, and displayed (e.g. base::).
|
|
161 std::string RequiredQualifier;
|
|
162 // Details to be displayed following the name. Not inserted.
|
|
163 std::string Signature;
|
|
164 // Text to be inserted following the name, in snippet format.
|
|
165 std::string SnippetSuffix;
|
|
166 // Type to be displayed for this completion.
|
|
167 std::string ReturnType;
|
173
|
168 // The parsed documentation comment.
|
|
169 llvm::Optional<markup::Document> Documentation;
|
150
|
170 CompletionItemKind Kind = CompletionItemKind::Missing;
|
|
171 // This completion item may represent several symbols that can be inserted in
|
|
172 // the same way, such as function overloads. In this case BundleSize > 1, and
|
|
173 // the following fields are summaries:
|
|
174 // - Signature is e.g. "(...)" for functions.
|
|
175 // - SnippetSuffix is similarly e.g. "(${0})".
|
|
176 // - ReturnType may be empty
|
|
177 // - Documentation may be from one symbol, or a combination of several
|
|
178 // Other fields should apply equally to all bundled completions.
|
|
179 unsigned BundleSize = 1;
|
|
180 SymbolOrigin Origin = SymbolOrigin::Unknown;
|
|
181
|
|
182 struct IncludeCandidate {
|
|
183 // The header through which this symbol could be included.
|
|
184 // Quoted string as expected by an #include directive, e.g. "<memory>".
|
|
185 // Empty for non-symbol completions, or when not known.
|
|
186 std::string Header;
|
|
187 // Present if Header should be inserted to use this item.
|
|
188 llvm::Optional<TextEdit> Insertion;
|
|
189 };
|
|
190 // All possible include headers ranked by preference. By default, the first
|
|
191 // include is used.
|
|
192 // If we've bundled together overloads that have different sets of includes,
|
|
193 // thse includes may not be accurate for all of them.
|
|
194 llvm::SmallVector<IncludeCandidate, 1> Includes;
|
|
195
|
|
196 /// Holds information about small corrections that needs to be done. Like
|
|
197 /// converting '->' to '.' on member access.
|
|
198 std::vector<TextEdit> FixIts;
|
|
199
|
|
200 /// Holds the range of the token we are going to replace with this completion.
|
|
201 Range CompletionTokenRange;
|
|
202
|
|
203 // Scores are used to rank completion items.
|
|
204 struct Scores {
|
|
205 // The score that items are ranked by.
|
|
206 float Total = 0.f;
|
|
207
|
|
208 // The finalScore with the fuzzy name match score excluded.
|
|
209 // When filtering client-side, editors should calculate the new fuzzy score,
|
|
210 // whose scale is 0-1 (with 1 = prefix match, special case 2 = exact match),
|
|
211 // and recompute finalScore = fuzzyScore * symbolScore.
|
|
212 float ExcludingName = 0.f;
|
|
213
|
|
214 // Component scores that contributed to the final score:
|
|
215
|
|
216 // Quality describes how important we think this candidate is,
|
|
217 // independent of the query.
|
|
218 // e.g. symbols with lots of incoming references have higher quality.
|
|
219 float Quality = 0.f;
|
|
220 // Relevance describes how well this candidate matched the query.
|
|
221 // e.g. symbols from nearby files have higher relevance.
|
|
222 float Relevance = 0.f;
|
|
223 };
|
|
224 Scores Score;
|
|
225
|
|
226 /// Indicates if this item is deprecated.
|
|
227 bool Deprecated = false;
|
|
228
|
|
229 // Serialize this to an LSP completion item. This is a lossy operation.
|
|
230 CompletionItem render(const CodeCompleteOptions &) const;
|
|
231 };
|
|
232 raw_ostream &operator<<(raw_ostream &, const CodeCompletion &);
|
|
233 struct CodeCompleteResult {
|
|
234 std::vector<CodeCompletion> Completions;
|
|
235 bool HasMore = false;
|
|
236 CodeCompletionContext::Kind Context = CodeCompletionContext::CCC_Other;
|
|
237 // The text that is being directly completed.
|
|
238 // Example: foo.pb^ -> foo.push_back()
|
|
239 // ~~
|
|
240 // Typically matches the textEdit.range of Completions, but not guaranteed to.
|
|
241 llvm::Optional<Range> CompletionRange;
|
|
242 // Usually the source will be parsed with a real C++ parser.
|
|
243 // But heuristics may be used instead if e.g. the preamble is not ready.
|
|
244 bool RanParser = true;
|
|
245 };
|
|
246 raw_ostream &operator<<(raw_ostream &, const CodeCompleteResult &);
|
|
247
|
|
248 /// A speculative and asynchronous fuzzy find index request (based on cached
|
|
249 /// request) that can be sent before parsing sema. This would reduce completion
|
|
250 /// latency if the speculation succeeds.
|
|
251 struct SpeculativeFuzzyFind {
|
|
252 /// A cached request from past code completions.
|
|
253 /// Set by caller of `codeComplete()`.
|
|
254 llvm::Optional<FuzzyFindRequest> CachedReq;
|
|
255 /// The actual request used by `codeComplete()`.
|
|
256 /// Set by `codeComplete()`. This can be used by callers to update cache.
|
|
257 llvm::Optional<FuzzyFindRequest> NewReq;
|
|
258 /// The result is consumed by `codeComplete()` if speculation succeeded.
|
|
259 /// NOTE: the destructor will wait for the async call to finish.
|
|
260 std::future<SymbolSlab> Result;
|
|
261 };
|
|
262
|
|
263 /// Gets code completions at a specified \p Pos in \p FileName.
|
|
264 ///
|
|
265 /// If \p Preamble is nullptr, this runs code completion without compiling the
|
|
266 /// code.
|
|
267 ///
|
|
268 /// If \p SpecFuzzyFind is set, a speculative and asynchronous fuzzy find index
|
|
269 /// request (based on cached request) will be run before parsing sema. In case
|
|
270 /// the speculative result is used by code completion (e.g. speculation failed),
|
|
271 /// the speculative result is not consumed, and `SpecFuzzyFind` is only
|
|
272 /// destroyed when the async request finishes.
|
|
273 CodeCompleteResult codeComplete(PathRef FileName,
|
|
274 const tooling::CompileCommand &Command,
|
|
275 const PreambleData *Preamble,
|
|
276 StringRef Contents, Position Pos,
|
|
277 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS,
|
|
278 CodeCompleteOptions Opts,
|
|
279 SpeculativeFuzzyFind *SpecFuzzyFind = nullptr);
|
|
280
|
|
281 /// Get signature help at a specified \p Pos in \p FileName.
|
|
282 SignatureHelp signatureHelp(PathRef FileName,
|
|
283 const tooling::CompileCommand &Command,
|
173
|
284 const PreambleData &Preamble, StringRef Contents,
|
150
|
285 Position Pos,
|
|
286 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS,
|
|
287 const SymbolIndex *Index);
|
|
288
|
|
289 // For index-based completion, we only consider:
|
|
290 // * symbols in namespaces or translation unit scopes (e.g. no class
|
|
291 // members, no locals)
|
|
292 // * enum constants in unscoped enum decl (e.g. "red" in "enum {red};")
|
|
293 // * primary templates (no specializations)
|
|
294 // For the other cases, we let Clang do the completion because it does not
|
|
295 // need any non-local information and it will be much better at following
|
|
296 // lookup rules. Other symbols still appear in the index for other purposes,
|
|
297 // like workspace/symbols or textDocument/definition, but are not used for code
|
|
298 // completion.
|
|
299 bool isIndexedForCodeCompletion(const NamedDecl &ND, ASTContext &ASTCtx);
|
|
300
|
|
301 // Text immediately before the completion point that should be completed.
|
|
302 // This is heuristically derived from the source code, and is used when:
|
|
303 // - semantic analysis fails
|
|
304 // - semantic analysis may be slow, and we speculatively query the index
|
|
305 struct CompletionPrefix {
|
|
306 // The unqualified partial name.
|
|
307 // If there is none, begin() == end() == completion position.
|
|
308 llvm::StringRef Name;
|
|
309 // The spelled scope qualifier, such as Foo::.
|
|
310 // If there is none, begin() == end() == Name.begin().
|
|
311 llvm::StringRef Qualifier;
|
|
312 };
|
|
313 // Heuristically parses before Offset to determine what should be completed.
|
|
314 CompletionPrefix guessCompletionPrefix(llvm::StringRef Content,
|
|
315 unsigned Offset);
|
|
316
|
173
|
317 // Whether it makes sense to complete at the point based on typed characters.
|
|
318 // For instance, we implicitly trigger at `a->^` but not at `a>^`.
|
|
319 bool allowImplicitCompletion(llvm::StringRef Content, unsigned Offset);
|
|
320
|
150
|
321 } // namespace clangd
|
|
322 } // namespace clang
|
|
323
|
|
324 #endif // LLVM_CLANG_TOOLS_EXTRA_CLANGD_CODECOMPLETE_H
|