clang-tools  7.0.0
CodeComplete.h
Go to the documentation of this file.
1 //===--- CodeComplete.h -----------------------------------------*- C++-*-===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===---------------------------------------------------------------------===//
9 //
10 // Code completion provides suggestions for what the user might type next.
11 // After "std::string S; S." we might suggest members of std::string.
12 // Signature help describes the parameters of a function as you type them.
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 "Logger.h"
20 #include "Path.h"
21 #include "Protocol.h"
22 #include "index/Index.h"
23 #include "clang/Frontend/PrecompiledPreamble.h"
24 #include "clang/Sema/CodeCompleteConsumer.h"
25 #include "clang/Sema/CodeCompleteOptions.h"
26 #include "clang/Tooling/CompilationDatabase.h"
27 
28 namespace clang {
29 class NamedDecl;
30 class PCHContainerOperations;
31 namespace clangd {
32 
34  /// Returns options that can be passed to clang's completion engine.
35  clang::CodeCompleteOptions getClangCompleteOpts() const;
36 
37  /// When true, completion items will contain expandable code snippets in
38  /// completion (e.g. `return ${1:expression}` or `foo(${1:int a}, ${2:int
39  /// b})).
40  bool EnableSnippets = false;
41 
42  /// Add code patterns to completion results.
43  /// If EnableSnippets is false, this options is ignored and code patterns will
44  /// always be omitted.
45  bool IncludeCodePatterns = true;
46 
47  /// Add macros to code completion results.
48  bool IncludeMacros = true;
49 
50  /// Add comments to code completion results, if available.
51  bool IncludeComments = true;
52 
53  /// Include results that are not legal completions in the current context.
54  /// For example, private members are usually inaccessible.
56 
57  /// Combine overloads into a single completion item where possible.
58  bool BundleOverloads = false;
59 
60  /// Limit the number of results returned (0 means no limit).
61  /// If more results are available, we set CompletionList.isIncomplete.
62  size_t Limit = 0;
63 
64  /// A visual indicator to prepend to the completion label to indicate whether
65  /// completion result would trigger an #include insertion or not.
67  std::string Insert = "•";
68  std::string NoInsert = " ";
70 
71  /// Expose origins of completion items in the label (for debugging).
72  bool ShowOrigins = false;
73 
74  // Populated internally by clangd, do not set.
75  /// If `Index` is set, it is used to augment the code completion
76  /// results.
77  /// FIXME(ioeric): we might want a better way to pass the index around inside
78  /// clangd.
79  const SymbolIndex *Index = nullptr;
80 };
81 
82 // Semi-structured representation of a code-complete suggestion for our C++ API.
83 // We don't use the LSP structures here (unlike most features) as we want
84 // to expose more data to allow for more precise testing and evaluation.
86  // The unqualified name of the symbol or other completion item.
87  std::string Name;
88  // The scope qualifier for the symbol name. e.g. "ns1::ns2::"
89  // Empty for non-symbol completions. Not inserted, but may be displayed.
90  std::string Scope;
91  // Text that must be inserted before the name, and displayed (e.g. base::).
92  std::string RequiredQualifier;
93  // Details to be displayed following the name. Not inserted.
94  std::string Signature;
95  // Text to be inserted following the name, in snippet format.
96  std::string SnippetSuffix;
97  // Type to be displayed for this completion.
98  std::string ReturnType;
99  std::string Documentation;
101  // This completion item may represent several symbols that can be inserted in
102  // the same way, such as function overloads. In this case BundleSize > 1, and
103  // the following fields are summaries:
104  // - Signature is e.g. "(...)" for functions.
105  // - SnippetSuffix is similarly e.g. "(${0})".
106  // - ReturnType may be empty
107  // - Documentation may be from one symbol, or a combination of several
108  // Other fields should apply equally to all bundled completions.
109  unsigned BundleSize = 1;
111  // The header through which this symbol could be included.
112  // Quoted string as expected by an #include directive, e.g. "<memory>".
113  // Empty for non-symbol completions, or when not known.
114  std::string Header;
115  // Present if Header is set and should be inserted to use this item.
116  llvm::Optional<TextEdit> HeaderInsertion;
117 
118  // Scores are used to rank completion items.
119  struct Scores {
120  // The score that items are ranked by.
121  float Total = 0.f;
122 
123  // The finalScore with the fuzzy name match score excluded.
124  // When filtering client-side, editors should calculate the new fuzzy score,
125  // whose scale is 0-1 (with 1 = prefix match, special case 2 = exact match),
126  // and recompute finalScore = fuzzyScore * symbolScore.
127  float ExcludingName = 0.f;
128 
129  // Component scores that contributed to the final score:
130 
131  // Quality describes how important we think this candidate is,
132  // independent of the query.
133  // e.g. symbols with lots of incoming references have higher quality.
134  float Quality = 0.f;
135  // Relevance describes how well this candidate matched the query.
136  // e.g. symbols from nearby files have higher relevance.
137  float Relevance = 0.f;
138  };
140 
141  // Serialize this to an LSP completion item. This is a lossy operation.
142  CompletionItem render(const CodeCompleteOptions &) const;
143 };
144 raw_ostream &operator<<(raw_ostream &, const CodeCompletion &);
146  std::vector<CodeCompletion> Completions;
147  bool HasMore = false;
148  CodeCompletionContext::Kind Context = CodeCompletionContext::CCC_Other;
149 };
150 raw_ostream &operator<<(raw_ostream &, const CodeCompleteResult &);
151 
152 /// Get code completions at a specified \p Pos in \p FileName.
154  const tooling::CompileCommand &Command,
155  PrecompiledPreamble const *Preamble,
156  const IncludeStructure &PreambleInclusions,
157  StringRef Contents, Position Pos,
158  IntrusiveRefCntPtr<vfs::FileSystem> VFS,
159  std::shared_ptr<PCHContainerOperations> PCHs,
160  CodeCompleteOptions Opts);
161 
162 /// Get signature help at a specified \p Pos in \p FileName.
164  const tooling::CompileCommand &Command,
165  PrecompiledPreamble const *Preamble,
166  StringRef Contents, Position Pos,
167  IntrusiveRefCntPtr<vfs::FileSystem> VFS,
168  std::shared_ptr<PCHContainerOperations> PCHs);
169 
170 // For index-based completion, we only consider:
171 // * symbols in namespaces or translation unit scopes (e.g. no class
172 // members, no locals)
173 // * enum constants in unscoped enum decl (e.g. "red" in "enum {red};")
174 // * primary templates (no specializations)
175 // For the other cases, we let Clang do the completion because it does not
176 // need any non-local information and it will be much better at following
177 // lookup rules. Other symbols still appear in the index for other purposes,
178 // like workspace/symbols or textDocument/definition, but are not used for code
179 // completion.
180 bool isIndexedForCodeCompletion(const NamedDecl &ND, ASTContext &ASTCtx);
181 } // namespace clangd
182 } // namespace clang
183 
184 #endif
bool ShowOrigins
Expose origins of completion items in the label (for debugging).
Definition: CodeComplete.h:72
bool BundleOverloads
Combine overloads into a single completion item where possible.
Definition: CodeComplete.h:58
size_t Limit
Limit the number of results returned (0 means no limit).
Definition: CodeComplete.h:62
CodeCompleteResult codeComplete(PathRef FileName, const tooling::CompileCommand &Command, PrecompiledPreamble const *Preamble, const IncludeStructure &PreambleInclusions, StringRef Contents, Position Pos, IntrusiveRefCntPtr< vfs::FileSystem > VFS, std::shared_ptr< PCHContainerOperations > PCHs, CodeCompleteOptions Opts)
Get code completions at a specified Pos in FileName.
SignatureHelp signatureHelp(PathRef FileName, const tooling::CompileCommand &Command, PrecompiledPreamble const *Preamble, StringRef Contents, Position Pos, IntrusiveRefCntPtr< vfs::FileSystem > VFS, std::shared_ptr< PCHContainerOperations > PCHs)
Get signature help at a specified Pos in FileName.
bool EnableSnippets
When true, completion items will contain expandable code snippets in completion (e.g.
Definition: CodeComplete.h:40
std::vector< CodeCompletion > Completions
Definition: CodeComplete.h:146
Interface for symbol indexes that can be used for searching or matching symbols among a set of symbol...
Definition: Index.h:317
llvm::StringRef PathRef
A typedef to represent a ref to file path.
Definition: Path.h:24
StringRef Contents
CompletionItemKind
The kind of a completion entry.
Definition: Protocol.h:644
BindArgumentKind Kind
bool IncludeComments
Add comments to code completion results, if available.
Definition: CodeComplete.h:51
bool IncludeCodePatterns
Add code patterns to completion results.
Definition: CodeComplete.h:45
bool isIndexedForCodeCompletion(const NamedDecl &ND, ASTContext &ASTCtx)
A visual indicator to prepend to the completion label to indicate whether completion result would tri...
Definition: CodeComplete.h:66
bool IncludeIneligibleResults
Include results that are not legal completions in the current context.
Definition: CodeComplete.h:55
PathRef FileName
PrecompiledPreamble const * Preamble
A context is an immutable container for per-request data that must be propagated through layers that ...
Definition: Context.h:70
clang::CodeCompleteOptions getClangCompleteOpts() const
Returns options that can be passed to clang&#39;s completion engine.
Position Pos
IntrusiveRefCntPtr< vfs::FileSystem > VFS
const SymbolIndex * Index
If Index is set, it is used to augment the code completion results.
Definition: CodeComplete.h:79
Represents the signature of a callable.
Definition: Protocol.h:778
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
llvm::Optional< TextEdit > HeaderInsertion
Definition: CodeComplete.h:116
std::shared_ptr< PCHContainerOperations > PCHs
struct clang::clangd::CodeCompleteOptions::IncludeInsertionIndicator IncludeIndicator
bool IncludeMacros
Add macros to code completion results.
Definition: CodeComplete.h:48
raw_ostream & operator<<(raw_ostream &OS, const CodeCompletion &C)