1 //===--- CodeComplete.cpp ----------------------------------------*- C++-*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // Code completion 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 14 // 15 // 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. 17 // 18 //===----------------------------------------------------------------------===// 19 20 #include "CodeComplete.h" 21 #include "AST.h" 22 #include "CodeCompletionStrings.h" 23 #include "Compiler.h" 24 #include "Diagnostics.h" 25 #include "ExpectedTypes.h" 26 #include "FileDistance.h" 27 #include "FuzzyMatch.h" 28 #include "Headers.h" 29 #include "Hover.h" 30 #include "Preamble.h" 31 #include "Protocol.h" 32 #include "Quality.h" 33 #include "SourceCode.h" 34 #include "TUScheduler.h" 35 #include "URI.h" 36 #include "index/Index.h" 37 #include "index/Symbol.h" 38 #include "index/SymbolOrigin.h" 39 #include "support/Logger.h" 40 #include "support/Threading.h" 41 #include "support/Trace.h" 42 #include "clang/AST/Decl.h" 43 #include "clang/AST/DeclBase.h" 44 #include "clang/Basic/CharInfo.h" 45 #include "clang/Basic/LangOptions.h" 46 #include "clang/Basic/SourceLocation.h" 47 #include "clang/Format/Format.h" 48 #include "clang/Frontend/CompilerInstance.h" 49 #include "clang/Frontend/FrontendActions.h" 50 #include "clang/Lex/ExternalPreprocessorSource.h" 51 #include "clang/Lex/Preprocessor.h" 52 #include "clang/Lex/PreprocessorOptions.h" 53 #include "clang/Sema/CodeCompleteConsumer.h" 54 #include "clang/Sema/DeclSpec.h" 55 #include "clang/Sema/Sema.h" 56 #include "llvm/ADT/ArrayRef.h" 57 #include "llvm/ADT/None.h" 58 #include "llvm/ADT/Optional.h" 59 #include "llvm/ADT/SmallVector.h" 60 #include "llvm/ADT/StringExtras.h" 61 #include "llvm/ADT/StringRef.h" 62 #include "llvm/Support/Compiler.h" 63 #include "llvm/Support/Debug.h" 64 #include "llvm/Support/Error.h" 65 #include "llvm/Support/Format.h" 66 #include "llvm/Support/FormatVariadic.h" 67 #include "llvm/Support/ScopedPrinter.h" 68 #include <algorithm> 69 #include <iterator> 70 71 // We log detailed candidate here if you run with -debug-only=codecomplete. 72 #define DEBUG_TYPE "CodeComplete" 73 74 namespace clang { 75 namespace clangd { 76 namespace { 77 78 CompletionItemKind toCompletionItemKind(index::SymbolKind Kind) { 79 using SK = index::SymbolKind; 80 switch (Kind) { 81 case SK::Unknown: 82 return CompletionItemKind::Missing; 83 case SK::Module: 84 case SK::Namespace: 85 case SK::NamespaceAlias: 86 return CompletionItemKind::Module; 87 case SK::Macro: 88 return CompletionItemKind::Text; 89 case SK::Enum: 90 return CompletionItemKind::Enum; 91 case SK::Struct: 92 return CompletionItemKind::Struct; 93 case SK::Class: 94 case SK::Protocol: 95 case SK::Extension: 96 case SK::Union: 97 return CompletionItemKind::Class; 98 case SK::TypeAlias: 99 // We use the same kind as the VSCode C++ extension. 100 // FIXME: pick a better option when we have one. 101 return CompletionItemKind::Interface; 102 case SK::Using: 103 return CompletionItemKind::Reference; 104 case SK::Function: 105 case SK::ConversionFunction: 106 return CompletionItemKind::Function; 107 case SK::Variable: 108 case SK::Parameter: 109 case SK::NonTypeTemplateParm: 110 return CompletionItemKind::Variable; 111 case SK::Field: 112 return CompletionItemKind::Field; 113 case SK::EnumConstant: 114 return CompletionItemKind::EnumMember; 115 case SK::InstanceMethod: 116 case SK::ClassMethod: 117 case SK::StaticMethod: 118 case SK::Destructor: 119 return CompletionItemKind::Method; 120 case SK::InstanceProperty: 121 case SK::ClassProperty: 122 case SK::StaticProperty: 123 return CompletionItemKind::Property; 124 case SK::Constructor: 125 return CompletionItemKind::Constructor; 126 case SK::TemplateTypeParm: 127 case SK::TemplateTemplateParm: 128 return CompletionItemKind::TypeParameter; 129 } 130 llvm_unreachable("Unhandled clang::index::SymbolKind."); 131 } 132 133 CompletionItemKind 134 toCompletionItemKind(CodeCompletionResult::ResultKind ResKind, 135 const NamedDecl *Decl, 136 CodeCompletionContext::Kind CtxKind) { 137 if (Decl) 138 return toCompletionItemKind(index::getSymbolInfo(Decl).Kind); 139 if (CtxKind == CodeCompletionContext::CCC_IncludedFile) 140 return CompletionItemKind::File; 141 switch (ResKind) { 142 case CodeCompletionResult::RK_Declaration: 143 llvm_unreachable("RK_Declaration without Decl"); 144 case CodeCompletionResult::RK_Keyword: 145 return CompletionItemKind::Keyword; 146 case CodeCompletionResult::RK_Macro: 147 return CompletionItemKind::Text; // unfortunately, there's no 'Macro' 148 // completion items in LSP. 149 case CodeCompletionResult::RK_Pattern: 150 return CompletionItemKind::Snippet; 151 } 152 llvm_unreachable("Unhandled CodeCompletionResult::ResultKind."); 153 } 154 155 // Identifier code completion result. 156 struct RawIdentifier { 157 llvm::StringRef Name; 158 unsigned References; // # of usages in file. 159 }; 160 161 /// A code completion result, in clang-native form. 162 /// It may be promoted to a CompletionItem if it's among the top-ranked results. 163 struct CompletionCandidate { 164 llvm::StringRef Name; // Used for filtering and sorting. 165 // We may have a result from Sema, from the index, or both. 166 const CodeCompletionResult *SemaResult = nullptr; 167 const Symbol *IndexResult = nullptr; 168 const RawIdentifier *IdentifierResult = nullptr; 169 llvm::SmallVector<llvm::StringRef, 1> RankedIncludeHeaders; 170 171 // Returns a token identifying the overload set this is part of. 172 // 0 indicates it's not part of any overload set. 173 size_t overloadSet(const CodeCompleteOptions &Opts) const { 174 if (!Opts.BundleOverloads.getValueOr(false)) 175 return 0; 176 llvm::SmallString<256> Scratch; 177 if (IndexResult) { 178 switch (IndexResult->SymInfo.Kind) { 179 case index::SymbolKind::ClassMethod: 180 case index::SymbolKind::InstanceMethod: 181 case index::SymbolKind::StaticMethod: 182 #ifndef NDEBUG 183 llvm_unreachable("Don't expect members from index in code completion"); 184 #else 185 LLVM_FALLTHROUGH; 186 #endif 187 case index::SymbolKind::Function: 188 // We can't group overloads together that need different #includes. 189 // This could break #include insertion. 190 return llvm::hash_combine( 191 (IndexResult->Scope + IndexResult->Name).toStringRef(Scratch), 192 headerToInsertIfAllowed(Opts).getValueOr("")); 193 default: 194 return 0; 195 } 196 } 197 if (SemaResult) { 198 // We need to make sure we're consistent with the IndexResult case! 199 const NamedDecl *D = SemaResult->Declaration; 200 if (!D || !D->isFunctionOrFunctionTemplate()) 201 return 0; 202 { 203 llvm::raw_svector_ostream OS(Scratch); 204 D->printQualifiedName(OS); 205 } 206 return llvm::hash_combine(Scratch, 207 headerToInsertIfAllowed(Opts).getValueOr("")); 208 } 209 assert(IdentifierResult); 210 return 0; 211 } 212 213 // The best header to include if include insertion is allowed. 214 llvm::Optional<llvm::StringRef> 215 headerToInsertIfAllowed(const CodeCompleteOptions &Opts) const { 216 if (Opts.InsertIncludes == CodeCompleteOptions::NeverInsert || 217 RankedIncludeHeaders.empty()) 218 return None; 219 if (SemaResult && SemaResult->Declaration) { 220 // Avoid inserting new #include if the declaration is found in the current 221 // file e.g. the symbol is forward declared. 222 auto &SM = SemaResult->Declaration->getASTContext().getSourceManager(); 223 for (const Decl *RD : SemaResult->Declaration->redecls()) 224 if (SM.isInMainFile(SM.getExpansionLoc(RD->getBeginLoc()))) 225 return None; 226 } 227 return RankedIncludeHeaders[0]; 228 } 229 230 using Bundle = llvm::SmallVector<CompletionCandidate, 4>; 231 }; 232 using ScoredBundle = 233 std::pair<CompletionCandidate::Bundle, CodeCompletion::Scores>; 234 struct ScoredBundleGreater { 235 bool operator()(const ScoredBundle &L, const ScoredBundle &R) { 236 if (L.second.Total != R.second.Total) 237 return L.second.Total > R.second.Total; 238 return L.first.front().Name < 239 R.first.front().Name; // Earlier name is better. 240 } 241 }; 242 243 // Assembles a code completion out of a bundle of >=1 completion candidates. 244 // Many of the expensive strings are only computed at this point, once we know 245 // the candidate bundle is going to be returned. 246 // 247 // Many fields are the same for all candidates in a bundle (e.g. name), and are 248 // computed from the first candidate, in the constructor. 249 // Others vary per candidate, so add() must be called for remaining candidates. 250 struct CodeCompletionBuilder { 251 CodeCompletionBuilder(ASTContext *ASTCtx, const CompletionCandidate &C, 252 CodeCompletionString *SemaCCS, 253 llvm::ArrayRef<std::string> QueryScopes, 254 const IncludeInserter &Includes, 255 llvm::StringRef FileName, 256 CodeCompletionContext::Kind ContextKind, 257 const CodeCompleteOptions &Opts, bool GenerateSnippets) 258 : ASTCtx(ASTCtx), ExtractDocumentation(Opts.IncludeComments), 259 EnableFunctionArgSnippets(Opts.EnableFunctionArgSnippets), 260 GenerateSnippets(GenerateSnippets) { 261 add(C, SemaCCS); 262 if (C.SemaResult) { 263 assert(ASTCtx); 264 Completion.Origin |= SymbolOrigin::AST; 265 Completion.Name = std::string(llvm::StringRef(SemaCCS->getTypedText())); 266 if (Completion.Scope.empty()) { 267 if ((C.SemaResult->Kind == CodeCompletionResult::RK_Declaration) || 268 (C.SemaResult->Kind == CodeCompletionResult::RK_Pattern)) 269 if (const auto *D = C.SemaResult->getDeclaration()) 270 if (const auto *ND = dyn_cast<NamedDecl>(D)) 271 Completion.Scope = std::string( 272 splitQualifiedName(printQualifiedName(*ND)).first); 273 } 274 Completion.Kind = toCompletionItemKind( 275 C.SemaResult->Kind, C.SemaResult->Declaration, ContextKind); 276 // Sema could provide more info on whether the completion was a file or 277 // folder. 278 if (Completion.Kind == CompletionItemKind::File && 279 Completion.Name.back() == '/') 280 Completion.Kind = CompletionItemKind::Folder; 281 for (const auto &FixIt : C.SemaResult->FixIts) { 282 Completion.FixIts.push_back(toTextEdit( 283 FixIt, ASTCtx->getSourceManager(), ASTCtx->getLangOpts())); 284 } 285 llvm::sort(Completion.FixIts, [](const TextEdit &X, const TextEdit &Y) { 286 return std::tie(X.range.start.line, X.range.start.character) < 287 std::tie(Y.range.start.line, Y.range.start.character); 288 }); 289 Completion.Deprecated |= 290 (C.SemaResult->Availability == CXAvailability_Deprecated); 291 } 292 if (C.IndexResult) { 293 Completion.Origin |= C.IndexResult->Origin; 294 if (Completion.Scope.empty()) 295 Completion.Scope = std::string(C.IndexResult->Scope); 296 if (Completion.Kind == CompletionItemKind::Missing) 297 Completion.Kind = toCompletionItemKind(C.IndexResult->SymInfo.Kind); 298 if (Completion.Name.empty()) 299 Completion.Name = std::string(C.IndexResult->Name); 300 // If the completion was visible to Sema, no qualifier is needed. This 301 // avoids unneeded qualifiers in cases like with `using ns::X`. 302 if (Completion.RequiredQualifier.empty() && !C.SemaResult) { 303 llvm::StringRef ShortestQualifier = C.IndexResult->Scope; 304 for (llvm::StringRef Scope : QueryScopes) { 305 llvm::StringRef Qualifier = C.IndexResult->Scope; 306 if (Qualifier.consume_front(Scope) && 307 Qualifier.size() < ShortestQualifier.size()) 308 ShortestQualifier = Qualifier; 309 } 310 Completion.RequiredQualifier = std::string(ShortestQualifier); 311 } 312 Completion.Deprecated |= (C.IndexResult->Flags & Symbol::Deprecated); 313 } 314 if (C.IdentifierResult) { 315 Completion.Origin |= SymbolOrigin::Identifier; 316 Completion.Kind = CompletionItemKind::Text; 317 Completion.Name = std::string(C.IdentifierResult->Name); 318 } 319 320 // Turn absolute path into a literal string that can be #included. 321 auto Inserted = [&](llvm::StringRef Header) 322 -> llvm::Expected<std::pair<std::string, bool>> { 323 auto ResolvedDeclaring = 324 URI::resolve(C.IndexResult->CanonicalDeclaration.FileURI, FileName); 325 if (!ResolvedDeclaring) 326 return ResolvedDeclaring.takeError(); 327 auto ResolvedInserted = toHeaderFile(Header, FileName); 328 if (!ResolvedInserted) 329 return ResolvedInserted.takeError(); 330 auto Spelled = Includes.calculateIncludePath(*ResolvedInserted, FileName); 331 if (!Spelled) 332 return llvm::createStringError(llvm::inconvertibleErrorCode(), 333 "Header not on include path"); 334 return std::make_pair( 335 std::move(*Spelled), 336 Includes.shouldInsertInclude(*ResolvedDeclaring, *ResolvedInserted)); 337 }; 338 bool ShouldInsert = C.headerToInsertIfAllowed(Opts).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)); 347 } else 348 log("Failed to generate include insertion edits for adding header " 349 "(FileURI='{0}', IncludeHeader='{1}') into {2}: {3}", 350 C.IndexResult->CanonicalDeclaration.FileURI, Inc, FileName, 351 ToInclude.takeError()); 352 } 353 // Prefer includes that do not need edits (i.e. already exist). 354 std::stable_partition(Completion.Includes.begin(), 355 Completion.Includes.end(), 356 [](const CodeCompletion::IncludeCandidate &I) { 357 return !I.Insertion.hasValue(); 358 }); 359 } 360 361 void add(const CompletionCandidate &C, CodeCompletionString *SemaCCS) { 362 assert(bool(C.SemaResult) == bool(SemaCCS)); 363 Bundled.emplace_back(); 364 BundledEntry &S = Bundled.back(); 365 if (C.SemaResult) { 366 bool IsPattern = C.SemaResult->Kind == CodeCompletionResult::RK_Pattern; 367 getSignature(*SemaCCS, &S.Signature, &S.SnippetSuffix, 368 &Completion.RequiredQualifier, IsPattern); 369 S.ReturnType = getReturnType(*SemaCCS); 370 } else if (C.IndexResult) { 371 S.Signature = std::string(C.IndexResult->Signature); 372 S.SnippetSuffix = std::string(C.IndexResult->CompletionSnippetSuffix); 373 S.ReturnType = std::string(C.IndexResult->ReturnType); 374 } 375 if (ExtractDocumentation && !Completion.Documentation) { 376 auto SetDoc = [&](llvm::StringRef Doc) { 377 if (!Doc.empty()) { 378 Completion.Documentation.emplace(); 379 parseDocumentation(Doc, *Completion.Documentation); 380 } 381 }; 382 if (C.IndexResult) { 383 SetDoc(C.IndexResult->Documentation); 384 } else if (C.SemaResult) { 385 SetDoc(getDocComment(*ASTCtx, *C.SemaResult, 386 /*CommentsFromHeader=*/false)); 387 } 388 } 389 } 390 391 CodeCompletion build() { 392 Completion.ReturnType = summarizeReturnType(); 393 Completion.Signature = summarizeSignature(); 394 Completion.SnippetSuffix = summarizeSnippet(); 395 Completion.BundleSize = Bundled.size(); 396 return std::move(Completion); 397 } 398 399 private: 400 struct BundledEntry { 401 std::string SnippetSuffix; 402 std::string Signature; 403 std::string ReturnType; 404 }; 405 406 // If all BundledEntries have the same value for a property, return it. 407 template <std::string BundledEntry::*Member> 408 const std::string *onlyValue() const { 409 auto B = Bundled.begin(), E = Bundled.end(); 410 for (auto I = B + 1; I != E; ++I) 411 if (I->*Member != B->*Member) 412 return nullptr; 413 return &(B->*Member); 414 } 415 416 template <bool BundledEntry::*Member> const bool *onlyValue() const { 417 auto B = Bundled.begin(), E = Bundled.end(); 418 for (auto I = B + 1; I != E; ++I) 419 if (I->*Member != B->*Member) 420 return nullptr; 421 return &(B->*Member); 422 } 423 424 std::string summarizeReturnType() const { 425 if (auto *RT = onlyValue<&BundledEntry::ReturnType>()) 426 return *RT; 427 return ""; 428 } 429 430 std::string summarizeSnippet() const { 431 if (!GenerateSnippets) 432 return ""; 433 auto *Snippet = onlyValue<&BundledEntry::SnippetSuffix>(); 434 if (!Snippet) 435 // All bundles are function calls. 436 // FIXME(ibiryukov): sometimes add template arguments to a snippet, e.g. 437 // we need to complete 'forward<$1>($0)'. 438 return "($0)"; 439 if (EnableFunctionArgSnippets) 440 return *Snippet; 441 442 // Replace argument snippets with a simplified pattern. 443 if (Snippet->empty()) 444 return ""; 445 if (Completion.Kind == CompletionItemKind::Function || 446 Completion.Kind == CompletionItemKind::Method) { 447 // Functions snippets can be of 2 types: 448 // - containing only function arguments, e.g. 449 // foo(${1:int p1}, ${2:int p2}); 450 // We transform this pattern to '($0)' or '()'. 451 // - template arguments and function arguments, e.g. 452 // foo<${1:class}>(${2:int p1}). 453 // We transform this pattern to '<$1>()$0' or '<$0>()'. 454 455 bool EmptyArgs = llvm::StringRef(*Snippet).endswith("()"); 456 if (Snippet->front() == '<') 457 return EmptyArgs ? "<$1>()$0" : "<$1>($0)"; 458 if (Snippet->front() == '(') 459 return EmptyArgs ? "()" : "($0)"; 460 return *Snippet; // Not an arg snippet? 461 } 462 // 'CompletionItemKind::Interface' matches template type aliases. 463 if (Completion.Kind == CompletionItemKind::Interface || 464 Completion.Kind == CompletionItemKind::Class) { 465 if (Snippet->front() != '<') 466 return *Snippet; // Not an arg snippet? 467 468 // Classes and template using aliases can only have template arguments, 469 // e.g. Foo<${1:class}>. 470 if (llvm::StringRef(*Snippet).endswith("<>")) 471 return "<>"; // can happen with defaulted template arguments. 472 return "<$0>"; 473 } 474 return *Snippet; 475 } 476 477 std::string summarizeSignature() const { 478 if (auto *Signature = onlyValue<&BundledEntry::Signature>()) 479 return *Signature; 480 // All bundles are function calls. 481 return "(…)"; 482 } 483 484 // ASTCtx can be nullptr if not run with sema. 485 ASTContext *ASTCtx; 486 CodeCompletion Completion; 487 llvm::SmallVector<BundledEntry, 1> Bundled; 488 bool ExtractDocumentation; 489 bool EnableFunctionArgSnippets; 490 /// When false, no snippets are generated argument lists. 491 bool GenerateSnippets; 492 }; 493 494 // Determine the symbol ID for a Sema code completion result, if possible. 495 llvm::Optional<SymbolID> getSymbolID(const CodeCompletionResult &R, 496 const SourceManager &SM) { 497 switch (R.Kind) { 498 case CodeCompletionResult::RK_Declaration: 499 case CodeCompletionResult::RK_Pattern: { 500 // Computing USR caches linkage, which may change after code completion. 501 if (hasUnstableLinkage(R.Declaration)) 502 return llvm::None; 503 return clang::clangd::getSymbolID(R.Declaration); 504 } 505 case CodeCompletionResult::RK_Macro: 506 return clang::clangd::getSymbolID(R.Macro->getName(), R.MacroDefInfo, SM); 507 case CodeCompletionResult::RK_Keyword: 508 return None; 509 } 510 llvm_unreachable("unknown CodeCompletionResult kind"); 511 } 512 513 // Scopes of the partial identifier we're trying to complete. 514 // It is used when we query the index for more completion results. 515 struct SpecifiedScope { 516 // The scopes we should look in, determined by Sema. 517 // 518 // If the qualifier was fully resolved, we look for completions in these 519 // scopes; if there is an unresolved part of the qualifier, it should be 520 // resolved within these scopes. 521 // 522 // Examples of qualified completion: 523 // 524 // "::vec" => {""} 525 // "using namespace std; ::vec^" => {"", "std::"} 526 // "namespace ns {using namespace std;} ns::^" => {"ns::", "std::"} 527 // "std::vec^" => {""} // "std" unresolved 528 // 529 // Examples of unqualified completion: 530 // 531 // "vec^" => {""} 532 // "using namespace std; vec^" => {"", "std::"} 533 // "using namespace std; namespace ns { vec^ }" => {"ns::", "std::", ""} 534 // 535 // "" for global namespace, "ns::" for normal namespace. 536 std::vector<std::string> AccessibleScopes; 537 // The full scope qualifier as typed by the user (without the leading "::"). 538 // Set if the qualifier is not fully resolved by Sema. 539 llvm::Optional<std::string> UnresolvedQualifier; 540 541 // Construct scopes being queried in indexes. The results are deduplicated. 542 // This method format the scopes to match the index request representation. 543 std::vector<std::string> scopesForIndexQuery() { 544 std::set<std::string> Results; 545 for (llvm::StringRef AS : AccessibleScopes) 546 Results.insert( 547 (AS + (UnresolvedQualifier ? *UnresolvedQualifier : "")).str()); 548 return {Results.begin(), Results.end()}; 549 } 550 }; 551 552 // Get all scopes that will be queried in indexes and whether symbols from 553 // any scope is allowed. The first scope in the list is the preferred scope 554 // (e.g. enclosing namespace). 555 std::pair<std::vector<std::string>, bool> 556 getQueryScopes(CodeCompletionContext &CCContext, const Sema &CCSema, 557 const CompletionPrefix &HeuristicPrefix, 558 const CodeCompleteOptions &Opts) { 559 SpecifiedScope Scopes; 560 for (auto *Context : CCContext.getVisitedContexts()) { 561 if (isa<TranslationUnitDecl>(Context)) 562 Scopes.AccessibleScopes.push_back(""); // global namespace 563 else if (isa<NamespaceDecl>(Context)) 564 Scopes.AccessibleScopes.push_back(printNamespaceScope(*Context)); 565 } 566 567 const CXXScopeSpec *SemaSpecifier = 568 CCContext.getCXXScopeSpecifier().getValueOr(nullptr); 569 // Case 1: unqualified completion. 570 if (!SemaSpecifier) { 571 // Case 2 (exception): sema saw no qualifier, but there appears to be one! 572 // This can happen e.g. in incomplete macro expansions. Use heuristics. 573 if (!HeuristicPrefix.Qualifier.empty()) { 574 vlog("Sema said no scope specifier, but we saw {0} in the source code", 575 HeuristicPrefix.Qualifier); 576 StringRef SpelledSpecifier = HeuristicPrefix.Qualifier; 577 if (SpelledSpecifier.consume_front("::")) 578 Scopes.AccessibleScopes = {""}; 579 Scopes.UnresolvedQualifier = std::string(SpelledSpecifier); 580 return {Scopes.scopesForIndexQuery(), false}; 581 } 582 // The enclosing namespace must be first, it gets a quality boost. 583 std::vector<std::string> EnclosingAtFront; 584 std::string EnclosingScope = printNamespaceScope(*CCSema.CurContext); 585 EnclosingAtFront.push_back(EnclosingScope); 586 for (auto &S : Scopes.scopesForIndexQuery()) { 587 if (EnclosingScope != S) 588 EnclosingAtFront.push_back(std::move(S)); 589 } 590 // Allow AllScopes completion as there is no explicit scope qualifier. 591 return {EnclosingAtFront, Opts.AllScopes}; 592 } 593 // Case 3: sema saw and resolved a scope qualifier. 594 if (SemaSpecifier && SemaSpecifier->isValid()) 595 return {Scopes.scopesForIndexQuery(), false}; 596 597 // Case 4: There was a qualifier, and Sema didn't resolve it. 598 Scopes.AccessibleScopes.push_back(""); // Make sure global scope is included. 599 llvm::StringRef SpelledSpecifier = Lexer::getSourceText( 600 CharSourceRange::getCharRange(SemaSpecifier->getRange()), 601 CCSema.SourceMgr, clang::LangOptions()); 602 if (SpelledSpecifier.consume_front("::")) 603 Scopes.AccessibleScopes = {""}; 604 Scopes.UnresolvedQualifier = std::string(SpelledSpecifier); 605 // Sema excludes the trailing "::". 606 if (!Scopes.UnresolvedQualifier->empty()) 607 *Scopes.UnresolvedQualifier += "::"; 608 609 return {Scopes.scopesForIndexQuery(), false}; 610 } 611 612 // Should we perform index-based completion in a context of the specified kind? 613 // FIXME: consider allowing completion, but restricting the result types. 614 bool contextAllowsIndex(enum CodeCompletionContext::Kind K) { 615 switch (K) { 616 case CodeCompletionContext::CCC_TopLevel: 617 case CodeCompletionContext::CCC_ObjCInterface: 618 case CodeCompletionContext::CCC_ObjCImplementation: 619 case CodeCompletionContext::CCC_ObjCIvarList: 620 case CodeCompletionContext::CCC_ClassStructUnion: 621 case CodeCompletionContext::CCC_Statement: 622 case CodeCompletionContext::CCC_Expression: 623 case CodeCompletionContext::CCC_ObjCMessageReceiver: 624 case CodeCompletionContext::CCC_EnumTag: 625 case CodeCompletionContext::CCC_UnionTag: 626 case CodeCompletionContext::CCC_ClassOrStructTag: 627 case CodeCompletionContext::CCC_ObjCProtocolName: 628 case CodeCompletionContext::CCC_Namespace: 629 case CodeCompletionContext::CCC_Type: 630 case CodeCompletionContext::CCC_ParenthesizedExpression: 631 case CodeCompletionContext::CCC_ObjCInterfaceName: 632 case CodeCompletionContext::CCC_ObjCCategoryName: 633 case CodeCompletionContext::CCC_Symbol: 634 case CodeCompletionContext::CCC_SymbolOrNewName: 635 return true; 636 case CodeCompletionContext::CCC_OtherWithMacros: 637 case CodeCompletionContext::CCC_DotMemberAccess: 638 case CodeCompletionContext::CCC_ArrowMemberAccess: 639 case CodeCompletionContext::CCC_ObjCPropertyAccess: 640 case CodeCompletionContext::CCC_MacroName: 641 case CodeCompletionContext::CCC_MacroNameUse: 642 case CodeCompletionContext::CCC_PreprocessorExpression: 643 case CodeCompletionContext::CCC_PreprocessorDirective: 644 case CodeCompletionContext::CCC_SelectorName: 645 case CodeCompletionContext::CCC_TypeQualifiers: 646 case CodeCompletionContext::CCC_ObjCInstanceMessage: 647 case CodeCompletionContext::CCC_ObjCClassMessage: 648 case CodeCompletionContext::CCC_IncludedFile: 649 // FIXME: Provide identifier based completions for the following contexts: 650 case CodeCompletionContext::CCC_Other: // Be conservative. 651 case CodeCompletionContext::CCC_NaturalLanguage: 652 case CodeCompletionContext::CCC_Recovery: 653 case CodeCompletionContext::CCC_NewName: 654 return false; 655 } 656 llvm_unreachable("unknown code completion context"); 657 } 658 659 static bool isInjectedClass(const NamedDecl &D) { 660 if (auto *R = dyn_cast_or_null<RecordDecl>(&D)) 661 if (R->isInjectedClassName()) 662 return true; 663 return false; 664 } 665 666 // Some member calls are blacklisted because they're so rarely useful. 667 static bool isBlacklistedMember(const NamedDecl &D) { 668 // Destructor completion is rarely useful, and works inconsistently. 669 // (s.^ completes ~string, but s.~st^ is an error). 670 if (D.getKind() == Decl::CXXDestructor) 671 return true; 672 // Injected name may be useful for A::foo(), but who writes A::A::foo()? 673 if (isInjectedClass(D)) 674 return true; 675 // Explicit calls to operators are also rare. 676 auto NameKind = D.getDeclName().getNameKind(); 677 if (NameKind == DeclarationName::CXXOperatorName || 678 NameKind == DeclarationName::CXXLiteralOperatorName || 679 NameKind == DeclarationName::CXXConversionFunctionName) 680 return true; 681 return false; 682 } 683 684 // The CompletionRecorder captures Sema code-complete output, including context. 685 // It filters out ignored results (but doesn't apply fuzzy-filtering yet). 686 // It doesn't do scoring or conversion to CompletionItem yet, as we want to 687 // merge with index results first. 688 // Generally the fields and methods of this object should only be used from 689 // within the callback. 690 struct CompletionRecorder : public CodeCompleteConsumer { 691 CompletionRecorder(const CodeCompleteOptions &Opts, 692 llvm::unique_function<void()> ResultsCallback) 693 : CodeCompleteConsumer(Opts.getClangCompleteOpts()), 694 CCContext(CodeCompletionContext::CCC_Other), Opts(Opts), 695 CCAllocator(std::make_shared<GlobalCodeCompletionAllocator>()), 696 CCTUInfo(CCAllocator), ResultsCallback(std::move(ResultsCallback)) { 697 assert(this->ResultsCallback); 698 } 699 700 std::vector<CodeCompletionResult> Results; 701 CodeCompletionContext CCContext; 702 Sema *CCSema = nullptr; // Sema that created the results. 703 // FIXME: Sema is scary. Can we store ASTContext and Preprocessor, instead? 704 705 void ProcessCodeCompleteResults(class Sema &S, CodeCompletionContext Context, 706 CodeCompletionResult *InResults, 707 unsigned NumResults) override final { 708 // Results from recovery mode are generally useless, and the callback after 709 // recovery (if any) is usually more interesting. To make sure we handle the 710 // future callback from sema, we just ignore all callbacks in recovery mode, 711 // as taking only results from recovery mode results in poor completion 712 // results. 713 // FIXME: in case there is no future sema completion callback after the 714 // recovery mode, we might still want to provide some results (e.g. trivial 715 // identifier-based completion). 716 if (Context.getKind() == CodeCompletionContext::CCC_Recovery) { 717 log("Code complete: Ignoring sema code complete callback with Recovery " 718 "context."); 719 return; 720 } 721 // If a callback is called without any sema result and the context does not 722 // support index-based completion, we simply skip it to give way to 723 // potential future callbacks with results. 724 if (NumResults == 0 && !contextAllowsIndex(Context.getKind())) 725 return; 726 if (CCSema) { 727 log("Multiple code complete callbacks (parser backtracked?). " 728 "Dropping results from context {0}, keeping results from {1}.", 729 getCompletionKindString(Context.getKind()), 730 getCompletionKindString(this->CCContext.getKind())); 731 return; 732 } 733 // Record the completion context. 734 CCSema = &S; 735 CCContext = Context; 736 737 // Retain the results we might want. 738 for (unsigned I = 0; I < NumResults; ++I) { 739 auto &Result = InResults[I]; 740 // Class members that are shadowed by subclasses are usually noise. 741 if (Result.Hidden && Result.Declaration && 742 Result.Declaration->isCXXClassMember()) 743 continue; 744 if (!Opts.IncludeIneligibleResults && 745 (Result.Availability == CXAvailability_NotAvailable || 746 Result.Availability == CXAvailability_NotAccessible)) 747 continue; 748 if (Result.Declaration && 749 !Context.getBaseType().isNull() // is this a member-access context? 750 && isBlacklistedMember(*Result.Declaration)) 751 continue; 752 // Skip injected class name when no class scope is not explicitly set. 753 // E.g. show injected A::A in `using A::A^` but not in "A^". 754 if (Result.Declaration && !Context.getCXXScopeSpecifier().hasValue() && 755 isInjectedClass(*Result.Declaration)) 756 continue; 757 // We choose to never append '::' to completion results in clangd. 758 Result.StartsNestedNameSpecifier = false; 759 Results.push_back(Result); 760 } 761 ResultsCallback(); 762 } 763 764 CodeCompletionAllocator &getAllocator() override { return *CCAllocator; } 765 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; } 766 767 // Returns the filtering/sorting name for Result, which must be from Results. 768 // Returned string is owned by this recorder (or the AST). 769 llvm::StringRef getName(const CodeCompletionResult &Result) { 770 switch (Result.Kind) { 771 case CodeCompletionResult::RK_Declaration: 772 if (auto *ID = Result.Declaration->getIdentifier()) 773 return ID->getName(); 774 break; 775 case CodeCompletionResult::RK_Keyword: 776 return Result.Keyword; 777 case CodeCompletionResult::RK_Macro: 778 return Result.Macro->getName(); 779 case CodeCompletionResult::RK_Pattern: 780 return Result.Pattern->getTypedText(); 781 } 782 auto *CCS = codeCompletionString(Result); 783 return CCS->getTypedText(); 784 } 785 786 // Build a CodeCompletion string for R, which must be from Results. 787 // The CCS will be owned by this recorder. 788 CodeCompletionString *codeCompletionString(const CodeCompletionResult &R) { 789 // CodeCompletionResult doesn't seem to be const-correct. We own it, anyway. 790 return const_cast<CodeCompletionResult &>(R).CreateCodeCompletionString( 791 *CCSema, CCContext, *CCAllocator, CCTUInfo, 792 /*IncludeBriefComments=*/false); 793 } 794 795 private: 796 CodeCompleteOptions Opts; 797 std::shared_ptr<GlobalCodeCompletionAllocator> CCAllocator; 798 CodeCompletionTUInfo CCTUInfo; 799 llvm::unique_function<void()> ResultsCallback; 800 }; 801 802 struct ScoredSignature { 803 // When set, requires documentation to be requested from the index with this 804 // ID. 805 llvm::Optional<SymbolID> IDForDoc; 806 SignatureInformation Signature; 807 SignatureQualitySignals Quality; 808 }; 809 810 class SignatureHelpCollector final : public CodeCompleteConsumer { 811 public: 812 SignatureHelpCollector(const clang::CodeCompleteOptions &CodeCompleteOpts, 813 const SymbolIndex *Index, SignatureHelp &SigHelp) 814 : CodeCompleteConsumer(CodeCompleteOpts), SigHelp(SigHelp), 815 Allocator(std::make_shared<clang::GlobalCodeCompletionAllocator>()), 816 CCTUInfo(Allocator), Index(Index) {} 817 818 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg, 819 OverloadCandidate *Candidates, 820 unsigned NumCandidates, 821 SourceLocation OpenParLoc) override { 822 assert(!OpenParLoc.isInvalid()); 823 SourceManager &SrcMgr = S.getSourceManager(); 824 OpenParLoc = SrcMgr.getFileLoc(OpenParLoc); 825 if (SrcMgr.isInMainFile(OpenParLoc)) 826 SigHelp.argListStart = sourceLocToPosition(SrcMgr, OpenParLoc); 827 else 828 elog("Location oustide main file in signature help: {0}", 829 OpenParLoc.printToString(SrcMgr)); 830 831 std::vector<ScoredSignature> ScoredSignatures; 832 SigHelp.signatures.reserve(NumCandidates); 833 ScoredSignatures.reserve(NumCandidates); 834 // FIXME(rwols): How can we determine the "active overload candidate"? 835 // Right now the overloaded candidates seem to be provided in a "best fit" 836 // order, so I'm not too worried about this. 837 SigHelp.activeSignature = 0; 838 assert(CurrentArg <= (unsigned)std::numeric_limits<int>::max() && 839 "too many arguments"); 840 SigHelp.activeParameter = static_cast<int>(CurrentArg); 841 for (unsigned I = 0; I < NumCandidates; ++I) { 842 OverloadCandidate Candidate = Candidates[I]; 843 // We want to avoid showing instantiated signatures, because they may be 844 // long in some cases (e.g. when 'T' is substituted with 'std::string', we 845 // would get 'std::basic_string<char>'). 846 if (auto *Func = Candidate.getFunction()) { 847 if (auto *Pattern = Func->getTemplateInstantiationPattern()) 848 Candidate = OverloadCandidate(Pattern); 849 } 850 851 const auto *CCS = Candidate.CreateSignatureString( 852 CurrentArg, S, *Allocator, CCTUInfo, true); 853 assert(CCS && "Expected the CodeCompletionString to be non-null"); 854 ScoredSignatures.push_back(processOverloadCandidate( 855 Candidate, *CCS, 856 Candidate.getFunction() 857 ? getDeclComment(S.getASTContext(), *Candidate.getFunction()) 858 : "")); 859 } 860 861 // Sema does not load the docs from the preamble, so we need to fetch extra 862 // docs from the index instead. 863 llvm::DenseMap<SymbolID, std::string> FetchedDocs; 864 if (Index) { 865 LookupRequest IndexRequest; 866 for (const auto &S : ScoredSignatures) { 867 if (!S.IDForDoc) 868 continue; 869 IndexRequest.IDs.insert(*S.IDForDoc); 870 } 871 Index->lookup(IndexRequest, [&](const Symbol &S) { 872 if (!S.Documentation.empty()) 873 FetchedDocs[S.ID] = std::string(S.Documentation); 874 }); 875 log("SigHelp: requested docs for {0} symbols from the index, got {1} " 876 "symbols with non-empty docs in the response", 877 IndexRequest.IDs.size(), FetchedDocs.size()); 878 } 879 880 llvm::sort(ScoredSignatures, [](const ScoredSignature &L, 881 const ScoredSignature &R) { 882 // Ordering follows: 883 // - Less number of parameters is better. 884 // - Function is better than FunctionType which is better than 885 // Function Template. 886 // - High score is better. 887 // - Shorter signature is better. 888 // - Alphabetically smaller is better. 889 if (L.Quality.NumberOfParameters != R.Quality.NumberOfParameters) 890 return L.Quality.NumberOfParameters < R.Quality.NumberOfParameters; 891 if (L.Quality.NumberOfOptionalParameters != 892 R.Quality.NumberOfOptionalParameters) 893 return L.Quality.NumberOfOptionalParameters < 894 R.Quality.NumberOfOptionalParameters; 895 if (L.Quality.Kind != R.Quality.Kind) { 896 using OC = CodeCompleteConsumer::OverloadCandidate; 897 switch (L.Quality.Kind) { 898 case OC::CK_Function: 899 return true; 900 case OC::CK_FunctionType: 901 return R.Quality.Kind != OC::CK_Function; 902 case OC::CK_FunctionTemplate: 903 return false; 904 } 905 llvm_unreachable("Unknown overload candidate type."); 906 } 907 if (L.Signature.label.size() != R.Signature.label.size()) 908 return L.Signature.label.size() < R.Signature.label.size(); 909 return L.Signature.label < R.Signature.label; 910 }); 911 912 for (auto &SS : ScoredSignatures) { 913 auto IndexDocIt = 914 SS.IDForDoc ? FetchedDocs.find(*SS.IDForDoc) : FetchedDocs.end(); 915 if (IndexDocIt != FetchedDocs.end()) 916 SS.Signature.documentation = IndexDocIt->second; 917 918 SigHelp.signatures.push_back(std::move(SS.Signature)); 919 } 920 } 921 922 GlobalCodeCompletionAllocator &getAllocator() override { return *Allocator; } 923 924 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; } 925 926 private: 927 void processParameterChunk(llvm::StringRef ChunkText, 928 SignatureInformation &Signature) const { 929 // (!) this is O(n), should still be fast compared to building ASTs. 930 unsigned ParamStartOffset = lspLength(Signature.label); 931 unsigned ParamEndOffset = ParamStartOffset + lspLength(ChunkText); 932 // A piece of text that describes the parameter that corresponds to 933 // the code-completion location within a function call, message send, 934 // macro invocation, etc. 935 Signature.label += ChunkText; 936 ParameterInformation Info; 937 Info.labelOffsets.emplace(ParamStartOffset, ParamEndOffset); 938 // FIXME: only set 'labelOffsets' when all clients migrate out of it. 939 Info.labelString = std::string(ChunkText); 940 941 Signature.parameters.push_back(std::move(Info)); 942 } 943 944 void processOptionalChunk(const CodeCompletionString &CCS, 945 SignatureInformation &Signature, 946 SignatureQualitySignals &Signal) const { 947 for (const auto &Chunk : CCS) { 948 switch (Chunk.Kind) { 949 case CodeCompletionString::CK_Optional: 950 assert(Chunk.Optional && 951 "Expected the optional code completion string to be non-null."); 952 processOptionalChunk(*Chunk.Optional, Signature, Signal); 953 break; 954 case CodeCompletionString::CK_VerticalSpace: 955 break; 956 case CodeCompletionString::CK_CurrentParameter: 957 case CodeCompletionString::CK_Placeholder: 958 processParameterChunk(Chunk.Text, Signature); 959 Signal.NumberOfOptionalParameters++; 960 break; 961 default: 962 Signature.label += Chunk.Text; 963 break; 964 } 965 } 966 } 967 968 // FIXME(ioeric): consider moving CodeCompletionString logic here to 969 // CompletionString.h. 970 ScoredSignature processOverloadCandidate(const OverloadCandidate &Candidate, 971 const CodeCompletionString &CCS, 972 llvm::StringRef DocComment) const { 973 SignatureInformation Signature; 974 SignatureQualitySignals Signal; 975 const char *ReturnType = nullptr; 976 977 Signature.documentation = formatDocumentation(CCS, DocComment); 978 Signal.Kind = Candidate.getKind(); 979 980 for (const auto &Chunk : CCS) { 981 switch (Chunk.Kind) { 982 case CodeCompletionString::CK_ResultType: 983 // A piece of text that describes the type of an entity or, 984 // for functions and methods, the return type. 985 assert(!ReturnType && "Unexpected CK_ResultType"); 986 ReturnType = Chunk.Text; 987 break; 988 case CodeCompletionString::CK_CurrentParameter: 989 case CodeCompletionString::CK_Placeholder: 990 processParameterChunk(Chunk.Text, Signature); 991 Signal.NumberOfParameters++; 992 break; 993 case CodeCompletionString::CK_Optional: { 994 // The rest of the parameters are defaulted/optional. 995 assert(Chunk.Optional && 996 "Expected the optional code completion string to be non-null."); 997 processOptionalChunk(*Chunk.Optional, Signature, Signal); 998 break; 999 } 1000 case CodeCompletionString::CK_VerticalSpace: 1001 break; 1002 default: 1003 Signature.label += Chunk.Text; 1004 break; 1005 } 1006 } 1007 if (ReturnType) { 1008 Signature.label += " -> "; 1009 Signature.label += ReturnType; 1010 } 1011 dlog("Signal for {0}: {1}", Signature, Signal); 1012 ScoredSignature Result; 1013 Result.Signature = std::move(Signature); 1014 Result.Quality = Signal; 1015 const FunctionDecl *Func = Candidate.getFunction(); 1016 if (Func && Result.Signature.documentation.empty()) { 1017 // Computing USR caches linkage, which may change after code completion. 1018 if (!hasUnstableLinkage(Func)) 1019 Result.IDForDoc = clangd::getSymbolID(Func); 1020 } 1021 return Result; 1022 } 1023 1024 SignatureHelp &SigHelp; 1025 std::shared_ptr<clang::GlobalCodeCompletionAllocator> Allocator; 1026 CodeCompletionTUInfo CCTUInfo; 1027 const SymbolIndex *Index; 1028 }; // SignatureHelpCollector 1029 1030 struct SemaCompleteInput { 1031 PathRef FileName; 1032 const tooling::CompileCommand &Command; 1033 const PreambleData &Preamble; 1034 const PreamblePatch &Patch; 1035 llvm::StringRef Contents; 1036 size_t Offset; 1037 llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS; 1038 }; 1039 1040 void loadMainFilePreambleMacros(const Preprocessor &PP, 1041 const PreambleData &Preamble) { 1042 // The ExternalPreprocessorSource has our macros, if we know where to look. 1043 // We can read all the macros using PreambleMacros->ReadDefinedMacros(), 1044 // but this includes transitively included files, so may deserialize a lot. 1045 ExternalPreprocessorSource *PreambleMacros = PP.getExternalSource(); 1046 // As we have the names of the macros, we can look up their IdentifierInfo 1047 // and then use this to load just the macros we want. 1048 IdentifierInfoLookup *PreambleIdentifiers = 1049 PP.getIdentifierTable().getExternalIdentifierLookup(); 1050 if (!PreambleIdentifiers || !PreambleMacros) 1051 return; 1052 for (const auto &MacroName : Preamble.Macros.Names) 1053 if (auto *II = PreambleIdentifiers->get(MacroName.getKey())) 1054 if (II->isOutOfDate()) 1055 PreambleMacros->updateOutOfDateIdentifier(*II); 1056 } 1057 1058 // Invokes Sema code completion on a file. 1059 // If \p Includes is set, it will be updated based on the compiler invocation. 1060 bool semaCodeComplete(std::unique_ptr<CodeCompleteConsumer> Consumer, 1061 const clang::CodeCompleteOptions &Options, 1062 const SemaCompleteInput &Input, 1063 IncludeStructure *Includes = nullptr) { 1064 trace::Span Tracer("Sema completion"); 1065 llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS = Input.VFS; 1066 if (Input.Preamble.StatCache) 1067 VFS = Input.Preamble.StatCache->getConsumingFS(std::move(VFS)); 1068 ParseInputs ParseInput; 1069 ParseInput.CompileCommand = Input.Command; 1070 ParseInput.FS = VFS; 1071 ParseInput.Contents = std::string(Input.Contents); 1072 1073 IgnoreDiagnostics IgnoreDiags; 1074 auto CI = buildCompilerInvocation(ParseInput, IgnoreDiags); 1075 if (!CI) { 1076 elog("Couldn't create CompilerInvocation"); 1077 return false; 1078 } 1079 auto &FrontendOpts = CI->getFrontendOpts(); 1080 FrontendOpts.SkipFunctionBodies = true; 1081 // Disable typo correction in Sema. 1082 CI->getLangOpts()->SpellChecking = false; 1083 // Code completion won't trigger in delayed template bodies. 1084 // This is on-by-default in windows to allow parsing SDK headers; we're only 1085 // disabling it for the main-file (not preamble). 1086 CI->getLangOpts()->DelayedTemplateParsing = false; 1087 // Setup code completion. 1088 FrontendOpts.CodeCompleteOpts = Options; 1089 FrontendOpts.CodeCompletionAt.FileName = std::string(Input.FileName); 1090 std::tie(FrontendOpts.CodeCompletionAt.Line, 1091 FrontendOpts.CodeCompletionAt.Column) = 1092 offsetToClangLineColumn(Input.Contents, Input.Offset); 1093 1094 std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer = 1095 llvm::MemoryBuffer::getMemBufferCopy(Input.Contents, Input.FileName); 1096 // The diagnostic options must be set before creating a CompilerInstance. 1097 CI->getDiagnosticOpts().IgnoreWarnings = true; 1098 // We reuse the preamble whether it's valid or not. This is a 1099 // correctness/performance tradeoff: building without a preamble is slow, and 1100 // completion is latency-sensitive. 1101 // However, if we're completing *inside* the preamble section of the draft, 1102 // overriding the preamble will break sema completion. Fortunately we can just 1103 // skip all includes in this case; these completions are really simple. 1104 PreambleBounds PreambleRegion = 1105 ComputePreambleBounds(*CI->getLangOpts(), ContentsBuffer.get(), 0); 1106 bool CompletingInPreamble = PreambleRegion.Size > Input.Offset; 1107 Input.Patch.apply(*CI); 1108 // NOTE: we must call BeginSourceFile after prepareCompilerInstance. Otherwise 1109 // the remapped buffers do not get freed. 1110 auto Clang = prepareCompilerInstance( 1111 std::move(CI), !CompletingInPreamble ? &Input.Preamble.Preamble : nullptr, 1112 std::move(ContentsBuffer), std::move(VFS), IgnoreDiags); 1113 Clang->getPreprocessorOpts().SingleFileParseMode = CompletingInPreamble; 1114 Clang->setCodeCompletionConsumer(Consumer.release()); 1115 1116 SyntaxOnlyAction Action; 1117 if (!Action.BeginSourceFile(*Clang, Clang->getFrontendOpts().Inputs[0])) { 1118 log("BeginSourceFile() failed when running codeComplete for {0}", 1119 Input.FileName); 1120 return false; 1121 } 1122 // Macros can be defined within the preamble region of the main file. 1123 // They don't fall nicely into our index/Sema dichotomy: 1124 // - they're not indexed for completion (they're not available across files) 1125 // - but Sema code complete won't see them: as part of the preamble, they're 1126 // deserialized only when mentioned. 1127 // Force them to be deserialized so SemaCodeComplete sees them. 1128 loadMainFilePreambleMacros(Clang->getPreprocessor(), Input.Preamble); 1129 if (Includes) 1130 Clang->getPreprocessor().addPPCallbacks( 1131 collectIncludeStructureCallback(Clang->getSourceManager(), Includes)); 1132 if (llvm::Error Err = Action.Execute()) { 1133 log("Execute() failed when running codeComplete for {0}: {1}", 1134 Input.FileName, toString(std::move(Err))); 1135 return false; 1136 } 1137 Action.EndSourceFile(); 1138 1139 return true; 1140 } 1141 1142 // Should we allow index completions in the specified context? 1143 bool allowIndex(CodeCompletionContext &CC) { 1144 if (!contextAllowsIndex(CC.getKind())) 1145 return false; 1146 // We also avoid ClassName::bar (but allow namespace::bar). 1147 auto Scope = CC.getCXXScopeSpecifier(); 1148 if (!Scope) 1149 return true; 1150 NestedNameSpecifier *NameSpec = (*Scope)->getScopeRep(); 1151 if (!NameSpec) 1152 return true; 1153 // We only query the index when qualifier is a namespace. 1154 // If it's a class, we rely solely on sema completions. 1155 switch (NameSpec->getKind()) { 1156 case NestedNameSpecifier::Global: 1157 case NestedNameSpecifier::Namespace: 1158 case NestedNameSpecifier::NamespaceAlias: 1159 return true; 1160 case NestedNameSpecifier::Super: 1161 case NestedNameSpecifier::TypeSpec: 1162 case NestedNameSpecifier::TypeSpecWithTemplate: 1163 // Unresolved inside a template. 1164 case NestedNameSpecifier::Identifier: 1165 return false; 1166 } 1167 llvm_unreachable("invalid NestedNameSpecifier kind"); 1168 } 1169 1170 std::future<SymbolSlab> startAsyncFuzzyFind(const SymbolIndex &Index, 1171 const FuzzyFindRequest &Req) { 1172 return runAsync<SymbolSlab>([&Index, Req]() { 1173 trace::Span Tracer("Async fuzzyFind"); 1174 SymbolSlab::Builder Syms; 1175 Index.fuzzyFind(Req, [&Syms](const Symbol &Sym) { Syms.insert(Sym); }); 1176 return std::move(Syms).build(); 1177 }); 1178 } 1179 1180 // Creates a `FuzzyFindRequest` based on the cached index request from the 1181 // last completion, if any, and the speculated completion filter text in the 1182 // source code. 1183 FuzzyFindRequest speculativeFuzzyFindRequestForCompletion( 1184 FuzzyFindRequest CachedReq, const CompletionPrefix &HeuristicPrefix) { 1185 CachedReq.Query = std::string(HeuristicPrefix.Name); 1186 return CachedReq; 1187 } 1188 1189 // Runs Sema-based (AST) and Index-based completion, returns merged results. 1190 // 1191 // There are a few tricky considerations: 1192 // - the AST provides information needed for the index query (e.g. which 1193 // namespaces to search in). So Sema must start first. 1194 // - we only want to return the top results (Opts.Limit). 1195 // Building CompletionItems for everything else is wasteful, so we want to 1196 // preserve the "native" format until we're done with scoring. 1197 // - the data underlying Sema completion items is owned by the AST and various 1198 // other arenas, which must stay alive for us to build CompletionItems. 1199 // - we may get duplicate results from Sema and the Index, we need to merge. 1200 // 1201 // So we start Sema completion first, and do all our work in its callback. 1202 // We use the Sema context information to query the index. 1203 // Then we merge the two result sets, producing items that are Sema/Index/Both. 1204 // These items are scored, and the top N are synthesized into the LSP response. 1205 // Finally, we can clean up the data structures created by Sema completion. 1206 // 1207 // Main collaborators are: 1208 // - semaCodeComplete sets up the compiler machinery to run code completion. 1209 // - CompletionRecorder captures Sema completion results, including context. 1210 // - SymbolIndex (Opts.Index) provides index completion results as Symbols 1211 // - CompletionCandidates are the result of merging Sema and Index results. 1212 // Each candidate points to an underlying CodeCompletionResult (Sema), a 1213 // Symbol (Index), or both. It computes the result quality score. 1214 // CompletionCandidate also does conversion to CompletionItem (at the end). 1215 // - FuzzyMatcher scores how the candidate matches the partial identifier. 1216 // This score is combined with the result quality score for the final score. 1217 // - TopN determines the results with the best score. 1218 class CodeCompleteFlow { 1219 PathRef FileName; 1220 IncludeStructure Includes; // Complete once the compiler runs. 1221 SpeculativeFuzzyFind *SpecFuzzyFind; // Can be nullptr. 1222 const CodeCompleteOptions &Opts; 1223 1224 // Sema takes ownership of Recorder. Recorder is valid until Sema cleanup. 1225 CompletionRecorder *Recorder = nullptr; 1226 CodeCompletionContext::Kind CCContextKind = CodeCompletionContext::CCC_Other; 1227 bool IsUsingDeclaration = false; 1228 // Counters for logging. 1229 int NSema = 0, NIndex = 0, NSemaAndIndex = 0, NIdent = 0; 1230 bool Incomplete = false; // Would more be available with a higher limit? 1231 CompletionPrefix HeuristicPrefix; 1232 llvm::Optional<FuzzyMatcher> Filter; // Initialized once Sema runs. 1233 Range ReplacedRange; 1234 std::vector<std::string> QueryScopes; // Initialized once Sema runs. 1235 // Initialized once QueryScopes is initialized, if there are scopes. 1236 llvm::Optional<ScopeDistance> ScopeProximity; 1237 llvm::Optional<OpaqueType> PreferredType; // Initialized once Sema runs. 1238 // Whether to query symbols from any scope. Initialized once Sema runs. 1239 bool AllScopes = false; 1240 llvm::StringSet<> ContextWords; 1241 // Include-insertion and proximity scoring rely on the include structure. 1242 // This is available after Sema has run. 1243 llvm::Optional<IncludeInserter> Inserter; // Available during runWithSema. 1244 llvm::Optional<URIDistance> FileProximity; // Initialized once Sema runs. 1245 /// Speculative request based on the cached request and the filter text before 1246 /// the cursor. 1247 /// Initialized right before sema run. This is only set if `SpecFuzzyFind` is 1248 /// set and contains a cached request. 1249 llvm::Optional<FuzzyFindRequest> SpecReq; 1250 1251 public: 1252 // A CodeCompleteFlow object is only useful for calling run() exactly once. 1253 CodeCompleteFlow(PathRef FileName, const IncludeStructure &Includes, 1254 SpeculativeFuzzyFind *SpecFuzzyFind, 1255 const CodeCompleteOptions &Opts) 1256 : FileName(FileName), Includes(Includes), SpecFuzzyFind(SpecFuzzyFind), 1257 Opts(Opts) {} 1258 1259 CodeCompleteResult run(const SemaCompleteInput &SemaCCInput) && { 1260 trace::Span Tracer("CodeCompleteFlow"); 1261 HeuristicPrefix = 1262 guessCompletionPrefix(SemaCCInput.Contents, SemaCCInput.Offset); 1263 populateContextWords(SemaCCInput.Contents); 1264 if (Opts.Index && SpecFuzzyFind && SpecFuzzyFind->CachedReq.hasValue()) { 1265 assert(!SpecFuzzyFind->Result.valid()); 1266 SpecReq = speculativeFuzzyFindRequestForCompletion( 1267 *SpecFuzzyFind->CachedReq, HeuristicPrefix); 1268 SpecFuzzyFind->Result = startAsyncFuzzyFind(*Opts.Index, *SpecReq); 1269 } 1270 1271 // We run Sema code completion first. It builds an AST and calculates: 1272 // - completion results based on the AST. 1273 // - partial identifier and context. We need these for the index query. 1274 CodeCompleteResult Output; 1275 auto RecorderOwner = std::make_unique<CompletionRecorder>(Opts, [&]() { 1276 assert(Recorder && "Recorder is not set"); 1277 CCContextKind = Recorder->CCContext.getKind(); 1278 IsUsingDeclaration = Recorder->CCContext.isUsingDeclaration(); 1279 auto Style = getFormatStyleForFile( 1280 SemaCCInput.FileName, SemaCCInput.Contents, SemaCCInput.VFS.get()); 1281 // If preprocessor was run, inclusions from preprocessor callback should 1282 // already be added to Includes. 1283 Inserter.emplace( 1284 SemaCCInput.FileName, SemaCCInput.Contents, Style, 1285 SemaCCInput.Command.Directory, 1286 &Recorder->CCSema->getPreprocessor().getHeaderSearchInfo()); 1287 for (const auto &Inc : Includes.MainFileIncludes) 1288 Inserter->addExisting(Inc); 1289 1290 // Most of the cost of file proximity is in initializing the FileDistance 1291 // structures based on the observed includes, once per query. Conceptually 1292 // that happens here (though the per-URI-scheme initialization is lazy). 1293 // The per-result proximity scoring is (amortized) very cheap. 1294 FileDistanceOptions ProxOpts{}; // Use defaults. 1295 const auto &SM = Recorder->CCSema->getSourceManager(); 1296 llvm::StringMap<SourceParams> ProxSources; 1297 for (auto &Entry : Includes.includeDepth( 1298 SM.getFileEntryForID(SM.getMainFileID())->getName())) { 1299 auto &Source = ProxSources[Entry.getKey()]; 1300 Source.Cost = Entry.getValue() * ProxOpts.IncludeCost; 1301 // Symbols near our transitive includes are good, but only consider 1302 // things in the same directory or below it. Otherwise there can be 1303 // many false positives. 1304 if (Entry.getValue() > 0) 1305 Source.MaxUpTraversals = 1; 1306 } 1307 FileProximity.emplace(ProxSources, ProxOpts); 1308 1309 Output = runWithSema(); 1310 Inserter.reset(); // Make sure this doesn't out-live Clang. 1311 SPAN_ATTACH(Tracer, "sema_completion_kind", 1312 getCompletionKindString(CCContextKind)); 1313 log("Code complete: sema context {0}, query scopes [{1}] (AnyScope={2}), " 1314 "expected type {3}{4}", 1315 getCompletionKindString(CCContextKind), 1316 llvm::join(QueryScopes.begin(), QueryScopes.end(), ","), AllScopes, 1317 PreferredType ? Recorder->CCContext.getPreferredType().getAsString() 1318 : "<none>", 1319 IsUsingDeclaration ? ", inside using declaration" : ""); 1320 }); 1321 1322 Recorder = RecorderOwner.get(); 1323 1324 semaCodeComplete(std::move(RecorderOwner), Opts.getClangCompleteOpts(), 1325 SemaCCInput, &Includes); 1326 logResults(Output, Tracer); 1327 return Output; 1328 } 1329 1330 void logResults(const CodeCompleteResult &Output, const trace::Span &Tracer) { 1331 SPAN_ATTACH(Tracer, "sema_results", NSema); 1332 SPAN_ATTACH(Tracer, "index_results", NIndex); 1333 SPAN_ATTACH(Tracer, "merged_results", NSemaAndIndex); 1334 SPAN_ATTACH(Tracer, "identifier_results", NIdent); 1335 SPAN_ATTACH(Tracer, "returned_results", int64_t(Output.Completions.size())); 1336 SPAN_ATTACH(Tracer, "incomplete", Output.HasMore); 1337 log("Code complete: {0} results from Sema, {1} from Index, " 1338 "{2} matched, {3} from identifiers, {4} returned{5}.", 1339 NSema, NIndex, NSemaAndIndex, NIdent, Output.Completions.size(), 1340 Output.HasMore ? " (incomplete)" : ""); 1341 assert(!Opts.Limit || Output.Completions.size() <= Opts.Limit); 1342 // We don't assert that isIncomplete means we hit a limit. 1343 // Indexes may choose to impose their own limits even if we don't have one. 1344 } 1345 1346 CodeCompleteResult 1347 runWithoutSema(llvm::StringRef Content, size_t Offset, 1348 llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) && { 1349 trace::Span Tracer("CodeCompleteWithoutSema"); 1350 // Fill in fields normally set by runWithSema() 1351 HeuristicPrefix = guessCompletionPrefix(Content, Offset); 1352 populateContextWords(Content); 1353 CCContextKind = CodeCompletionContext::CCC_Recovery; 1354 IsUsingDeclaration = false; 1355 Filter = FuzzyMatcher(HeuristicPrefix.Name); 1356 auto Pos = offsetToPosition(Content, Offset); 1357 ReplacedRange.start = ReplacedRange.end = Pos; 1358 ReplacedRange.start.character -= HeuristicPrefix.Name.size(); 1359 1360 llvm::StringMap<SourceParams> ProxSources; 1361 ProxSources[FileName].Cost = 0; 1362 FileProximity.emplace(ProxSources); 1363 1364 auto Style = getFormatStyleForFile(FileName, Content, VFS.get()); 1365 // This will only insert verbatim headers. 1366 Inserter.emplace(FileName, Content, Style, 1367 /*BuildDir=*/"", /*HeaderSearchInfo=*/nullptr); 1368 1369 auto Identifiers = collectIdentifiers(Content, Style); 1370 std::vector<RawIdentifier> IdentifierResults; 1371 for (const auto &IDAndCount : Identifiers) { 1372 RawIdentifier ID; 1373 ID.Name = IDAndCount.first(); 1374 ID.References = IDAndCount.second; 1375 // Avoid treating typed filter as an identifier. 1376 if (ID.Name == HeuristicPrefix.Name) 1377 --ID.References; 1378 if (ID.References > 0) 1379 IdentifierResults.push_back(std::move(ID)); 1380 } 1381 1382 // Simplified version of getQueryScopes(): 1383 // - accessible scopes are determined heuristically. 1384 // - all-scopes query if no qualifier was typed (and it's allowed). 1385 SpecifiedScope Scopes; 1386 Scopes.AccessibleScopes = visibleNamespaces( 1387 Content.take_front(Offset), format::getFormattingLangOpts(Style)); 1388 for (std::string &S : Scopes.AccessibleScopes) 1389 if (!S.empty()) 1390 S.append("::"); // visibleNamespaces doesn't include trailing ::. 1391 if (HeuristicPrefix.Qualifier.empty()) 1392 AllScopes = Opts.AllScopes; 1393 else if (HeuristicPrefix.Qualifier.startswith("::")) { 1394 Scopes.AccessibleScopes = {""}; 1395 Scopes.UnresolvedQualifier = 1396 std::string(HeuristicPrefix.Qualifier.drop_front(2)); 1397 } else 1398 Scopes.UnresolvedQualifier = std::string(HeuristicPrefix.Qualifier); 1399 // First scope is the (modified) enclosing scope. 1400 QueryScopes = Scopes.scopesForIndexQuery(); 1401 ScopeProximity.emplace(QueryScopes); 1402 1403 SymbolSlab IndexResults = Opts.Index ? queryIndex() : SymbolSlab(); 1404 1405 CodeCompleteResult Output = toCodeCompleteResult(mergeResults( 1406 /*SemaResults=*/{}, IndexResults, IdentifierResults)); 1407 Output.RanParser = false; 1408 logResults(Output, Tracer); 1409 return Output; 1410 } 1411 1412 private: 1413 void populateContextWords(llvm::StringRef Content) { 1414 // Take last 3 lines before the completion point. 1415 unsigned RangeEnd = HeuristicPrefix.Qualifier.begin() - Content.data(), 1416 RangeBegin = RangeEnd; 1417 for (size_t I = 0; I < 3 && RangeBegin > 0; ++I) { 1418 auto PrevNL = Content.rfind('\n', RangeBegin); 1419 if (PrevNL == StringRef::npos) { 1420 RangeBegin = 0; 1421 break; 1422 } 1423 RangeBegin = PrevNL; 1424 } 1425 1426 ContextWords = collectWords(Content.slice(RangeBegin, RangeEnd)); 1427 dlog("Completion context words: {0}", 1428 llvm::join(ContextWords.keys(), ", ")); 1429 } 1430 1431 // This is called by run() once Sema code completion is done, but before the 1432 // Sema data structures are torn down. It does all the real work. 1433 CodeCompleteResult runWithSema() { 1434 const auto &CodeCompletionRange = CharSourceRange::getCharRange( 1435 Recorder->CCSema->getPreprocessor().getCodeCompletionTokenRange()); 1436 // When we are getting completions with an empty identifier, for example 1437 // std::vector<int> asdf; 1438 // asdf.^; 1439 // Then the range will be invalid and we will be doing insertion, use 1440 // current cursor position in such cases as range. 1441 if (CodeCompletionRange.isValid()) { 1442 ReplacedRange = halfOpenToRange(Recorder->CCSema->getSourceManager(), 1443 CodeCompletionRange); 1444 } else { 1445 const auto &Pos = sourceLocToPosition( 1446 Recorder->CCSema->getSourceManager(), 1447 Recorder->CCSema->getPreprocessor().getCodeCompletionLoc()); 1448 ReplacedRange.start = ReplacedRange.end = Pos; 1449 } 1450 Filter = FuzzyMatcher( 1451 Recorder->CCSema->getPreprocessor().getCodeCompletionFilter()); 1452 std::tie(QueryScopes, AllScopes) = getQueryScopes( 1453 Recorder->CCContext, *Recorder->CCSema, HeuristicPrefix, Opts); 1454 if (!QueryScopes.empty()) 1455 ScopeProximity.emplace(QueryScopes); 1456 PreferredType = 1457 OpaqueType::fromType(Recorder->CCSema->getASTContext(), 1458 Recorder->CCContext.getPreferredType()); 1459 // Sema provides the needed context to query the index. 1460 // FIXME: in addition to querying for extra/overlapping symbols, we should 1461 // explicitly request symbols corresponding to Sema results. 1462 // We can use their signals even if the index can't suggest them. 1463 // We must copy index results to preserve them, but there are at most Limit. 1464 auto IndexResults = (Opts.Index && allowIndex(Recorder->CCContext)) 1465 ? queryIndex() 1466 : SymbolSlab(); 1467 trace::Span Tracer("Populate CodeCompleteResult"); 1468 // Merge Sema and Index results, score them, and pick the winners. 1469 auto Top = 1470 mergeResults(Recorder->Results, IndexResults, /*Identifiers*/ {}); 1471 return toCodeCompleteResult(Top); 1472 } 1473 1474 CodeCompleteResult 1475 toCodeCompleteResult(const std::vector<ScoredBundle> &Scored) { 1476 CodeCompleteResult Output; 1477 1478 // Convert the results to final form, assembling the expensive strings. 1479 for (auto &C : Scored) { 1480 Output.Completions.push_back(toCodeCompletion(C.first)); 1481 Output.Completions.back().Score = C.second; 1482 Output.Completions.back().CompletionTokenRange = ReplacedRange; 1483 } 1484 Output.HasMore = Incomplete; 1485 Output.Context = CCContextKind; 1486 Output.CompletionRange = ReplacedRange; 1487 return Output; 1488 } 1489 1490 SymbolSlab queryIndex() { 1491 trace::Span Tracer("Query index"); 1492 SPAN_ATTACH(Tracer, "limit", int64_t(Opts.Limit)); 1493 1494 // Build the query. 1495 FuzzyFindRequest Req; 1496 if (Opts.Limit) 1497 Req.Limit = Opts.Limit; 1498 Req.Query = std::string(Filter->pattern()); 1499 Req.RestrictForCodeCompletion = true; 1500 Req.Scopes = QueryScopes; 1501 Req.AnyScope = AllScopes; 1502 // FIXME: we should send multiple weighted paths here. 1503 Req.ProximityPaths.push_back(std::string(FileName)); 1504 if (PreferredType) 1505 Req.PreferredTypes.push_back(std::string(PreferredType->raw())); 1506 vlog("Code complete: fuzzyFind({0:2})", toJSON(Req)); 1507 1508 if (SpecFuzzyFind) 1509 SpecFuzzyFind->NewReq = Req; 1510 if (SpecFuzzyFind && SpecFuzzyFind->Result.valid() && (*SpecReq == Req)) { 1511 vlog("Code complete: speculative fuzzy request matches the actual index " 1512 "request. Waiting for the speculative index results."); 1513 SPAN_ATTACH(Tracer, "Speculative results", true); 1514 1515 trace::Span WaitSpec("Wait speculative results"); 1516 return SpecFuzzyFind->Result.get(); 1517 } 1518 1519 SPAN_ATTACH(Tracer, "Speculative results", false); 1520 1521 // Run the query against the index. 1522 SymbolSlab::Builder ResultsBuilder; 1523 if (Opts.Index->fuzzyFind( 1524 Req, [&](const Symbol &Sym) { ResultsBuilder.insert(Sym); })) 1525 Incomplete = true; 1526 return std::move(ResultsBuilder).build(); 1527 } 1528 1529 // Merges Sema and Index results where possible, to form CompletionCandidates. 1530 // \p Identifiers is raw identifiers that can also be completion candidates. 1531 // Identifiers are not merged with results from index or sema. 1532 // Groups overloads if desired, to form CompletionCandidate::Bundles. The 1533 // bundles are scored and top results are returned, best to worst. 1534 std::vector<ScoredBundle> 1535 mergeResults(const std::vector<CodeCompletionResult> &SemaResults, 1536 const SymbolSlab &IndexResults, 1537 const std::vector<RawIdentifier> &IdentifierResults) { 1538 trace::Span Tracer("Merge and score results"); 1539 std::vector<CompletionCandidate::Bundle> Bundles; 1540 llvm::DenseMap<size_t, size_t> BundleLookup; 1541 auto AddToBundles = [&](const CodeCompletionResult *SemaResult, 1542 const Symbol *IndexResult, 1543 const RawIdentifier *IdentifierResult) { 1544 CompletionCandidate C; 1545 C.SemaResult = SemaResult; 1546 C.IndexResult = IndexResult; 1547 C.IdentifierResult = IdentifierResult; 1548 if (C.IndexResult) { 1549 C.Name = IndexResult->Name; 1550 C.RankedIncludeHeaders = getRankedIncludes(*C.IndexResult); 1551 } else if (C.SemaResult) { 1552 C.Name = Recorder->getName(*SemaResult); 1553 } else { 1554 assert(IdentifierResult); 1555 C.Name = IdentifierResult->Name; 1556 } 1557 if (auto OverloadSet = C.overloadSet(Opts)) { 1558 auto Ret = BundleLookup.try_emplace(OverloadSet, Bundles.size()); 1559 if (Ret.second) 1560 Bundles.emplace_back(); 1561 Bundles[Ret.first->second].push_back(std::move(C)); 1562 } else { 1563 Bundles.emplace_back(); 1564 Bundles.back().push_back(std::move(C)); 1565 } 1566 }; 1567 llvm::DenseSet<const Symbol *> UsedIndexResults; 1568 auto CorrespondingIndexResult = 1569 [&](const CodeCompletionResult &SemaResult) -> const Symbol * { 1570 if (auto SymID = 1571 getSymbolID(SemaResult, Recorder->CCSema->getSourceManager())) { 1572 auto I = IndexResults.find(*SymID); 1573 if (I != IndexResults.end()) { 1574 UsedIndexResults.insert(&*I); 1575 return &*I; 1576 } 1577 } 1578 return nullptr; 1579 }; 1580 // Emit all Sema results, merging them with Index results if possible. 1581 for (auto &SemaResult : SemaResults) 1582 AddToBundles(&SemaResult, CorrespondingIndexResult(SemaResult), nullptr); 1583 // Now emit any Index-only results. 1584 for (const auto &IndexResult : IndexResults) { 1585 if (UsedIndexResults.count(&IndexResult)) 1586 continue; 1587 AddToBundles(/*SemaResult=*/nullptr, &IndexResult, nullptr); 1588 } 1589 // Emit identifier results. 1590 for (const auto &Ident : IdentifierResults) 1591 AddToBundles(/*SemaResult=*/nullptr, /*IndexResult=*/nullptr, &Ident); 1592 // We only keep the best N results at any time, in "native" format. 1593 TopN<ScoredBundle, ScoredBundleGreater> Top( 1594 Opts.Limit == 0 ? std::numeric_limits<size_t>::max() : Opts.Limit); 1595 for (auto &Bundle : Bundles) 1596 addCandidate(Top, std::move(Bundle)); 1597 return std::move(Top).items(); 1598 } 1599 1600 llvm::Optional<float> fuzzyScore(const CompletionCandidate &C) { 1601 // Macros can be very spammy, so we only support prefix completion. 1602 // We won't end up with underfull index results, as macros are sema-only. 1603 if (C.SemaResult && C.SemaResult->Kind == CodeCompletionResult::RK_Macro && 1604 !C.Name.startswith_lower(Filter->pattern())) 1605 return None; 1606 return Filter->match(C.Name); 1607 } 1608 1609 // Scores a candidate and adds it to the TopN structure. 1610 void addCandidate(TopN<ScoredBundle, ScoredBundleGreater> &Candidates, 1611 CompletionCandidate::Bundle Bundle) { 1612 SymbolQualitySignals Quality; 1613 SymbolRelevanceSignals Relevance; 1614 Relevance.Context = CCContextKind; 1615 Relevance.Name = Bundle.front().Name; 1616 Relevance.Query = SymbolRelevanceSignals::CodeComplete; 1617 Relevance.FileProximityMatch = FileProximity.getPointer(); 1618 if (ScopeProximity) 1619 Relevance.ScopeProximityMatch = ScopeProximity.getPointer(); 1620 if (PreferredType) 1621 Relevance.HadContextType = true; 1622 Relevance.ContextWords = &ContextWords; 1623 1624 auto &First = Bundle.front(); 1625 if (auto FuzzyScore = fuzzyScore(First)) 1626 Relevance.NameMatch = *FuzzyScore; 1627 else 1628 return; 1629 SymbolOrigin Origin = SymbolOrigin::Unknown; 1630 bool FromIndex = false; 1631 for (const auto &Candidate : Bundle) { 1632 if (Candidate.IndexResult) { 1633 Quality.merge(*Candidate.IndexResult); 1634 Relevance.merge(*Candidate.IndexResult); 1635 Origin |= Candidate.IndexResult->Origin; 1636 FromIndex = true; 1637 if (!Candidate.IndexResult->Type.empty()) 1638 Relevance.HadSymbolType |= true; 1639 if (PreferredType && 1640 PreferredType->raw() == Candidate.IndexResult->Type) { 1641 Relevance.TypeMatchesPreferred = true; 1642 } 1643 } 1644 if (Candidate.SemaResult) { 1645 Quality.merge(*Candidate.SemaResult); 1646 Relevance.merge(*Candidate.SemaResult); 1647 if (PreferredType) { 1648 if (auto CompletionType = OpaqueType::fromCompletionResult( 1649 Recorder->CCSema->getASTContext(), *Candidate.SemaResult)) { 1650 Relevance.HadSymbolType |= true; 1651 if (PreferredType == CompletionType) 1652 Relevance.TypeMatchesPreferred = true; 1653 } 1654 } 1655 Origin |= SymbolOrigin::AST; 1656 } 1657 if (Candidate.IdentifierResult) { 1658 Quality.References = Candidate.IdentifierResult->References; 1659 Relevance.Scope = SymbolRelevanceSignals::FileScope; 1660 Origin |= SymbolOrigin::Identifier; 1661 } 1662 } 1663 1664 CodeCompletion::Scores Scores; 1665 Scores.Quality = Quality.evaluate(); 1666 Scores.Relevance = Relevance.evaluate(); 1667 Scores.Total = evaluateSymbolAndRelevance(Scores.Quality, Scores.Relevance); 1668 // NameMatch is in fact a multiplier on total score, so rescoring is sound. 1669 Scores.ExcludingName = Relevance.NameMatch 1670 ? Scores.Total / Relevance.NameMatch 1671 : Scores.Quality; 1672 1673 if (Opts.RecordCCResult) 1674 Opts.RecordCCResult(toCodeCompletion(Bundle), Quality, Relevance, 1675 Scores.Total); 1676 1677 dlog("CodeComplete: {0} ({1}) = {2}\n{3}{4}\n", First.Name, 1678 llvm::to_string(Origin), Scores.Total, llvm::to_string(Quality), 1679 llvm::to_string(Relevance)); 1680 1681 NSema += bool(Origin & SymbolOrigin::AST); 1682 NIndex += FromIndex; 1683 NSemaAndIndex += bool(Origin & SymbolOrigin::AST) && FromIndex; 1684 NIdent += bool(Origin & SymbolOrigin::Identifier); 1685 if (Candidates.push({std::move(Bundle), Scores})) 1686 Incomplete = true; 1687 } 1688 1689 CodeCompletion toCodeCompletion(const CompletionCandidate::Bundle &Bundle) { 1690 llvm::Optional<CodeCompletionBuilder> Builder; 1691 for (const auto &Item : Bundle) { 1692 CodeCompletionString *SemaCCS = 1693 Item.SemaResult ? Recorder->codeCompletionString(*Item.SemaResult) 1694 : nullptr; 1695 if (!Builder) 1696 Builder.emplace(Recorder ? &Recorder->CCSema->getASTContext() : nullptr, 1697 Item, SemaCCS, QueryScopes, *Inserter, FileName, 1698 CCContextKind, Opts, 1699 /*GenerateSnippets=*/!IsUsingDeclaration); 1700 else 1701 Builder->add(Item, SemaCCS); 1702 } 1703 return Builder->build(); 1704 } 1705 }; 1706 1707 } // namespace 1708 1709 clang::CodeCompleteOptions CodeCompleteOptions::getClangCompleteOpts() const { 1710 clang::CodeCompleteOptions Result; 1711 Result.IncludeCodePatterns = EnableSnippets && IncludeCodePatterns; 1712 Result.IncludeMacros = IncludeMacros; 1713 Result.IncludeGlobals = true; 1714 // We choose to include full comments and not do doxygen parsing in 1715 // completion. 1716 // FIXME: ideally, we should support doxygen in some form, e.g. do markdown 1717 // formatting of the comments. 1718 Result.IncludeBriefComments = false; 1719 1720 // When an is used, Sema is responsible for completing the main file, 1721 // the index can provide results from the preamble. 1722 // Tell Sema not to deserialize the preamble to look for results. 1723 Result.LoadExternal = !Index; 1724 Result.IncludeFixIts = IncludeFixIts; 1725 1726 return Result; 1727 } 1728 1729 CompletionPrefix guessCompletionPrefix(llvm::StringRef Content, 1730 unsigned Offset) { 1731 assert(Offset <= Content.size()); 1732 StringRef Rest = Content.take_front(Offset); 1733 CompletionPrefix Result; 1734 1735 // Consume the unqualified name. We only handle ASCII characters. 1736 // isIdentifierBody will let us match "0invalid", but we don't mind. 1737 while (!Rest.empty() && isIdentifierBody(Rest.back())) 1738 Rest = Rest.drop_back(); 1739 Result.Name = Content.slice(Rest.size(), Offset); 1740 1741 // Consume qualifiers. 1742 while (Rest.consume_back("::") && !Rest.endswith(":")) // reject :::: 1743 while (!Rest.empty() && isIdentifierBody(Rest.back())) 1744 Rest = Rest.drop_back(); 1745 Result.Qualifier = 1746 Content.slice(Rest.size(), Result.Name.begin() - Content.begin()); 1747 1748 return Result; 1749 } 1750 1751 CodeCompleteResult 1752 codeComplete(PathRef FileName, const tooling::CompileCommand &Command, 1753 const PreambleData *Preamble, llvm::StringRef Contents, 1754 Position Pos, llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS, 1755 CodeCompleteOptions Opts, SpeculativeFuzzyFind *SpecFuzzyFind) { 1756 auto Offset = positionToOffset(Contents, Pos); 1757 if (!Offset) { 1758 elog("Code completion position was invalid {0}", Offset.takeError()); 1759 return CodeCompleteResult(); 1760 } 1761 auto Flow = CodeCompleteFlow( 1762 FileName, Preamble ? Preamble->Includes : IncludeStructure(), 1763 SpecFuzzyFind, Opts); 1764 return (!Preamble || Opts.RunParser == CodeCompleteOptions::NeverParse) 1765 ? std::move(Flow).runWithoutSema(Contents, *Offset, VFS) 1766 : std::move(Flow).run({FileName, Command, *Preamble, 1767 // We want to serve code completions with 1768 // low latency, so don't bother patching. 1769 PreamblePatch(), Contents, *Offset, VFS}); 1770 } 1771 1772 SignatureHelp signatureHelp(PathRef FileName, 1773 const tooling::CompileCommand &Command, 1774 const PreambleData &Preamble, 1775 llvm::StringRef Contents, Position Pos, 1776 llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS, 1777 const SymbolIndex *Index) { 1778 auto Offset = positionToOffset(Contents, Pos); 1779 if (!Offset) { 1780 elog("Code completion position was invalid {0}", Offset.takeError()); 1781 return SignatureHelp(); 1782 } 1783 SignatureHelp Result; 1784 clang::CodeCompleteOptions Options; 1785 Options.IncludeGlobals = false; 1786 Options.IncludeMacros = false; 1787 Options.IncludeCodePatterns = false; 1788 Options.IncludeBriefComments = false; 1789 1790 ParseInputs PI; 1791 PI.CompileCommand = Command; 1792 PI.Contents = Contents.str(); 1793 PI.FS = std::move(VFS); 1794 auto PP = PreamblePatch::create(FileName, PI, Preamble); 1795 semaCodeComplete( 1796 std::make_unique<SignatureHelpCollector>(Options, Index, Result), Options, 1797 {FileName, Command, Preamble, PP, Contents, *Offset, std::move(PI.FS)}); 1798 return Result; 1799 } 1800 1801 bool isIndexedForCodeCompletion(const NamedDecl &ND, ASTContext &ASTCtx) { 1802 auto InTopLevelScope = [](const NamedDecl &ND) { 1803 switch (ND.getDeclContext()->getDeclKind()) { 1804 case Decl::TranslationUnit: 1805 case Decl::Namespace: 1806 case Decl::LinkageSpec: 1807 return true; 1808 default: 1809 break; 1810 }; 1811 return false; 1812 }; 1813 // We only complete symbol's name, which is the same as the name of the 1814 // *primary* template in case of template specializations. 1815 if (isExplicitTemplateSpecialization(&ND)) 1816 return false; 1817 1818 if (InTopLevelScope(ND)) 1819 return true; 1820 1821 if (const auto *EnumDecl = dyn_cast<clang::EnumDecl>(ND.getDeclContext())) 1822 return InTopLevelScope(*EnumDecl) && !EnumDecl->isScoped(); 1823 1824 return false; 1825 } 1826 1827 // FIXME: find a home for this (that can depend on both markup and Protocol). 1828 static MarkupContent renderDoc(const markup::Document &Doc, MarkupKind Kind) { 1829 MarkupContent Result; 1830 Result.kind = Kind; 1831 switch (Kind) { 1832 case MarkupKind::PlainText: 1833 Result.value.append(Doc.asPlainText()); 1834 break; 1835 case MarkupKind::Markdown: 1836 Result.value.append(Doc.asMarkdown()); 1837 break; 1838 } 1839 return Result; 1840 } 1841 1842 CompletionItem CodeCompletion::render(const CodeCompleteOptions &Opts) const { 1843 CompletionItem LSP; 1844 const auto *InsertInclude = Includes.empty() ? nullptr : &Includes[0]; 1845 LSP.label = ((InsertInclude && InsertInclude->Insertion) 1846 ? Opts.IncludeIndicator.Insert 1847 : Opts.IncludeIndicator.NoInsert) + 1848 (Opts.ShowOrigins ? "[" + llvm::to_string(Origin) + "]" : "") + 1849 RequiredQualifier + Name + Signature; 1850 1851 LSP.kind = Kind; 1852 LSP.detail = BundleSize > 1 1853 ? std::string(llvm::formatv("[{0} overloads]", BundleSize)) 1854 : ReturnType; 1855 LSP.deprecated = Deprecated; 1856 // Combine header information and documentation in LSP `documentation` field. 1857 // This is not quite right semantically, but tends to display well in editors. 1858 if (InsertInclude || Documentation) { 1859 markup::Document Doc; 1860 if (InsertInclude) 1861 Doc.addParagraph().appendText("From ").appendCode(InsertInclude->Header); 1862 if (Documentation) 1863 Doc.append(*Documentation); 1864 LSP.documentation = renderDoc(Doc, Opts.DocumentationFormat); 1865 } 1866 LSP.sortText = sortText(Score.Total, Name); 1867 LSP.filterText = Name; 1868 LSP.textEdit = {CompletionTokenRange, RequiredQualifier + Name}; 1869 // Merge continuous additionalTextEdits into main edit. The main motivation 1870 // behind this is to help LSP clients, it seems most of them are confused when 1871 // they are provided with additionalTextEdits that are consecutive to main 1872 // edit. 1873 // Note that we store additional text edits from back to front in a line. That 1874 // is mainly to help LSP clients again, so that changes do not effect each 1875 // other. 1876 for (const auto &FixIt : FixIts) { 1877 if (FixIt.range.end == LSP.textEdit->range.start) { 1878 LSP.textEdit->newText = FixIt.newText + LSP.textEdit->newText; 1879 LSP.textEdit->range.start = FixIt.range.start; 1880 } else { 1881 LSP.additionalTextEdits.push_back(FixIt); 1882 } 1883 } 1884 if (Opts.EnableSnippets) 1885 LSP.textEdit->newText += SnippetSuffix; 1886 1887 // FIXME(kadircet): Do not even fill insertText after making sure textEdit is 1888 // compatible with most of the editors. 1889 LSP.insertText = LSP.textEdit->newText; 1890 LSP.insertTextFormat = Opts.EnableSnippets ? InsertTextFormat::Snippet 1891 : InsertTextFormat::PlainText; 1892 if (InsertInclude && InsertInclude->Insertion) 1893 LSP.additionalTextEdits.push_back(*InsertInclude->Insertion); 1894 1895 LSP.score = Score.ExcludingName; 1896 1897 return LSP; 1898 } 1899 1900 llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const CodeCompletion &C) { 1901 // For now just lean on CompletionItem. 1902 return OS << C.render(CodeCompleteOptions()); 1903 } 1904 1905 llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, 1906 const CodeCompleteResult &R) { 1907 OS << "CodeCompleteResult: " << R.Completions.size() << (R.HasMore ? "+" : "") 1908 << " (" << getCompletionKindString(R.Context) << ")" 1909 << " items:\n"; 1910 for (const auto &C : R.Completions) 1911 OS << C << "\n"; 1912 return OS; 1913 } 1914 1915 } // namespace clangd 1916 } // namespace clang 1917