blob: 83dcfb7af65d8f643594a65cce6383d6347ad886 [file] [log] [blame]
Kirill Bobyrev8e35f1e2018-08-14 16:03:32 +00001//===--- CodeComplete.cpp ----------------------------------------*- C++-*-===//
Sam McCall98775c52017-12-04 13:49:59 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Sam McCall98775c52017-12-04 13:49:59 +00006//
Kirill Bobyrev8e35f1e2018-08-14 16:03:32 +00007//===----------------------------------------------------------------------===//
Sam McCall98775c52017-12-04 13:49:59 +00008//
Sam McCallc18c2802018-06-15 11:06:29 +00009// Code completion has several moving parts:
10// - AST-based completions are provided using the completion hooks in Sema.
11// - external completions are retrieved from the index (using hints from Sema)
12// - the two sources overlap, and must be merged and overloads bundled
13// - results must be scored and ranked (see Quality.h) before rendering
Sam McCall98775c52017-12-04 13:49:59 +000014//
Sam McCallc18c2802018-06-15 11:06:29 +000015// Signature help works in a similar way as code completion, but it is simpler:
16// it's purely AST-based, and there are few candidates.
Sam McCall98775c52017-12-04 13:49:59 +000017//
Kirill Bobyrev8e35f1e2018-08-14 16:03:32 +000018//===----------------------------------------------------------------------===//
Sam McCall98775c52017-12-04 13:49:59 +000019
20#include "CodeComplete.h"
Eric Liu7ad16962018-06-22 10:46:59 +000021#include "AST.h"
Eric Liub1d75422018-10-02 10:43:55 +000022#include "ClangdUnit.h"
Eric Liu63696e12017-12-20 17:24:31 +000023#include "CodeCompletionStrings.h"
Sam McCall98775c52017-12-04 13:49:59 +000024#include "Compiler.h"
Kadir Cetinkaya2f84d912018-08-08 08:59:29 +000025#include "Diagnostics.h"
Ilya Biryukov647da3e2018-11-26 15:38:01 +000026#include "ExpectedTypes.h"
Sam McCall3f0243f2018-07-03 08:09:29 +000027#include "FileDistance.h"
Sam McCall84652cc2018-01-12 16:16:09 +000028#include "FuzzyMatch.h"
Eric Liu63f419a2018-05-15 15:29:32 +000029#include "Headers.h"
Eric Liu6f648df2017-12-19 16:50:37 +000030#include "Logger.h"
Sam McCallc5707b62018-05-15 17:43:27 +000031#include "Quality.h"
Eric Liuc5105f92018-02-16 14:15:55 +000032#include "SourceCode.h"
Eric Liu25d74e92018-08-24 11:23:56 +000033#include "TUScheduler.h"
Sam McCall2b780162018-01-30 17:20:54 +000034#include "Trace.h"
Eric Liu63f419a2018-05-15 15:29:32 +000035#include "URI.h"
Eric Liu6f648df2017-12-19 16:50:37 +000036#include "index/Index.h"
Eric Liu3fac4ef2018-10-17 11:19:02 +000037#include "clang/AST/Decl.h"
38#include "clang/AST/DeclBase.h"
Ilya Biryukovc22d3442018-05-16 12:32:49 +000039#include "clang/Basic/LangOptions.h"
Kadir Cetinkayaa9c9d002018-08-13 08:23:01 +000040#include "clang/Basic/SourceLocation.h"
Eric Liuc5105f92018-02-16 14:15:55 +000041#include "clang/Format/Format.h"
Sam McCall98775c52017-12-04 13:49:59 +000042#include "clang/Frontend/CompilerInstance.h"
43#include "clang/Frontend/FrontendActions.h"
Sam McCallebef8122018-09-14 12:36:06 +000044#include "clang/Lex/PreprocessorOptions.h"
Sam McCall98775c52017-12-04 13:49:59 +000045#include "clang/Sema/CodeCompleteConsumer.h"
46#include "clang/Sema/Sema.h"
Eric Liu670c1472018-09-27 18:46:00 +000047#include "llvm/ADT/ArrayRef.h"
Eric Liu3fac4ef2018-10-17 11:19:02 +000048#include "llvm/ADT/None.h"
Eric Liu25d74e92018-08-24 11:23:56 +000049#include "llvm/ADT/Optional.h"
Eric Liu83f63e42018-09-03 10:18:21 +000050#include "llvm/ADT/SmallVector.h"
Eric Liu25d74e92018-08-24 11:23:56 +000051#include "llvm/Support/Error.h"
Haojian Wuba28e9a2018-01-10 14:44:34 +000052#include "llvm/Support/Format.h"
Eric Liubc25ef72018-07-05 08:29:33 +000053#include "llvm/Support/FormatVariadic.h"
Sam McCall2161ec72018-07-05 06:20:41 +000054#include "llvm/Support/ScopedPrinter.h"
Eric Liu83f63e42018-09-03 10:18:21 +000055#include <algorithm>
56#include <iterator>
Sam McCall98775c52017-12-04 13:49:59 +000057
Sam McCallc5707b62018-05-15 17:43:27 +000058// We log detailed candidate here if you run with -debug-only=codecomplete.
Sam McCall27c979a2018-06-29 14:47:57 +000059#define DEBUG_TYPE "CodeComplete"
Sam McCallc5707b62018-05-15 17:43:27 +000060
Sam McCall98775c52017-12-04 13:49:59 +000061namespace clang {
62namespace clangd {
63namespace {
64
Eric Liu6f648df2017-12-19 16:50:37 +000065CompletionItemKind toCompletionItemKind(index::SymbolKind Kind) {
66 using SK = index::SymbolKind;
67 switch (Kind) {
68 case SK::Unknown:
69 return CompletionItemKind::Missing;
70 case SK::Module:
71 case SK::Namespace:
72 case SK::NamespaceAlias:
73 return CompletionItemKind::Module;
74 case SK::Macro:
75 return CompletionItemKind::Text;
76 case SK::Enum:
77 return CompletionItemKind::Enum;
78 // FIXME(ioeric): use LSP struct instead of class when it is suppoted in the
79 // protocol.
80 case SK::Struct:
81 case SK::Class:
82 case SK::Protocol:
83 case SK::Extension:
84 case SK::Union:
85 return CompletionItemKind::Class;
86 // FIXME(ioeric): figure out whether reference is the right type for aliases.
87 case SK::TypeAlias:
88 case SK::Using:
89 return CompletionItemKind::Reference;
90 case SK::Function:
91 // FIXME(ioeric): this should probably be an operator. This should be fixed
92 // when `Operator` is support type in the protocol.
93 case SK::ConversionFunction:
94 return CompletionItemKind::Function;
95 case SK::Variable:
96 case SK::Parameter:
97 return CompletionItemKind::Variable;
98 case SK::Field:
99 return CompletionItemKind::Field;
100 // FIXME(ioeric): use LSP enum constant when it is supported in the protocol.
101 case SK::EnumConstant:
102 return CompletionItemKind::Value;
103 case SK::InstanceMethod:
104 case SK::ClassMethod:
105 case SK::StaticMethod:
106 case SK::Destructor:
107 return CompletionItemKind::Method;
108 case SK::InstanceProperty:
109 case SK::ClassProperty:
110 case SK::StaticProperty:
111 return CompletionItemKind::Property;
112 case SK::Constructor:
113 return CompletionItemKind::Constructor;
114 }
115 llvm_unreachable("Unhandled clang::index::SymbolKind.");
116}
117
Sam McCall83305892018-06-08 21:17:19 +0000118CompletionItemKind
119toCompletionItemKind(CodeCompletionResult::ResultKind ResKind,
Sam McCall4c077f92018-09-18 09:08:28 +0000120 const NamedDecl *Decl,
121 CodeCompletionContext::Kind CtxKind) {
Sam McCall83305892018-06-08 21:17:19 +0000122 if (Decl)
123 return toCompletionItemKind(index::getSymbolInfo(Decl).Kind);
Sam McCall4c077f92018-09-18 09:08:28 +0000124 if (CtxKind == CodeCompletionContext::CCC_IncludedFile)
125 return CompletionItemKind::File;
Sam McCall83305892018-06-08 21:17:19 +0000126 switch (ResKind) {
127 case CodeCompletionResult::RK_Declaration:
128 llvm_unreachable("RK_Declaration without Decl");
129 case CodeCompletionResult::RK_Keyword:
130 return CompletionItemKind::Keyword;
131 case CodeCompletionResult::RK_Macro:
132 return CompletionItemKind::Text; // unfortunately, there's no 'Macro'
133 // completion items in LSP.
134 case CodeCompletionResult::RK_Pattern:
135 return CompletionItemKind::Snippet;
136 }
137 llvm_unreachable("Unhandled CodeCompletionResult::ResultKind.");
138}
139
Sam McCall98775c52017-12-04 13:49:59 +0000140/// Get the optional chunk as a string. This function is possibly recursive.
141///
142/// The parameter info for each parameter is appended to the Parameters.
Kadir Cetinkayae486e372018-08-13 08:40:05 +0000143std::string getOptionalParameters(const CodeCompletionString &CCS,
144 std::vector<ParameterInformation> &Parameters,
145 SignatureQualitySignals &Signal) {
Sam McCall98775c52017-12-04 13:49:59 +0000146 std::string Result;
147 for (const auto &Chunk : CCS) {
148 switch (Chunk.Kind) {
149 case CodeCompletionString::CK_Optional:
150 assert(Chunk.Optional &&
151 "Expected the optional code completion string to be non-null.");
Kadir Cetinkayae486e372018-08-13 08:40:05 +0000152 Result += getOptionalParameters(*Chunk.Optional, Parameters, Signal);
Sam McCall98775c52017-12-04 13:49:59 +0000153 break;
154 case CodeCompletionString::CK_VerticalSpace:
155 break;
156 case CodeCompletionString::CK_Placeholder:
157 // A string that acts as a placeholder for, e.g., a function call
158 // argument.
159 // Intentional fallthrough here.
160 case CodeCompletionString::CK_CurrentParameter: {
161 // A piece of text that describes the parameter that corresponds to
162 // the code-completion location within a function call, message send,
163 // macro invocation, etc.
164 Result += Chunk.Text;
165 ParameterInformation Info;
166 Info.label = Chunk.Text;
167 Parameters.push_back(std::move(Info));
Kadir Cetinkayae486e372018-08-13 08:40:05 +0000168 Signal.ContainsActiveParameter = true;
169 Signal.NumberOfOptionalParameters++;
Sam McCall98775c52017-12-04 13:49:59 +0000170 break;
171 }
172 default:
173 Result += Chunk.Text;
174 break;
175 }
176 }
177 return Result;
178}
179
Sam McCall545a20d2018-01-19 14:34:02 +0000180/// A code completion result, in clang-native form.
Sam McCall98775c52017-12-04 13:49:59 +0000181/// It may be promoted to a CompletionItem if it's among the top-ranked results.
182struct CompletionCandidate {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000183 llvm::StringRef Name; // Used for filtering and sorting.
Sam McCall545a20d2018-01-19 14:34:02 +0000184 // We may have a result from Sema, from the index, or both.
185 const CodeCompletionResult *SemaResult = nullptr;
186 const Symbol *IndexResult = nullptr;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000187 llvm::SmallVector<llvm::StringRef, 1> RankedIncludeHeaders;
Sam McCall98775c52017-12-04 13:49:59 +0000188
Sam McCallc18c2802018-06-15 11:06:29 +0000189 // Returns a token identifying the overload set this is part of.
190 // 0 indicates it's not part of any overload set.
191 size_t overloadSet() const {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000192 llvm::SmallString<256> Scratch;
Sam McCallc18c2802018-06-15 11:06:29 +0000193 if (IndexResult) {
194 switch (IndexResult->SymInfo.Kind) {
195 case index::SymbolKind::ClassMethod:
196 case index::SymbolKind::InstanceMethod:
197 case index::SymbolKind::StaticMethod:
Fangrui Song12e4ee72018-11-02 05:59:29 +0000198#ifndef NDEBUG
199 llvm_unreachable("Don't expect members from index in code completion");
200#else
Fangrui Songa3ed05b2018-11-02 04:23:50 +0000201 LLVM_FALLTHROUGH;
Fangrui Song12e4ee72018-11-02 05:59:29 +0000202#endif
Sam McCallc18c2802018-06-15 11:06:29 +0000203 case index::SymbolKind::Function:
204 // We can't group overloads together that need different #includes.
205 // This could break #include insertion.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000206 return llvm::hash_combine(
Sam McCallc18c2802018-06-15 11:06:29 +0000207 (IndexResult->Scope + IndexResult->Name).toStringRef(Scratch),
Eric Liu83f63e42018-09-03 10:18:21 +0000208 headerToInsertIfAllowed().getValueOr(""));
Sam McCallc18c2802018-06-15 11:06:29 +0000209 default:
210 return 0;
211 }
212 }
213 assert(SemaResult);
214 // We need to make sure we're consistent with the IndexResult case!
215 const NamedDecl *D = SemaResult->Declaration;
216 if (!D || !D->isFunctionOrFunctionTemplate())
217 return 0;
218 {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000219 llvm::raw_svector_ostream OS(Scratch);
Sam McCallc18c2802018-06-15 11:06:29 +0000220 D->printQualifiedName(OS);
221 }
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000222 return llvm::hash_combine(Scratch,
223 headerToInsertIfAllowed().getValueOr(""));
Sam McCallc18c2802018-06-15 11:06:29 +0000224 }
225
Eric Liu83f63e42018-09-03 10:18:21 +0000226 // The best header to include if include insertion is allowed.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000227 llvm::Optional<llvm::StringRef> headerToInsertIfAllowed() const {
Eric Liu83f63e42018-09-03 10:18:21 +0000228 if (RankedIncludeHeaders.empty())
Sam McCallc008af62018-10-20 15:30:37 +0000229 return None;
Sam McCallc18c2802018-06-15 11:06:29 +0000230 if (SemaResult && SemaResult->Declaration) {
231 // Avoid inserting new #include if the declaration is found in the current
232 // file e.g. the symbol is forward declared.
233 auto &SM = SemaResult->Declaration->getASTContext().getSourceManager();
234 for (const Decl *RD : SemaResult->Declaration->redecls())
Stephen Kelly43465bf2018-08-09 22:42:26 +0000235 if (SM.isInMainFile(SM.getExpansionLoc(RD->getBeginLoc())))
Sam McCallc008af62018-10-20 15:30:37 +0000236 return None;
Sam McCallc18c2802018-06-15 11:06:29 +0000237 }
Eric Liu83f63e42018-09-03 10:18:21 +0000238 return RankedIncludeHeaders[0];
Sam McCallc18c2802018-06-15 11:06:29 +0000239 }
240
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000241 using Bundle = llvm::SmallVector<CompletionCandidate, 4>;
Sam McCall98775c52017-12-04 13:49:59 +0000242};
Sam McCallc18c2802018-06-15 11:06:29 +0000243using ScoredBundle =
Sam McCall27c979a2018-06-29 14:47:57 +0000244 std::pair<CompletionCandidate::Bundle, CodeCompletion::Scores>;
Sam McCallc18c2802018-06-15 11:06:29 +0000245struct ScoredBundleGreater {
246 bool operator()(const ScoredBundle &L, const ScoredBundle &R) {
Sam McCall27c979a2018-06-29 14:47:57 +0000247 if (L.second.Total != R.second.Total)
248 return L.second.Total > R.second.Total;
Sam McCallc18c2802018-06-15 11:06:29 +0000249 return L.first.front().Name <
250 R.first.front().Name; // Earlier name is better.
251 }
252};
Sam McCall98775c52017-12-04 13:49:59 +0000253
Sam McCall27c979a2018-06-29 14:47:57 +0000254// Assembles a code completion out of a bundle of >=1 completion candidates.
255// Many of the expensive strings are only computed at this point, once we know
256// the candidate bundle is going to be returned.
257//
258// Many fields are the same for all candidates in a bundle (e.g. name), and are
259// computed from the first candidate, in the constructor.
260// Others vary per candidate, so add() must be called for remaining candidates.
261struct CodeCompletionBuilder {
262 CodeCompletionBuilder(ASTContext &ASTCtx, const CompletionCandidate &C,
263 CodeCompletionString *SemaCCS,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000264 llvm::ArrayRef<std::string> QueryScopes,
265 const IncludeInserter &Includes,
266 llvm::StringRef FileName,
Sam McCall4c077f92018-09-18 09:08:28 +0000267 CodeCompletionContext::Kind ContextKind,
Sam McCall27c979a2018-06-29 14:47:57 +0000268 const CodeCompleteOptions &Opts)
Kadir Cetinkaya516fcda2018-08-23 12:19:39 +0000269 : ASTCtx(ASTCtx), ExtractDocumentation(Opts.IncludeComments),
270 EnableFunctionArgSnippets(Opts.EnableFunctionArgSnippets) {
Sam McCall27c979a2018-06-29 14:47:57 +0000271 add(C, SemaCCS);
272 if (C.SemaResult) {
Sam McCall4e5742a2018-07-06 11:50:49 +0000273 Completion.Origin |= SymbolOrigin::AST;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000274 Completion.Name = llvm::StringRef(SemaCCS->getTypedText());
Eric Liuf433c2d2018-07-18 15:31:14 +0000275 if (Completion.Scope.empty()) {
276 if ((C.SemaResult->Kind == CodeCompletionResult::RK_Declaration) ||
277 (C.SemaResult->Kind == CodeCompletionResult::RK_Pattern))
Sam McCall27c979a2018-06-29 14:47:57 +0000278 if (const auto *D = C.SemaResult->getDeclaration())
Sam McCallc008af62018-10-20 15:30:37 +0000279 if (const auto *ND = dyn_cast<NamedDecl>(D))
Sam McCall27c979a2018-06-29 14:47:57 +0000280 Completion.Scope =
281 splitQualifiedName(printQualifiedName(*ND)).first;
Eric Liuf433c2d2018-07-18 15:31:14 +0000282 }
Sam McCall4c077f92018-09-18 09:08:28 +0000283 Completion.Kind = toCompletionItemKind(
284 C.SemaResult->Kind, C.SemaResult->Declaration, ContextKind);
Kadir Cetinkaya0ed5d292018-09-27 14:21:07 +0000285 // Sema could provide more info on whether the completion was a file or
286 // folder.
287 if (Completion.Kind == CompletionItemKind::File &&
288 Completion.Name.back() == '/')
289 Completion.Kind = CompletionItemKind::Folder;
Kadir Cetinkaya2f84d912018-08-08 08:59:29 +0000290 for (const auto &FixIt : C.SemaResult->FixIts) {
291 Completion.FixIts.push_back(
292 toTextEdit(FixIt, ASTCtx.getSourceManager(), ASTCtx.getLangOpts()));
293 }
Kirill Bobyrev4a5ff882018-10-07 14:49:41 +0000294 llvm::sort(Completion.FixIts, [](const TextEdit &X, const TextEdit &Y) {
295 return std::tie(X.range.start.line, X.range.start.character) <
296 std::tie(Y.range.start.line, Y.range.start.character);
297 });
Eric Liu6df66002018-09-06 18:52:26 +0000298 Completion.Deprecated |=
299 (C.SemaResult->Availability == CXAvailability_Deprecated);
Sam McCall27c979a2018-06-29 14:47:57 +0000300 }
301 if (C.IndexResult) {
Sam McCall4e5742a2018-07-06 11:50:49 +0000302 Completion.Origin |= C.IndexResult->Origin;
Sam McCall27c979a2018-06-29 14:47:57 +0000303 if (Completion.Scope.empty())
304 Completion.Scope = C.IndexResult->Scope;
305 if (Completion.Kind == CompletionItemKind::Missing)
306 Completion.Kind = toCompletionItemKind(C.IndexResult->SymInfo.Kind);
307 if (Completion.Name.empty())
308 Completion.Name = C.IndexResult->Name;
Eric Liu670c1472018-09-27 18:46:00 +0000309 // If the completion was visible to Sema, no qualifier is needed. This
310 // avoids unneeded qualifiers in cases like with `using ns::X`.
311 if (Completion.RequiredQualifier.empty() && !C.SemaResult) {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000312 llvm::StringRef ShortestQualifier = C.IndexResult->Scope;
313 for (llvm::StringRef Scope : QueryScopes) {
314 llvm::StringRef Qualifier = C.IndexResult->Scope;
Eric Liu670c1472018-09-27 18:46:00 +0000315 if (Qualifier.consume_front(Scope) &&
316 Qualifier.size() < ShortestQualifier.size())
317 ShortestQualifier = Qualifier;
318 }
319 Completion.RequiredQualifier = ShortestQualifier;
320 }
Eric Liu6df66002018-09-06 18:52:26 +0000321 Completion.Deprecated |= (C.IndexResult->Flags & Symbol::Deprecated);
Sam McCall27c979a2018-06-29 14:47:57 +0000322 }
Eric Liu83f63e42018-09-03 10:18:21 +0000323
324 // Turn absolute path into a literal string that can be #included.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000325 auto Inserted = [&](llvm::StringRef Header)
326 -> llvm::Expected<std::pair<std::string, bool>> {
Eric Liu83f63e42018-09-03 10:18:21 +0000327 auto ResolvedDeclaring =
328 toHeaderFile(C.IndexResult->CanonicalDeclaration.FileURI, FileName);
329 if (!ResolvedDeclaring)
330 return ResolvedDeclaring.takeError();
331 auto ResolvedInserted = toHeaderFile(Header, FileName);
332 if (!ResolvedInserted)
333 return ResolvedInserted.takeError();
334 return std::make_pair(
335 Includes.calculateIncludePath(*ResolvedDeclaring, *ResolvedInserted),
336 Includes.shouldInsertInclude(*ResolvedDeclaring, *ResolvedInserted));
337 };
338 bool ShouldInsert = C.headerToInsertIfAllowed().hasValue();
339 // Calculate include paths and edits for all possible headers.
340 for (const auto &Inc : C.RankedIncludeHeaders) {
341 if (auto ToInclude = Inserted(Inc)) {
342 CodeCompletion::IncludeCandidate Include;
343 Include.Header = ToInclude->first;
344 if (ToInclude->second && ShouldInsert)
345 Include.Insertion = Includes.insert(ToInclude->first);
346 Completion.Includes.push_back(std::move(Include));
Sam McCall27c979a2018-06-29 14:47:57 +0000347 } else
Sam McCallbed58852018-07-11 10:35:11 +0000348 log("Failed to generate include insertion edits for adding header "
Sam McCall27c979a2018-06-29 14:47:57 +0000349 "(FileURI='{0}', IncludeHeader='{1}') into {2}",
Eric Liu83f63e42018-09-03 10:18:21 +0000350 C.IndexResult->CanonicalDeclaration.FileURI, Inc, FileName);
Sam McCall27c979a2018-06-29 14:47:57 +0000351 }
Eric Liu83f63e42018-09-03 10:18:21 +0000352 // Prefer includes that do not need edits (i.e. already exist).
353 std::stable_partition(Completion.Includes.begin(),
354 Completion.Includes.end(),
355 [](const CodeCompletion::IncludeCandidate &I) {
356 return !I.Insertion.hasValue();
357 });
Sam McCall27c979a2018-06-29 14:47:57 +0000358 }
359
360 void add(const CompletionCandidate &C, CodeCompletionString *SemaCCS) {
361 assert(bool(C.SemaResult) == bool(SemaCCS));
362 Bundled.emplace_back();
363 BundledEntry &S = Bundled.back();
364 if (C.SemaResult) {
365 getSignature(*SemaCCS, &S.Signature, &S.SnippetSuffix,
366 &Completion.RequiredQualifier);
367 S.ReturnType = getReturnType(*SemaCCS);
368 } else if (C.IndexResult) {
369 S.Signature = C.IndexResult->Signature;
370 S.SnippetSuffix = C.IndexResult->CompletionSnippetSuffix;
Sam McCall2e5700f2018-08-31 13:55:01 +0000371 S.ReturnType = C.IndexResult->ReturnType;
Sam McCall27c979a2018-06-29 14:47:57 +0000372 }
373 if (ExtractDocumentation && Completion.Documentation.empty()) {
Sam McCall2e5700f2018-08-31 13:55:01 +0000374 if (C.IndexResult)
375 Completion.Documentation = C.IndexResult->Documentation;
Sam McCall27c979a2018-06-29 14:47:57 +0000376 else if (C.SemaResult)
377 Completion.Documentation = getDocComment(ASTCtx, *C.SemaResult,
378 /*CommentsFromHeader=*/false);
379 }
380 }
381
382 CodeCompletion build() {
383 Completion.ReturnType = summarizeReturnType();
384 Completion.Signature = summarizeSignature();
385 Completion.SnippetSuffix = summarizeSnippet();
386 Completion.BundleSize = Bundled.size();
387 return std::move(Completion);
388 }
389
390private:
391 struct BundledEntry {
392 std::string SnippetSuffix;
393 std::string Signature;
394 std::string ReturnType;
395 };
396
397 // If all BundledEntrys have the same value for a property, return it.
398 template <std::string BundledEntry::*Member>
399 const std::string *onlyValue() const {
400 auto B = Bundled.begin(), E = Bundled.end();
401 for (auto I = B + 1; I != E; ++I)
402 if (I->*Member != B->*Member)
403 return nullptr;
404 return &(B->*Member);
405 }
406
Kadir Cetinkayaf8b85a32018-08-23 13:14:50 +0000407 template <bool BundledEntry::*Member> const bool *onlyValue() const {
408 auto B = Bundled.begin(), E = Bundled.end();
409 for (auto I = B + 1; I != E; ++I)
410 if (I->*Member != B->*Member)
411 return nullptr;
412 return &(B->*Member);
413 }
414
Sam McCall27c979a2018-06-29 14:47:57 +0000415 std::string summarizeReturnType() const {
416 if (auto *RT = onlyValue<&BundledEntry::ReturnType>())
417 return *RT;
418 return "";
419 }
420
421 std::string summarizeSnippet() const {
Kadir Cetinkaya516fcda2018-08-23 12:19:39 +0000422 auto *Snippet = onlyValue<&BundledEntry::SnippetSuffix>();
423 if (!Snippet)
424 // All bundles are function calls.
Ilya Biryukov4f984702018-09-26 05:45:31 +0000425 // FIXME(ibiryukov): sometimes add template arguments to a snippet, e.g.
426 // we need to complete 'forward<$1>($0)'.
Kadir Cetinkaya516fcda2018-08-23 12:19:39 +0000427 return "($0)";
Ilya Biryukov4f984702018-09-26 05:45:31 +0000428 if (EnableFunctionArgSnippets)
429 return *Snippet;
430
431 // Replace argument snippets with a simplified pattern.
432 if (Snippet->empty())
433 return "";
434 if (Completion.Kind == CompletionItemKind::Function ||
435 Completion.Kind == CompletionItemKind::Method) {
436 // Functions snippets can be of 2 types:
437 // - containing only function arguments, e.g.
438 // foo(${1:int p1}, ${2:int p2});
439 // We transform this pattern to '($0)' or '()'.
440 // - template arguments and function arguments, e.g.
441 // foo<${1:class}>(${2:int p1}).
442 // We transform this pattern to '<$1>()$0' or '<$0>()'.
443
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000444 bool EmptyArgs = llvm::StringRef(*Snippet).endswith("()");
Ilya Biryukov4f984702018-09-26 05:45:31 +0000445 if (Snippet->front() == '<')
446 return EmptyArgs ? "<$1>()$0" : "<$1>($0)";
447 if (Snippet->front() == '(')
448 return EmptyArgs ? "()" : "($0)";
449 return *Snippet; // Not an arg snippet?
450 }
451 if (Completion.Kind == CompletionItemKind::Reference ||
452 Completion.Kind == CompletionItemKind::Class) {
453 if (Snippet->front() != '<')
454 return *Snippet; // Not an arg snippet?
455
456 // Classes and template using aliases can only have template arguments,
457 // e.g. Foo<${1:class}>.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000458 if (llvm::StringRef(*Snippet).endswith("<>"))
Ilya Biryukov4f984702018-09-26 05:45:31 +0000459 return "<>"; // can happen with defaulted template arguments.
460 return "<$0>";
461 }
Kadir Cetinkaya516fcda2018-08-23 12:19:39 +0000462 return *Snippet;
Sam McCall27c979a2018-06-29 14:47:57 +0000463 }
464
465 std::string summarizeSignature() const {
466 if (auto *Signature = onlyValue<&BundledEntry::Signature>())
467 return *Signature;
468 // All bundles are function calls.
469 return "(…)";
470 }
471
472 ASTContext &ASTCtx;
473 CodeCompletion Completion;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000474 llvm::SmallVector<BundledEntry, 1> Bundled;
Sam McCall27c979a2018-06-29 14:47:57 +0000475 bool ExtractDocumentation;
Kadir Cetinkaya516fcda2018-08-23 12:19:39 +0000476 bool EnableFunctionArgSnippets;
Sam McCall27c979a2018-06-29 14:47:57 +0000477};
478
Sam McCall545a20d2018-01-19 14:34:02 +0000479// Determine the symbol ID for a Sema code completion result, if possible.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000480llvm::Optional<SymbolID> getSymbolID(const CodeCompletionResult &R,
481 const SourceManager &SM) {
Sam McCall545a20d2018-01-19 14:34:02 +0000482 switch (R.Kind) {
483 case CodeCompletionResult::RK_Declaration:
484 case CodeCompletionResult::RK_Pattern: {
Haojian Wuc6ddb462018-08-07 08:57:52 +0000485 return clang::clangd::getSymbolID(R.Declaration);
Sam McCall545a20d2018-01-19 14:34:02 +0000486 }
487 case CodeCompletionResult::RK_Macro:
Eric Liud25f1212018-09-06 09:59:37 +0000488 return clang::clangd::getSymbolID(*R.Macro, R.MacroDefInfo, SM);
Sam McCall545a20d2018-01-19 14:34:02 +0000489 case CodeCompletionResult::RK_Keyword:
490 return None;
491 }
492 llvm_unreachable("unknown CodeCompletionResult kind");
493}
494
Haojian Wu061c73e2018-01-23 11:37:26 +0000495// Scopes of the paritial identifier we're trying to complete.
496// It is used when we query the index for more completion results.
Eric Liu6f648df2017-12-19 16:50:37 +0000497struct SpecifiedScope {
Haojian Wu061c73e2018-01-23 11:37:26 +0000498 // The scopes we should look in, determined by Sema.
499 //
500 // If the qualifier was fully resolved, we look for completions in these
501 // scopes; if there is an unresolved part of the qualifier, it should be
502 // resolved within these scopes.
503 //
504 // Examples of qualified completion:
505 //
506 // "::vec" => {""}
507 // "using namespace std; ::vec^" => {"", "std::"}
508 // "namespace ns {using namespace std;} ns::^" => {"ns::", "std::"}
509 // "std::vec^" => {""} // "std" unresolved
510 //
511 // Examples of unqualified completion:
512 //
513 // "vec^" => {""}
514 // "using namespace std; vec^" => {"", "std::"}
515 // "using namespace std; namespace ns { vec^ }" => {"ns::", "std::", ""}
516 //
517 // "" for global namespace, "ns::" for normal namespace.
518 std::vector<std::string> AccessibleScopes;
519 // The full scope qualifier as typed by the user (without the leading "::").
520 // Set if the qualifier is not fully resolved by Sema.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000521 llvm::Optional<std::string> UnresolvedQualifier;
Sam McCall545a20d2018-01-19 14:34:02 +0000522
Eric Liuabbd7132018-11-06 11:17:40 +0000523 // Construct scopes being queried in indexes. The results are deduplicated.
Haojian Wu061c73e2018-01-23 11:37:26 +0000524 // This method format the scopes to match the index request representation.
525 std::vector<std::string> scopesForIndexQuery() {
Eric Liuabbd7132018-11-06 11:17:40 +0000526 std::set<std::string> Results;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000527 for (llvm::StringRef AS : AccessibleScopes)
Eric Liuabbd7132018-11-06 11:17:40 +0000528 Results.insert(
529 ((UnresolvedQualifier ? *UnresolvedQualifier : "") + AS).str());
530 return {Results.begin(), Results.end()};
Sam McCall545a20d2018-01-19 14:34:02 +0000531 }
Eric Liu6f648df2017-12-19 16:50:37 +0000532};
533
Eric Liu670c1472018-09-27 18:46:00 +0000534// Get all scopes that will be queried in indexes and whether symbols from
Eric Liu3fac4ef2018-10-17 11:19:02 +0000535// any scope is allowed. The first scope in the list is the preferred scope
536// (e.g. enclosing namespace).
Eric Liu670c1472018-09-27 18:46:00 +0000537std::pair<std::vector<std::string>, bool>
Eric Liu3fac4ef2018-10-17 11:19:02 +0000538getQueryScopes(CodeCompletionContext &CCContext, const Sema &CCSema,
Eric Liu670c1472018-09-27 18:46:00 +0000539 const CodeCompleteOptions &Opts) {
Kirill Bobyrev5a267ed2018-05-29 11:50:51 +0000540 auto GetAllAccessibleScopes = [](CodeCompletionContext &CCContext) {
Haojian Wu061c73e2018-01-23 11:37:26 +0000541 SpecifiedScope Info;
Kirill Bobyrev5a267ed2018-05-29 11:50:51 +0000542 for (auto *Context : CCContext.getVisitedContexts()) {
Haojian Wu061c73e2018-01-23 11:37:26 +0000543 if (isa<TranslationUnitDecl>(Context))
544 Info.AccessibleScopes.push_back(""); // global namespace
Mikael Holmenfa41add2018-10-18 06:00:39 +0000545 else if (isa<NamespaceDecl>(Context))
Eric Liu3fac4ef2018-10-17 11:19:02 +0000546 Info.AccessibleScopes.push_back(printNamespaceScope(*Context));
Haojian Wu061c73e2018-01-23 11:37:26 +0000547 }
548 return Info;
549 };
550
551 auto SS = CCContext.getCXXScopeSpecifier();
552
553 // Unqualified completion (e.g. "vec^").
554 if (!SS) {
Eric Liu3fac4ef2018-10-17 11:19:02 +0000555 std::vector<std::string> Scopes;
556 std::string EnclosingScope = printNamespaceScope(*CCSema.CurContext);
557 Scopes.push_back(EnclosingScope);
558 for (auto &S : GetAllAccessibleScopes(CCContext).scopesForIndexQuery()) {
559 if (EnclosingScope != S)
560 Scopes.push_back(std::move(S));
561 }
Eric Liu670c1472018-09-27 18:46:00 +0000562 // Allow AllScopes completion only for there is no explicit scope qualifier.
563 return {Scopes, Opts.AllScopes};
Haojian Wu061c73e2018-01-23 11:37:26 +0000564 }
565
566 // Qualified completion ("std::vec^"), we have two cases depending on whether
567 // the qualifier can be resolved by Sema.
568 if ((*SS)->isValid()) { // Resolved qualifier.
Eric Liu670c1472018-09-27 18:46:00 +0000569 return {GetAllAccessibleScopes(CCContext).scopesForIndexQuery(), false};
Haojian Wu061c73e2018-01-23 11:37:26 +0000570 }
571
572 // Unresolved qualifier.
573 // FIXME: When Sema can resolve part of a scope chain (e.g.
574 // "known::unknown::id"), we should expand the known part ("known::") rather
575 // than treating the whole thing as unknown.
576 SpecifiedScope Info;
577 Info.AccessibleScopes.push_back(""); // global namespace
578
579 Info.UnresolvedQualifier =
Eric Liu3fac4ef2018-10-17 11:19:02 +0000580 Lexer::getSourceText(CharSourceRange::getCharRange((*SS)->getRange()),
581 CCSema.SourceMgr, clang::LangOptions())
Kirill Bobyrev5a267ed2018-05-29 11:50:51 +0000582 .ltrim("::");
Haojian Wu061c73e2018-01-23 11:37:26 +0000583 // Sema excludes the trailing "::".
584 if (!Info.UnresolvedQualifier->empty())
585 *Info.UnresolvedQualifier += "::";
586
Eric Liu670c1472018-09-27 18:46:00 +0000587 return {Info.scopesForIndexQuery(), false};
Haojian Wu061c73e2018-01-23 11:37:26 +0000588}
589
Eric Liu42abe412018-05-24 11:20:19 +0000590// Should we perform index-based completion in a context of the specified kind?
591// FIXME: consider allowing completion, but restricting the result types.
592bool contextAllowsIndex(enum CodeCompletionContext::Kind K) {
593 switch (K) {
594 case CodeCompletionContext::CCC_TopLevel:
595 case CodeCompletionContext::CCC_ObjCInterface:
596 case CodeCompletionContext::CCC_ObjCImplementation:
597 case CodeCompletionContext::CCC_ObjCIvarList:
598 case CodeCompletionContext::CCC_ClassStructUnion:
599 case CodeCompletionContext::CCC_Statement:
600 case CodeCompletionContext::CCC_Expression:
601 case CodeCompletionContext::CCC_ObjCMessageReceiver:
602 case CodeCompletionContext::CCC_EnumTag:
603 case CodeCompletionContext::CCC_UnionTag:
604 case CodeCompletionContext::CCC_ClassOrStructTag:
605 case CodeCompletionContext::CCC_ObjCProtocolName:
606 case CodeCompletionContext::CCC_Namespace:
607 case CodeCompletionContext::CCC_Type:
Eric Liu42abe412018-05-24 11:20:19 +0000608 case CodeCompletionContext::CCC_ParenthesizedExpression:
609 case CodeCompletionContext::CCC_ObjCInterfaceName:
610 case CodeCompletionContext::CCC_ObjCCategoryName:
Kadir Cetinkayab9157902018-10-24 15:24:29 +0000611 case CodeCompletionContext::CCC_Symbol:
612 case CodeCompletionContext::CCC_SymbolOrNewName:
Eric Liu42abe412018-05-24 11:20:19 +0000613 return true;
Eric Liu42abe412018-05-24 11:20:19 +0000614 case CodeCompletionContext::CCC_OtherWithMacros:
615 case CodeCompletionContext::CCC_DotMemberAccess:
616 case CodeCompletionContext::CCC_ArrowMemberAccess:
617 case CodeCompletionContext::CCC_ObjCPropertyAccess:
618 case CodeCompletionContext::CCC_MacroName:
619 case CodeCompletionContext::CCC_MacroNameUse:
620 case CodeCompletionContext::CCC_PreprocessorExpression:
621 case CodeCompletionContext::CCC_PreprocessorDirective:
Eric Liu42abe412018-05-24 11:20:19 +0000622 case CodeCompletionContext::CCC_SelectorName:
623 case CodeCompletionContext::CCC_TypeQualifiers:
624 case CodeCompletionContext::CCC_ObjCInstanceMessage:
625 case CodeCompletionContext::CCC_ObjCClassMessage:
Sam McCall4c077f92018-09-18 09:08:28 +0000626 case CodeCompletionContext::CCC_IncludedFile:
Kadir Cetinkayab9157902018-10-24 15:24:29 +0000627 // FIXME: Provide identifier based completions for the following contexts:
628 case CodeCompletionContext::CCC_Other: // Be conservative.
629 case CodeCompletionContext::CCC_NaturalLanguage:
Eric Liu42abe412018-05-24 11:20:19 +0000630 case CodeCompletionContext::CCC_Recovery:
Kadir Cetinkayab9157902018-10-24 15:24:29 +0000631 case CodeCompletionContext::CCC_NewName:
Eric Liu42abe412018-05-24 11:20:19 +0000632 return false;
633 }
634 llvm_unreachable("unknown code completion context");
635}
636
Eric Liub1317fa2018-11-30 11:12:40 +0000637static bool isInjectedClass(const NamedDecl &D) {
638 if (auto *R = dyn_cast_or_null<RecordDecl>(&D))
639 if (R->isInjectedClassName())
640 return true;
641 return false;
642}
643
Sam McCall4caa8512018-06-07 12:49:17 +0000644// Some member calls are blacklisted because they're so rarely useful.
645static bool isBlacklistedMember(const NamedDecl &D) {
646 // Destructor completion is rarely useful, and works inconsistently.
647 // (s.^ completes ~string, but s.~st^ is an error).
648 if (D.getKind() == Decl::CXXDestructor)
649 return true;
650 // Injected name may be useful for A::foo(), but who writes A::A::foo()?
Eric Liub1317fa2018-11-30 11:12:40 +0000651 if (isInjectedClass(D))
652 return true;
Sam McCall4caa8512018-06-07 12:49:17 +0000653 // Explicit calls to operators are also rare.
654 auto NameKind = D.getDeclName().getNameKind();
655 if (NameKind == DeclarationName::CXXOperatorName ||
656 NameKind == DeclarationName::CXXLiteralOperatorName ||
657 NameKind == DeclarationName::CXXConversionFunctionName)
658 return true;
659 return false;
660}
661
Sam McCall545a20d2018-01-19 14:34:02 +0000662// The CompletionRecorder captures Sema code-complete output, including context.
663// It filters out ignored results (but doesn't apply fuzzy-filtering yet).
664// It doesn't do scoring or conversion to CompletionItem yet, as we want to
665// merge with index results first.
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000666// Generally the fields and methods of this object should only be used from
667// within the callback.
Sam McCall545a20d2018-01-19 14:34:02 +0000668struct CompletionRecorder : public CodeCompleteConsumer {
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000669 CompletionRecorder(const CodeCompleteOptions &Opts,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000670 llvm::unique_function<void()> ResultsCallback)
Sam McCall545a20d2018-01-19 14:34:02 +0000671 : CodeCompleteConsumer(Opts.getClangCompleteOpts(),
Sam McCall98775c52017-12-04 13:49:59 +0000672 /*OutputIsBinary=*/false),
Sam McCall545a20d2018-01-19 14:34:02 +0000673 CCContext(CodeCompletionContext::CCC_Other), Opts(Opts),
674 CCAllocator(std::make_shared<GlobalCodeCompletionAllocator>()),
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000675 CCTUInfo(CCAllocator), ResultsCallback(std::move(ResultsCallback)) {
676 assert(this->ResultsCallback);
677 }
678
Sam McCall545a20d2018-01-19 14:34:02 +0000679 std::vector<CodeCompletionResult> Results;
680 CodeCompletionContext CCContext;
681 Sema *CCSema = nullptr; // Sema that created the results.
682 // FIXME: Sema is scary. Can we store ASTContext and Preprocessor, instead?
Sam McCall98775c52017-12-04 13:49:59 +0000683
Sam McCall545a20d2018-01-19 14:34:02 +0000684 void ProcessCodeCompleteResults(class Sema &S, CodeCompletionContext Context,
685 CodeCompletionResult *InResults,
Sam McCall98775c52017-12-04 13:49:59 +0000686 unsigned NumResults) override final {
Eric Liu485074f2018-07-11 13:15:31 +0000687 // Results from recovery mode are generally useless, and the callback after
688 // recovery (if any) is usually more interesting. To make sure we handle the
689 // future callback from sema, we just ignore all callbacks in recovery mode,
690 // as taking only results from recovery mode results in poor completion
691 // results.
692 // FIXME: in case there is no future sema completion callback after the
693 // recovery mode, we might still want to provide some results (e.g. trivial
694 // identifier-based completion).
695 if (Context.getKind() == CodeCompletionContext::CCC_Recovery) {
696 log("Code complete: Ignoring sema code complete callback with Recovery "
697 "context.");
698 return;
699 }
Eric Liu42abe412018-05-24 11:20:19 +0000700 // If a callback is called without any sema result and the context does not
701 // support index-based completion, we simply skip it to give way to
702 // potential future callbacks with results.
703 if (NumResults == 0 && !contextAllowsIndex(Context.getKind()))
704 return;
Ilya Biryukov94da7bd2018-03-16 15:23:44 +0000705 if (CCSema) {
Sam McCallbed58852018-07-11 10:35:11 +0000706 log("Multiple code complete callbacks (parser backtracked?). "
Ilya Biryukov94da7bd2018-03-16 15:23:44 +0000707 "Dropping results from context {0}, keeping results from {1}.",
Eric Liu42abe412018-05-24 11:20:19 +0000708 getCompletionKindString(Context.getKind()),
Sam McCallbed58852018-07-11 10:35:11 +0000709 getCompletionKindString(this->CCContext.getKind()));
Ilya Biryukov94da7bd2018-03-16 15:23:44 +0000710 return;
711 }
Sam McCall545a20d2018-01-19 14:34:02 +0000712 // Record the completion context.
Sam McCall545a20d2018-01-19 14:34:02 +0000713 CCSema = &S;
714 CCContext = Context;
Eric Liu6f648df2017-12-19 16:50:37 +0000715
Sam McCall545a20d2018-01-19 14:34:02 +0000716 // Retain the results we might want.
Sam McCall98775c52017-12-04 13:49:59 +0000717 for (unsigned I = 0; I < NumResults; ++I) {
Sam McCall545a20d2018-01-19 14:34:02 +0000718 auto &Result = InResults[I];
Sam McCalle8437cb2018-10-24 13:51:44 +0000719 // Class members that are shadowed by subclasses are usually noise.
720 if (Result.Hidden && Result.Declaration &&
721 Result.Declaration->isCXXClassMember())
Ilya Biryukovf60bf342018-01-10 13:51:09 +0000722 continue;
Sam McCall545a20d2018-01-19 14:34:02 +0000723 if (!Opts.IncludeIneligibleResults &&
Sam McCall98775c52017-12-04 13:49:59 +0000724 (Result.Availability == CXAvailability_NotAvailable ||
725 Result.Availability == CXAvailability_NotAccessible))
726 continue;
Sam McCall4caa8512018-06-07 12:49:17 +0000727 if (Result.Declaration &&
728 !Context.getBaseType().isNull() // is this a member-access context?
729 && isBlacklistedMember(*Result.Declaration))
Sam McCalld2a95922018-01-22 21:05:00 +0000730 continue;
Eric Liub1317fa2018-11-30 11:12:40 +0000731 // Skip injected class name when no class scope is not explicitly set.
732 // E.g. show injected A::A in `using A::A^` but not in "A^".
733 if (Result.Declaration && !Context.getCXXScopeSpecifier().hasValue() &&
734 isInjectedClass(*Result.Declaration))
735 continue;
Ilya Biryukov53d6d932018-03-06 16:45:21 +0000736 // We choose to never append '::' to completion results in clangd.
737 Result.StartsNestedNameSpecifier = false;
Sam McCall545a20d2018-01-19 14:34:02 +0000738 Results.push_back(Result);
Sam McCall98775c52017-12-04 13:49:59 +0000739 }
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000740 ResultsCallback();
Sam McCall98775c52017-12-04 13:49:59 +0000741 }
742
Sam McCall545a20d2018-01-19 14:34:02 +0000743 CodeCompletionAllocator &getAllocator() override { return *CCAllocator; }
Sam McCall98775c52017-12-04 13:49:59 +0000744 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
745
Sam McCall545a20d2018-01-19 14:34:02 +0000746 // Returns the filtering/sorting name for Result, which must be from Results.
747 // Returned string is owned by this recorder (or the AST).
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000748 llvm::StringRef getName(const CodeCompletionResult &Result) {
Sam McCall98775c52017-12-04 13:49:59 +0000749 switch (Result.Kind) {
750 case CodeCompletionResult::RK_Declaration:
751 if (auto *ID = Result.Declaration->getIdentifier())
Sam McCall545a20d2018-01-19 14:34:02 +0000752 return ID->getName();
Sam McCall98775c52017-12-04 13:49:59 +0000753 break;
754 case CodeCompletionResult::RK_Keyword:
Sam McCall545a20d2018-01-19 14:34:02 +0000755 return Result.Keyword;
Sam McCall98775c52017-12-04 13:49:59 +0000756 case CodeCompletionResult::RK_Macro:
Sam McCall545a20d2018-01-19 14:34:02 +0000757 return Result.Macro->getName();
Sam McCall98775c52017-12-04 13:49:59 +0000758 case CodeCompletionResult::RK_Pattern:
Sam McCall545a20d2018-01-19 14:34:02 +0000759 return Result.Pattern->getTypedText();
Sam McCall98775c52017-12-04 13:49:59 +0000760 }
Ilya Biryukov43714502018-05-16 12:32:44 +0000761 auto *CCS = codeCompletionString(Result);
Sam McCall545a20d2018-01-19 14:34:02 +0000762 return CCS->getTypedText();
Sam McCall98775c52017-12-04 13:49:59 +0000763 }
764
Sam McCall545a20d2018-01-19 14:34:02 +0000765 // Build a CodeCompletion string for R, which must be from Results.
766 // The CCS will be owned by this recorder.
Ilya Biryukov43714502018-05-16 12:32:44 +0000767 CodeCompletionString *codeCompletionString(const CodeCompletionResult &R) {
Sam McCall545a20d2018-01-19 14:34:02 +0000768 // CodeCompletionResult doesn't seem to be const-correct. We own it, anyway.
769 return const_cast<CodeCompletionResult &>(R).CreateCodeCompletionString(
Ilya Biryukov43714502018-05-16 12:32:44 +0000770 *CCSema, CCContext, *CCAllocator, CCTUInfo,
771 /*IncludeBriefComments=*/false);
Sam McCall98775c52017-12-04 13:49:59 +0000772 }
773
Sam McCall545a20d2018-01-19 14:34:02 +0000774private:
775 CodeCompleteOptions Opts;
776 std::shared_ptr<GlobalCodeCompletionAllocator> CCAllocator;
Sam McCall98775c52017-12-04 13:49:59 +0000777 CodeCompletionTUInfo CCTUInfo;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000778 llvm::unique_function<void()> ResultsCallback;
Sam McCall545a20d2018-01-19 14:34:02 +0000779};
780
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +0000781struct ScoredSignature {
782 // When set, requires documentation to be requested from the index with this
783 // ID.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000784 llvm::Optional<SymbolID> IDForDoc;
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +0000785 SignatureInformation Signature;
786 SignatureQualitySignals Quality;
787};
Kadir Cetinkayae486e372018-08-13 08:40:05 +0000788
Sam McCall98775c52017-12-04 13:49:59 +0000789class SignatureHelpCollector final : public CodeCompleteConsumer {
Sam McCall98775c52017-12-04 13:49:59 +0000790public:
791 SignatureHelpCollector(const clang::CodeCompleteOptions &CodeCompleteOpts,
Sam McCall046557b2018-09-03 16:37:59 +0000792 const SymbolIndex *Index, SignatureHelp &SigHelp)
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +0000793 : CodeCompleteConsumer(CodeCompleteOpts,
794 /*OutputIsBinary=*/false),
Sam McCall98775c52017-12-04 13:49:59 +0000795 SigHelp(SigHelp),
796 Allocator(std::make_shared<clang::GlobalCodeCompletionAllocator>()),
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +0000797 CCTUInfo(Allocator), Index(Index) {}
Sam McCall98775c52017-12-04 13:49:59 +0000798
799 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
800 OverloadCandidate *Candidates,
Ilya Biryukov43c292c2018-08-30 13:14:31 +0000801 unsigned NumCandidates,
802 SourceLocation OpenParLoc) override {
803 assert(!OpenParLoc.isInvalid());
804 SourceManager &SrcMgr = S.getSourceManager();
805 OpenParLoc = SrcMgr.getFileLoc(OpenParLoc);
806 if (SrcMgr.isInMainFile(OpenParLoc))
807 SigHelp.argListStart = sourceLocToPosition(SrcMgr, OpenParLoc);
808 else
809 elog("Location oustide main file in signature help: {0}",
810 OpenParLoc.printToString(SrcMgr));
811
Kadir Cetinkayae486e372018-08-13 08:40:05 +0000812 std::vector<ScoredSignature> ScoredSignatures;
Sam McCall98775c52017-12-04 13:49:59 +0000813 SigHelp.signatures.reserve(NumCandidates);
Kadir Cetinkayae486e372018-08-13 08:40:05 +0000814 ScoredSignatures.reserve(NumCandidates);
Sam McCall98775c52017-12-04 13:49:59 +0000815 // FIXME(rwols): How can we determine the "active overload candidate"?
816 // Right now the overloaded candidates seem to be provided in a "best fit"
817 // order, so I'm not too worried about this.
818 SigHelp.activeSignature = 0;
819 assert(CurrentArg <= (unsigned)std::numeric_limits<int>::max() &&
820 "too many arguments");
821 SigHelp.activeParameter = static_cast<int>(CurrentArg);
822 for (unsigned I = 0; I < NumCandidates; ++I) {
Ilya Biryukov8fd44bb2018-08-14 09:36:32 +0000823 OverloadCandidate Candidate = Candidates[I];
824 // We want to avoid showing instantiated signatures, because they may be
825 // long in some cases (e.g. when 'T' is substituted with 'std::string', we
826 // would get 'std::basic_string<char>').
827 if (auto *Func = Candidate.getFunction()) {
828 if (auto *Pattern = Func->getTemplateInstantiationPattern())
829 Candidate = OverloadCandidate(Pattern);
830 }
831
Sam McCall98775c52017-12-04 13:49:59 +0000832 const auto *CCS = Candidate.CreateSignatureString(
833 CurrentArg, S, *Allocator, CCTUInfo, true);
834 assert(CCS && "Expected the CodeCompletionString to be non-null");
Kadir Cetinkayae486e372018-08-13 08:40:05 +0000835 ScoredSignatures.push_back(processOverloadCandidate(
Ilya Biryukov43714502018-05-16 12:32:44 +0000836 Candidate, *CCS,
Ilya Biryukov5f4a3512018-08-17 09:29:38 +0000837 Candidate.getFunction()
838 ? getDeclComment(S.getASTContext(), *Candidate.getFunction())
839 : ""));
Sam McCall98775c52017-12-04 13:49:59 +0000840 }
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +0000841
842 // Sema does not load the docs from the preamble, so we need to fetch extra
843 // docs from the index instead.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000844 llvm::DenseMap<SymbolID, std::string> FetchedDocs;
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +0000845 if (Index) {
846 LookupRequest IndexRequest;
847 for (const auto &S : ScoredSignatures) {
848 if (!S.IDForDoc)
849 continue;
850 IndexRequest.IDs.insert(*S.IDForDoc);
851 }
852 Index->lookup(IndexRequest, [&](const Symbol &S) {
Sam McCall2e5700f2018-08-31 13:55:01 +0000853 if (!S.Documentation.empty())
854 FetchedDocs[S.ID] = S.Documentation;
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +0000855 });
856 log("SigHelp: requested docs for {0} symbols from the index, got {1} "
857 "symbols with non-empty docs in the response",
858 IndexRequest.IDs.size(), FetchedDocs.size());
859 }
860
Ilya Biryukov22fa4652019-01-03 13:28:05 +0000861 llvm::sort(ScoredSignatures, [](const ScoredSignature &L,
862 const ScoredSignature &R) {
863 // Ordering follows:
864 // - Less number of parameters is better.
865 // - Function is better than FunctionType which is better than
866 // Function Template.
867 // - High score is better.
868 // - Shorter signature is better.
869 // - Alphebatically smaller is better.
870 if (L.Quality.NumberOfParameters != R.Quality.NumberOfParameters)
871 return L.Quality.NumberOfParameters < R.Quality.NumberOfParameters;
872 if (L.Quality.NumberOfOptionalParameters !=
873 R.Quality.NumberOfOptionalParameters)
874 return L.Quality.NumberOfOptionalParameters <
875 R.Quality.NumberOfOptionalParameters;
876 if (L.Quality.Kind != R.Quality.Kind) {
877 using OC = CodeCompleteConsumer::OverloadCandidate;
878 switch (L.Quality.Kind) {
879 case OC::CK_Function:
880 return true;
881 case OC::CK_FunctionType:
882 return R.Quality.Kind != OC::CK_Function;
883 case OC::CK_FunctionTemplate:
884 return false;
885 }
886 llvm_unreachable("Unknown overload candidate type.");
887 }
888 if (L.Signature.label.size() != R.Signature.label.size())
889 return L.Signature.label.size() < R.Signature.label.size();
890 return L.Signature.label < R.Signature.label;
891 });
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +0000892
893 for (auto &SS : ScoredSignatures) {
894 auto IndexDocIt =
895 SS.IDForDoc ? FetchedDocs.find(*SS.IDForDoc) : FetchedDocs.end();
896 if (IndexDocIt != FetchedDocs.end())
897 SS.Signature.documentation = IndexDocIt->second;
898
899 SigHelp.signatures.push_back(std::move(SS.Signature));
900 }
Sam McCall98775c52017-12-04 13:49:59 +0000901 }
902
903 GlobalCodeCompletionAllocator &getAllocator() override { return *Allocator; }
904
905 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
906
907private:
Eric Liu63696e12017-12-20 17:24:31 +0000908 // FIXME(ioeric): consider moving CodeCompletionString logic here to
909 // CompletionString.h.
Kadir Cetinkayae486e372018-08-13 08:40:05 +0000910 ScoredSignature processOverloadCandidate(const OverloadCandidate &Candidate,
911 const CodeCompletionString &CCS,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000912 llvm::StringRef DocComment) const {
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +0000913 SignatureInformation Signature;
Kadir Cetinkayae486e372018-08-13 08:40:05 +0000914 SignatureQualitySignals Signal;
Sam McCall98775c52017-12-04 13:49:59 +0000915 const char *ReturnType = nullptr;
916
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +0000917 Signature.documentation = formatDocumentation(CCS, DocComment);
Kadir Cetinkayae486e372018-08-13 08:40:05 +0000918 Signal.Kind = Candidate.getKind();
Sam McCall98775c52017-12-04 13:49:59 +0000919
920 for (const auto &Chunk : CCS) {
921 switch (Chunk.Kind) {
922 case CodeCompletionString::CK_ResultType:
923 // A piece of text that describes the type of an entity or,
924 // for functions and methods, the return type.
925 assert(!ReturnType && "Unexpected CK_ResultType");
926 ReturnType = Chunk.Text;
927 break;
928 case CodeCompletionString::CK_Placeholder:
929 // A string that acts as a placeholder for, e.g., a function call
930 // argument.
931 // Intentional fallthrough here.
932 case CodeCompletionString::CK_CurrentParameter: {
933 // A piece of text that describes the parameter that corresponds to
934 // the code-completion location within a function call, message send,
935 // macro invocation, etc.
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +0000936 Signature.label += Chunk.Text;
Sam McCall98775c52017-12-04 13:49:59 +0000937 ParameterInformation Info;
938 Info.label = Chunk.Text;
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +0000939 Signature.parameters.push_back(std::move(Info));
Kadir Cetinkayae486e372018-08-13 08:40:05 +0000940 Signal.NumberOfParameters++;
941 Signal.ContainsActiveParameter = true;
Sam McCall98775c52017-12-04 13:49:59 +0000942 break;
943 }
944 case CodeCompletionString::CK_Optional: {
945 // The rest of the parameters are defaulted/optional.
946 assert(Chunk.Optional &&
947 "Expected the optional code completion string to be non-null.");
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +0000948 Signature.label += getOptionalParameters(*Chunk.Optional,
949 Signature.parameters, Signal);
Sam McCall98775c52017-12-04 13:49:59 +0000950 break;
951 }
952 case CodeCompletionString::CK_VerticalSpace:
953 break;
954 default:
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +0000955 Signature.label += Chunk.Text;
Sam McCall98775c52017-12-04 13:49:59 +0000956 break;
957 }
958 }
959 if (ReturnType) {
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +0000960 Signature.label += " -> ";
961 Signature.label += ReturnType;
Sam McCall98775c52017-12-04 13:49:59 +0000962 }
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +0000963 dlog("Signal for {0}: {1}", Signature, Signal);
964 ScoredSignature Result;
965 Result.Signature = std::move(Signature);
966 Result.Quality = Signal;
967 Result.IDForDoc =
968 Result.Signature.documentation.empty() && Candidate.getFunction()
969 ? clangd::getSymbolID(Candidate.getFunction())
Sam McCallc008af62018-10-20 15:30:37 +0000970 : None;
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +0000971 return Result;
Sam McCall98775c52017-12-04 13:49:59 +0000972 }
973
974 SignatureHelp &SigHelp;
975 std::shared_ptr<clang::GlobalCodeCompletionAllocator> Allocator;
976 CodeCompletionTUInfo CCTUInfo;
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +0000977 const SymbolIndex *Index;
Sam McCall98775c52017-12-04 13:49:59 +0000978}; // SignatureHelpCollector
979
Sam McCall545a20d2018-01-19 14:34:02 +0000980struct SemaCompleteInput {
981 PathRef FileName;
982 const tooling::CompileCommand &Command;
Eric Liub1d75422018-10-02 10:43:55 +0000983 const PreambleData *Preamble;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000984 llvm::StringRef Contents;
Sam McCall545a20d2018-01-19 14:34:02 +0000985 Position Pos;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000986 llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS;
Sam McCall545a20d2018-01-19 14:34:02 +0000987 std::shared_ptr<PCHContainerOperations> PCHs;
988};
989
990// Invokes Sema code completion on a file.
Sam McCall3f0243f2018-07-03 08:09:29 +0000991// If \p Includes is set, it will be updated based on the compiler invocation.
Sam McCalld1a7a372018-01-31 13:40:48 +0000992bool semaCodeComplete(std::unique_ptr<CodeCompleteConsumer> Consumer,
Sam McCall545a20d2018-01-19 14:34:02 +0000993 const clang::CodeCompleteOptions &Options,
Eric Liu63f419a2018-05-15 15:29:32 +0000994 const SemaCompleteInput &Input,
Sam McCall3f0243f2018-07-03 08:09:29 +0000995 IncludeStructure *Includes = nullptr) {
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000996 trace::Span Tracer("Sema completion");
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000997 llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS = Input.VFS;
Eric Liub1d75422018-10-02 10:43:55 +0000998 if (Input.Preamble && Input.Preamble->StatCache)
999 VFS = Input.Preamble->StatCache->getConsumingFS(std::move(VFS));
Eric Liudd662772019-01-28 14:01:55 +00001000 ParseInputs ParseInput;
1001 ParseInput.CompileCommand = Input.Command;
1002 ParseInput.FS = VFS;
1003 ParseInput.Contents = Input.Contents;
1004 ParseInput.Opts = ParseOptions();
1005 auto CI = buildCompilerInvocation(ParseInput);
Ilya Biryukovb6ad25c2018-02-09 13:51:57 +00001006 if (!CI) {
Sam McCallbed58852018-07-11 10:35:11 +00001007 elog("Couldn't create CompilerInvocation");
Ilya Biryukovb6ad25c2018-02-09 13:51:57 +00001008 return false;
1009 }
Ilya Biryukov981a35d2018-05-28 12:11:37 +00001010 auto &FrontendOpts = CI->getFrontendOpts();
Sam McCall98775c52017-12-04 13:49:59 +00001011 FrontendOpts.SkipFunctionBodies = true;
Ilya Biryukov981a35d2018-05-28 12:11:37 +00001012 // Disable typo correction in Sema.
1013 CI->getLangOpts()->SpellChecking = false;
1014 // Setup code completion.
Sam McCall98775c52017-12-04 13:49:59 +00001015 FrontendOpts.CodeCompleteOpts = Options;
Sam McCall545a20d2018-01-19 14:34:02 +00001016 FrontendOpts.CodeCompletionAt.FileName = Input.FileName;
Sam McCalla4962cc2018-04-27 11:59:28 +00001017 auto Offset = positionToOffset(Input.Contents, Input.Pos);
1018 if (!Offset) {
Sam McCallbed58852018-07-11 10:35:11 +00001019 elog("Code completion position was invalid {0}", Offset.takeError());
Sam McCalla4962cc2018-04-27 11:59:28 +00001020 return false;
1021 }
1022 std::tie(FrontendOpts.CodeCompletionAt.Line,
1023 FrontendOpts.CodeCompletionAt.Column) =
1024 offsetToClangLineColumn(Input.Contents, *Offset);
Sam McCall98775c52017-12-04 13:49:59 +00001025
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001026 std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer =
1027 llvm::MemoryBuffer::getMemBufferCopy(Input.Contents, Input.FileName);
Ilya Biryukov981a35d2018-05-28 12:11:37 +00001028 // The diagnostic options must be set before creating a CompilerInstance.
1029 CI->getDiagnosticOpts().IgnoreWarnings = true;
1030 // We reuse the preamble whether it's valid or not. This is a
1031 // correctness/performance tradeoff: building without a preamble is slow, and
1032 // completion is latency-sensitive.
Sam McCallebef8122018-09-14 12:36:06 +00001033 // However, if we're completing *inside* the preamble section of the draft,
1034 // overriding the preamble will break sema completion. Fortunately we can just
1035 // skip all includes in this case; these completions are really simple.
1036 bool CompletingInPreamble =
1037 ComputePreambleBounds(*CI->getLangOpts(), ContentsBuffer.get(), 0).Size >
1038 *Offset;
Ilya Biryukov981a35d2018-05-28 12:11:37 +00001039 // NOTE: we must call BeginSourceFile after prepareCompilerInstance. Otherwise
1040 // the remapped buffers do not get freed.
Kadir Cetinkayaa65bcbf2019-01-22 09:58:53 +00001041 IgnoreDiagnostics DummyDiagsConsumer;
Ilya Biryukov981a35d2018-05-28 12:11:37 +00001042 auto Clang = prepareCompilerInstance(
Eric Liub1d75422018-10-02 10:43:55 +00001043 std::move(CI),
1044 (Input.Preamble && !CompletingInPreamble) ? &Input.Preamble->Preamble
1045 : nullptr,
1046 std::move(ContentsBuffer), std::move(Input.PCHs), std::move(VFS),
Sam McCallebef8122018-09-14 12:36:06 +00001047 DummyDiagsConsumer);
1048 Clang->getPreprocessorOpts().SingleFileParseMode = CompletingInPreamble;
Sam McCall98775c52017-12-04 13:49:59 +00001049 Clang->setCodeCompletionConsumer(Consumer.release());
1050
1051 SyntaxOnlyAction Action;
1052 if (!Action.BeginSourceFile(*Clang, Clang->getFrontendOpts().Inputs[0])) {
Sam McCallbed58852018-07-11 10:35:11 +00001053 log("BeginSourceFile() failed when running codeComplete for {0}",
Sam McCalld1a7a372018-01-31 13:40:48 +00001054 Input.FileName);
Sam McCall98775c52017-12-04 13:49:59 +00001055 return false;
1056 }
Sam McCall3f0243f2018-07-03 08:09:29 +00001057 if (Includes)
1058 Clang->getPreprocessor().addPPCallbacks(
1059 collectIncludeStructureCallback(Clang->getSourceManager(), Includes));
Sam McCall98775c52017-12-04 13:49:59 +00001060 if (!Action.Execute()) {
Sam McCallbed58852018-07-11 10:35:11 +00001061 log("Execute() failed when running codeComplete for {0}", Input.FileName);
Sam McCall98775c52017-12-04 13:49:59 +00001062 return false;
1063 }
Sam McCall98775c52017-12-04 13:49:59 +00001064 Action.EndSourceFile();
1065
1066 return true;
1067}
1068
Ilya Biryukova907ba42018-05-14 10:50:04 +00001069// Should we allow index completions in the specified context?
1070bool allowIndex(CodeCompletionContext &CC) {
1071 if (!contextAllowsIndex(CC.getKind()))
1072 return false;
1073 // We also avoid ClassName::bar (but allow namespace::bar).
1074 auto Scope = CC.getCXXScopeSpecifier();
1075 if (!Scope)
1076 return true;
1077 NestedNameSpecifier *NameSpec = (*Scope)->getScopeRep();
1078 if (!NameSpec)
1079 return true;
1080 // We only query the index when qualifier is a namespace.
1081 // If it's a class, we rely solely on sema completions.
1082 switch (NameSpec->getKind()) {
1083 case NestedNameSpecifier::Global:
1084 case NestedNameSpecifier::Namespace:
1085 case NestedNameSpecifier::NamespaceAlias:
1086 return true;
1087 case NestedNameSpecifier::Super:
1088 case NestedNameSpecifier::TypeSpec:
1089 case NestedNameSpecifier::TypeSpecWithTemplate:
1090 // Unresolved inside a template.
1091 case NestedNameSpecifier::Identifier:
1092 return false;
1093 }
Ilya Biryukova6556e22018-05-14 11:47:30 +00001094 llvm_unreachable("invalid NestedNameSpecifier kind");
Ilya Biryukova907ba42018-05-14 10:50:04 +00001095}
1096
Eric Liu25d74e92018-08-24 11:23:56 +00001097std::future<SymbolSlab> startAsyncFuzzyFind(const SymbolIndex &Index,
1098 const FuzzyFindRequest &Req) {
1099 return runAsync<SymbolSlab>([&Index, Req]() {
1100 trace::Span Tracer("Async fuzzyFind");
1101 SymbolSlab::Builder Syms;
1102 Index.fuzzyFind(Req, [&Syms](const Symbol &Sym) { Syms.insert(Sym); });
1103 return std::move(Syms).build();
1104 });
1105}
1106
1107// Creates a `FuzzyFindRequest` based on the cached index request from the
1108// last completion, if any, and the speculated completion filter text in the
1109// source code.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001110llvm::Optional<FuzzyFindRequest>
1111speculativeFuzzyFindRequestForCompletion(FuzzyFindRequest CachedReq,
1112 PathRef File, llvm::StringRef Content,
1113 Position Pos) {
Eric Liu25d74e92018-08-24 11:23:56 +00001114 auto Filter = speculateCompletionFilter(Content, Pos);
1115 if (!Filter) {
1116 elog("Failed to speculate filter text for code completion at Pos "
1117 "{0}:{1}: {2}",
1118 Pos.line, Pos.character, Filter.takeError());
Sam McCallc008af62018-10-20 15:30:37 +00001119 return None;
Eric Liu25d74e92018-08-24 11:23:56 +00001120 }
1121 CachedReq.Query = *Filter;
1122 return CachedReq;
1123}
1124
Sam McCall545a20d2018-01-19 14:34:02 +00001125// Runs Sema-based (AST) and Index-based completion, returns merged results.
1126//
1127// There are a few tricky considerations:
1128// - the AST provides information needed for the index query (e.g. which
1129// namespaces to search in). So Sema must start first.
1130// - we only want to return the top results (Opts.Limit).
1131// Building CompletionItems for everything else is wasteful, so we want to
1132// preserve the "native" format until we're done with scoring.
1133// - the data underlying Sema completion items is owned by the AST and various
1134// other arenas, which must stay alive for us to build CompletionItems.
1135// - we may get duplicate results from Sema and the Index, we need to merge.
1136//
Ilya Biryukovddf6a332018-03-02 12:28:27 +00001137// So we start Sema completion first, and do all our work in its callback.
Sam McCall545a20d2018-01-19 14:34:02 +00001138// We use the Sema context information to query the index.
1139// Then we merge the two result sets, producing items that are Sema/Index/Both.
1140// These items are scored, and the top N are synthesized into the LSP response.
1141// Finally, we can clean up the data structures created by Sema completion.
1142//
1143// Main collaborators are:
1144// - semaCodeComplete sets up the compiler machinery to run code completion.
1145// - CompletionRecorder captures Sema completion results, including context.
1146// - SymbolIndex (Opts.Index) provides index completion results as Symbols
1147// - CompletionCandidates are the result of merging Sema and Index results.
1148// Each candidate points to an underlying CodeCompletionResult (Sema), a
1149// Symbol (Index), or both. It computes the result quality score.
1150// CompletionCandidate also does conversion to CompletionItem (at the end).
1151// - FuzzyMatcher scores how the candidate matches the partial identifier.
1152// This score is combined with the result quality score for the final score.
1153// - TopN determines the results with the best score.
1154class CodeCompleteFlow {
Eric Liuc5105f92018-02-16 14:15:55 +00001155 PathRef FileName;
Ilya Biryukov22fa4652019-01-03 13:28:05 +00001156 IncludeStructure Includes; // Complete once the compiler runs.
Eric Liu25d74e92018-08-24 11:23:56 +00001157 SpeculativeFuzzyFind *SpecFuzzyFind; // Can be nullptr.
Sam McCall545a20d2018-01-19 14:34:02 +00001158 const CodeCompleteOptions &Opts;
Eric Liu25d74e92018-08-24 11:23:56 +00001159
Sam McCall545a20d2018-01-19 14:34:02 +00001160 // Sema takes ownership of Recorder. Recorder is valid until Sema cleanup.
Ilya Biryukovddf6a332018-03-02 12:28:27 +00001161 CompletionRecorder *Recorder = nullptr;
Sam McCall545a20d2018-01-19 14:34:02 +00001162 int NSema = 0, NIndex = 0, NBoth = 0; // Counters for logging.
Ilya Biryukov22fa4652019-01-03 13:28:05 +00001163 bool Incomplete = false; // Would more be available with a higher limit?
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001164 llvm::Optional<FuzzyMatcher> Filter; // Initialized once Sema runs.
Eric Liu670c1472018-09-27 18:46:00 +00001165 std::vector<std::string> QueryScopes; // Initialized once Sema runs.
Eric Liu3fac4ef2018-10-17 11:19:02 +00001166 // Initialized once QueryScopes is initialized, if there are scopes.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001167 llvm::Optional<ScopeDistance> ScopeProximity;
Ilya Biryukov647da3e2018-11-26 15:38:01 +00001168 llvm::Optional<OpaqueType> PreferredType; // Initialized once Sema runs.
Eric Liu670c1472018-09-27 18:46:00 +00001169 // Whether to query symbols from any scope. Initialized once Sema runs.
1170 bool AllScopes = false;
Sam McCall3f0243f2018-07-03 08:09:29 +00001171 // Include-insertion and proximity scoring rely on the include structure.
1172 // This is available after Sema has run.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001173 llvm::Optional<IncludeInserter> Inserter; // Available during runWithSema.
1174 llvm::Optional<URIDistance> FileProximity; // Initialized once Sema runs.
Eric Liu25d74e92018-08-24 11:23:56 +00001175 /// Speculative request based on the cached request and the filter text before
1176 /// the cursor.
1177 /// Initialized right before sema run. This is only set if `SpecFuzzyFind` is
1178 /// set and contains a cached request.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001179 llvm::Optional<FuzzyFindRequest> SpecReq;
Sam McCall545a20d2018-01-19 14:34:02 +00001180
1181public:
1182 // A CodeCompleteFlow object is only useful for calling run() exactly once.
Sam McCall3f0243f2018-07-03 08:09:29 +00001183 CodeCompleteFlow(PathRef FileName, const IncludeStructure &Includes,
Eric Liu25d74e92018-08-24 11:23:56 +00001184 SpeculativeFuzzyFind *SpecFuzzyFind,
Sam McCall3f0243f2018-07-03 08:09:29 +00001185 const CodeCompleteOptions &Opts)
Eric Liu25d74e92018-08-24 11:23:56 +00001186 : FileName(FileName), Includes(Includes), SpecFuzzyFind(SpecFuzzyFind),
1187 Opts(Opts) {}
Sam McCall545a20d2018-01-19 14:34:02 +00001188
Sam McCall27c979a2018-06-29 14:47:57 +00001189 CodeCompleteResult run(const SemaCompleteInput &SemaCCInput) && {
Sam McCalld1a7a372018-01-31 13:40:48 +00001190 trace::Span Tracer("CodeCompleteFlow");
Eric Liu25d74e92018-08-24 11:23:56 +00001191 if (Opts.Index && SpecFuzzyFind && SpecFuzzyFind->CachedReq.hasValue()) {
1192 assert(!SpecFuzzyFind->Result.valid());
1193 if ((SpecReq = speculativeFuzzyFindRequestForCompletion(
1194 *SpecFuzzyFind->CachedReq, SemaCCInput.FileName,
1195 SemaCCInput.Contents, SemaCCInput.Pos)))
1196 SpecFuzzyFind->Result = startAsyncFuzzyFind(*Opts.Index, *SpecReq);
1197 }
Eric Liu63f419a2018-05-15 15:29:32 +00001198
Sam McCall545a20d2018-01-19 14:34:02 +00001199 // We run Sema code completion first. It builds an AST and calculates:
Ilya Biryukovddf6a332018-03-02 12:28:27 +00001200 // - completion results based on the AST.
Sam McCall545a20d2018-01-19 14:34:02 +00001201 // - partial identifier and context. We need these for the index query.
Sam McCall27c979a2018-06-29 14:47:57 +00001202 CodeCompleteResult Output;
Ilya Biryukovddf6a332018-03-02 12:28:27 +00001203 auto RecorderOwner = llvm::make_unique<CompletionRecorder>(Opts, [&]() {
1204 assert(Recorder && "Recorder is not set");
Eric Liudd662772019-01-28 14:01:55 +00001205 auto Style = getFormatStyleForFile(
1206 SemaCCInput.FileName, SemaCCInput.Contents, SemaCCInput.VFS.get());
Eric Liu63f419a2018-05-15 15:29:32 +00001207 // If preprocessor was run, inclusions from preprocessor callback should
Sam McCall3f0243f2018-07-03 08:09:29 +00001208 // already be added to Includes.
1209 Inserter.emplace(
Eric Liudd662772019-01-28 14:01:55 +00001210 SemaCCInput.FileName, SemaCCInput.Contents, Style,
Sam McCall3f0243f2018-07-03 08:09:29 +00001211 SemaCCInput.Command.Directory,
1212 Recorder->CCSema->getPreprocessor().getHeaderSearchInfo());
1213 for (const auto &Inc : Includes.MainFileIncludes)
1214 Inserter->addExisting(Inc);
1215
1216 // Most of the cost of file proximity is in initializing the FileDistance
1217 // structures based on the observed includes, once per query. Conceptually
1218 // that happens here (though the per-URI-scheme initialization is lazy).
1219 // The per-result proximity scoring is (amortized) very cheap.
1220 FileDistanceOptions ProxOpts{}; // Use defaults.
1221 const auto &SM = Recorder->CCSema->getSourceManager();
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001222 llvm::StringMap<SourceParams> ProxSources;
Sam McCall3f0243f2018-07-03 08:09:29 +00001223 for (auto &Entry : Includes.includeDepth(
1224 SM.getFileEntryForID(SM.getMainFileID())->getName())) {
1225 auto &Source = ProxSources[Entry.getKey()];
1226 Source.Cost = Entry.getValue() * ProxOpts.IncludeCost;
1227 // Symbols near our transitive includes are good, but only consider
1228 // things in the same directory or below it. Otherwise there can be
1229 // many false positives.
1230 if (Entry.getValue() > 0)
1231 Source.MaxUpTraversals = 1;
1232 }
1233 FileProximity.emplace(ProxSources, ProxOpts);
1234
Ilya Biryukovddf6a332018-03-02 12:28:27 +00001235 Output = runWithSema();
Sam McCall3f0243f2018-07-03 08:09:29 +00001236 Inserter.reset(); // Make sure this doesn't out-live Clang.
Ilya Biryukovddf6a332018-03-02 12:28:27 +00001237 SPAN_ATTACH(Tracer, "sema_completion_kind",
1238 getCompletionKindString(Recorder->CCContext.getKind()));
Ilya Biryukov647da3e2018-11-26 15:38:01 +00001239 log("Code complete: sema context {0}, query scopes [{1}] (AnyScope={2}), "
1240 "expected type {3}",
Eric Liubc25ef72018-07-05 08:29:33 +00001241 getCompletionKindString(Recorder->CCContext.getKind()),
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001242 llvm::join(QueryScopes.begin(), QueryScopes.end(), ","), AllScopes,
Ilya Biryukov647da3e2018-11-26 15:38:01 +00001243 PreferredType ? Recorder->CCContext.getPreferredType().getAsString()
1244 : "<none>");
Ilya Biryukovddf6a332018-03-02 12:28:27 +00001245 });
1246
1247 Recorder = RecorderOwner.get();
Eric Liu25d74e92018-08-24 11:23:56 +00001248
Sam McCalld1a7a372018-01-31 13:40:48 +00001249 semaCodeComplete(std::move(RecorderOwner), Opts.getClangCompleteOpts(),
Eric Liu63f419a2018-05-15 15:29:32 +00001250 SemaCCInput, &Includes);
Sam McCall545a20d2018-01-19 14:34:02 +00001251
Sam McCall2b780162018-01-30 17:20:54 +00001252 SPAN_ATTACH(Tracer, "sema_results", NSema);
1253 SPAN_ATTACH(Tracer, "index_results", NIndex);
1254 SPAN_ATTACH(Tracer, "merged_results", NBoth);
Sam McCalld20d7982018-07-09 14:25:59 +00001255 SPAN_ATTACH(Tracer, "returned_results", int64_t(Output.Completions.size()));
Sam McCall27c979a2018-06-29 14:47:57 +00001256 SPAN_ATTACH(Tracer, "incomplete", Output.HasMore);
Sam McCallbed58852018-07-11 10:35:11 +00001257 log("Code complete: {0} results from Sema, {1} from Index, "
1258 "{2} matched, {3} returned{4}.",
1259 NSema, NIndex, NBoth, Output.Completions.size(),
1260 Output.HasMore ? " (incomplete)" : "");
Sam McCall27c979a2018-06-29 14:47:57 +00001261 assert(!Opts.Limit || Output.Completions.size() <= Opts.Limit);
Sam McCall545a20d2018-01-19 14:34:02 +00001262 // We don't assert that isIncomplete means we hit a limit.
1263 // Indexes may choose to impose their own limits even if we don't have one.
1264 return Output;
1265 }
1266
1267private:
1268 // This is called by run() once Sema code completion is done, but before the
1269 // Sema data structures are torn down. It does all the real work.
Sam McCall27c979a2018-06-29 14:47:57 +00001270 CodeCompleteResult runWithSema() {
Kadir Cetinkayaa9c9d002018-08-13 08:23:01 +00001271 const auto &CodeCompletionRange = CharSourceRange::getCharRange(
1272 Recorder->CCSema->getPreprocessor().getCodeCompletionTokenRange());
1273 Range TextEditRange;
1274 // When we are getting completions with an empty identifier, for example
1275 // std::vector<int> asdf;
1276 // asdf.^;
1277 // Then the range will be invalid and we will be doing insertion, use
1278 // current cursor position in such cases as range.
1279 if (CodeCompletionRange.isValid()) {
1280 TextEditRange = halfOpenToRange(Recorder->CCSema->getSourceManager(),
1281 CodeCompletionRange);
1282 } else {
1283 const auto &Pos = sourceLocToPosition(
1284 Recorder->CCSema->getSourceManager(),
1285 Recorder->CCSema->getPreprocessor().getCodeCompletionLoc());
1286 TextEditRange.start = TextEditRange.end = Pos;
1287 }
Sam McCall545a20d2018-01-19 14:34:02 +00001288 Filter = FuzzyMatcher(
Ilya Biryukovddf6a332018-03-02 12:28:27 +00001289 Recorder->CCSema->getPreprocessor().getCodeCompletionFilter());
Eric Liu3fac4ef2018-10-17 11:19:02 +00001290 std::tie(QueryScopes, AllScopes) =
1291 getQueryScopes(Recorder->CCContext, *Recorder->CCSema, Opts);
1292 if (!QueryScopes.empty())
1293 ScopeProximity.emplace(QueryScopes);
Ilya Biryukov647da3e2018-11-26 15:38:01 +00001294 PreferredType =
1295 OpaqueType::fromType(Recorder->CCSema->getASTContext(),
1296 Recorder->CCContext.getPreferredType());
Sam McCall545a20d2018-01-19 14:34:02 +00001297 // Sema provides the needed context to query the index.
1298 // FIXME: in addition to querying for extra/overlapping symbols, we should
1299 // explicitly request symbols corresponding to Sema results.
1300 // We can use their signals even if the index can't suggest them.
1301 // We must copy index results to preserve them, but there are at most Limit.
Eric Liu8f3678d2018-06-15 13:34:18 +00001302 auto IndexResults = (Opts.Index && allowIndex(Recorder->CCContext))
1303 ? queryIndex()
1304 : SymbolSlab();
Eric Liu25d74e92018-08-24 11:23:56 +00001305 trace::Span Tracer("Populate CodeCompleteResult");
Kadir Cetinkayab15b8dc2018-10-02 09:42:17 +00001306 // Merge Sema and Index results, score them, and pick the winners.
1307 auto Top = mergeResults(Recorder->Results, IndexResults);
Sam McCall27c979a2018-06-29 14:47:57 +00001308 CodeCompleteResult Output;
Kadir Cetinkayaf8b85a32018-08-23 13:14:50 +00001309
1310 // Convert the results to final form, assembling the expensive strings.
Sam McCall27c979a2018-06-29 14:47:57 +00001311 for (auto &C : Top) {
1312 Output.Completions.push_back(toCodeCompletion(C.first));
1313 Output.Completions.back().Score = C.second;
Kadir Cetinkayaa9c9d002018-08-13 08:23:01 +00001314 Output.Completions.back().CompletionTokenRange = TextEditRange;
Sam McCall27c979a2018-06-29 14:47:57 +00001315 }
1316 Output.HasMore = Incomplete;
Eric Liu5d2a8072018-07-23 10:56:37 +00001317 Output.Context = Recorder->CCContext.getKind();
Kadir Cetinkayaf8b85a32018-08-23 13:14:50 +00001318
Sam McCall545a20d2018-01-19 14:34:02 +00001319 return Output;
1320 }
1321
1322 SymbolSlab queryIndex() {
Sam McCalld1a7a372018-01-31 13:40:48 +00001323 trace::Span Tracer("Query index");
Sam McCalld20d7982018-07-09 14:25:59 +00001324 SPAN_ATTACH(Tracer, "limit", int64_t(Opts.Limit));
Sam McCall2b780162018-01-30 17:20:54 +00001325
Sam McCall545a20d2018-01-19 14:34:02 +00001326 // Build the query.
1327 FuzzyFindRequest Req;
Haojian Wu48b48652018-01-25 09:20:09 +00001328 if (Opts.Limit)
Kirill Bobyreve6dd0802018-09-13 14:27:03 +00001329 Req.Limit = Opts.Limit;
Sam McCall545a20d2018-01-19 14:34:02 +00001330 Req.Query = Filter->pattern();
Marc-Andre Laperle945b5a32018-06-05 14:01:40 +00001331 Req.RestrictForCodeCompletion = true;
Eric Liubc25ef72018-07-05 08:29:33 +00001332 Req.Scopes = QueryScopes;
Eric Liu670c1472018-09-27 18:46:00 +00001333 Req.AnyScope = AllScopes;
Sam McCall3f0243f2018-07-03 08:09:29 +00001334 // FIXME: we should send multiple weighted paths here.
Eric Liu6de95ec2018-06-12 08:48:20 +00001335 Req.ProximityPaths.push_back(FileName);
Kirill Bobyrev09f00dc2018-09-10 11:51:05 +00001336 vlog("Code complete: fuzzyFind({0:2})", toJSON(Req));
Eric Liu25d74e92018-08-24 11:23:56 +00001337
1338 if (SpecFuzzyFind)
1339 SpecFuzzyFind->NewReq = Req;
1340 if (SpecFuzzyFind && SpecFuzzyFind->Result.valid() && (*SpecReq == Req)) {
1341 vlog("Code complete: speculative fuzzy request matches the actual index "
1342 "request. Waiting for the speculative index results.");
1343 SPAN_ATTACH(Tracer, "Speculative results", true);
1344
1345 trace::Span WaitSpec("Wait speculative results");
1346 return SpecFuzzyFind->Result.get();
1347 }
1348
1349 SPAN_ATTACH(Tracer, "Speculative results", false);
1350
Sam McCall545a20d2018-01-19 14:34:02 +00001351 // Run the query against the index.
Eric Liu25d74e92018-08-24 11:23:56 +00001352 SymbolSlab::Builder ResultsBuilder;
Sam McCallab8e3932018-02-19 13:04:41 +00001353 if (Opts.Index->fuzzyFind(
1354 Req, [&](const Symbol &Sym) { ResultsBuilder.insert(Sym); }))
1355 Incomplete = true;
Sam McCall545a20d2018-01-19 14:34:02 +00001356 return std::move(ResultsBuilder).build();
1357 }
1358
Kadir Cetinkayab15b8dc2018-10-02 09:42:17 +00001359 // Merges Sema and Index results where possible, to form CompletionCandidates.
1360 // Groups overloads if desired, to form CompletionCandidate::Bundles. The
1361 // bundles are scored and top results are returned, best to worst.
Sam McCallc18c2802018-06-15 11:06:29 +00001362 std::vector<ScoredBundle>
Kadir Cetinkayaf8b85a32018-08-23 13:14:50 +00001363 mergeResults(const std::vector<CodeCompletionResult> &SemaResults,
Kadir Cetinkayab15b8dc2018-10-02 09:42:17 +00001364 const SymbolSlab &IndexResults) {
Sam McCalld1a7a372018-01-31 13:40:48 +00001365 trace::Span Tracer("Merge and score results");
Sam McCallc18c2802018-06-15 11:06:29 +00001366 std::vector<CompletionCandidate::Bundle> Bundles;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001367 llvm::DenseMap<size_t, size_t> BundleLookup;
Sam McCallc18c2802018-06-15 11:06:29 +00001368 auto AddToBundles = [&](const CodeCompletionResult *SemaResult,
Kadir Cetinkayab15b8dc2018-10-02 09:42:17 +00001369 const Symbol *IndexResult) {
Sam McCallc18c2802018-06-15 11:06:29 +00001370 CompletionCandidate C;
1371 C.SemaResult = SemaResult;
1372 C.IndexResult = IndexResult;
Eric Liu83f63e42018-09-03 10:18:21 +00001373 if (C.IndexResult)
1374 C.RankedIncludeHeaders = getRankedIncludes(*C.IndexResult);
Sam McCallc18c2802018-06-15 11:06:29 +00001375 C.Name = IndexResult ? IndexResult->Name : Recorder->getName(*SemaResult);
1376 if (auto OverloadSet = Opts.BundleOverloads ? C.overloadSet() : 0) {
1377 auto Ret = BundleLookup.try_emplace(OverloadSet, Bundles.size());
1378 if (Ret.second)
1379 Bundles.emplace_back();
1380 Bundles[Ret.first->second].push_back(std::move(C));
1381 } else {
1382 Bundles.emplace_back();
1383 Bundles.back().push_back(std::move(C));
1384 }
1385 };
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001386 llvm::DenseSet<const Symbol *> UsedIndexResults;
Sam McCall545a20d2018-01-19 14:34:02 +00001387 auto CorrespondingIndexResult =
1388 [&](const CodeCompletionResult &SemaResult) -> const Symbol * {
Eric Liud25f1212018-09-06 09:59:37 +00001389 if (auto SymID =
1390 getSymbolID(SemaResult, Recorder->CCSema->getSourceManager())) {
Sam McCall545a20d2018-01-19 14:34:02 +00001391 auto I = IndexResults.find(*SymID);
1392 if (I != IndexResults.end()) {
1393 UsedIndexResults.insert(&*I);
1394 return &*I;
1395 }
1396 }
1397 return nullptr;
1398 };
1399 // Emit all Sema results, merging them with Index results if possible.
Ilya Biryukovddf6a332018-03-02 12:28:27 +00001400 for (auto &SemaResult : Recorder->Results)
Kadir Cetinkayab15b8dc2018-10-02 09:42:17 +00001401 AddToBundles(&SemaResult, CorrespondingIndexResult(SemaResult));
Sam McCall545a20d2018-01-19 14:34:02 +00001402 // Now emit any Index-only results.
1403 for (const auto &IndexResult : IndexResults) {
1404 if (UsedIndexResults.count(&IndexResult))
1405 continue;
Kadir Cetinkayab15b8dc2018-10-02 09:42:17 +00001406 AddToBundles(/*SemaResult=*/nullptr, &IndexResult);
Sam McCall545a20d2018-01-19 14:34:02 +00001407 }
Sam McCallc18c2802018-06-15 11:06:29 +00001408 // We only keep the best N results at any time, in "native" format.
1409 TopN<ScoredBundle, ScoredBundleGreater> Top(
1410 Opts.Limit == 0 ? std::numeric_limits<size_t>::max() : Opts.Limit);
1411 for (auto &Bundle : Bundles)
1412 addCandidate(Top, std::move(Bundle));
Sam McCall545a20d2018-01-19 14:34:02 +00001413 return std::move(Top).items();
1414 }
1415
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001416 llvm::Optional<float> fuzzyScore(const CompletionCandidate &C) {
Sam McCall80ad7072018-06-08 13:32:25 +00001417 // Macros can be very spammy, so we only support prefix completion.
1418 // We won't end up with underfull index results, as macros are sema-only.
1419 if (C.SemaResult && C.SemaResult->Kind == CodeCompletionResult::RK_Macro &&
1420 !C.Name.startswith_lower(Filter->pattern()))
1421 return None;
1422 return Filter->match(C.Name);
1423 }
1424
Sam McCall545a20d2018-01-19 14:34:02 +00001425 // Scores a candidate and adds it to the TopN structure.
Sam McCallc18c2802018-06-15 11:06:29 +00001426 void addCandidate(TopN<ScoredBundle, ScoredBundleGreater> &Candidates,
1427 CompletionCandidate::Bundle Bundle) {
Sam McCallc5707b62018-05-15 17:43:27 +00001428 SymbolQualitySignals Quality;
1429 SymbolRelevanceSignals Relevance;
Eric Liu5d2a8072018-07-23 10:56:37 +00001430 Relevance.Context = Recorder->CCContext.getKind();
Sam McCalld9b54f02018-06-05 16:30:25 +00001431 Relevance.Query = SymbolRelevanceSignals::CodeComplete;
Sam McCallf84dd022018-07-05 08:26:53 +00001432 Relevance.FileProximityMatch = FileProximity.getPointer();
Eric Liu3fac4ef2018-10-17 11:19:02 +00001433 if (ScopeProximity)
1434 Relevance.ScopeProximityMatch = ScopeProximity.getPointer();
Ilya Biryukov647da3e2018-11-26 15:38:01 +00001435 if (PreferredType)
1436 Relevance.HadContextType = true;
Eric Liu670c1472018-09-27 18:46:00 +00001437
Sam McCallc18c2802018-06-15 11:06:29 +00001438 auto &First = Bundle.front();
1439 if (auto FuzzyScore = fuzzyScore(First))
Sam McCallc5707b62018-05-15 17:43:27 +00001440 Relevance.NameMatch = *FuzzyScore;
Sam McCall545a20d2018-01-19 14:34:02 +00001441 else
1442 return;
Sam McCall2161ec72018-07-05 06:20:41 +00001443 SymbolOrigin Origin = SymbolOrigin::Unknown;
Sam McCall4e5742a2018-07-06 11:50:49 +00001444 bool FromIndex = false;
Sam McCallc18c2802018-06-15 11:06:29 +00001445 for (const auto &Candidate : Bundle) {
1446 if (Candidate.IndexResult) {
1447 Quality.merge(*Candidate.IndexResult);
1448 Relevance.merge(*Candidate.IndexResult);
Sam McCall4e5742a2018-07-06 11:50:49 +00001449 Origin |= Candidate.IndexResult->Origin;
1450 FromIndex = true;
Ilya Biryukov647da3e2018-11-26 15:38:01 +00001451 if (!Candidate.IndexResult->Type.empty())
1452 Relevance.HadSymbolType |= true;
1453 if (PreferredType &&
1454 PreferredType->raw() == Candidate.IndexResult->Type) {
1455 Relevance.TypeMatchesPreferred = true;
1456 }
Sam McCallc18c2802018-06-15 11:06:29 +00001457 }
1458 if (Candidate.SemaResult) {
1459 Quality.merge(*Candidate.SemaResult);
1460 Relevance.merge(*Candidate.SemaResult);
Ilya Biryukov647da3e2018-11-26 15:38:01 +00001461 if (PreferredType) {
1462 if (auto CompletionType = OpaqueType::fromCompletionResult(
1463 Recorder->CCSema->getASTContext(), *Candidate.SemaResult)) {
1464 Relevance.HadSymbolType |= true;
1465 if (PreferredType == CompletionType)
1466 Relevance.TypeMatchesPreferred = true;
1467 }
1468 }
Sam McCall4e5742a2018-07-06 11:50:49 +00001469 Origin |= SymbolOrigin::AST;
Sam McCallc18c2802018-06-15 11:06:29 +00001470 }
Sam McCallc5707b62018-05-15 17:43:27 +00001471 }
1472
Sam McCall27c979a2018-06-29 14:47:57 +00001473 CodeCompletion::Scores Scores;
1474 Scores.Quality = Quality.evaluate();
1475 Scores.Relevance = Relevance.evaluate();
1476 Scores.Total = evaluateSymbolAndRelevance(Scores.Quality, Scores.Relevance);
1477 // NameMatch is in fact a multiplier on total score, so rescoring is sound.
1478 Scores.ExcludingName = Relevance.NameMatch
1479 ? Scores.Total / Relevance.NameMatch
1480 : Scores.Quality;
Sam McCallc5707b62018-05-15 17:43:27 +00001481
Sam McCallbed58852018-07-11 10:35:11 +00001482 dlog("CodeComplete: {0} ({1}) = {2}\n{3}{4}\n", First.Name,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001483 llvm::to_string(Origin), Scores.Total, llvm::to_string(Quality),
1484 llvm::to_string(Relevance));
Sam McCall545a20d2018-01-19 14:34:02 +00001485
Sam McCall2161ec72018-07-05 06:20:41 +00001486 NSema += bool(Origin & SymbolOrigin::AST);
Sam McCall4e5742a2018-07-06 11:50:49 +00001487 NIndex += FromIndex;
1488 NBoth += bool(Origin & SymbolOrigin::AST) && FromIndex;
Sam McCallc18c2802018-06-15 11:06:29 +00001489 if (Candidates.push({std::move(Bundle), Scores}))
Sam McCallab8e3932018-02-19 13:04:41 +00001490 Incomplete = true;
Sam McCall545a20d2018-01-19 14:34:02 +00001491 }
1492
Sam McCall27c979a2018-06-29 14:47:57 +00001493 CodeCompletion toCodeCompletion(const CompletionCandidate::Bundle &Bundle) {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001494 llvm::Optional<CodeCompletionBuilder> Builder;
Sam McCall27c979a2018-06-29 14:47:57 +00001495 for (const auto &Item : Bundle) {
1496 CodeCompletionString *SemaCCS =
1497 Item.SemaResult ? Recorder->codeCompletionString(*Item.SemaResult)
1498 : nullptr;
1499 if (!Builder)
1500 Builder.emplace(Recorder->CCSema->getASTContext(), Item, SemaCCS,
Eric Liu670c1472018-09-27 18:46:00 +00001501 QueryScopes, *Inserter, FileName,
1502 Recorder->CCContext.getKind(), Opts);
Sam McCall27c979a2018-06-29 14:47:57 +00001503 else
1504 Builder->add(Item, SemaCCS);
Ilya Biryukov43714502018-05-16 12:32:44 +00001505 }
Sam McCall27c979a2018-06-29 14:47:57 +00001506 return Builder->build();
Sam McCall545a20d2018-01-19 14:34:02 +00001507 }
1508};
1509
Haojian Wu9ff50012019-01-03 15:36:18 +00001510} // namespace
1511
1512clang::CodeCompleteOptions CodeCompleteOptions::getClangCompleteOpts() const {
1513 clang::CodeCompleteOptions Result;
1514 Result.IncludeCodePatterns = EnableSnippets && IncludeCodePatterns;
1515 Result.IncludeMacros = IncludeMacros;
1516 Result.IncludeGlobals = true;
1517 // We choose to include full comments and not do doxygen parsing in
1518 // completion.
1519 // FIXME: ideally, we should support doxygen in some form, e.g. do markdown
1520 // formatting of the comments.
1521 Result.IncludeBriefComments = false;
1522
1523 // When an is used, Sema is responsible for completing the main file,
1524 // the index can provide results from the preamble.
1525 // Tell Sema not to deserialize the preamble to look for results.
1526 Result.LoadExternal = !Index;
1527 Result.IncludeFixIts = IncludeFixIts;
1528
1529 return Result;
1530}
1531
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001532llvm::Expected<llvm::StringRef>
1533speculateCompletionFilter(llvm::StringRef Content, Position Pos) {
Eric Liu25d74e92018-08-24 11:23:56 +00001534 auto Offset = positionToOffset(Content, Pos);
1535 if (!Offset)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001536 return llvm::make_error<llvm::StringError>(
Eric Liu25d74e92018-08-24 11:23:56 +00001537 "Failed to convert position to offset in content.",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001538 llvm::inconvertibleErrorCode());
Eric Liu25d74e92018-08-24 11:23:56 +00001539 if (*Offset == 0)
1540 return "";
1541
1542 // Start from the character before the cursor.
1543 int St = *Offset - 1;
1544 // FIXME(ioeric): consider UTF characters?
Haojian Wuaa3ed5a2019-01-25 15:14:03 +00001545 auto IsValidIdentifierChar = [](char C) {
1546 return ((C >= 'a' && C <= 'z') || (C >= 'A' && C <= 'Z') ||
1547 (C >= '0' && C <= '9') || (C == '_'));
Eric Liu25d74e92018-08-24 11:23:56 +00001548 };
1549 size_t Len = 0;
1550 for (; (St >= 0) && IsValidIdentifierChar(Content[St]); --St, ++Len) {
1551 }
1552 if (Len > 0)
1553 St++; // Shift to the first valid character.
1554 return Content.substr(St, Len);
1555}
1556
1557CodeCompleteResult
1558codeComplete(PathRef FileName, const tooling::CompileCommand &Command,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001559 const PreambleData *Preamble, llvm::StringRef Contents,
1560 Position Pos, llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS,
Eric Liu25d74e92018-08-24 11:23:56 +00001561 std::shared_ptr<PCHContainerOperations> PCHs,
1562 CodeCompleteOptions Opts, SpeculativeFuzzyFind *SpecFuzzyFind) {
Eric Liub1d75422018-10-02 10:43:55 +00001563 return CodeCompleteFlow(FileName,
1564 Preamble ? Preamble->Includes : IncludeStructure(),
1565 SpecFuzzyFind, Opts)
Sam McCall3f0243f2018-07-03 08:09:29 +00001566 .run({FileName, Command, Preamble, Contents, Pos, VFS, PCHs});
Sam McCall98775c52017-12-04 13:49:59 +00001567}
1568
Sam McCalld1a7a372018-01-31 13:40:48 +00001569SignatureHelp signatureHelp(PathRef FileName,
Ilya Biryukov940901e2017-12-13 12:51:22 +00001570 const tooling::CompileCommand &Command,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001571 const PreambleData *Preamble,
1572 llvm::StringRef Contents, Position Pos,
1573 llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS,
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +00001574 std::shared_ptr<PCHContainerOperations> PCHs,
Sam McCall046557b2018-09-03 16:37:59 +00001575 const SymbolIndex *Index) {
Sam McCall98775c52017-12-04 13:49:59 +00001576 SignatureHelp Result;
1577 clang::CodeCompleteOptions Options;
1578 Options.IncludeGlobals = false;
1579 Options.IncludeMacros = false;
1580 Options.IncludeCodePatterns = false;
Ilya Biryukov43714502018-05-16 12:32:44 +00001581 Options.IncludeBriefComments = false;
Sam McCall3f0243f2018-07-03 08:09:29 +00001582 IncludeStructure PreambleInclusions; // Unused for signatureHelp
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +00001583 semaCodeComplete(
1584 llvm::make_unique<SignatureHelpCollector>(Options, Index, Result),
1585 Options,
1586 {FileName, Command, Preamble, Contents, Pos, std::move(VFS),
1587 std::move(PCHs)});
Sam McCall98775c52017-12-04 13:49:59 +00001588 return Result;
1589}
1590
Marc-Andre Laperle945b5a32018-06-05 14:01:40 +00001591bool isIndexedForCodeCompletion(const NamedDecl &ND, ASTContext &ASTCtx) {
Haojian Wudd61ccb2018-12-03 12:53:19 +00001592 auto InTopLevelScope = [](const NamedDecl &ND) {
1593 switch (ND.getDeclContext()->getDeclKind()) {
1594 case Decl::TranslationUnit:
1595 case Decl::Namespace:
1596 case Decl::LinkageSpec:
1597 return true;
1598 default:
1599 break;
1600 };
1601 return false;
1602 };
1603 if (InTopLevelScope(ND))
1604 return true;
1605
1606 if (const auto *EnumDecl = dyn_cast<clang::EnumDecl>(ND.getDeclContext()))
1607 return InTopLevelScope(*EnumDecl) && !EnumDecl->isScoped();
1608
1609 return false;
Marc-Andre Laperle945b5a32018-06-05 14:01:40 +00001610}
1611
Sam McCall27c979a2018-06-29 14:47:57 +00001612CompletionItem CodeCompletion::render(const CodeCompleteOptions &Opts) const {
1613 CompletionItem LSP;
Eric Liu83f63e42018-09-03 10:18:21 +00001614 const auto *InsertInclude = Includes.empty() ? nullptr : &Includes[0];
1615 LSP.label = ((InsertInclude && InsertInclude->Insertion)
1616 ? Opts.IncludeIndicator.Insert
1617 : Opts.IncludeIndicator.NoInsert) +
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001618 (Opts.ShowOrigins ? "[" + llvm::to_string(Origin) + "]" : "") +
Sam McCall27c979a2018-06-29 14:47:57 +00001619 RequiredQualifier + Name + Signature;
Sam McCall2161ec72018-07-05 06:20:41 +00001620
Sam McCall27c979a2018-06-29 14:47:57 +00001621 LSP.kind = Kind;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001622 LSP.detail = BundleSize > 1 ? llvm::formatv("[{0} overloads]", BundleSize)
1623 : ReturnType;
Eric Liu6df66002018-09-06 18:52:26 +00001624 LSP.deprecated = Deprecated;
Eric Liu83f63e42018-09-03 10:18:21 +00001625 if (InsertInclude)
1626 LSP.detail += "\n" + InsertInclude->Header;
Sam McCall27c979a2018-06-29 14:47:57 +00001627 LSP.documentation = Documentation;
1628 LSP.sortText = sortText(Score.Total, Name);
1629 LSP.filterText = Name;
Kadir Cetinkayaa9c9d002018-08-13 08:23:01 +00001630 LSP.textEdit = {CompletionTokenRange, RequiredQualifier + Name};
Fangrui Song445bdd12018-09-05 08:01:37 +00001631 // Merge continuous additionalTextEdits into main edit. The main motivation
Kadir Cetinkayaa9c9d002018-08-13 08:23:01 +00001632 // behind this is to help LSP clients, it seems most of them are confused when
1633 // they are provided with additionalTextEdits that are consecutive to main
1634 // edit.
1635 // Note that we store additional text edits from back to front in a line. That
1636 // is mainly to help LSP clients again, so that changes do not effect each
1637 // other.
1638 for (const auto &FixIt : FixIts) {
Haojian Wuaa3ed5a2019-01-25 15:14:03 +00001639 if (isRangeConsecutive(FixIt.range, LSP.textEdit->range)) {
Kadir Cetinkayaa9c9d002018-08-13 08:23:01 +00001640 LSP.textEdit->newText = FixIt.newText + LSP.textEdit->newText;
1641 LSP.textEdit->range.start = FixIt.range.start;
1642 } else {
1643 LSP.additionalTextEdits.push_back(FixIt);
1644 }
1645 }
Kadir Cetinkaya516fcda2018-08-23 12:19:39 +00001646 if (Opts.EnableSnippets)
1647 LSP.textEdit->newText += SnippetSuffix;
Kadir Cetinkaya6c9f15c2018-08-17 15:42:54 +00001648
Kadir Cetinkayaa9c9d002018-08-13 08:23:01 +00001649 // FIXME(kadircet): Do not even fill insertText after making sure textEdit is
1650 // compatible with most of the editors.
1651 LSP.insertText = LSP.textEdit->newText;
Sam McCall27c979a2018-06-29 14:47:57 +00001652 LSP.insertTextFormat = Opts.EnableSnippets ? InsertTextFormat::Snippet
1653 : InsertTextFormat::PlainText;
Eric Liu83f63e42018-09-03 10:18:21 +00001654 if (InsertInclude && InsertInclude->Insertion)
1655 LSP.additionalTextEdits.push_back(*InsertInclude->Insertion);
Eric Liu6df66002018-09-06 18:52:26 +00001656
Sam McCall27c979a2018-06-29 14:47:57 +00001657 return LSP;
1658}
1659
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001660llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const CodeCompletion &C) {
Sam McCalle746a2b2018-07-02 11:13:16 +00001661 // For now just lean on CompletionItem.
1662 return OS << C.render(CodeCompleteOptions());
1663}
1664
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001665llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
1666 const CodeCompleteResult &R) {
Sam McCalle746a2b2018-07-02 11:13:16 +00001667 OS << "CodeCompleteResult: " << R.Completions.size() << (R.HasMore ? "+" : "")
Eric Liu5d2a8072018-07-23 10:56:37 +00001668 << " (" << getCompletionKindString(R.Context) << ")"
Sam McCalle746a2b2018-07-02 11:13:16 +00001669 << " items:\n";
1670 for (const auto &C : R.Completions)
1671 OS << C << "\n";
1672 return OS;
1673}
1674
Sam McCall98775c52017-12-04 13:49:59 +00001675} // namespace clangd
1676} // namespace clang