blob: 7642ea9da7d9b636c5a9627338067f03f3dd108a [file] [log] [blame]
Kirill Bobyrev8e35f1e2018-08-14 16:03:32 +00001//===--- CodeComplete.cpp ----------------------------------------*- C++-*-===//
Sam McCall98775c52017-12-04 13:49:59 +00002//
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//
Kirill Bobyrev8e35f1e2018-08-14 16:03:32 +00008//===----------------------------------------------------------------------===//
Sam McCall98775c52017-12-04 13:49:59 +00009//
Sam McCallc18c2802018-06-15 11:06:29 +000010// Code completion has several moving parts:
11// - AST-based completions are provided using the completion hooks in Sema.
12// - external completions are retrieved from the index (using hints from Sema)
13// - the two sources overlap, and must be merged and overloads bundled
14// - results must be scored and ranked (see Quality.h) before rendering
Sam McCall98775c52017-12-04 13:49:59 +000015//
Sam McCallc18c2802018-06-15 11:06:29 +000016// Signature help works in a similar way as code completion, but it is simpler:
17// it's purely AST-based, and there are few candidates.
Sam McCall98775c52017-12-04 13:49:59 +000018//
Kirill Bobyrev8e35f1e2018-08-14 16:03:32 +000019//===----------------------------------------------------------------------===//
Sam McCall98775c52017-12-04 13:49:59 +000020
21#include "CodeComplete.h"
Eric Liu7ad16962018-06-22 10:46:59 +000022#include "AST.h"
Eric Liub1d75422018-10-02 10:43:55 +000023#include "ClangdUnit.h"
Eric Liu63696e12017-12-20 17:24:31 +000024#include "CodeCompletionStrings.h"
Sam McCall98775c52017-12-04 13:49:59 +000025#include "Compiler.h"
Kadir Cetinkaya2f84d912018-08-08 08:59:29 +000026#include "Diagnostics.h"
Ilya Biryukov647da3e2018-11-26 15:38:01 +000027#include "ExpectedTypes.h"
Sam McCall3f0243f2018-07-03 08:09:29 +000028#include "FileDistance.h"
Sam McCall84652cc2018-01-12 16:16:09 +000029#include "FuzzyMatch.h"
Eric Liu63f419a2018-05-15 15:29:32 +000030#include "Headers.h"
Eric Liu6f648df2017-12-19 16:50:37 +000031#include "Logger.h"
Sam McCallc5707b62018-05-15 17:43:27 +000032#include "Quality.h"
Eric Liuc5105f92018-02-16 14:15:55 +000033#include "SourceCode.h"
Eric Liu25d74e92018-08-24 11:23:56 +000034#include "TUScheduler.h"
Sam McCall2b780162018-01-30 17:20:54 +000035#include "Trace.h"
Eric Liu63f419a2018-05-15 15:29:32 +000036#include "URI.h"
Eric Liu6f648df2017-12-19 16:50:37 +000037#include "index/Index.h"
Eric Liu3fac4ef2018-10-17 11:19:02 +000038#include "clang/AST/Decl.h"
39#include "clang/AST/DeclBase.h"
Ilya Biryukovc22d3442018-05-16 12:32:49 +000040#include "clang/Basic/LangOptions.h"
Kadir Cetinkayaa9c9d002018-08-13 08:23:01 +000041#include "clang/Basic/SourceLocation.h"
Eric Liuc5105f92018-02-16 14:15:55 +000042#include "clang/Format/Format.h"
Sam McCall98775c52017-12-04 13:49:59 +000043#include "clang/Frontend/CompilerInstance.h"
44#include "clang/Frontend/FrontendActions.h"
Sam McCallebef8122018-09-14 12:36:06 +000045#include "clang/Lex/PreprocessorOptions.h"
Sam McCall98775c52017-12-04 13:49:59 +000046#include "clang/Sema/CodeCompleteConsumer.h"
47#include "clang/Sema/Sema.h"
Eric Liu670c1472018-09-27 18:46:00 +000048#include "llvm/ADT/ArrayRef.h"
Eric Liu3fac4ef2018-10-17 11:19:02 +000049#include "llvm/ADT/None.h"
Eric Liu25d74e92018-08-24 11:23:56 +000050#include "llvm/ADT/Optional.h"
Eric Liu83f63e42018-09-03 10:18:21 +000051#include "llvm/ADT/SmallVector.h"
Eric Liu25d74e92018-08-24 11:23:56 +000052#include "llvm/Support/Error.h"
Haojian Wuba28e9a2018-01-10 14:44:34 +000053#include "llvm/Support/Format.h"
Eric Liubc25ef72018-07-05 08:29:33 +000054#include "llvm/Support/FormatVariadic.h"
Sam McCall2161ec72018-07-05 06:20:41 +000055#include "llvm/Support/ScopedPrinter.h"
Eric Liu83f63e42018-09-03 10:18:21 +000056#include <algorithm>
57#include <iterator>
Sam McCall98775c52017-12-04 13:49:59 +000058
Sam McCallc5707b62018-05-15 17:43:27 +000059// We log detailed candidate here if you run with -debug-only=codecomplete.
Sam McCall27c979a2018-06-29 14:47:57 +000060#define DEBUG_TYPE "CodeComplete"
Sam McCallc5707b62018-05-15 17:43:27 +000061
Sam McCall98775c52017-12-04 13:49:59 +000062namespace clang {
63namespace clangd {
64namespace {
65
Eric Liu6f648df2017-12-19 16:50:37 +000066CompletionItemKind toCompletionItemKind(index::SymbolKind Kind) {
67 using SK = index::SymbolKind;
68 switch (Kind) {
69 case SK::Unknown:
70 return CompletionItemKind::Missing;
71 case SK::Module:
72 case SK::Namespace:
73 case SK::NamespaceAlias:
74 return CompletionItemKind::Module;
75 case SK::Macro:
76 return CompletionItemKind::Text;
77 case SK::Enum:
78 return CompletionItemKind::Enum;
79 // FIXME(ioeric): use LSP struct instead of class when it is suppoted in the
80 // protocol.
81 case SK::Struct:
82 case SK::Class:
83 case SK::Protocol:
84 case SK::Extension:
85 case SK::Union:
86 return CompletionItemKind::Class;
87 // FIXME(ioeric): figure out whether reference is the right type for aliases.
88 case SK::TypeAlias:
89 case SK::Using:
90 return CompletionItemKind::Reference;
91 case SK::Function:
92 // FIXME(ioeric): this should probably be an operator. This should be fixed
93 // when `Operator` is support type in the protocol.
94 case SK::ConversionFunction:
95 return CompletionItemKind::Function;
96 case SK::Variable:
97 case SK::Parameter:
98 return CompletionItemKind::Variable;
99 case SK::Field:
100 return CompletionItemKind::Field;
101 // FIXME(ioeric): use LSP enum constant when it is supported in the protocol.
102 case SK::EnumConstant:
103 return CompletionItemKind::Value;
104 case SK::InstanceMethod:
105 case SK::ClassMethod:
106 case SK::StaticMethod:
107 case SK::Destructor:
108 return CompletionItemKind::Method;
109 case SK::InstanceProperty:
110 case SK::ClassProperty:
111 case SK::StaticProperty:
112 return CompletionItemKind::Property;
113 case SK::Constructor:
114 return CompletionItemKind::Constructor;
115 }
116 llvm_unreachable("Unhandled clang::index::SymbolKind.");
117}
118
Sam McCall83305892018-06-08 21:17:19 +0000119CompletionItemKind
120toCompletionItemKind(CodeCompletionResult::ResultKind ResKind,
Sam McCall4c077f92018-09-18 09:08:28 +0000121 const NamedDecl *Decl,
122 CodeCompletionContext::Kind CtxKind) {
Sam McCall83305892018-06-08 21:17:19 +0000123 if (Decl)
124 return toCompletionItemKind(index::getSymbolInfo(Decl).Kind);
Sam McCall4c077f92018-09-18 09:08:28 +0000125 if (CtxKind == CodeCompletionContext::CCC_IncludedFile)
126 return CompletionItemKind::File;
Sam McCall83305892018-06-08 21:17:19 +0000127 switch (ResKind) {
128 case CodeCompletionResult::RK_Declaration:
129 llvm_unreachable("RK_Declaration without Decl");
130 case CodeCompletionResult::RK_Keyword:
131 return CompletionItemKind::Keyword;
132 case CodeCompletionResult::RK_Macro:
133 return CompletionItemKind::Text; // unfortunately, there's no 'Macro'
134 // completion items in LSP.
135 case CodeCompletionResult::RK_Pattern:
136 return CompletionItemKind::Snippet;
137 }
138 llvm_unreachable("Unhandled CodeCompletionResult::ResultKind.");
139}
140
Sam McCall98775c52017-12-04 13:49:59 +0000141/// Get the optional chunk as a string. This function is possibly recursive.
142///
143/// The parameter info for each parameter is appended to the Parameters.
Kadir Cetinkayae486e372018-08-13 08:40:05 +0000144std::string getOptionalParameters(const CodeCompletionString &CCS,
145 std::vector<ParameterInformation> &Parameters,
146 SignatureQualitySignals &Signal) {
Sam McCall98775c52017-12-04 13:49:59 +0000147 std::string Result;
148 for (const auto &Chunk : CCS) {
149 switch (Chunk.Kind) {
150 case CodeCompletionString::CK_Optional:
151 assert(Chunk.Optional &&
152 "Expected the optional code completion string to be non-null.");
Kadir Cetinkayae486e372018-08-13 08:40:05 +0000153 Result += getOptionalParameters(*Chunk.Optional, Parameters, Signal);
Sam McCall98775c52017-12-04 13:49:59 +0000154 break;
155 case CodeCompletionString::CK_VerticalSpace:
156 break;
157 case CodeCompletionString::CK_Placeholder:
158 // A string that acts as a placeholder for, e.g., a function call
159 // argument.
160 // Intentional fallthrough here.
161 case CodeCompletionString::CK_CurrentParameter: {
162 // A piece of text that describes the parameter that corresponds to
163 // the code-completion location within a function call, message send,
164 // macro invocation, etc.
165 Result += Chunk.Text;
166 ParameterInformation Info;
167 Info.label = Chunk.Text;
168 Parameters.push_back(std::move(Info));
Kadir Cetinkayae486e372018-08-13 08:40:05 +0000169 Signal.ContainsActiveParameter = true;
170 Signal.NumberOfOptionalParameters++;
Sam McCall98775c52017-12-04 13:49:59 +0000171 break;
172 }
173 default:
174 Result += Chunk.Text;
175 break;
176 }
177 }
178 return Result;
179}
180
Eric Liu63f419a2018-05-15 15:29:32 +0000181/// Creates a `HeaderFile` from \p Header which can be either a URI or a literal
182/// include.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000183static llvm::Expected<HeaderFile> toHeaderFile(llvm::StringRef Header,
184 llvm::StringRef HintPath) {
Eric Liu63f419a2018-05-15 15:29:32 +0000185 if (isLiteralInclude(Header))
186 return HeaderFile{Header.str(), /*Verbatim=*/true};
187 auto U = URI::parse(Header);
188 if (!U)
189 return U.takeError();
190
191 auto IncludePath = URI::includeSpelling(*U);
192 if (!IncludePath)
193 return IncludePath.takeError();
194 if (!IncludePath->empty())
195 return HeaderFile{std::move(*IncludePath), /*Verbatim=*/true};
196
197 auto Resolved = URI::resolve(*U, HintPath);
198 if (!Resolved)
199 return Resolved.takeError();
200 return HeaderFile{std::move(*Resolved), /*Verbatim=*/false};
201}
202
Sam McCall545a20d2018-01-19 14:34:02 +0000203/// A code completion result, in clang-native form.
Sam McCall98775c52017-12-04 13:49:59 +0000204/// It may be promoted to a CompletionItem if it's among the top-ranked results.
205struct CompletionCandidate {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000206 llvm::StringRef Name; // Used for filtering and sorting.
Sam McCall545a20d2018-01-19 14:34:02 +0000207 // We may have a result from Sema, from the index, or both.
208 const CodeCompletionResult *SemaResult = nullptr;
209 const Symbol *IndexResult = nullptr;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000210 llvm::SmallVector<llvm::StringRef, 1> RankedIncludeHeaders;
Sam McCall98775c52017-12-04 13:49:59 +0000211
Sam McCallc18c2802018-06-15 11:06:29 +0000212 // Returns a token identifying the overload set this is part of.
213 // 0 indicates it's not part of any overload set.
214 size_t overloadSet() const {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000215 llvm::SmallString<256> Scratch;
Sam McCallc18c2802018-06-15 11:06:29 +0000216 if (IndexResult) {
217 switch (IndexResult->SymInfo.Kind) {
218 case index::SymbolKind::ClassMethod:
219 case index::SymbolKind::InstanceMethod:
220 case index::SymbolKind::StaticMethod:
Fangrui Song12e4ee72018-11-02 05:59:29 +0000221#ifndef NDEBUG
222 llvm_unreachable("Don't expect members from index in code completion");
223#else
Fangrui Songa3ed05b2018-11-02 04:23:50 +0000224 LLVM_FALLTHROUGH;
Fangrui Song12e4ee72018-11-02 05:59:29 +0000225#endif
Sam McCallc18c2802018-06-15 11:06:29 +0000226 case index::SymbolKind::Function:
227 // We can't group overloads together that need different #includes.
228 // This could break #include insertion.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000229 return llvm::hash_combine(
Sam McCallc18c2802018-06-15 11:06:29 +0000230 (IndexResult->Scope + IndexResult->Name).toStringRef(Scratch),
Eric Liu83f63e42018-09-03 10:18:21 +0000231 headerToInsertIfAllowed().getValueOr(""));
Sam McCallc18c2802018-06-15 11:06:29 +0000232 default:
233 return 0;
234 }
235 }
236 assert(SemaResult);
237 // We need to make sure we're consistent with the IndexResult case!
238 const NamedDecl *D = SemaResult->Declaration;
239 if (!D || !D->isFunctionOrFunctionTemplate())
240 return 0;
241 {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000242 llvm::raw_svector_ostream OS(Scratch);
Sam McCallc18c2802018-06-15 11:06:29 +0000243 D->printQualifiedName(OS);
244 }
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000245 return llvm::hash_combine(Scratch,
246 headerToInsertIfAllowed().getValueOr(""));
Sam McCallc18c2802018-06-15 11:06:29 +0000247 }
248
Eric Liu83f63e42018-09-03 10:18:21 +0000249 // The best header to include if include insertion is allowed.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000250 llvm::Optional<llvm::StringRef> headerToInsertIfAllowed() const {
Eric Liu83f63e42018-09-03 10:18:21 +0000251 if (RankedIncludeHeaders.empty())
Sam McCallc008af62018-10-20 15:30:37 +0000252 return None;
Sam McCallc18c2802018-06-15 11:06:29 +0000253 if (SemaResult && SemaResult->Declaration) {
254 // Avoid inserting new #include if the declaration is found in the current
255 // file e.g. the symbol is forward declared.
256 auto &SM = SemaResult->Declaration->getASTContext().getSourceManager();
257 for (const Decl *RD : SemaResult->Declaration->redecls())
Stephen Kelly43465bf2018-08-09 22:42:26 +0000258 if (SM.isInMainFile(SM.getExpansionLoc(RD->getBeginLoc())))
Sam McCallc008af62018-10-20 15:30:37 +0000259 return None;
Sam McCallc18c2802018-06-15 11:06:29 +0000260 }
Eric Liu83f63e42018-09-03 10:18:21 +0000261 return RankedIncludeHeaders[0];
Sam McCallc18c2802018-06-15 11:06:29 +0000262 }
263
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000264 using Bundle = llvm::SmallVector<CompletionCandidate, 4>;
Sam McCall98775c52017-12-04 13:49:59 +0000265};
Sam McCallc18c2802018-06-15 11:06:29 +0000266using ScoredBundle =
Sam McCall27c979a2018-06-29 14:47:57 +0000267 std::pair<CompletionCandidate::Bundle, CodeCompletion::Scores>;
Sam McCallc18c2802018-06-15 11:06:29 +0000268struct ScoredBundleGreater {
269 bool operator()(const ScoredBundle &L, const ScoredBundle &R) {
Sam McCall27c979a2018-06-29 14:47:57 +0000270 if (L.second.Total != R.second.Total)
271 return L.second.Total > R.second.Total;
Sam McCallc18c2802018-06-15 11:06:29 +0000272 return L.first.front().Name <
273 R.first.front().Name; // Earlier name is better.
274 }
275};
Sam McCall98775c52017-12-04 13:49:59 +0000276
Sam McCall27c979a2018-06-29 14:47:57 +0000277// Assembles a code completion out of a bundle of >=1 completion candidates.
278// Many of the expensive strings are only computed at this point, once we know
279// the candidate bundle is going to be returned.
280//
281// Many fields are the same for all candidates in a bundle (e.g. name), and are
282// computed from the first candidate, in the constructor.
283// Others vary per candidate, so add() must be called for remaining candidates.
284struct CodeCompletionBuilder {
285 CodeCompletionBuilder(ASTContext &ASTCtx, const CompletionCandidate &C,
286 CodeCompletionString *SemaCCS,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000287 llvm::ArrayRef<std::string> QueryScopes,
288 const IncludeInserter &Includes,
289 llvm::StringRef FileName,
Sam McCall4c077f92018-09-18 09:08:28 +0000290 CodeCompletionContext::Kind ContextKind,
Sam McCall27c979a2018-06-29 14:47:57 +0000291 const CodeCompleteOptions &Opts)
Kadir Cetinkaya516fcda2018-08-23 12:19:39 +0000292 : ASTCtx(ASTCtx), ExtractDocumentation(Opts.IncludeComments),
293 EnableFunctionArgSnippets(Opts.EnableFunctionArgSnippets) {
Sam McCall27c979a2018-06-29 14:47:57 +0000294 add(C, SemaCCS);
295 if (C.SemaResult) {
Sam McCall4e5742a2018-07-06 11:50:49 +0000296 Completion.Origin |= SymbolOrigin::AST;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000297 Completion.Name = llvm::StringRef(SemaCCS->getTypedText());
Eric Liuf433c2d2018-07-18 15:31:14 +0000298 if (Completion.Scope.empty()) {
299 if ((C.SemaResult->Kind == CodeCompletionResult::RK_Declaration) ||
300 (C.SemaResult->Kind == CodeCompletionResult::RK_Pattern))
Sam McCall27c979a2018-06-29 14:47:57 +0000301 if (const auto *D = C.SemaResult->getDeclaration())
Sam McCallc008af62018-10-20 15:30:37 +0000302 if (const auto *ND = dyn_cast<NamedDecl>(D))
Sam McCall27c979a2018-06-29 14:47:57 +0000303 Completion.Scope =
304 splitQualifiedName(printQualifiedName(*ND)).first;
Eric Liuf433c2d2018-07-18 15:31:14 +0000305 }
Sam McCall4c077f92018-09-18 09:08:28 +0000306 Completion.Kind = toCompletionItemKind(
307 C.SemaResult->Kind, C.SemaResult->Declaration, ContextKind);
Kadir Cetinkaya0ed5d292018-09-27 14:21:07 +0000308 // Sema could provide more info on whether the completion was a file or
309 // folder.
310 if (Completion.Kind == CompletionItemKind::File &&
311 Completion.Name.back() == '/')
312 Completion.Kind = CompletionItemKind::Folder;
Kadir Cetinkaya2f84d912018-08-08 08:59:29 +0000313 for (const auto &FixIt : C.SemaResult->FixIts) {
314 Completion.FixIts.push_back(
315 toTextEdit(FixIt, ASTCtx.getSourceManager(), ASTCtx.getLangOpts()));
316 }
Kirill Bobyrev4a5ff882018-10-07 14:49:41 +0000317 llvm::sort(Completion.FixIts, [](const TextEdit &X, const TextEdit &Y) {
318 return std::tie(X.range.start.line, X.range.start.character) <
319 std::tie(Y.range.start.line, Y.range.start.character);
320 });
Eric Liu6df66002018-09-06 18:52:26 +0000321 Completion.Deprecated |=
322 (C.SemaResult->Availability == CXAvailability_Deprecated);
Sam McCall27c979a2018-06-29 14:47:57 +0000323 }
324 if (C.IndexResult) {
Sam McCall4e5742a2018-07-06 11:50:49 +0000325 Completion.Origin |= C.IndexResult->Origin;
Sam McCall27c979a2018-06-29 14:47:57 +0000326 if (Completion.Scope.empty())
327 Completion.Scope = C.IndexResult->Scope;
328 if (Completion.Kind == CompletionItemKind::Missing)
329 Completion.Kind = toCompletionItemKind(C.IndexResult->SymInfo.Kind);
330 if (Completion.Name.empty())
331 Completion.Name = C.IndexResult->Name;
Eric Liu670c1472018-09-27 18:46:00 +0000332 // If the completion was visible to Sema, no qualifier is needed. This
333 // avoids unneeded qualifiers in cases like with `using ns::X`.
334 if (Completion.RequiredQualifier.empty() && !C.SemaResult) {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000335 llvm::StringRef ShortestQualifier = C.IndexResult->Scope;
336 for (llvm::StringRef Scope : QueryScopes) {
337 llvm::StringRef Qualifier = C.IndexResult->Scope;
Eric Liu670c1472018-09-27 18:46:00 +0000338 if (Qualifier.consume_front(Scope) &&
339 Qualifier.size() < ShortestQualifier.size())
340 ShortestQualifier = Qualifier;
341 }
342 Completion.RequiredQualifier = ShortestQualifier;
343 }
Eric Liu6df66002018-09-06 18:52:26 +0000344 Completion.Deprecated |= (C.IndexResult->Flags & Symbol::Deprecated);
Sam McCall27c979a2018-06-29 14:47:57 +0000345 }
Eric Liu83f63e42018-09-03 10:18:21 +0000346
347 // Turn absolute path into a literal string that can be #included.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000348 auto Inserted = [&](llvm::StringRef Header)
349 -> llvm::Expected<std::pair<std::string, bool>> {
Eric Liu83f63e42018-09-03 10:18:21 +0000350 auto ResolvedDeclaring =
351 toHeaderFile(C.IndexResult->CanonicalDeclaration.FileURI, FileName);
352 if (!ResolvedDeclaring)
353 return ResolvedDeclaring.takeError();
354 auto ResolvedInserted = toHeaderFile(Header, FileName);
355 if (!ResolvedInserted)
356 return ResolvedInserted.takeError();
357 return std::make_pair(
358 Includes.calculateIncludePath(*ResolvedDeclaring, *ResolvedInserted),
359 Includes.shouldInsertInclude(*ResolvedDeclaring, *ResolvedInserted));
360 };
361 bool ShouldInsert = C.headerToInsertIfAllowed().hasValue();
362 // Calculate include paths and edits for all possible headers.
363 for (const auto &Inc : C.RankedIncludeHeaders) {
364 if (auto ToInclude = Inserted(Inc)) {
365 CodeCompletion::IncludeCandidate Include;
366 Include.Header = ToInclude->first;
367 if (ToInclude->second && ShouldInsert)
368 Include.Insertion = Includes.insert(ToInclude->first);
369 Completion.Includes.push_back(std::move(Include));
Sam McCall27c979a2018-06-29 14:47:57 +0000370 } else
Sam McCallbed58852018-07-11 10:35:11 +0000371 log("Failed to generate include insertion edits for adding header "
Sam McCall27c979a2018-06-29 14:47:57 +0000372 "(FileURI='{0}', IncludeHeader='{1}') into {2}",
Eric Liu83f63e42018-09-03 10:18:21 +0000373 C.IndexResult->CanonicalDeclaration.FileURI, Inc, FileName);
Sam McCall27c979a2018-06-29 14:47:57 +0000374 }
Eric Liu83f63e42018-09-03 10:18:21 +0000375 // Prefer includes that do not need edits (i.e. already exist).
376 std::stable_partition(Completion.Includes.begin(),
377 Completion.Includes.end(),
378 [](const CodeCompletion::IncludeCandidate &I) {
379 return !I.Insertion.hasValue();
380 });
Sam McCall27c979a2018-06-29 14:47:57 +0000381 }
382
383 void add(const CompletionCandidate &C, CodeCompletionString *SemaCCS) {
384 assert(bool(C.SemaResult) == bool(SemaCCS));
385 Bundled.emplace_back();
386 BundledEntry &S = Bundled.back();
387 if (C.SemaResult) {
388 getSignature(*SemaCCS, &S.Signature, &S.SnippetSuffix,
389 &Completion.RequiredQualifier);
390 S.ReturnType = getReturnType(*SemaCCS);
391 } else if (C.IndexResult) {
392 S.Signature = C.IndexResult->Signature;
393 S.SnippetSuffix = C.IndexResult->CompletionSnippetSuffix;
Sam McCall2e5700f2018-08-31 13:55:01 +0000394 S.ReturnType = C.IndexResult->ReturnType;
Sam McCall27c979a2018-06-29 14:47:57 +0000395 }
396 if (ExtractDocumentation && Completion.Documentation.empty()) {
Sam McCall2e5700f2018-08-31 13:55:01 +0000397 if (C.IndexResult)
398 Completion.Documentation = C.IndexResult->Documentation;
Sam McCall27c979a2018-06-29 14:47:57 +0000399 else if (C.SemaResult)
400 Completion.Documentation = getDocComment(ASTCtx, *C.SemaResult,
401 /*CommentsFromHeader=*/false);
402 }
403 }
404
405 CodeCompletion build() {
406 Completion.ReturnType = summarizeReturnType();
407 Completion.Signature = summarizeSignature();
408 Completion.SnippetSuffix = summarizeSnippet();
409 Completion.BundleSize = Bundled.size();
410 return std::move(Completion);
411 }
412
413private:
414 struct BundledEntry {
415 std::string SnippetSuffix;
416 std::string Signature;
417 std::string ReturnType;
418 };
419
420 // If all BundledEntrys have the same value for a property, return it.
421 template <std::string BundledEntry::*Member>
422 const std::string *onlyValue() const {
423 auto B = Bundled.begin(), E = Bundled.end();
424 for (auto I = B + 1; I != E; ++I)
425 if (I->*Member != B->*Member)
426 return nullptr;
427 return &(B->*Member);
428 }
429
Kadir Cetinkayaf8b85a32018-08-23 13:14:50 +0000430 template <bool BundledEntry::*Member> const bool *onlyValue() const {
431 auto B = Bundled.begin(), E = Bundled.end();
432 for (auto I = B + 1; I != E; ++I)
433 if (I->*Member != B->*Member)
434 return nullptr;
435 return &(B->*Member);
436 }
437
Sam McCall27c979a2018-06-29 14:47:57 +0000438 std::string summarizeReturnType() const {
439 if (auto *RT = onlyValue<&BundledEntry::ReturnType>())
440 return *RT;
441 return "";
442 }
443
444 std::string summarizeSnippet() const {
Kadir Cetinkaya516fcda2018-08-23 12:19:39 +0000445 auto *Snippet = onlyValue<&BundledEntry::SnippetSuffix>();
446 if (!Snippet)
447 // All bundles are function calls.
Ilya Biryukov4f984702018-09-26 05:45:31 +0000448 // FIXME(ibiryukov): sometimes add template arguments to a snippet, e.g.
449 // we need to complete 'forward<$1>($0)'.
Kadir Cetinkaya516fcda2018-08-23 12:19:39 +0000450 return "($0)";
Ilya Biryukov4f984702018-09-26 05:45:31 +0000451 if (EnableFunctionArgSnippets)
452 return *Snippet;
453
454 // Replace argument snippets with a simplified pattern.
455 if (Snippet->empty())
456 return "";
457 if (Completion.Kind == CompletionItemKind::Function ||
458 Completion.Kind == CompletionItemKind::Method) {
459 // Functions snippets can be of 2 types:
460 // - containing only function arguments, e.g.
461 // foo(${1:int p1}, ${2:int p2});
462 // We transform this pattern to '($0)' or '()'.
463 // - template arguments and function arguments, e.g.
464 // foo<${1:class}>(${2:int p1}).
465 // We transform this pattern to '<$1>()$0' or '<$0>()'.
466
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000467 bool EmptyArgs = llvm::StringRef(*Snippet).endswith("()");
Ilya Biryukov4f984702018-09-26 05:45:31 +0000468 if (Snippet->front() == '<')
469 return EmptyArgs ? "<$1>()$0" : "<$1>($0)";
470 if (Snippet->front() == '(')
471 return EmptyArgs ? "()" : "($0)";
472 return *Snippet; // Not an arg snippet?
473 }
474 if (Completion.Kind == CompletionItemKind::Reference ||
475 Completion.Kind == CompletionItemKind::Class) {
476 if (Snippet->front() != '<')
477 return *Snippet; // Not an arg snippet?
478
479 // Classes and template using aliases can only have template arguments,
480 // e.g. Foo<${1:class}>.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000481 if (llvm::StringRef(*Snippet).endswith("<>"))
Ilya Biryukov4f984702018-09-26 05:45:31 +0000482 return "<>"; // can happen with defaulted template arguments.
483 return "<$0>";
484 }
Kadir Cetinkaya516fcda2018-08-23 12:19:39 +0000485 return *Snippet;
Sam McCall27c979a2018-06-29 14:47:57 +0000486 }
487
488 std::string summarizeSignature() const {
489 if (auto *Signature = onlyValue<&BundledEntry::Signature>())
490 return *Signature;
491 // All bundles are function calls.
492 return "(…)";
493 }
494
495 ASTContext &ASTCtx;
496 CodeCompletion Completion;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000497 llvm::SmallVector<BundledEntry, 1> Bundled;
Sam McCall27c979a2018-06-29 14:47:57 +0000498 bool ExtractDocumentation;
Kadir Cetinkaya516fcda2018-08-23 12:19:39 +0000499 bool EnableFunctionArgSnippets;
Sam McCall27c979a2018-06-29 14:47:57 +0000500};
501
Sam McCall545a20d2018-01-19 14:34:02 +0000502// Determine the symbol ID for a Sema code completion result, if possible.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000503llvm::Optional<SymbolID> getSymbolID(const CodeCompletionResult &R,
504 const SourceManager &SM) {
Sam McCall545a20d2018-01-19 14:34:02 +0000505 switch (R.Kind) {
506 case CodeCompletionResult::RK_Declaration:
507 case CodeCompletionResult::RK_Pattern: {
Haojian Wuc6ddb462018-08-07 08:57:52 +0000508 return clang::clangd::getSymbolID(R.Declaration);
Sam McCall545a20d2018-01-19 14:34:02 +0000509 }
510 case CodeCompletionResult::RK_Macro:
Eric Liud25f1212018-09-06 09:59:37 +0000511 return clang::clangd::getSymbolID(*R.Macro, R.MacroDefInfo, SM);
Sam McCall545a20d2018-01-19 14:34:02 +0000512 case CodeCompletionResult::RK_Keyword:
513 return None;
514 }
515 llvm_unreachable("unknown CodeCompletionResult kind");
516}
517
Haojian Wu061c73e2018-01-23 11:37:26 +0000518// Scopes of the paritial identifier we're trying to complete.
519// It is used when we query the index for more completion results.
Eric Liu6f648df2017-12-19 16:50:37 +0000520struct SpecifiedScope {
Haojian Wu061c73e2018-01-23 11:37:26 +0000521 // The scopes we should look in, determined by Sema.
522 //
523 // If the qualifier was fully resolved, we look for completions in these
524 // scopes; if there is an unresolved part of the qualifier, it should be
525 // resolved within these scopes.
526 //
527 // Examples of qualified completion:
528 //
529 // "::vec" => {""}
530 // "using namespace std; ::vec^" => {"", "std::"}
531 // "namespace ns {using namespace std;} ns::^" => {"ns::", "std::"}
532 // "std::vec^" => {""} // "std" unresolved
533 //
534 // Examples of unqualified completion:
535 //
536 // "vec^" => {""}
537 // "using namespace std; vec^" => {"", "std::"}
538 // "using namespace std; namespace ns { vec^ }" => {"ns::", "std::", ""}
539 //
540 // "" for global namespace, "ns::" for normal namespace.
541 std::vector<std::string> AccessibleScopes;
542 // The full scope qualifier as typed by the user (without the leading "::").
543 // Set if the qualifier is not fully resolved by Sema.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000544 llvm::Optional<std::string> UnresolvedQualifier;
Sam McCall545a20d2018-01-19 14:34:02 +0000545
Eric Liuabbd7132018-11-06 11:17:40 +0000546 // Construct scopes being queried in indexes. The results are deduplicated.
Haojian Wu061c73e2018-01-23 11:37:26 +0000547 // This method format the scopes to match the index request representation.
548 std::vector<std::string> scopesForIndexQuery() {
Eric Liuabbd7132018-11-06 11:17:40 +0000549 std::set<std::string> Results;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000550 for (llvm::StringRef AS : AccessibleScopes)
Eric Liuabbd7132018-11-06 11:17:40 +0000551 Results.insert(
552 ((UnresolvedQualifier ? *UnresolvedQualifier : "") + AS).str());
553 return {Results.begin(), Results.end()};
Sam McCall545a20d2018-01-19 14:34:02 +0000554 }
Eric Liu6f648df2017-12-19 16:50:37 +0000555};
556
Eric Liu670c1472018-09-27 18:46:00 +0000557// Get all scopes that will be queried in indexes and whether symbols from
Eric Liu3fac4ef2018-10-17 11:19:02 +0000558// any scope is allowed. The first scope in the list is the preferred scope
559// (e.g. enclosing namespace).
Eric Liu670c1472018-09-27 18:46:00 +0000560std::pair<std::vector<std::string>, bool>
Eric Liu3fac4ef2018-10-17 11:19:02 +0000561getQueryScopes(CodeCompletionContext &CCContext, const Sema &CCSema,
Eric Liu670c1472018-09-27 18:46:00 +0000562 const CodeCompleteOptions &Opts) {
Kirill Bobyrev5a267ed2018-05-29 11:50:51 +0000563 auto GetAllAccessibleScopes = [](CodeCompletionContext &CCContext) {
Haojian Wu061c73e2018-01-23 11:37:26 +0000564 SpecifiedScope Info;
Kirill Bobyrev5a267ed2018-05-29 11:50:51 +0000565 for (auto *Context : CCContext.getVisitedContexts()) {
Haojian Wu061c73e2018-01-23 11:37:26 +0000566 if (isa<TranslationUnitDecl>(Context))
567 Info.AccessibleScopes.push_back(""); // global namespace
Mikael Holmenfa41add2018-10-18 06:00:39 +0000568 else if (isa<NamespaceDecl>(Context))
Eric Liu3fac4ef2018-10-17 11:19:02 +0000569 Info.AccessibleScopes.push_back(printNamespaceScope(*Context));
Haojian Wu061c73e2018-01-23 11:37:26 +0000570 }
571 return Info;
572 };
573
574 auto SS = CCContext.getCXXScopeSpecifier();
575
576 // Unqualified completion (e.g. "vec^").
577 if (!SS) {
Eric Liu3fac4ef2018-10-17 11:19:02 +0000578 std::vector<std::string> Scopes;
579 std::string EnclosingScope = printNamespaceScope(*CCSema.CurContext);
580 Scopes.push_back(EnclosingScope);
581 for (auto &S : GetAllAccessibleScopes(CCContext).scopesForIndexQuery()) {
582 if (EnclosingScope != S)
583 Scopes.push_back(std::move(S));
584 }
Eric Liu670c1472018-09-27 18:46:00 +0000585 // Allow AllScopes completion only for there is no explicit scope qualifier.
586 return {Scopes, Opts.AllScopes};
Haojian Wu061c73e2018-01-23 11:37:26 +0000587 }
588
589 // Qualified completion ("std::vec^"), we have two cases depending on whether
590 // the qualifier can be resolved by Sema.
591 if ((*SS)->isValid()) { // Resolved qualifier.
Eric Liu670c1472018-09-27 18:46:00 +0000592 return {GetAllAccessibleScopes(CCContext).scopesForIndexQuery(), false};
Haojian Wu061c73e2018-01-23 11:37:26 +0000593 }
594
595 // Unresolved qualifier.
596 // FIXME: When Sema can resolve part of a scope chain (e.g.
597 // "known::unknown::id"), we should expand the known part ("known::") rather
598 // than treating the whole thing as unknown.
599 SpecifiedScope Info;
600 Info.AccessibleScopes.push_back(""); // global namespace
601
602 Info.UnresolvedQualifier =
Eric Liu3fac4ef2018-10-17 11:19:02 +0000603 Lexer::getSourceText(CharSourceRange::getCharRange((*SS)->getRange()),
604 CCSema.SourceMgr, clang::LangOptions())
Kirill Bobyrev5a267ed2018-05-29 11:50:51 +0000605 .ltrim("::");
Haojian Wu061c73e2018-01-23 11:37:26 +0000606 // Sema excludes the trailing "::".
607 if (!Info.UnresolvedQualifier->empty())
608 *Info.UnresolvedQualifier += "::";
609
Eric Liu670c1472018-09-27 18:46:00 +0000610 return {Info.scopesForIndexQuery(), false};
Haojian Wu061c73e2018-01-23 11:37:26 +0000611}
612
Eric Liu42abe412018-05-24 11:20:19 +0000613// Should we perform index-based completion in a context of the specified kind?
614// FIXME: consider allowing completion, but restricting the result types.
615bool contextAllowsIndex(enum CodeCompletionContext::Kind K) {
616 switch (K) {
617 case CodeCompletionContext::CCC_TopLevel:
618 case CodeCompletionContext::CCC_ObjCInterface:
619 case CodeCompletionContext::CCC_ObjCImplementation:
620 case CodeCompletionContext::CCC_ObjCIvarList:
621 case CodeCompletionContext::CCC_ClassStructUnion:
622 case CodeCompletionContext::CCC_Statement:
623 case CodeCompletionContext::CCC_Expression:
624 case CodeCompletionContext::CCC_ObjCMessageReceiver:
625 case CodeCompletionContext::CCC_EnumTag:
626 case CodeCompletionContext::CCC_UnionTag:
627 case CodeCompletionContext::CCC_ClassOrStructTag:
628 case CodeCompletionContext::CCC_ObjCProtocolName:
629 case CodeCompletionContext::CCC_Namespace:
630 case CodeCompletionContext::CCC_Type:
Eric Liu42abe412018-05-24 11:20:19 +0000631 case CodeCompletionContext::CCC_ParenthesizedExpression:
632 case CodeCompletionContext::CCC_ObjCInterfaceName:
633 case CodeCompletionContext::CCC_ObjCCategoryName:
Kadir Cetinkayab9157902018-10-24 15:24:29 +0000634 case CodeCompletionContext::CCC_Symbol:
635 case CodeCompletionContext::CCC_SymbolOrNewName:
Eric Liu42abe412018-05-24 11:20:19 +0000636 return true;
Eric Liu42abe412018-05-24 11:20:19 +0000637 case CodeCompletionContext::CCC_OtherWithMacros:
638 case CodeCompletionContext::CCC_DotMemberAccess:
639 case CodeCompletionContext::CCC_ArrowMemberAccess:
640 case CodeCompletionContext::CCC_ObjCPropertyAccess:
641 case CodeCompletionContext::CCC_MacroName:
642 case CodeCompletionContext::CCC_MacroNameUse:
643 case CodeCompletionContext::CCC_PreprocessorExpression:
644 case CodeCompletionContext::CCC_PreprocessorDirective:
Eric Liu42abe412018-05-24 11:20:19 +0000645 case CodeCompletionContext::CCC_SelectorName:
646 case CodeCompletionContext::CCC_TypeQualifiers:
647 case CodeCompletionContext::CCC_ObjCInstanceMessage:
648 case CodeCompletionContext::CCC_ObjCClassMessage:
Sam McCall4c077f92018-09-18 09:08:28 +0000649 case CodeCompletionContext::CCC_IncludedFile:
Kadir Cetinkayab9157902018-10-24 15:24:29 +0000650 // FIXME: Provide identifier based completions for the following contexts:
651 case CodeCompletionContext::CCC_Other: // Be conservative.
652 case CodeCompletionContext::CCC_NaturalLanguage:
Eric Liu42abe412018-05-24 11:20:19 +0000653 case CodeCompletionContext::CCC_Recovery:
Kadir Cetinkayab9157902018-10-24 15:24:29 +0000654 case CodeCompletionContext::CCC_NewName:
Eric Liu42abe412018-05-24 11:20:19 +0000655 return false;
656 }
657 llvm_unreachable("unknown code completion context");
658}
659
Eric Liub1317fa2018-11-30 11:12:40 +0000660static bool isInjectedClass(const NamedDecl &D) {
661 if (auto *R = dyn_cast_or_null<RecordDecl>(&D))
662 if (R->isInjectedClassName())
663 return true;
664 return false;
665}
666
Sam McCall4caa8512018-06-07 12:49:17 +0000667// Some member calls are blacklisted because they're so rarely useful.
668static bool isBlacklistedMember(const NamedDecl &D) {
669 // Destructor completion is rarely useful, and works inconsistently.
670 // (s.^ completes ~string, but s.~st^ is an error).
671 if (D.getKind() == Decl::CXXDestructor)
672 return true;
673 // Injected name may be useful for A::foo(), but who writes A::A::foo()?
Eric Liub1317fa2018-11-30 11:12:40 +0000674 if (isInjectedClass(D))
675 return true;
Sam McCall4caa8512018-06-07 12:49:17 +0000676 // Explicit calls to operators are also rare.
677 auto NameKind = D.getDeclName().getNameKind();
678 if (NameKind == DeclarationName::CXXOperatorName ||
679 NameKind == DeclarationName::CXXLiteralOperatorName ||
680 NameKind == DeclarationName::CXXConversionFunctionName)
681 return true;
682 return false;
683}
684
Sam McCall545a20d2018-01-19 14:34:02 +0000685// The CompletionRecorder captures Sema code-complete output, including context.
686// It filters out ignored results (but doesn't apply fuzzy-filtering yet).
687// It doesn't do scoring or conversion to CompletionItem yet, as we want to
688// merge with index results first.
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000689// Generally the fields and methods of this object should only be used from
690// within the callback.
Sam McCall545a20d2018-01-19 14:34:02 +0000691struct CompletionRecorder : public CodeCompleteConsumer {
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000692 CompletionRecorder(const CodeCompleteOptions &Opts,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000693 llvm::unique_function<void()> ResultsCallback)
Sam McCall545a20d2018-01-19 14:34:02 +0000694 : CodeCompleteConsumer(Opts.getClangCompleteOpts(),
Sam McCall98775c52017-12-04 13:49:59 +0000695 /*OutputIsBinary=*/false),
Sam McCall545a20d2018-01-19 14:34:02 +0000696 CCContext(CodeCompletionContext::CCC_Other), Opts(Opts),
697 CCAllocator(std::make_shared<GlobalCodeCompletionAllocator>()),
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000698 CCTUInfo(CCAllocator), ResultsCallback(std::move(ResultsCallback)) {
699 assert(this->ResultsCallback);
700 }
701
Sam McCall545a20d2018-01-19 14:34:02 +0000702 std::vector<CodeCompletionResult> Results;
703 CodeCompletionContext CCContext;
704 Sema *CCSema = nullptr; // Sema that created the results.
705 // FIXME: Sema is scary. Can we store ASTContext and Preprocessor, instead?
Sam McCall98775c52017-12-04 13:49:59 +0000706
Sam McCall545a20d2018-01-19 14:34:02 +0000707 void ProcessCodeCompleteResults(class Sema &S, CodeCompletionContext Context,
708 CodeCompletionResult *InResults,
Sam McCall98775c52017-12-04 13:49:59 +0000709 unsigned NumResults) override final {
Eric Liu485074f2018-07-11 13:15:31 +0000710 // Results from recovery mode are generally useless, and the callback after
711 // recovery (if any) is usually more interesting. To make sure we handle the
712 // future callback from sema, we just ignore all callbacks in recovery mode,
713 // as taking only results from recovery mode results in poor completion
714 // results.
715 // FIXME: in case there is no future sema completion callback after the
716 // recovery mode, we might still want to provide some results (e.g. trivial
717 // identifier-based completion).
718 if (Context.getKind() == CodeCompletionContext::CCC_Recovery) {
719 log("Code complete: Ignoring sema code complete callback with Recovery "
720 "context.");
721 return;
722 }
Eric Liu42abe412018-05-24 11:20:19 +0000723 // If a callback is called without any sema result and the context does not
724 // support index-based completion, we simply skip it to give way to
725 // potential future callbacks with results.
726 if (NumResults == 0 && !contextAllowsIndex(Context.getKind()))
727 return;
Ilya Biryukov94da7bd2018-03-16 15:23:44 +0000728 if (CCSema) {
Sam McCallbed58852018-07-11 10:35:11 +0000729 log("Multiple code complete callbacks (parser backtracked?). "
Ilya Biryukov94da7bd2018-03-16 15:23:44 +0000730 "Dropping results from context {0}, keeping results from {1}.",
Eric Liu42abe412018-05-24 11:20:19 +0000731 getCompletionKindString(Context.getKind()),
Sam McCallbed58852018-07-11 10:35:11 +0000732 getCompletionKindString(this->CCContext.getKind()));
Ilya Biryukov94da7bd2018-03-16 15:23:44 +0000733 return;
734 }
Sam McCall545a20d2018-01-19 14:34:02 +0000735 // Record the completion context.
Sam McCall545a20d2018-01-19 14:34:02 +0000736 CCSema = &S;
737 CCContext = Context;
Eric Liu6f648df2017-12-19 16:50:37 +0000738
Sam McCall545a20d2018-01-19 14:34:02 +0000739 // Retain the results we might want.
Sam McCall98775c52017-12-04 13:49:59 +0000740 for (unsigned I = 0; I < NumResults; ++I) {
Sam McCall545a20d2018-01-19 14:34:02 +0000741 auto &Result = InResults[I];
Sam McCalle8437cb2018-10-24 13:51:44 +0000742 // Class members that are shadowed by subclasses are usually noise.
743 if (Result.Hidden && Result.Declaration &&
744 Result.Declaration->isCXXClassMember())
Ilya Biryukovf60bf342018-01-10 13:51:09 +0000745 continue;
Sam McCall545a20d2018-01-19 14:34:02 +0000746 if (!Opts.IncludeIneligibleResults &&
Sam McCall98775c52017-12-04 13:49:59 +0000747 (Result.Availability == CXAvailability_NotAvailable ||
748 Result.Availability == CXAvailability_NotAccessible))
749 continue;
Sam McCall4caa8512018-06-07 12:49:17 +0000750 if (Result.Declaration &&
751 !Context.getBaseType().isNull() // is this a member-access context?
752 && isBlacklistedMember(*Result.Declaration))
Sam McCalld2a95922018-01-22 21:05:00 +0000753 continue;
Eric Liub1317fa2018-11-30 11:12:40 +0000754 // Skip injected class name when no class scope is not explicitly set.
755 // E.g. show injected A::A in `using A::A^` but not in "A^".
756 if (Result.Declaration && !Context.getCXXScopeSpecifier().hasValue() &&
757 isInjectedClass(*Result.Declaration))
758 continue;
Ilya Biryukov53d6d932018-03-06 16:45:21 +0000759 // We choose to never append '::' to completion results in clangd.
760 Result.StartsNestedNameSpecifier = false;
Sam McCall545a20d2018-01-19 14:34:02 +0000761 Results.push_back(Result);
Sam McCall98775c52017-12-04 13:49:59 +0000762 }
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000763 ResultsCallback();
Sam McCall98775c52017-12-04 13:49:59 +0000764 }
765
Sam McCall545a20d2018-01-19 14:34:02 +0000766 CodeCompletionAllocator &getAllocator() override { return *CCAllocator; }
Sam McCall98775c52017-12-04 13:49:59 +0000767 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
768
Sam McCall545a20d2018-01-19 14:34:02 +0000769 // Returns the filtering/sorting name for Result, which must be from Results.
770 // Returned string is owned by this recorder (or the AST).
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000771 llvm::StringRef getName(const CodeCompletionResult &Result) {
Sam McCall98775c52017-12-04 13:49:59 +0000772 switch (Result.Kind) {
773 case CodeCompletionResult::RK_Declaration:
774 if (auto *ID = Result.Declaration->getIdentifier())
Sam McCall545a20d2018-01-19 14:34:02 +0000775 return ID->getName();
Sam McCall98775c52017-12-04 13:49:59 +0000776 break;
777 case CodeCompletionResult::RK_Keyword:
Sam McCall545a20d2018-01-19 14:34:02 +0000778 return Result.Keyword;
Sam McCall98775c52017-12-04 13:49:59 +0000779 case CodeCompletionResult::RK_Macro:
Sam McCall545a20d2018-01-19 14:34:02 +0000780 return Result.Macro->getName();
Sam McCall98775c52017-12-04 13:49:59 +0000781 case CodeCompletionResult::RK_Pattern:
Sam McCall545a20d2018-01-19 14:34:02 +0000782 return Result.Pattern->getTypedText();
Sam McCall98775c52017-12-04 13:49:59 +0000783 }
Ilya Biryukov43714502018-05-16 12:32:44 +0000784 auto *CCS = codeCompletionString(Result);
Sam McCall545a20d2018-01-19 14:34:02 +0000785 return CCS->getTypedText();
Sam McCall98775c52017-12-04 13:49:59 +0000786 }
787
Sam McCall545a20d2018-01-19 14:34:02 +0000788 // Build a CodeCompletion string for R, which must be from Results.
789 // The CCS will be owned by this recorder.
Ilya Biryukov43714502018-05-16 12:32:44 +0000790 CodeCompletionString *codeCompletionString(const CodeCompletionResult &R) {
Sam McCall545a20d2018-01-19 14:34:02 +0000791 // CodeCompletionResult doesn't seem to be const-correct. We own it, anyway.
792 return const_cast<CodeCompletionResult &>(R).CreateCodeCompletionString(
Ilya Biryukov43714502018-05-16 12:32:44 +0000793 *CCSema, CCContext, *CCAllocator, CCTUInfo,
794 /*IncludeBriefComments=*/false);
Sam McCall98775c52017-12-04 13:49:59 +0000795 }
796
Sam McCall545a20d2018-01-19 14:34:02 +0000797private:
798 CodeCompleteOptions Opts;
799 std::shared_ptr<GlobalCodeCompletionAllocator> CCAllocator;
Sam McCall98775c52017-12-04 13:49:59 +0000800 CodeCompletionTUInfo CCTUInfo;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000801 llvm::unique_function<void()> ResultsCallback;
Sam McCall545a20d2018-01-19 14:34:02 +0000802};
803
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +0000804struct ScoredSignature {
805 // When set, requires documentation to be requested from the index with this
806 // ID.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000807 llvm::Optional<SymbolID> IDForDoc;
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +0000808 SignatureInformation Signature;
809 SignatureQualitySignals Quality;
810};
Kadir Cetinkayae486e372018-08-13 08:40:05 +0000811
Sam McCall98775c52017-12-04 13:49:59 +0000812class SignatureHelpCollector final : public CodeCompleteConsumer {
Sam McCall98775c52017-12-04 13:49:59 +0000813public:
814 SignatureHelpCollector(const clang::CodeCompleteOptions &CodeCompleteOpts,
Sam McCall046557b2018-09-03 16:37:59 +0000815 const SymbolIndex *Index, SignatureHelp &SigHelp)
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +0000816 : CodeCompleteConsumer(CodeCompleteOpts,
817 /*OutputIsBinary=*/false),
Sam McCall98775c52017-12-04 13:49:59 +0000818 SigHelp(SigHelp),
819 Allocator(std::make_shared<clang::GlobalCodeCompletionAllocator>()),
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +0000820 CCTUInfo(Allocator), Index(Index) {}
Sam McCall98775c52017-12-04 13:49:59 +0000821
822 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
823 OverloadCandidate *Candidates,
Ilya Biryukov43c292c2018-08-30 13:14:31 +0000824 unsigned NumCandidates,
825 SourceLocation OpenParLoc) override {
826 assert(!OpenParLoc.isInvalid());
827 SourceManager &SrcMgr = S.getSourceManager();
828 OpenParLoc = SrcMgr.getFileLoc(OpenParLoc);
829 if (SrcMgr.isInMainFile(OpenParLoc))
830 SigHelp.argListStart = sourceLocToPosition(SrcMgr, OpenParLoc);
831 else
832 elog("Location oustide main file in signature help: {0}",
833 OpenParLoc.printToString(SrcMgr));
834
Kadir Cetinkayae486e372018-08-13 08:40:05 +0000835 std::vector<ScoredSignature> ScoredSignatures;
Sam McCall98775c52017-12-04 13:49:59 +0000836 SigHelp.signatures.reserve(NumCandidates);
Kadir Cetinkayae486e372018-08-13 08:40:05 +0000837 ScoredSignatures.reserve(NumCandidates);
Sam McCall98775c52017-12-04 13:49:59 +0000838 // FIXME(rwols): How can we determine the "active overload candidate"?
839 // Right now the overloaded candidates seem to be provided in a "best fit"
840 // order, so I'm not too worried about this.
841 SigHelp.activeSignature = 0;
842 assert(CurrentArg <= (unsigned)std::numeric_limits<int>::max() &&
843 "too many arguments");
844 SigHelp.activeParameter = static_cast<int>(CurrentArg);
845 for (unsigned I = 0; I < NumCandidates; ++I) {
Ilya Biryukov8fd44bb2018-08-14 09:36:32 +0000846 OverloadCandidate Candidate = Candidates[I];
847 // We want to avoid showing instantiated signatures, because they may be
848 // long in some cases (e.g. when 'T' is substituted with 'std::string', we
849 // would get 'std::basic_string<char>').
850 if (auto *Func = Candidate.getFunction()) {
851 if (auto *Pattern = Func->getTemplateInstantiationPattern())
852 Candidate = OverloadCandidate(Pattern);
853 }
854
Sam McCall98775c52017-12-04 13:49:59 +0000855 const auto *CCS = Candidate.CreateSignatureString(
856 CurrentArg, S, *Allocator, CCTUInfo, true);
857 assert(CCS && "Expected the CodeCompletionString to be non-null");
Kadir Cetinkayae486e372018-08-13 08:40:05 +0000858 ScoredSignatures.push_back(processOverloadCandidate(
Ilya Biryukov43714502018-05-16 12:32:44 +0000859 Candidate, *CCS,
Ilya Biryukov5f4a3512018-08-17 09:29:38 +0000860 Candidate.getFunction()
861 ? getDeclComment(S.getASTContext(), *Candidate.getFunction())
862 : ""));
Sam McCall98775c52017-12-04 13:49:59 +0000863 }
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +0000864
865 // Sema does not load the docs from the preamble, so we need to fetch extra
866 // docs from the index instead.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000867 llvm::DenseMap<SymbolID, std::string> FetchedDocs;
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +0000868 if (Index) {
869 LookupRequest IndexRequest;
870 for (const auto &S : ScoredSignatures) {
871 if (!S.IDForDoc)
872 continue;
873 IndexRequest.IDs.insert(*S.IDForDoc);
874 }
875 Index->lookup(IndexRequest, [&](const Symbol &S) {
Sam McCall2e5700f2018-08-31 13:55:01 +0000876 if (!S.Documentation.empty())
877 FetchedDocs[S.ID] = S.Documentation;
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +0000878 });
879 log("SigHelp: requested docs for {0} symbols from the index, got {1} "
880 "symbols with non-empty docs in the response",
881 IndexRequest.IDs.size(), FetchedDocs.size());
882 }
883
Ilya Biryukov22fa4652019-01-03 13:28:05 +0000884 llvm::sort(ScoredSignatures, [](const ScoredSignature &L,
885 const ScoredSignature &R) {
886 // Ordering follows:
887 // - Less number of parameters is better.
888 // - Function is better than FunctionType which is better than
889 // Function Template.
890 // - High score is better.
891 // - Shorter signature is better.
892 // - Alphebatically smaller is better.
893 if (L.Quality.NumberOfParameters != R.Quality.NumberOfParameters)
894 return L.Quality.NumberOfParameters < R.Quality.NumberOfParameters;
895 if (L.Quality.NumberOfOptionalParameters !=
896 R.Quality.NumberOfOptionalParameters)
897 return L.Quality.NumberOfOptionalParameters <
898 R.Quality.NumberOfOptionalParameters;
899 if (L.Quality.Kind != R.Quality.Kind) {
900 using OC = CodeCompleteConsumer::OverloadCandidate;
901 switch (L.Quality.Kind) {
902 case OC::CK_Function:
903 return true;
904 case OC::CK_FunctionType:
905 return R.Quality.Kind != OC::CK_Function;
906 case OC::CK_FunctionTemplate:
907 return false;
908 }
909 llvm_unreachable("Unknown overload candidate type.");
910 }
911 if (L.Signature.label.size() != R.Signature.label.size())
912 return L.Signature.label.size() < R.Signature.label.size();
913 return L.Signature.label < R.Signature.label;
914 });
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +0000915
916 for (auto &SS : ScoredSignatures) {
917 auto IndexDocIt =
918 SS.IDForDoc ? FetchedDocs.find(*SS.IDForDoc) : FetchedDocs.end();
919 if (IndexDocIt != FetchedDocs.end())
920 SS.Signature.documentation = IndexDocIt->second;
921
922 SigHelp.signatures.push_back(std::move(SS.Signature));
923 }
Sam McCall98775c52017-12-04 13:49:59 +0000924 }
925
926 GlobalCodeCompletionAllocator &getAllocator() override { return *Allocator; }
927
928 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
929
930private:
Eric Liu63696e12017-12-20 17:24:31 +0000931 // FIXME(ioeric): consider moving CodeCompletionString logic here to
932 // CompletionString.h.
Kadir Cetinkayae486e372018-08-13 08:40:05 +0000933 ScoredSignature processOverloadCandidate(const OverloadCandidate &Candidate,
934 const CodeCompletionString &CCS,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000935 llvm::StringRef DocComment) const {
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +0000936 SignatureInformation Signature;
Kadir Cetinkayae486e372018-08-13 08:40:05 +0000937 SignatureQualitySignals Signal;
Sam McCall98775c52017-12-04 13:49:59 +0000938 const char *ReturnType = nullptr;
939
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +0000940 Signature.documentation = formatDocumentation(CCS, DocComment);
Kadir Cetinkayae486e372018-08-13 08:40:05 +0000941 Signal.Kind = Candidate.getKind();
Sam McCall98775c52017-12-04 13:49:59 +0000942
943 for (const auto &Chunk : CCS) {
944 switch (Chunk.Kind) {
945 case CodeCompletionString::CK_ResultType:
946 // A piece of text that describes the type of an entity or,
947 // for functions and methods, the return type.
948 assert(!ReturnType && "Unexpected CK_ResultType");
949 ReturnType = Chunk.Text;
950 break;
951 case CodeCompletionString::CK_Placeholder:
952 // A string that acts as a placeholder for, e.g., a function call
953 // argument.
954 // Intentional fallthrough here.
955 case CodeCompletionString::CK_CurrentParameter: {
956 // A piece of text that describes the parameter that corresponds to
957 // the code-completion location within a function call, message send,
958 // macro invocation, etc.
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +0000959 Signature.label += Chunk.Text;
Sam McCall98775c52017-12-04 13:49:59 +0000960 ParameterInformation Info;
961 Info.label = Chunk.Text;
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +0000962 Signature.parameters.push_back(std::move(Info));
Kadir Cetinkayae486e372018-08-13 08:40:05 +0000963 Signal.NumberOfParameters++;
964 Signal.ContainsActiveParameter = true;
Sam McCall98775c52017-12-04 13:49:59 +0000965 break;
966 }
967 case CodeCompletionString::CK_Optional: {
968 // The rest of the parameters are defaulted/optional.
969 assert(Chunk.Optional &&
970 "Expected the optional code completion string to be non-null.");
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +0000971 Signature.label += getOptionalParameters(*Chunk.Optional,
972 Signature.parameters, Signal);
Sam McCall98775c52017-12-04 13:49:59 +0000973 break;
974 }
975 case CodeCompletionString::CK_VerticalSpace:
976 break;
977 default:
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +0000978 Signature.label += Chunk.Text;
Sam McCall98775c52017-12-04 13:49:59 +0000979 break;
980 }
981 }
982 if (ReturnType) {
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +0000983 Signature.label += " -> ";
984 Signature.label += ReturnType;
Sam McCall98775c52017-12-04 13:49:59 +0000985 }
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +0000986 dlog("Signal for {0}: {1}", Signature, Signal);
987 ScoredSignature Result;
988 Result.Signature = std::move(Signature);
989 Result.Quality = Signal;
990 Result.IDForDoc =
991 Result.Signature.documentation.empty() && Candidate.getFunction()
992 ? clangd::getSymbolID(Candidate.getFunction())
Sam McCallc008af62018-10-20 15:30:37 +0000993 : None;
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +0000994 return Result;
Sam McCall98775c52017-12-04 13:49:59 +0000995 }
996
997 SignatureHelp &SigHelp;
998 std::shared_ptr<clang::GlobalCodeCompletionAllocator> Allocator;
999 CodeCompletionTUInfo CCTUInfo;
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +00001000 const SymbolIndex *Index;
Sam McCall98775c52017-12-04 13:49:59 +00001001}; // SignatureHelpCollector
1002
Sam McCall545a20d2018-01-19 14:34:02 +00001003struct SemaCompleteInput {
1004 PathRef FileName;
1005 const tooling::CompileCommand &Command;
Eric Liub1d75422018-10-02 10:43:55 +00001006 const PreambleData *Preamble;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001007 llvm::StringRef Contents;
Sam McCall545a20d2018-01-19 14:34:02 +00001008 Position Pos;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001009 llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS;
Sam McCall545a20d2018-01-19 14:34:02 +00001010 std::shared_ptr<PCHContainerOperations> PCHs;
1011};
1012
1013// Invokes Sema code completion on a file.
Sam McCall3f0243f2018-07-03 08:09:29 +00001014// If \p Includes is set, it will be updated based on the compiler invocation.
Sam McCalld1a7a372018-01-31 13:40:48 +00001015bool semaCodeComplete(std::unique_ptr<CodeCompleteConsumer> Consumer,
Sam McCall545a20d2018-01-19 14:34:02 +00001016 const clang::CodeCompleteOptions &Options,
Eric Liu63f419a2018-05-15 15:29:32 +00001017 const SemaCompleteInput &Input,
Sam McCall3f0243f2018-07-03 08:09:29 +00001018 IncludeStructure *Includes = nullptr) {
Ilya Biryukovddf6a332018-03-02 12:28:27 +00001019 trace::Span Tracer("Sema completion");
Sam McCall98775c52017-12-04 13:49:59 +00001020 std::vector<const char *> ArgStrs;
Sam McCall545a20d2018-01-19 14:34:02 +00001021 for (const auto &S : Input.Command.CommandLine)
Sam McCall98775c52017-12-04 13:49:59 +00001022 ArgStrs.push_back(S.c_str());
1023
Ilya Biryukova9cf3112018-02-13 17:15:06 +00001024 if (Input.VFS->setCurrentWorkingDirectory(Input.Command.Directory)) {
1025 log("Couldn't set working directory");
1026 // We run parsing anyway, our lit-tests rely on results for non-existing
1027 // working dirs.
1028 }
Sam McCall98775c52017-12-04 13:49:59 +00001029
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001030 llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS = Input.VFS;
Eric Liub1d75422018-10-02 10:43:55 +00001031 if (Input.Preamble && Input.Preamble->StatCache)
1032 VFS = Input.Preamble->StatCache->getConsumingFS(std::move(VFS));
Sam McCall98775c52017-12-04 13:49:59 +00001033 IgnoreDiagnostics DummyDiagsConsumer;
1034 auto CI = createInvocationFromCommandLine(
1035 ArgStrs,
1036 CompilerInstance::createDiagnostics(new DiagnosticOptions,
1037 &DummyDiagsConsumer, false),
Eric Liub1d75422018-10-02 10:43:55 +00001038 VFS);
Ilya Biryukovb6ad25c2018-02-09 13:51:57 +00001039 if (!CI) {
Sam McCallbed58852018-07-11 10:35:11 +00001040 elog("Couldn't create CompilerInvocation");
Ilya Biryukovb6ad25c2018-02-09 13:51:57 +00001041 return false;
1042 }
Ilya Biryukov981a35d2018-05-28 12:11:37 +00001043 auto &FrontendOpts = CI->getFrontendOpts();
1044 FrontendOpts.DisableFree = false;
Sam McCall98775c52017-12-04 13:49:59 +00001045 FrontendOpts.SkipFunctionBodies = true;
Ilya Biryukov981a35d2018-05-28 12:11:37 +00001046 CI->getLangOpts()->CommentOpts.ParseAllComments = true;
1047 // Disable typo correction in Sema.
1048 CI->getLangOpts()->SpellChecking = false;
1049 // Setup code completion.
Sam McCall98775c52017-12-04 13:49:59 +00001050 FrontendOpts.CodeCompleteOpts = Options;
Sam McCall545a20d2018-01-19 14:34:02 +00001051 FrontendOpts.CodeCompletionAt.FileName = Input.FileName;
Sam McCalla4962cc2018-04-27 11:59:28 +00001052 auto Offset = positionToOffset(Input.Contents, Input.Pos);
1053 if (!Offset) {
Sam McCallbed58852018-07-11 10:35:11 +00001054 elog("Code completion position was invalid {0}", Offset.takeError());
Sam McCalla4962cc2018-04-27 11:59:28 +00001055 return false;
1056 }
1057 std::tie(FrontendOpts.CodeCompletionAt.Line,
1058 FrontendOpts.CodeCompletionAt.Column) =
1059 offsetToClangLineColumn(Input.Contents, *Offset);
Sam McCall98775c52017-12-04 13:49:59 +00001060
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001061 std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer =
1062 llvm::MemoryBuffer::getMemBufferCopy(Input.Contents, Input.FileName);
Ilya Biryukov981a35d2018-05-28 12:11:37 +00001063 // The diagnostic options must be set before creating a CompilerInstance.
1064 CI->getDiagnosticOpts().IgnoreWarnings = true;
1065 // We reuse the preamble whether it's valid or not. This is a
1066 // correctness/performance tradeoff: building without a preamble is slow, and
1067 // completion is latency-sensitive.
Sam McCallebef8122018-09-14 12:36:06 +00001068 // However, if we're completing *inside* the preamble section of the draft,
1069 // overriding the preamble will break sema completion. Fortunately we can just
1070 // skip all includes in this case; these completions are really simple.
1071 bool CompletingInPreamble =
1072 ComputePreambleBounds(*CI->getLangOpts(), ContentsBuffer.get(), 0).Size >
1073 *Offset;
Ilya Biryukov981a35d2018-05-28 12:11:37 +00001074 // NOTE: we must call BeginSourceFile after prepareCompilerInstance. Otherwise
1075 // the remapped buffers do not get freed.
1076 auto Clang = prepareCompilerInstance(
Eric Liub1d75422018-10-02 10:43:55 +00001077 std::move(CI),
1078 (Input.Preamble && !CompletingInPreamble) ? &Input.Preamble->Preamble
1079 : nullptr,
1080 std::move(ContentsBuffer), std::move(Input.PCHs), std::move(VFS),
Sam McCallebef8122018-09-14 12:36:06 +00001081 DummyDiagsConsumer);
1082 Clang->getPreprocessorOpts().SingleFileParseMode = CompletingInPreamble;
Sam McCall98775c52017-12-04 13:49:59 +00001083 Clang->setCodeCompletionConsumer(Consumer.release());
1084
1085 SyntaxOnlyAction Action;
1086 if (!Action.BeginSourceFile(*Clang, Clang->getFrontendOpts().Inputs[0])) {
Sam McCallbed58852018-07-11 10:35:11 +00001087 log("BeginSourceFile() failed when running codeComplete for {0}",
Sam McCalld1a7a372018-01-31 13:40:48 +00001088 Input.FileName);
Sam McCall98775c52017-12-04 13:49:59 +00001089 return false;
1090 }
Sam McCall3f0243f2018-07-03 08:09:29 +00001091 if (Includes)
1092 Clang->getPreprocessor().addPPCallbacks(
1093 collectIncludeStructureCallback(Clang->getSourceManager(), Includes));
Sam McCall98775c52017-12-04 13:49:59 +00001094 if (!Action.Execute()) {
Sam McCallbed58852018-07-11 10:35:11 +00001095 log("Execute() failed when running codeComplete for {0}", Input.FileName);
Sam McCall98775c52017-12-04 13:49:59 +00001096 return false;
1097 }
Sam McCall98775c52017-12-04 13:49:59 +00001098 Action.EndSourceFile();
1099
1100 return true;
1101}
1102
Ilya Biryukova907ba42018-05-14 10:50:04 +00001103// Should we allow index completions in the specified context?
1104bool allowIndex(CodeCompletionContext &CC) {
1105 if (!contextAllowsIndex(CC.getKind()))
1106 return false;
1107 // We also avoid ClassName::bar (but allow namespace::bar).
1108 auto Scope = CC.getCXXScopeSpecifier();
1109 if (!Scope)
1110 return true;
1111 NestedNameSpecifier *NameSpec = (*Scope)->getScopeRep();
1112 if (!NameSpec)
1113 return true;
1114 // We only query the index when qualifier is a namespace.
1115 // If it's a class, we rely solely on sema completions.
1116 switch (NameSpec->getKind()) {
1117 case NestedNameSpecifier::Global:
1118 case NestedNameSpecifier::Namespace:
1119 case NestedNameSpecifier::NamespaceAlias:
1120 return true;
1121 case NestedNameSpecifier::Super:
1122 case NestedNameSpecifier::TypeSpec:
1123 case NestedNameSpecifier::TypeSpecWithTemplate:
1124 // Unresolved inside a template.
1125 case NestedNameSpecifier::Identifier:
1126 return false;
1127 }
Ilya Biryukova6556e22018-05-14 11:47:30 +00001128 llvm_unreachable("invalid NestedNameSpecifier kind");
Ilya Biryukova907ba42018-05-14 10:50:04 +00001129}
1130
Eric Liu25d74e92018-08-24 11:23:56 +00001131std::future<SymbolSlab> startAsyncFuzzyFind(const SymbolIndex &Index,
1132 const FuzzyFindRequest &Req) {
1133 return runAsync<SymbolSlab>([&Index, Req]() {
1134 trace::Span Tracer("Async fuzzyFind");
1135 SymbolSlab::Builder Syms;
1136 Index.fuzzyFind(Req, [&Syms](const Symbol &Sym) { Syms.insert(Sym); });
1137 return std::move(Syms).build();
1138 });
1139}
1140
1141// Creates a `FuzzyFindRequest` based on the cached index request from the
1142// last completion, if any, and the speculated completion filter text in the
1143// source code.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001144llvm::Optional<FuzzyFindRequest>
1145speculativeFuzzyFindRequestForCompletion(FuzzyFindRequest CachedReq,
1146 PathRef File, llvm::StringRef Content,
1147 Position Pos) {
Eric Liu25d74e92018-08-24 11:23:56 +00001148 auto Filter = speculateCompletionFilter(Content, Pos);
1149 if (!Filter) {
1150 elog("Failed to speculate filter text for code completion at Pos "
1151 "{0}:{1}: {2}",
1152 Pos.line, Pos.character, Filter.takeError());
Sam McCallc008af62018-10-20 15:30:37 +00001153 return None;
Eric Liu25d74e92018-08-24 11:23:56 +00001154 }
1155 CachedReq.Query = *Filter;
1156 return CachedReq;
1157}
1158
Eric Liu83f63e42018-09-03 10:18:21 +00001159// Returns the most popular include header for \p Sym. If two headers are
1160// equally popular, prefer the shorter one. Returns empty string if \p Sym has
1161// no include header.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001162llvm::SmallVector<llvm::StringRef, 1> getRankedIncludes(const Symbol &Sym) {
Eric Liu83f63e42018-09-03 10:18:21 +00001163 auto Includes = Sym.IncludeHeaders;
1164 // Sort in descending order by reference count and header length.
Kirill Bobyrev4a5ff882018-10-07 14:49:41 +00001165 llvm::sort(Includes, [](const Symbol::IncludeHeaderWithReferences &LHS,
1166 const Symbol::IncludeHeaderWithReferences &RHS) {
1167 if (LHS.References == RHS.References)
1168 return LHS.IncludeHeader.size() < RHS.IncludeHeader.size();
1169 return LHS.References > RHS.References;
1170 });
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001171 llvm::SmallVector<llvm::StringRef, 1> Headers;
Eric Liu83f63e42018-09-03 10:18:21 +00001172 for (const auto &Include : Includes)
1173 Headers.push_back(Include.IncludeHeader);
1174 return Headers;
1175}
1176
Sam McCall545a20d2018-01-19 14:34:02 +00001177// Runs Sema-based (AST) and Index-based completion, returns merged results.
1178//
1179// There are a few tricky considerations:
1180// - the AST provides information needed for the index query (e.g. which
1181// namespaces to search in). So Sema must start first.
1182// - we only want to return the top results (Opts.Limit).
1183// Building CompletionItems for everything else is wasteful, so we want to
1184// preserve the "native" format until we're done with scoring.
1185// - the data underlying Sema completion items is owned by the AST and various
1186// other arenas, which must stay alive for us to build CompletionItems.
1187// - we may get duplicate results from Sema and the Index, we need to merge.
1188//
Ilya Biryukovddf6a332018-03-02 12:28:27 +00001189// So we start Sema completion first, and do all our work in its callback.
Sam McCall545a20d2018-01-19 14:34:02 +00001190// We use the Sema context information to query the index.
1191// Then we merge the two result sets, producing items that are Sema/Index/Both.
1192// These items are scored, and the top N are synthesized into the LSP response.
1193// Finally, we can clean up the data structures created by Sema completion.
1194//
1195// Main collaborators are:
1196// - semaCodeComplete sets up the compiler machinery to run code completion.
1197// - CompletionRecorder captures Sema completion results, including context.
1198// - SymbolIndex (Opts.Index) provides index completion results as Symbols
1199// - CompletionCandidates are the result of merging Sema and Index results.
1200// Each candidate points to an underlying CodeCompletionResult (Sema), a
1201// Symbol (Index), or both. It computes the result quality score.
1202// CompletionCandidate also does conversion to CompletionItem (at the end).
1203// - FuzzyMatcher scores how the candidate matches the partial identifier.
1204// This score is combined with the result quality score for the final score.
1205// - TopN determines the results with the best score.
1206class CodeCompleteFlow {
Eric Liuc5105f92018-02-16 14:15:55 +00001207 PathRef FileName;
Ilya Biryukov22fa4652019-01-03 13:28:05 +00001208 IncludeStructure Includes; // Complete once the compiler runs.
Eric Liu25d74e92018-08-24 11:23:56 +00001209 SpeculativeFuzzyFind *SpecFuzzyFind; // Can be nullptr.
Sam McCall545a20d2018-01-19 14:34:02 +00001210 const CodeCompleteOptions &Opts;
Eric Liu25d74e92018-08-24 11:23:56 +00001211
Sam McCall545a20d2018-01-19 14:34:02 +00001212 // Sema takes ownership of Recorder. Recorder is valid until Sema cleanup.
Ilya Biryukovddf6a332018-03-02 12:28:27 +00001213 CompletionRecorder *Recorder = nullptr;
Sam McCall545a20d2018-01-19 14:34:02 +00001214 int NSema = 0, NIndex = 0, NBoth = 0; // Counters for logging.
Ilya Biryukov22fa4652019-01-03 13:28:05 +00001215 bool Incomplete = false; // Would more be available with a higher limit?
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001216 llvm::Optional<FuzzyMatcher> Filter; // Initialized once Sema runs.
Eric Liu670c1472018-09-27 18:46:00 +00001217 std::vector<std::string> QueryScopes; // Initialized once Sema runs.
Eric Liu3fac4ef2018-10-17 11:19:02 +00001218 // Initialized once QueryScopes is initialized, if there are scopes.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001219 llvm::Optional<ScopeDistance> ScopeProximity;
Ilya Biryukov647da3e2018-11-26 15:38:01 +00001220 llvm::Optional<OpaqueType> PreferredType; // Initialized once Sema runs.
Eric Liu670c1472018-09-27 18:46:00 +00001221 // Whether to query symbols from any scope. Initialized once Sema runs.
1222 bool AllScopes = false;
Sam McCall3f0243f2018-07-03 08:09:29 +00001223 // Include-insertion and proximity scoring rely on the include structure.
1224 // This is available after Sema has run.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001225 llvm::Optional<IncludeInserter> Inserter; // Available during runWithSema.
1226 llvm::Optional<URIDistance> FileProximity; // Initialized once Sema runs.
Eric Liu25d74e92018-08-24 11:23:56 +00001227 /// Speculative request based on the cached request and the filter text before
1228 /// the cursor.
1229 /// Initialized right before sema run. This is only set if `SpecFuzzyFind` is
1230 /// set and contains a cached request.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001231 llvm::Optional<FuzzyFindRequest> SpecReq;
Sam McCall545a20d2018-01-19 14:34:02 +00001232
1233public:
1234 // A CodeCompleteFlow object is only useful for calling run() exactly once.
Sam McCall3f0243f2018-07-03 08:09:29 +00001235 CodeCompleteFlow(PathRef FileName, const IncludeStructure &Includes,
Eric Liu25d74e92018-08-24 11:23:56 +00001236 SpeculativeFuzzyFind *SpecFuzzyFind,
Sam McCall3f0243f2018-07-03 08:09:29 +00001237 const CodeCompleteOptions &Opts)
Eric Liu25d74e92018-08-24 11:23:56 +00001238 : FileName(FileName), Includes(Includes), SpecFuzzyFind(SpecFuzzyFind),
1239 Opts(Opts) {}
Sam McCall545a20d2018-01-19 14:34:02 +00001240
Sam McCall27c979a2018-06-29 14:47:57 +00001241 CodeCompleteResult run(const SemaCompleteInput &SemaCCInput) && {
Sam McCalld1a7a372018-01-31 13:40:48 +00001242 trace::Span Tracer("CodeCompleteFlow");
Eric Liu25d74e92018-08-24 11:23:56 +00001243 if (Opts.Index && SpecFuzzyFind && SpecFuzzyFind->CachedReq.hasValue()) {
1244 assert(!SpecFuzzyFind->Result.valid());
1245 if ((SpecReq = speculativeFuzzyFindRequestForCompletion(
1246 *SpecFuzzyFind->CachedReq, SemaCCInput.FileName,
1247 SemaCCInput.Contents, SemaCCInput.Pos)))
1248 SpecFuzzyFind->Result = startAsyncFuzzyFind(*Opts.Index, *SpecReq);
1249 }
Eric Liu63f419a2018-05-15 15:29:32 +00001250
Sam McCall545a20d2018-01-19 14:34:02 +00001251 // We run Sema code completion first. It builds an AST and calculates:
Ilya Biryukovddf6a332018-03-02 12:28:27 +00001252 // - completion results based on the AST.
Sam McCall545a20d2018-01-19 14:34:02 +00001253 // - partial identifier and context. We need these for the index query.
Sam McCall27c979a2018-06-29 14:47:57 +00001254 CodeCompleteResult Output;
Ilya Biryukovddf6a332018-03-02 12:28:27 +00001255 auto RecorderOwner = llvm::make_unique<CompletionRecorder>(Opts, [&]() {
1256 assert(Recorder && "Recorder is not set");
Sam McCall3f0243f2018-07-03 08:09:29 +00001257 auto Style =
Eric Liu9338a882018-07-03 14:51:23 +00001258 format::getStyle(format::DefaultFormatStyle, SemaCCInput.FileName,
1259 format::DefaultFallbackStyle, SemaCCInput.Contents,
1260 SemaCCInput.VFS.get());
Sam McCall3f0243f2018-07-03 08:09:29 +00001261 if (!Style) {
Sam McCallbed58852018-07-11 10:35:11 +00001262 log("getStyle() failed for file {0}: {1}. Fallback is LLVM style.",
1263 SemaCCInput.FileName, Style.takeError());
Sam McCall3f0243f2018-07-03 08:09:29 +00001264 Style = format::getLLVMStyle();
1265 }
Eric Liu63f419a2018-05-15 15:29:32 +00001266 // If preprocessor was run, inclusions from preprocessor callback should
Sam McCall3f0243f2018-07-03 08:09:29 +00001267 // already be added to Includes.
1268 Inserter.emplace(
1269 SemaCCInput.FileName, SemaCCInput.Contents, *Style,
1270 SemaCCInput.Command.Directory,
1271 Recorder->CCSema->getPreprocessor().getHeaderSearchInfo());
1272 for (const auto &Inc : Includes.MainFileIncludes)
1273 Inserter->addExisting(Inc);
1274
1275 // Most of the cost of file proximity is in initializing the FileDistance
1276 // structures based on the observed includes, once per query. Conceptually
1277 // that happens here (though the per-URI-scheme initialization is lazy).
1278 // The per-result proximity scoring is (amortized) very cheap.
1279 FileDistanceOptions ProxOpts{}; // Use defaults.
1280 const auto &SM = Recorder->CCSema->getSourceManager();
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001281 llvm::StringMap<SourceParams> ProxSources;
Sam McCall3f0243f2018-07-03 08:09:29 +00001282 for (auto &Entry : Includes.includeDepth(
1283 SM.getFileEntryForID(SM.getMainFileID())->getName())) {
1284 auto &Source = ProxSources[Entry.getKey()];
1285 Source.Cost = Entry.getValue() * ProxOpts.IncludeCost;
1286 // Symbols near our transitive includes are good, but only consider
1287 // things in the same directory or below it. Otherwise there can be
1288 // many false positives.
1289 if (Entry.getValue() > 0)
1290 Source.MaxUpTraversals = 1;
1291 }
1292 FileProximity.emplace(ProxSources, ProxOpts);
1293
Ilya Biryukovddf6a332018-03-02 12:28:27 +00001294 Output = runWithSema();
Sam McCall3f0243f2018-07-03 08:09:29 +00001295 Inserter.reset(); // Make sure this doesn't out-live Clang.
Ilya Biryukovddf6a332018-03-02 12:28:27 +00001296 SPAN_ATTACH(Tracer, "sema_completion_kind",
1297 getCompletionKindString(Recorder->CCContext.getKind()));
Ilya Biryukov647da3e2018-11-26 15:38:01 +00001298 log("Code complete: sema context {0}, query scopes [{1}] (AnyScope={2}), "
1299 "expected type {3}",
Eric Liubc25ef72018-07-05 08:29:33 +00001300 getCompletionKindString(Recorder->CCContext.getKind()),
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001301 llvm::join(QueryScopes.begin(), QueryScopes.end(), ","), AllScopes,
Ilya Biryukov647da3e2018-11-26 15:38:01 +00001302 PreferredType ? Recorder->CCContext.getPreferredType().getAsString()
1303 : "<none>");
Ilya Biryukovddf6a332018-03-02 12:28:27 +00001304 });
1305
1306 Recorder = RecorderOwner.get();
Eric Liu25d74e92018-08-24 11:23:56 +00001307
Sam McCalld1a7a372018-01-31 13:40:48 +00001308 semaCodeComplete(std::move(RecorderOwner), Opts.getClangCompleteOpts(),
Eric Liu63f419a2018-05-15 15:29:32 +00001309 SemaCCInput, &Includes);
Sam McCall545a20d2018-01-19 14:34:02 +00001310
Sam McCall2b780162018-01-30 17:20:54 +00001311 SPAN_ATTACH(Tracer, "sema_results", NSema);
1312 SPAN_ATTACH(Tracer, "index_results", NIndex);
1313 SPAN_ATTACH(Tracer, "merged_results", NBoth);
Sam McCalld20d7982018-07-09 14:25:59 +00001314 SPAN_ATTACH(Tracer, "returned_results", int64_t(Output.Completions.size()));
Sam McCall27c979a2018-06-29 14:47:57 +00001315 SPAN_ATTACH(Tracer, "incomplete", Output.HasMore);
Sam McCallbed58852018-07-11 10:35:11 +00001316 log("Code complete: {0} results from Sema, {1} from Index, "
1317 "{2} matched, {3} returned{4}.",
1318 NSema, NIndex, NBoth, Output.Completions.size(),
1319 Output.HasMore ? " (incomplete)" : "");
Sam McCall27c979a2018-06-29 14:47:57 +00001320 assert(!Opts.Limit || Output.Completions.size() <= Opts.Limit);
Sam McCall545a20d2018-01-19 14:34:02 +00001321 // We don't assert that isIncomplete means we hit a limit.
1322 // Indexes may choose to impose their own limits even if we don't have one.
1323 return Output;
1324 }
1325
1326private:
1327 // This is called by run() once Sema code completion is done, but before the
1328 // Sema data structures are torn down. It does all the real work.
Sam McCall27c979a2018-06-29 14:47:57 +00001329 CodeCompleteResult runWithSema() {
Kadir Cetinkayaa9c9d002018-08-13 08:23:01 +00001330 const auto &CodeCompletionRange = CharSourceRange::getCharRange(
1331 Recorder->CCSema->getPreprocessor().getCodeCompletionTokenRange());
1332 Range TextEditRange;
1333 // When we are getting completions with an empty identifier, for example
1334 // std::vector<int> asdf;
1335 // asdf.^;
1336 // Then the range will be invalid and we will be doing insertion, use
1337 // current cursor position in such cases as range.
1338 if (CodeCompletionRange.isValid()) {
1339 TextEditRange = halfOpenToRange(Recorder->CCSema->getSourceManager(),
1340 CodeCompletionRange);
1341 } else {
1342 const auto &Pos = sourceLocToPosition(
1343 Recorder->CCSema->getSourceManager(),
1344 Recorder->CCSema->getPreprocessor().getCodeCompletionLoc());
1345 TextEditRange.start = TextEditRange.end = Pos;
1346 }
Sam McCall545a20d2018-01-19 14:34:02 +00001347 Filter = FuzzyMatcher(
Ilya Biryukovddf6a332018-03-02 12:28:27 +00001348 Recorder->CCSema->getPreprocessor().getCodeCompletionFilter());
Eric Liu3fac4ef2018-10-17 11:19:02 +00001349 std::tie(QueryScopes, AllScopes) =
1350 getQueryScopes(Recorder->CCContext, *Recorder->CCSema, Opts);
1351 if (!QueryScopes.empty())
1352 ScopeProximity.emplace(QueryScopes);
Ilya Biryukov647da3e2018-11-26 15:38:01 +00001353 PreferredType =
1354 OpaqueType::fromType(Recorder->CCSema->getASTContext(),
1355 Recorder->CCContext.getPreferredType());
Sam McCall545a20d2018-01-19 14:34:02 +00001356 // Sema provides the needed context to query the index.
1357 // FIXME: in addition to querying for extra/overlapping symbols, we should
1358 // explicitly request symbols corresponding to Sema results.
1359 // We can use their signals even if the index can't suggest them.
1360 // We must copy index results to preserve them, but there are at most Limit.
Eric Liu8f3678d2018-06-15 13:34:18 +00001361 auto IndexResults = (Opts.Index && allowIndex(Recorder->CCContext))
1362 ? queryIndex()
1363 : SymbolSlab();
Eric Liu25d74e92018-08-24 11:23:56 +00001364 trace::Span Tracer("Populate CodeCompleteResult");
Kadir Cetinkayab15b8dc2018-10-02 09:42:17 +00001365 // Merge Sema and Index results, score them, and pick the winners.
1366 auto Top = mergeResults(Recorder->Results, IndexResults);
Sam McCall27c979a2018-06-29 14:47:57 +00001367 CodeCompleteResult Output;
Kadir Cetinkayaf8b85a32018-08-23 13:14:50 +00001368
1369 // Convert the results to final form, assembling the expensive strings.
Sam McCall27c979a2018-06-29 14:47:57 +00001370 for (auto &C : Top) {
1371 Output.Completions.push_back(toCodeCompletion(C.first));
1372 Output.Completions.back().Score = C.second;
Kadir Cetinkayaa9c9d002018-08-13 08:23:01 +00001373 Output.Completions.back().CompletionTokenRange = TextEditRange;
Sam McCall27c979a2018-06-29 14:47:57 +00001374 }
1375 Output.HasMore = Incomplete;
Eric Liu5d2a8072018-07-23 10:56:37 +00001376 Output.Context = Recorder->CCContext.getKind();
Kadir Cetinkayaf8b85a32018-08-23 13:14:50 +00001377
Sam McCall545a20d2018-01-19 14:34:02 +00001378 return Output;
1379 }
1380
1381 SymbolSlab queryIndex() {
Sam McCalld1a7a372018-01-31 13:40:48 +00001382 trace::Span Tracer("Query index");
Sam McCalld20d7982018-07-09 14:25:59 +00001383 SPAN_ATTACH(Tracer, "limit", int64_t(Opts.Limit));
Sam McCall2b780162018-01-30 17:20:54 +00001384
Sam McCall545a20d2018-01-19 14:34:02 +00001385 // Build the query.
1386 FuzzyFindRequest Req;
Haojian Wu48b48652018-01-25 09:20:09 +00001387 if (Opts.Limit)
Kirill Bobyreve6dd0802018-09-13 14:27:03 +00001388 Req.Limit = Opts.Limit;
Sam McCall545a20d2018-01-19 14:34:02 +00001389 Req.Query = Filter->pattern();
Marc-Andre Laperle945b5a32018-06-05 14:01:40 +00001390 Req.RestrictForCodeCompletion = true;
Eric Liubc25ef72018-07-05 08:29:33 +00001391 Req.Scopes = QueryScopes;
Eric Liu670c1472018-09-27 18:46:00 +00001392 Req.AnyScope = AllScopes;
Sam McCall3f0243f2018-07-03 08:09:29 +00001393 // FIXME: we should send multiple weighted paths here.
Eric Liu6de95ec2018-06-12 08:48:20 +00001394 Req.ProximityPaths.push_back(FileName);
Kirill Bobyrev09f00dc2018-09-10 11:51:05 +00001395 vlog("Code complete: fuzzyFind({0:2})", toJSON(Req));
Eric Liu25d74e92018-08-24 11:23:56 +00001396
1397 if (SpecFuzzyFind)
1398 SpecFuzzyFind->NewReq = Req;
1399 if (SpecFuzzyFind && SpecFuzzyFind->Result.valid() && (*SpecReq == Req)) {
1400 vlog("Code complete: speculative fuzzy request matches the actual index "
1401 "request. Waiting for the speculative index results.");
1402 SPAN_ATTACH(Tracer, "Speculative results", true);
1403
1404 trace::Span WaitSpec("Wait speculative results");
1405 return SpecFuzzyFind->Result.get();
1406 }
1407
1408 SPAN_ATTACH(Tracer, "Speculative results", false);
1409
Sam McCall545a20d2018-01-19 14:34:02 +00001410 // Run the query against the index.
Eric Liu25d74e92018-08-24 11:23:56 +00001411 SymbolSlab::Builder ResultsBuilder;
Sam McCallab8e3932018-02-19 13:04:41 +00001412 if (Opts.Index->fuzzyFind(
1413 Req, [&](const Symbol &Sym) { ResultsBuilder.insert(Sym); }))
1414 Incomplete = true;
Sam McCall545a20d2018-01-19 14:34:02 +00001415 return std::move(ResultsBuilder).build();
1416 }
1417
Kadir Cetinkayab15b8dc2018-10-02 09:42:17 +00001418 // Merges Sema and Index results where possible, to form CompletionCandidates.
1419 // Groups overloads if desired, to form CompletionCandidate::Bundles. The
1420 // bundles are scored and top results are returned, best to worst.
Sam McCallc18c2802018-06-15 11:06:29 +00001421 std::vector<ScoredBundle>
Kadir Cetinkayaf8b85a32018-08-23 13:14:50 +00001422 mergeResults(const std::vector<CodeCompletionResult> &SemaResults,
Kadir Cetinkayab15b8dc2018-10-02 09:42:17 +00001423 const SymbolSlab &IndexResults) {
Sam McCalld1a7a372018-01-31 13:40:48 +00001424 trace::Span Tracer("Merge and score results");
Sam McCallc18c2802018-06-15 11:06:29 +00001425 std::vector<CompletionCandidate::Bundle> Bundles;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001426 llvm::DenseMap<size_t, size_t> BundleLookup;
Sam McCallc18c2802018-06-15 11:06:29 +00001427 auto AddToBundles = [&](const CodeCompletionResult *SemaResult,
Kadir Cetinkayab15b8dc2018-10-02 09:42:17 +00001428 const Symbol *IndexResult) {
Sam McCallc18c2802018-06-15 11:06:29 +00001429 CompletionCandidate C;
1430 C.SemaResult = SemaResult;
1431 C.IndexResult = IndexResult;
Eric Liu83f63e42018-09-03 10:18:21 +00001432 if (C.IndexResult)
1433 C.RankedIncludeHeaders = getRankedIncludes(*C.IndexResult);
Sam McCallc18c2802018-06-15 11:06:29 +00001434 C.Name = IndexResult ? IndexResult->Name : Recorder->getName(*SemaResult);
1435 if (auto OverloadSet = Opts.BundleOverloads ? C.overloadSet() : 0) {
1436 auto Ret = BundleLookup.try_emplace(OverloadSet, Bundles.size());
1437 if (Ret.second)
1438 Bundles.emplace_back();
1439 Bundles[Ret.first->second].push_back(std::move(C));
1440 } else {
1441 Bundles.emplace_back();
1442 Bundles.back().push_back(std::move(C));
1443 }
1444 };
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001445 llvm::DenseSet<const Symbol *> UsedIndexResults;
Sam McCall545a20d2018-01-19 14:34:02 +00001446 auto CorrespondingIndexResult =
1447 [&](const CodeCompletionResult &SemaResult) -> const Symbol * {
Eric Liud25f1212018-09-06 09:59:37 +00001448 if (auto SymID =
1449 getSymbolID(SemaResult, Recorder->CCSema->getSourceManager())) {
Sam McCall545a20d2018-01-19 14:34:02 +00001450 auto I = IndexResults.find(*SymID);
1451 if (I != IndexResults.end()) {
1452 UsedIndexResults.insert(&*I);
1453 return &*I;
1454 }
1455 }
1456 return nullptr;
1457 };
1458 // Emit all Sema results, merging them with Index results if possible.
Ilya Biryukovddf6a332018-03-02 12:28:27 +00001459 for (auto &SemaResult : Recorder->Results)
Kadir Cetinkayab15b8dc2018-10-02 09:42:17 +00001460 AddToBundles(&SemaResult, CorrespondingIndexResult(SemaResult));
Sam McCall545a20d2018-01-19 14:34:02 +00001461 // Now emit any Index-only results.
1462 for (const auto &IndexResult : IndexResults) {
1463 if (UsedIndexResults.count(&IndexResult))
1464 continue;
Kadir Cetinkayab15b8dc2018-10-02 09:42:17 +00001465 AddToBundles(/*SemaResult=*/nullptr, &IndexResult);
Sam McCall545a20d2018-01-19 14:34:02 +00001466 }
Sam McCallc18c2802018-06-15 11:06:29 +00001467 // We only keep the best N results at any time, in "native" format.
1468 TopN<ScoredBundle, ScoredBundleGreater> Top(
1469 Opts.Limit == 0 ? std::numeric_limits<size_t>::max() : Opts.Limit);
1470 for (auto &Bundle : Bundles)
1471 addCandidate(Top, std::move(Bundle));
Sam McCall545a20d2018-01-19 14:34:02 +00001472 return std::move(Top).items();
1473 }
1474
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001475 llvm::Optional<float> fuzzyScore(const CompletionCandidate &C) {
Sam McCall80ad7072018-06-08 13:32:25 +00001476 // Macros can be very spammy, so we only support prefix completion.
1477 // We won't end up with underfull index results, as macros are sema-only.
1478 if (C.SemaResult && C.SemaResult->Kind == CodeCompletionResult::RK_Macro &&
1479 !C.Name.startswith_lower(Filter->pattern()))
1480 return None;
1481 return Filter->match(C.Name);
1482 }
1483
Sam McCall545a20d2018-01-19 14:34:02 +00001484 // Scores a candidate and adds it to the TopN structure.
Sam McCallc18c2802018-06-15 11:06:29 +00001485 void addCandidate(TopN<ScoredBundle, ScoredBundleGreater> &Candidates,
1486 CompletionCandidate::Bundle Bundle) {
Sam McCallc5707b62018-05-15 17:43:27 +00001487 SymbolQualitySignals Quality;
1488 SymbolRelevanceSignals Relevance;
Eric Liu5d2a8072018-07-23 10:56:37 +00001489 Relevance.Context = Recorder->CCContext.getKind();
Sam McCalld9b54f02018-06-05 16:30:25 +00001490 Relevance.Query = SymbolRelevanceSignals::CodeComplete;
Sam McCallf84dd022018-07-05 08:26:53 +00001491 Relevance.FileProximityMatch = FileProximity.getPointer();
Eric Liu3fac4ef2018-10-17 11:19:02 +00001492 if (ScopeProximity)
1493 Relevance.ScopeProximityMatch = ScopeProximity.getPointer();
Ilya Biryukov647da3e2018-11-26 15:38:01 +00001494 if (PreferredType)
1495 Relevance.HadContextType = true;
Eric Liu670c1472018-09-27 18:46:00 +00001496
Sam McCallc18c2802018-06-15 11:06:29 +00001497 auto &First = Bundle.front();
1498 if (auto FuzzyScore = fuzzyScore(First))
Sam McCallc5707b62018-05-15 17:43:27 +00001499 Relevance.NameMatch = *FuzzyScore;
Sam McCall545a20d2018-01-19 14:34:02 +00001500 else
1501 return;
Sam McCall2161ec72018-07-05 06:20:41 +00001502 SymbolOrigin Origin = SymbolOrigin::Unknown;
Sam McCall4e5742a2018-07-06 11:50:49 +00001503 bool FromIndex = false;
Sam McCallc18c2802018-06-15 11:06:29 +00001504 for (const auto &Candidate : Bundle) {
1505 if (Candidate.IndexResult) {
1506 Quality.merge(*Candidate.IndexResult);
1507 Relevance.merge(*Candidate.IndexResult);
Sam McCall4e5742a2018-07-06 11:50:49 +00001508 Origin |= Candidate.IndexResult->Origin;
1509 FromIndex = true;
Ilya Biryukov647da3e2018-11-26 15:38:01 +00001510 if (!Candidate.IndexResult->Type.empty())
1511 Relevance.HadSymbolType |= true;
1512 if (PreferredType &&
1513 PreferredType->raw() == Candidate.IndexResult->Type) {
1514 Relevance.TypeMatchesPreferred = true;
1515 }
Sam McCallc18c2802018-06-15 11:06:29 +00001516 }
1517 if (Candidate.SemaResult) {
1518 Quality.merge(*Candidate.SemaResult);
1519 Relevance.merge(*Candidate.SemaResult);
Ilya Biryukov647da3e2018-11-26 15:38:01 +00001520 if (PreferredType) {
1521 if (auto CompletionType = OpaqueType::fromCompletionResult(
1522 Recorder->CCSema->getASTContext(), *Candidate.SemaResult)) {
1523 Relevance.HadSymbolType |= true;
1524 if (PreferredType == CompletionType)
1525 Relevance.TypeMatchesPreferred = true;
1526 }
1527 }
Sam McCall4e5742a2018-07-06 11:50:49 +00001528 Origin |= SymbolOrigin::AST;
Sam McCallc18c2802018-06-15 11:06:29 +00001529 }
Sam McCallc5707b62018-05-15 17:43:27 +00001530 }
1531
Sam McCall27c979a2018-06-29 14:47:57 +00001532 CodeCompletion::Scores Scores;
1533 Scores.Quality = Quality.evaluate();
1534 Scores.Relevance = Relevance.evaluate();
1535 Scores.Total = evaluateSymbolAndRelevance(Scores.Quality, Scores.Relevance);
1536 // NameMatch is in fact a multiplier on total score, so rescoring is sound.
1537 Scores.ExcludingName = Relevance.NameMatch
1538 ? Scores.Total / Relevance.NameMatch
1539 : Scores.Quality;
Sam McCallc5707b62018-05-15 17:43:27 +00001540
Sam McCallbed58852018-07-11 10:35:11 +00001541 dlog("CodeComplete: {0} ({1}) = {2}\n{3}{4}\n", First.Name,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001542 llvm::to_string(Origin), Scores.Total, llvm::to_string(Quality),
1543 llvm::to_string(Relevance));
Sam McCall545a20d2018-01-19 14:34:02 +00001544
Sam McCall2161ec72018-07-05 06:20:41 +00001545 NSema += bool(Origin & SymbolOrigin::AST);
Sam McCall4e5742a2018-07-06 11:50:49 +00001546 NIndex += FromIndex;
1547 NBoth += bool(Origin & SymbolOrigin::AST) && FromIndex;
Sam McCallc18c2802018-06-15 11:06:29 +00001548 if (Candidates.push({std::move(Bundle), Scores}))
Sam McCallab8e3932018-02-19 13:04:41 +00001549 Incomplete = true;
Sam McCall545a20d2018-01-19 14:34:02 +00001550 }
1551
Sam McCall27c979a2018-06-29 14:47:57 +00001552 CodeCompletion toCodeCompletion(const CompletionCandidate::Bundle &Bundle) {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001553 llvm::Optional<CodeCompletionBuilder> Builder;
Sam McCall27c979a2018-06-29 14:47:57 +00001554 for (const auto &Item : Bundle) {
1555 CodeCompletionString *SemaCCS =
1556 Item.SemaResult ? Recorder->codeCompletionString(*Item.SemaResult)
1557 : nullptr;
1558 if (!Builder)
1559 Builder.emplace(Recorder->CCSema->getASTContext(), Item, SemaCCS,
Eric Liu670c1472018-09-27 18:46:00 +00001560 QueryScopes, *Inserter, FileName,
1561 Recorder->CCContext.getKind(), Opts);
Sam McCall27c979a2018-06-29 14:47:57 +00001562 else
1563 Builder->add(Item, SemaCCS);
Ilya Biryukov43714502018-05-16 12:32:44 +00001564 }
Sam McCall27c979a2018-06-29 14:47:57 +00001565 return Builder->build();
Sam McCall545a20d2018-01-19 14:34:02 +00001566 }
1567};
1568
Haojian Wu9ff50012019-01-03 15:36:18 +00001569} // namespace
1570
1571clang::CodeCompleteOptions CodeCompleteOptions::getClangCompleteOpts() const {
1572 clang::CodeCompleteOptions Result;
1573 Result.IncludeCodePatterns = EnableSnippets && IncludeCodePatterns;
1574 Result.IncludeMacros = IncludeMacros;
1575 Result.IncludeGlobals = true;
1576 // We choose to include full comments and not do doxygen parsing in
1577 // completion.
1578 // FIXME: ideally, we should support doxygen in some form, e.g. do markdown
1579 // formatting of the comments.
1580 Result.IncludeBriefComments = false;
1581
1582 // When an is used, Sema is responsible for completing the main file,
1583 // the index can provide results from the preamble.
1584 // Tell Sema not to deserialize the preamble to look for results.
1585 Result.LoadExternal = !Index;
1586 Result.IncludeFixIts = IncludeFixIts;
1587
1588 return Result;
1589}
1590
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001591llvm::Expected<llvm::StringRef>
1592speculateCompletionFilter(llvm::StringRef Content, Position Pos) {
Eric Liu25d74e92018-08-24 11:23:56 +00001593 auto Offset = positionToOffset(Content, Pos);
1594 if (!Offset)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001595 return llvm::make_error<llvm::StringError>(
Eric Liu25d74e92018-08-24 11:23:56 +00001596 "Failed to convert position to offset in content.",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001597 llvm::inconvertibleErrorCode());
Eric Liu25d74e92018-08-24 11:23:56 +00001598 if (*Offset == 0)
1599 return "";
1600
1601 // Start from the character before the cursor.
1602 int St = *Offset - 1;
1603 // FIXME(ioeric): consider UTF characters?
1604 auto IsValidIdentifierChar = [](char c) {
1605 return ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
1606 (c >= '0' && c <= '9') || (c == '_'));
1607 };
1608 size_t Len = 0;
1609 for (; (St >= 0) && IsValidIdentifierChar(Content[St]); --St, ++Len) {
1610 }
1611 if (Len > 0)
1612 St++; // Shift to the first valid character.
1613 return Content.substr(St, Len);
1614}
1615
1616CodeCompleteResult
1617codeComplete(PathRef FileName, const tooling::CompileCommand &Command,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001618 const PreambleData *Preamble, llvm::StringRef Contents,
1619 Position Pos, llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS,
Eric Liu25d74e92018-08-24 11:23:56 +00001620 std::shared_ptr<PCHContainerOperations> PCHs,
1621 CodeCompleteOptions Opts, SpeculativeFuzzyFind *SpecFuzzyFind) {
Eric Liub1d75422018-10-02 10:43:55 +00001622 return CodeCompleteFlow(FileName,
1623 Preamble ? Preamble->Includes : IncludeStructure(),
1624 SpecFuzzyFind, Opts)
Sam McCall3f0243f2018-07-03 08:09:29 +00001625 .run({FileName, Command, Preamble, Contents, Pos, VFS, PCHs});
Sam McCall98775c52017-12-04 13:49:59 +00001626}
1627
Sam McCalld1a7a372018-01-31 13:40:48 +00001628SignatureHelp signatureHelp(PathRef FileName,
Ilya Biryukov940901e2017-12-13 12:51:22 +00001629 const tooling::CompileCommand &Command,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001630 const PreambleData *Preamble,
1631 llvm::StringRef Contents, Position Pos,
1632 llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS,
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +00001633 std::shared_ptr<PCHContainerOperations> PCHs,
Sam McCall046557b2018-09-03 16:37:59 +00001634 const SymbolIndex *Index) {
Sam McCall98775c52017-12-04 13:49:59 +00001635 SignatureHelp Result;
1636 clang::CodeCompleteOptions Options;
1637 Options.IncludeGlobals = false;
1638 Options.IncludeMacros = false;
1639 Options.IncludeCodePatterns = false;
Ilya Biryukov43714502018-05-16 12:32:44 +00001640 Options.IncludeBriefComments = false;
Sam McCall3f0243f2018-07-03 08:09:29 +00001641 IncludeStructure PreambleInclusions; // Unused for signatureHelp
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +00001642 semaCodeComplete(
1643 llvm::make_unique<SignatureHelpCollector>(Options, Index, Result),
1644 Options,
1645 {FileName, Command, Preamble, Contents, Pos, std::move(VFS),
1646 std::move(PCHs)});
Sam McCall98775c52017-12-04 13:49:59 +00001647 return Result;
1648}
1649
Marc-Andre Laperle945b5a32018-06-05 14:01:40 +00001650bool isIndexedForCodeCompletion(const NamedDecl &ND, ASTContext &ASTCtx) {
Haojian Wudd61ccb2018-12-03 12:53:19 +00001651 auto InTopLevelScope = [](const NamedDecl &ND) {
1652 switch (ND.getDeclContext()->getDeclKind()) {
1653 case Decl::TranslationUnit:
1654 case Decl::Namespace:
1655 case Decl::LinkageSpec:
1656 return true;
1657 default:
1658 break;
1659 };
1660 return false;
1661 };
1662 if (InTopLevelScope(ND))
1663 return true;
1664
1665 if (const auto *EnumDecl = dyn_cast<clang::EnumDecl>(ND.getDeclContext()))
1666 return InTopLevelScope(*EnumDecl) && !EnumDecl->isScoped();
1667
1668 return false;
Marc-Andre Laperle945b5a32018-06-05 14:01:40 +00001669}
1670
Sam McCall27c979a2018-06-29 14:47:57 +00001671CompletionItem CodeCompletion::render(const CodeCompleteOptions &Opts) const {
1672 CompletionItem LSP;
Eric Liu83f63e42018-09-03 10:18:21 +00001673 const auto *InsertInclude = Includes.empty() ? nullptr : &Includes[0];
1674 LSP.label = ((InsertInclude && InsertInclude->Insertion)
1675 ? Opts.IncludeIndicator.Insert
1676 : Opts.IncludeIndicator.NoInsert) +
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001677 (Opts.ShowOrigins ? "[" + llvm::to_string(Origin) + "]" : "") +
Sam McCall27c979a2018-06-29 14:47:57 +00001678 RequiredQualifier + Name + Signature;
Sam McCall2161ec72018-07-05 06:20:41 +00001679
Sam McCall27c979a2018-06-29 14:47:57 +00001680 LSP.kind = Kind;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001681 LSP.detail = BundleSize > 1 ? llvm::formatv("[{0} overloads]", BundleSize)
1682 : ReturnType;
Eric Liu6df66002018-09-06 18:52:26 +00001683 LSP.deprecated = Deprecated;
Eric Liu83f63e42018-09-03 10:18:21 +00001684 if (InsertInclude)
1685 LSP.detail += "\n" + InsertInclude->Header;
Sam McCall27c979a2018-06-29 14:47:57 +00001686 LSP.documentation = Documentation;
1687 LSP.sortText = sortText(Score.Total, Name);
1688 LSP.filterText = Name;
Kadir Cetinkayaa9c9d002018-08-13 08:23:01 +00001689 LSP.textEdit = {CompletionTokenRange, RequiredQualifier + Name};
Fangrui Song445bdd12018-09-05 08:01:37 +00001690 // Merge continuous additionalTextEdits into main edit. The main motivation
Kadir Cetinkayaa9c9d002018-08-13 08:23:01 +00001691 // behind this is to help LSP clients, it seems most of them are confused when
1692 // they are provided with additionalTextEdits that are consecutive to main
1693 // edit.
1694 // Note that we store additional text edits from back to front in a line. That
1695 // is mainly to help LSP clients again, so that changes do not effect each
1696 // other.
1697 for (const auto &FixIt : FixIts) {
1698 if (IsRangeConsecutive(FixIt.range, LSP.textEdit->range)) {
1699 LSP.textEdit->newText = FixIt.newText + LSP.textEdit->newText;
1700 LSP.textEdit->range.start = FixIt.range.start;
1701 } else {
1702 LSP.additionalTextEdits.push_back(FixIt);
1703 }
1704 }
Kadir Cetinkaya516fcda2018-08-23 12:19:39 +00001705 if (Opts.EnableSnippets)
1706 LSP.textEdit->newText += SnippetSuffix;
Kadir Cetinkaya6c9f15c2018-08-17 15:42:54 +00001707
Kadir Cetinkayaa9c9d002018-08-13 08:23:01 +00001708 // FIXME(kadircet): Do not even fill insertText after making sure textEdit is
1709 // compatible with most of the editors.
1710 LSP.insertText = LSP.textEdit->newText;
Sam McCall27c979a2018-06-29 14:47:57 +00001711 LSP.insertTextFormat = Opts.EnableSnippets ? InsertTextFormat::Snippet
1712 : InsertTextFormat::PlainText;
Eric Liu83f63e42018-09-03 10:18:21 +00001713 if (InsertInclude && InsertInclude->Insertion)
1714 LSP.additionalTextEdits.push_back(*InsertInclude->Insertion);
Eric Liu6df66002018-09-06 18:52:26 +00001715
Sam McCall27c979a2018-06-29 14:47:57 +00001716 return LSP;
1717}
1718
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001719llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const CodeCompletion &C) {
Sam McCalle746a2b2018-07-02 11:13:16 +00001720 // For now just lean on CompletionItem.
1721 return OS << C.render(CodeCompleteOptions());
1722}
1723
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001724llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
1725 const CodeCompleteResult &R) {
Sam McCalle746a2b2018-07-02 11:13:16 +00001726 OS << "CodeCompleteResult: " << R.Completions.size() << (R.HasMore ? "+" : "")
Eric Liu5d2a8072018-07-23 10:56:37 +00001727 << " (" << getCompletionKindString(R.Context) << ")"
Sam McCalle746a2b2018-07-02 11:13:16 +00001728 << " items:\n";
1729 for (const auto &C : R.Completions)
1730 OS << C << "\n";
1731 return OS;
1732}
1733
Sam McCall98775c52017-12-04 13:49:59 +00001734} // namespace clangd
1735} // namespace clang