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