1 //===--- CodeComplete.cpp ----------------------------------------*- C++-*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // Code completion has several moving parts: 11 // - AST-based completions are provided using the completion hooks in Sema. 12 // - external completions are retrieved from the index (using hints from Sema) 13 // - the two sources overlap, and must be merged and overloads bundled 14 // - results must be scored and ranked (see Quality.h) before rendering 15 // 16 // Signature help works in a similar way as code completion, but it is simpler: 17 // it's purely AST-based, and there are few candidates. 18 // 19 //===----------------------------------------------------------------------===// 20 21 #include "CodeComplete.h" 22 #include "AST.h" 23 #include "CodeCompletionStrings.h" 24 #include "Compiler.h" 25 #include "Diagnostics.h" 26 #include "FileDistance.h" 27 #include "FuzzyMatch.h" 28 #include "Headers.h" 29 #include "Logger.h" 30 #include "Quality.h" 31 #include "SourceCode.h" 32 #include "Trace.h" 33 #include "URI.h" 34 #include "index/Index.h" 35 #include "clang/ASTMatchers/ASTMatchFinder.h" 36 #include "clang/Basic/LangOptions.h" 37 #include "clang/Basic/SourceLocation.h" 38 #include "clang/Format/Format.h" 39 #include "clang/Frontend/CompilerInstance.h" 40 #include "clang/Frontend/FrontendActions.h" 41 #include "clang/Index/USRGeneration.h" 42 #include "clang/Sema/CodeCompleteConsumer.h" 43 #include "clang/Sema/Sema.h" 44 #include "clang/Tooling/Core/Replacement.h" 45 #include "llvm/Support/Format.h" 46 #include "llvm/Support/FormatVariadic.h" 47 #include "llvm/Support/ScopedPrinter.h" 48 #include <queue> 49 50 // We log detailed candidate here if you run with -debug-only=codecomplete. 51 #define DEBUG_TYPE "CodeComplete" 52 53 namespace clang { 54 namespace clangd { 55 namespace { 56 57 CompletionItemKind toCompletionItemKind(index::SymbolKind Kind) { 58 using SK = index::SymbolKind; 59 switch (Kind) { 60 case SK::Unknown: 61 return CompletionItemKind::Missing; 62 case SK::Module: 63 case SK::Namespace: 64 case SK::NamespaceAlias: 65 return CompletionItemKind::Module; 66 case SK::Macro: 67 return CompletionItemKind::Text; 68 case SK::Enum: 69 return CompletionItemKind::Enum; 70 // FIXME(ioeric): use LSP struct instead of class when it is suppoted in the 71 // protocol. 72 case SK::Struct: 73 case SK::Class: 74 case SK::Protocol: 75 case SK::Extension: 76 case SK::Union: 77 return CompletionItemKind::Class; 78 // FIXME(ioeric): figure out whether reference is the right type for aliases. 79 case SK::TypeAlias: 80 case SK::Using: 81 return CompletionItemKind::Reference; 82 case SK::Function: 83 // FIXME(ioeric): this should probably be an operator. This should be fixed 84 // when `Operator` is support type in the protocol. 85 case SK::ConversionFunction: 86 return CompletionItemKind::Function; 87 case SK::Variable: 88 case SK::Parameter: 89 return CompletionItemKind::Variable; 90 case SK::Field: 91 return CompletionItemKind::Field; 92 // FIXME(ioeric): use LSP enum constant when it is supported in the protocol. 93 case SK::EnumConstant: 94 return CompletionItemKind::Value; 95 case SK::InstanceMethod: 96 case SK::ClassMethod: 97 case SK::StaticMethod: 98 case SK::Destructor: 99 return CompletionItemKind::Method; 100 case SK::InstanceProperty: 101 case SK::ClassProperty: 102 case SK::StaticProperty: 103 return CompletionItemKind::Property; 104 case SK::Constructor: 105 return CompletionItemKind::Constructor; 106 } 107 llvm_unreachable("Unhandled clang::index::SymbolKind."); 108 } 109 110 CompletionItemKind 111 toCompletionItemKind(CodeCompletionResult::ResultKind ResKind, 112 const NamedDecl *Decl) { 113 if (Decl) 114 return toCompletionItemKind(index::getSymbolInfo(Decl).Kind); 115 switch (ResKind) { 116 case CodeCompletionResult::RK_Declaration: 117 llvm_unreachable("RK_Declaration without Decl"); 118 case CodeCompletionResult::RK_Keyword: 119 return CompletionItemKind::Keyword; 120 case CodeCompletionResult::RK_Macro: 121 return CompletionItemKind::Text; // unfortunately, there's no 'Macro' 122 // completion items in LSP. 123 case CodeCompletionResult::RK_Pattern: 124 return CompletionItemKind::Snippet; 125 } 126 llvm_unreachable("Unhandled CodeCompletionResult::ResultKind."); 127 } 128 129 /// Get the optional chunk as a string. This function is possibly recursive. 130 /// 131 /// The parameter info for each parameter is appended to the Parameters. 132 std::string getOptionalParameters(const CodeCompletionString &CCS, 133 std::vector<ParameterInformation> &Parameters, 134 SignatureQualitySignals &Signal) { 135 std::string Result; 136 for (const auto &Chunk : CCS) { 137 switch (Chunk.Kind) { 138 case CodeCompletionString::CK_Optional: 139 assert(Chunk.Optional && 140 "Expected the optional code completion string to be non-null."); 141 Result += getOptionalParameters(*Chunk.Optional, Parameters, Signal); 142 break; 143 case CodeCompletionString::CK_VerticalSpace: 144 break; 145 case CodeCompletionString::CK_Placeholder: 146 // A string that acts as a placeholder for, e.g., a function call 147 // argument. 148 // Intentional fallthrough here. 149 case CodeCompletionString::CK_CurrentParameter: { 150 // A piece of text that describes the parameter that corresponds to 151 // the code-completion location within a function call, message send, 152 // macro invocation, etc. 153 Result += Chunk.Text; 154 ParameterInformation Info; 155 Info.label = Chunk.Text; 156 Parameters.push_back(std::move(Info)); 157 Signal.ContainsActiveParameter = true; 158 Signal.NumberOfOptionalParameters++; 159 break; 160 } 161 default: 162 Result += Chunk.Text; 163 break; 164 } 165 } 166 return Result; 167 } 168 169 /// Creates a `HeaderFile` from \p Header which can be either a URI or a literal 170 /// include. 171 static llvm::Expected<HeaderFile> toHeaderFile(StringRef Header, 172 llvm::StringRef HintPath) { 173 if (isLiteralInclude(Header)) 174 return HeaderFile{Header.str(), /*Verbatim=*/true}; 175 auto U = URI::parse(Header); 176 if (!U) 177 return U.takeError(); 178 179 auto IncludePath = URI::includeSpelling(*U); 180 if (!IncludePath) 181 return IncludePath.takeError(); 182 if (!IncludePath->empty()) 183 return HeaderFile{std::move(*IncludePath), /*Verbatim=*/true}; 184 185 auto Resolved = URI::resolve(*U, HintPath); 186 if (!Resolved) 187 return Resolved.takeError(); 188 return HeaderFile{std::move(*Resolved), /*Verbatim=*/false}; 189 } 190 191 /// A code completion result, in clang-native form. 192 /// It may be promoted to a CompletionItem if it's among the top-ranked results. 193 struct CompletionCandidate { 194 llvm::StringRef Name; // Used for filtering and sorting. 195 // We may have a result from Sema, from the index, or both. 196 const CodeCompletionResult *SemaResult = nullptr; 197 const Symbol *IndexResult = nullptr; 198 199 // Returns a token identifying the overload set this is part of. 200 // 0 indicates it's not part of any overload set. 201 size_t overloadSet() const { 202 SmallString<256> Scratch; 203 if (IndexResult) { 204 switch (IndexResult->SymInfo.Kind) { 205 case index::SymbolKind::ClassMethod: 206 case index::SymbolKind::InstanceMethod: 207 case index::SymbolKind::StaticMethod: 208 assert(false && "Don't expect members from index in code completion"); 209 // fall through 210 case index::SymbolKind::Function: 211 // We can't group overloads together that need different #includes. 212 // This could break #include insertion. 213 return hash_combine( 214 (IndexResult->Scope + IndexResult->Name).toStringRef(Scratch), 215 headerToInsertIfNotPresent().getValueOr("")); 216 default: 217 return 0; 218 } 219 } 220 assert(SemaResult); 221 // We need to make sure we're consistent with the IndexResult case! 222 const NamedDecl *D = SemaResult->Declaration; 223 if (!D || !D->isFunctionOrFunctionTemplate()) 224 return 0; 225 { 226 llvm::raw_svector_ostream OS(Scratch); 227 D->printQualifiedName(OS); 228 } 229 return hash_combine(Scratch, headerToInsertIfNotPresent().getValueOr("")); 230 } 231 232 llvm::Optional<llvm::StringRef> headerToInsertIfNotPresent() const { 233 if (!IndexResult || !IndexResult->Detail || 234 IndexResult->Detail->IncludeHeader.empty()) 235 return llvm::None; 236 if (SemaResult && SemaResult->Declaration) { 237 // Avoid inserting new #include if the declaration is found in the current 238 // file e.g. the symbol is forward declared. 239 auto &SM = SemaResult->Declaration->getASTContext().getSourceManager(); 240 for (const Decl *RD : SemaResult->Declaration->redecls()) 241 if (SM.isInMainFile(SM.getExpansionLoc(RD->getBeginLoc()))) 242 return llvm::None; 243 } 244 return IndexResult->Detail->IncludeHeader; 245 } 246 247 using Bundle = llvm::SmallVector<CompletionCandidate, 4>; 248 }; 249 using ScoredBundle = 250 std::pair<CompletionCandidate::Bundle, CodeCompletion::Scores>; 251 struct ScoredBundleGreater { 252 bool operator()(const ScoredBundle &L, const ScoredBundle &R) { 253 if (L.second.Total != R.second.Total) 254 return L.second.Total > R.second.Total; 255 return L.first.front().Name < 256 R.first.front().Name; // Earlier name is better. 257 } 258 }; 259 260 // Assembles a code completion out of a bundle of >=1 completion candidates. 261 // Many of the expensive strings are only computed at this point, once we know 262 // the candidate bundle is going to be returned. 263 // 264 // Many fields are the same for all candidates in a bundle (e.g. name), and are 265 // computed from the first candidate, in the constructor. 266 // Others vary per candidate, so add() must be called for remaining candidates. 267 struct CodeCompletionBuilder { 268 CodeCompletionBuilder(ASTContext &ASTCtx, const CompletionCandidate &C, 269 CodeCompletionString *SemaCCS, 270 const IncludeInserter &Includes, StringRef FileName, 271 const CodeCompleteOptions &Opts) 272 : ASTCtx(ASTCtx), ExtractDocumentation(Opts.IncludeComments) { 273 add(C, SemaCCS); 274 if (C.SemaResult) { 275 Completion.Origin |= SymbolOrigin::AST; 276 Completion.Name = llvm::StringRef(SemaCCS->getTypedText()); 277 if (Completion.Scope.empty()) { 278 if ((C.SemaResult->Kind == CodeCompletionResult::RK_Declaration) || 279 (C.SemaResult->Kind == CodeCompletionResult::RK_Pattern)) 280 if (const auto *D = C.SemaResult->getDeclaration()) 281 if (const auto *ND = llvm::dyn_cast<NamedDecl>(D)) 282 Completion.Scope = 283 splitQualifiedName(printQualifiedName(*ND)).first; 284 } 285 Completion.Kind = 286 toCompletionItemKind(C.SemaResult->Kind, C.SemaResult->Declaration); 287 for (const auto &FixIt : C.SemaResult->FixIts) { 288 Completion.FixIts.push_back( 289 toTextEdit(FixIt, ASTCtx.getSourceManager(), ASTCtx.getLangOpts())); 290 } 291 std::sort(Completion.FixIts.begin(), Completion.FixIts.end(), 292 [](const TextEdit &X, const TextEdit &Y) { 293 return std::tie(X.range.start.line, X.range.start.character) < 294 std::tie(Y.range.start.line, Y.range.start.character); 295 }); 296 } 297 if (C.IndexResult) { 298 Completion.Origin |= C.IndexResult->Origin; 299 if (Completion.Scope.empty()) 300 Completion.Scope = C.IndexResult->Scope; 301 if (Completion.Kind == CompletionItemKind::Missing) 302 Completion.Kind = toCompletionItemKind(C.IndexResult->SymInfo.Kind); 303 if (Completion.Name.empty()) 304 Completion.Name = C.IndexResult->Name; 305 } 306 if (auto Inserted = C.headerToInsertIfNotPresent()) { 307 // Turn absolute path into a literal string that can be #included. 308 auto Include = [&]() -> Expected<std::pair<std::string, bool>> { 309 auto ResolvedDeclaring = 310 toHeaderFile(C.IndexResult->CanonicalDeclaration.FileURI, FileName); 311 if (!ResolvedDeclaring) 312 return ResolvedDeclaring.takeError(); 313 auto ResolvedInserted = toHeaderFile(*Inserted, FileName); 314 if (!ResolvedInserted) 315 return ResolvedInserted.takeError(); 316 return std::make_pair(Includes.calculateIncludePath(*ResolvedDeclaring, 317 *ResolvedInserted), 318 Includes.shouldInsertInclude(*ResolvedDeclaring, 319 *ResolvedInserted)); 320 }(); 321 if (Include) { 322 Completion.Header = Include->first; 323 if (Include->second) 324 Completion.HeaderInsertion = Includes.insert(Include->first); 325 } else 326 log("Failed to generate include insertion edits for adding header " 327 "(FileURI='{0}', IncludeHeader='{1}') into {2}", 328 C.IndexResult->CanonicalDeclaration.FileURI, 329 C.IndexResult->Detail->IncludeHeader, FileName); 330 } 331 } 332 333 void add(const CompletionCandidate &C, CodeCompletionString *SemaCCS) { 334 assert(bool(C.SemaResult) == bool(SemaCCS)); 335 Bundled.emplace_back(); 336 BundledEntry &S = Bundled.back(); 337 if (C.SemaResult) { 338 getSignature(*SemaCCS, &S.Signature, &S.SnippetSuffix, 339 &Completion.RequiredQualifier); 340 S.ReturnType = getReturnType(*SemaCCS); 341 } else if (C.IndexResult) { 342 S.Signature = C.IndexResult->Signature; 343 S.SnippetSuffix = C.IndexResult->CompletionSnippetSuffix; 344 if (auto *D = C.IndexResult->Detail) 345 S.ReturnType = D->ReturnType; 346 } 347 if (ExtractDocumentation && Completion.Documentation.empty()) { 348 if (C.IndexResult && C.IndexResult->Detail) 349 Completion.Documentation = C.IndexResult->Detail->Documentation; 350 else if (C.SemaResult) 351 Completion.Documentation = getDocComment(ASTCtx, *C.SemaResult, 352 /*CommentsFromHeader=*/false); 353 } 354 } 355 356 CodeCompletion build() { 357 Completion.ReturnType = summarizeReturnType(); 358 Completion.Signature = summarizeSignature(); 359 Completion.SnippetSuffix = summarizeSnippet(); 360 Completion.BundleSize = Bundled.size(); 361 return std::move(Completion); 362 } 363 364 private: 365 struct BundledEntry { 366 std::string SnippetSuffix; 367 std::string Signature; 368 std::string ReturnType; 369 }; 370 371 // If all BundledEntrys have the same value for a property, return it. 372 template <std::string BundledEntry::*Member> 373 const std::string *onlyValue() const { 374 auto B = Bundled.begin(), E = Bundled.end(); 375 for (auto I = B + 1; I != E; ++I) 376 if (I->*Member != B->*Member) 377 return nullptr; 378 return &(B->*Member); 379 } 380 381 std::string summarizeReturnType() const { 382 if (auto *RT = onlyValue<&BundledEntry::ReturnType>()) 383 return *RT; 384 return ""; 385 } 386 387 std::string summarizeSnippet() const { 388 if (auto *Snippet = onlyValue<&BundledEntry::SnippetSuffix>()) 389 return *Snippet; 390 // All bundles are function calls. 391 return "(${0})"; 392 } 393 394 std::string summarizeSignature() const { 395 if (auto *Signature = onlyValue<&BundledEntry::Signature>()) 396 return *Signature; 397 // All bundles are function calls. 398 return "(…)"; 399 } 400 401 ASTContext &ASTCtx; 402 CodeCompletion Completion; 403 SmallVector<BundledEntry, 1> Bundled; 404 bool ExtractDocumentation; 405 }; 406 407 // Determine the symbol ID for a Sema code completion result, if possible. 408 llvm::Optional<SymbolID> getSymbolID(const CodeCompletionResult &R) { 409 switch (R.Kind) { 410 case CodeCompletionResult::RK_Declaration: 411 case CodeCompletionResult::RK_Pattern: { 412 return clang::clangd::getSymbolID(R.Declaration); 413 } 414 case CodeCompletionResult::RK_Macro: 415 // FIXME: Macros do have USRs, but the CCR doesn't contain enough info. 416 case CodeCompletionResult::RK_Keyword: 417 return None; 418 } 419 llvm_unreachable("unknown CodeCompletionResult kind"); 420 } 421 422 // Scopes of the paritial identifier we're trying to complete. 423 // It is used when we query the index for more completion results. 424 struct SpecifiedScope { 425 // The scopes we should look in, determined by Sema. 426 // 427 // If the qualifier was fully resolved, we look for completions in these 428 // scopes; if there is an unresolved part of the qualifier, it should be 429 // resolved within these scopes. 430 // 431 // Examples of qualified completion: 432 // 433 // "::vec" => {""} 434 // "using namespace std; ::vec^" => {"", "std::"} 435 // "namespace ns {using namespace std;} ns::^" => {"ns::", "std::"} 436 // "std::vec^" => {""} // "std" unresolved 437 // 438 // Examples of unqualified completion: 439 // 440 // "vec^" => {""} 441 // "using namespace std; vec^" => {"", "std::"} 442 // "using namespace std; namespace ns { vec^ }" => {"ns::", "std::", ""} 443 // 444 // "" for global namespace, "ns::" for normal namespace. 445 std::vector<std::string> AccessibleScopes; 446 // The full scope qualifier as typed by the user (without the leading "::"). 447 // Set if the qualifier is not fully resolved by Sema. 448 llvm::Optional<std::string> UnresolvedQualifier; 449 450 // Construct scopes being queried in indexes. 451 // This method format the scopes to match the index request representation. 452 std::vector<std::string> scopesForIndexQuery() { 453 std::vector<std::string> Results; 454 for (llvm::StringRef AS : AccessibleScopes) { 455 Results.push_back(AS); 456 if (UnresolvedQualifier) 457 Results.back() += *UnresolvedQualifier; 458 } 459 return Results; 460 } 461 }; 462 463 // Get all scopes that will be queried in indexes. 464 std::vector<std::string> getQueryScopes(CodeCompletionContext &CCContext, 465 const SourceManager &SM) { 466 auto GetAllAccessibleScopes = [](CodeCompletionContext &CCContext) { 467 SpecifiedScope Info; 468 for (auto *Context : CCContext.getVisitedContexts()) { 469 if (isa<TranslationUnitDecl>(Context)) 470 Info.AccessibleScopes.push_back(""); // global namespace 471 else if (const auto *NS = dyn_cast<NamespaceDecl>(Context)) 472 Info.AccessibleScopes.push_back(NS->getQualifiedNameAsString() + "::"); 473 } 474 return Info; 475 }; 476 477 auto SS = CCContext.getCXXScopeSpecifier(); 478 479 // Unqualified completion (e.g. "vec^"). 480 if (!SS) { 481 // FIXME: Once we can insert namespace qualifiers and use the in-scope 482 // namespaces for scoring, search in all namespaces. 483 // FIXME: Capture scopes and use for scoring, for example, 484 // "using namespace std; namespace foo {v^}" => 485 // foo::value > std::vector > boost::variant 486 return GetAllAccessibleScopes(CCContext).scopesForIndexQuery(); 487 } 488 489 // Qualified completion ("std::vec^"), we have two cases depending on whether 490 // the qualifier can be resolved by Sema. 491 if ((*SS)->isValid()) { // Resolved qualifier. 492 return GetAllAccessibleScopes(CCContext).scopesForIndexQuery(); 493 } 494 495 // Unresolved qualifier. 496 // FIXME: When Sema can resolve part of a scope chain (e.g. 497 // "known::unknown::id"), we should expand the known part ("known::") rather 498 // than treating the whole thing as unknown. 499 SpecifiedScope Info; 500 Info.AccessibleScopes.push_back(""); // global namespace 501 502 Info.UnresolvedQualifier = 503 Lexer::getSourceText(CharSourceRange::getCharRange((*SS)->getRange()), SM, 504 clang::LangOptions()) 505 .ltrim("::"); 506 // Sema excludes the trailing "::". 507 if (!Info.UnresolvedQualifier->empty()) 508 *Info.UnresolvedQualifier += "::"; 509 510 return Info.scopesForIndexQuery(); 511 } 512 513 // Should we perform index-based completion in a context of the specified kind? 514 // FIXME: consider allowing completion, but restricting the result types. 515 bool contextAllowsIndex(enum CodeCompletionContext::Kind K) { 516 switch (K) { 517 case CodeCompletionContext::CCC_TopLevel: 518 case CodeCompletionContext::CCC_ObjCInterface: 519 case CodeCompletionContext::CCC_ObjCImplementation: 520 case CodeCompletionContext::CCC_ObjCIvarList: 521 case CodeCompletionContext::CCC_ClassStructUnion: 522 case CodeCompletionContext::CCC_Statement: 523 case CodeCompletionContext::CCC_Expression: 524 case CodeCompletionContext::CCC_ObjCMessageReceiver: 525 case CodeCompletionContext::CCC_EnumTag: 526 case CodeCompletionContext::CCC_UnionTag: 527 case CodeCompletionContext::CCC_ClassOrStructTag: 528 case CodeCompletionContext::CCC_ObjCProtocolName: 529 case CodeCompletionContext::CCC_Namespace: 530 case CodeCompletionContext::CCC_Type: 531 case CodeCompletionContext::CCC_Name: // FIXME: why does ns::^ give this? 532 case CodeCompletionContext::CCC_PotentiallyQualifiedName: 533 case CodeCompletionContext::CCC_ParenthesizedExpression: 534 case CodeCompletionContext::CCC_ObjCInterfaceName: 535 case CodeCompletionContext::CCC_ObjCCategoryName: 536 return true; 537 case CodeCompletionContext::CCC_Other: // Be conservative. 538 case CodeCompletionContext::CCC_OtherWithMacros: 539 case CodeCompletionContext::CCC_DotMemberAccess: 540 case CodeCompletionContext::CCC_ArrowMemberAccess: 541 case CodeCompletionContext::CCC_ObjCPropertyAccess: 542 case CodeCompletionContext::CCC_MacroName: 543 case CodeCompletionContext::CCC_MacroNameUse: 544 case CodeCompletionContext::CCC_PreprocessorExpression: 545 case CodeCompletionContext::CCC_PreprocessorDirective: 546 case CodeCompletionContext::CCC_NaturalLanguage: 547 case CodeCompletionContext::CCC_SelectorName: 548 case CodeCompletionContext::CCC_TypeQualifiers: 549 case CodeCompletionContext::CCC_ObjCInstanceMessage: 550 case CodeCompletionContext::CCC_ObjCClassMessage: 551 case CodeCompletionContext::CCC_Recovery: 552 return false; 553 } 554 llvm_unreachable("unknown code completion context"); 555 } 556 557 // Some member calls are blacklisted because they're so rarely useful. 558 static bool isBlacklistedMember(const NamedDecl &D) { 559 // Destructor completion is rarely useful, and works inconsistently. 560 // (s.^ completes ~string, but s.~st^ is an error). 561 if (D.getKind() == Decl::CXXDestructor) 562 return true; 563 // Injected name may be useful for A::foo(), but who writes A::A::foo()? 564 if (auto *R = dyn_cast_or_null<RecordDecl>(&D)) 565 if (R->isInjectedClassName()) 566 return true; 567 // Explicit calls to operators are also rare. 568 auto NameKind = D.getDeclName().getNameKind(); 569 if (NameKind == DeclarationName::CXXOperatorName || 570 NameKind == DeclarationName::CXXLiteralOperatorName || 571 NameKind == DeclarationName::CXXConversionFunctionName) 572 return true; 573 return false; 574 } 575 576 // The CompletionRecorder captures Sema code-complete output, including context. 577 // It filters out ignored results (but doesn't apply fuzzy-filtering yet). 578 // It doesn't do scoring or conversion to CompletionItem yet, as we want to 579 // merge with index results first. 580 // Generally the fields and methods of this object should only be used from 581 // within the callback. 582 struct CompletionRecorder : public CodeCompleteConsumer { 583 CompletionRecorder(const CodeCompleteOptions &Opts, 584 llvm::unique_function<void()> ResultsCallback) 585 : CodeCompleteConsumer(Opts.getClangCompleteOpts(), 586 /*OutputIsBinary=*/false), 587 CCContext(CodeCompletionContext::CCC_Other), Opts(Opts), 588 CCAllocator(std::make_shared<GlobalCodeCompletionAllocator>()), 589 CCTUInfo(CCAllocator), ResultsCallback(std::move(ResultsCallback)) { 590 assert(this->ResultsCallback); 591 } 592 593 std::vector<CodeCompletionResult> Results; 594 CodeCompletionContext CCContext; 595 Sema *CCSema = nullptr; // Sema that created the results. 596 // FIXME: Sema is scary. Can we store ASTContext and Preprocessor, instead? 597 598 void ProcessCodeCompleteResults(class Sema &S, CodeCompletionContext Context, 599 CodeCompletionResult *InResults, 600 unsigned NumResults) override final { 601 // Results from recovery mode are generally useless, and the callback after 602 // recovery (if any) is usually more interesting. To make sure we handle the 603 // future callback from sema, we just ignore all callbacks in recovery mode, 604 // as taking only results from recovery mode results in poor completion 605 // results. 606 // FIXME: in case there is no future sema completion callback after the 607 // recovery mode, we might still want to provide some results (e.g. trivial 608 // identifier-based completion). 609 if (Context.getKind() == CodeCompletionContext::CCC_Recovery) { 610 log("Code complete: Ignoring sema code complete callback with Recovery " 611 "context."); 612 return; 613 } 614 // If a callback is called without any sema result and the context does not 615 // support index-based completion, we simply skip it to give way to 616 // potential future callbacks with results. 617 if (NumResults == 0 && !contextAllowsIndex(Context.getKind())) 618 return; 619 if (CCSema) { 620 log("Multiple code complete callbacks (parser backtracked?). " 621 "Dropping results from context {0}, keeping results from {1}.", 622 getCompletionKindString(Context.getKind()), 623 getCompletionKindString(this->CCContext.getKind())); 624 return; 625 } 626 // Record the completion context. 627 CCSema = &S; 628 CCContext = Context; 629 630 // Retain the results we might want. 631 for (unsigned I = 0; I < NumResults; ++I) { 632 auto &Result = InResults[I]; 633 // Drop hidden items which cannot be found by lookup after completion. 634 // Exception: some items can be named by using a qualifier. 635 if (Result.Hidden && (!Result.Qualifier || Result.QualifierIsInformative)) 636 continue; 637 if (!Opts.IncludeIneligibleResults && 638 (Result.Availability == CXAvailability_NotAvailable || 639 Result.Availability == CXAvailability_NotAccessible)) 640 continue; 641 if (Result.Declaration && 642 !Context.getBaseType().isNull() // is this a member-access context? 643 && isBlacklistedMember(*Result.Declaration)) 644 continue; 645 // We choose to never append '::' to completion results in clangd. 646 Result.StartsNestedNameSpecifier = false; 647 Results.push_back(Result); 648 } 649 ResultsCallback(); 650 } 651 652 CodeCompletionAllocator &getAllocator() override { return *CCAllocator; } 653 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; } 654 655 // Returns the filtering/sorting name for Result, which must be from Results. 656 // Returned string is owned by this recorder (or the AST). 657 llvm::StringRef getName(const CodeCompletionResult &Result) { 658 switch (Result.Kind) { 659 case CodeCompletionResult::RK_Declaration: 660 if (auto *ID = Result.Declaration->getIdentifier()) 661 return ID->getName(); 662 break; 663 case CodeCompletionResult::RK_Keyword: 664 return Result.Keyword; 665 case CodeCompletionResult::RK_Macro: 666 return Result.Macro->getName(); 667 case CodeCompletionResult::RK_Pattern: 668 return Result.Pattern->getTypedText(); 669 } 670 auto *CCS = codeCompletionString(Result); 671 return CCS->getTypedText(); 672 } 673 674 // Build a CodeCompletion string for R, which must be from Results. 675 // The CCS will be owned by this recorder. 676 CodeCompletionString *codeCompletionString(const CodeCompletionResult &R) { 677 // CodeCompletionResult doesn't seem to be const-correct. We own it, anyway. 678 return const_cast<CodeCompletionResult &>(R).CreateCodeCompletionString( 679 *CCSema, CCContext, *CCAllocator, CCTUInfo, 680 /*IncludeBriefComments=*/false); 681 } 682 683 private: 684 CodeCompleteOptions Opts; 685 std::shared_ptr<GlobalCodeCompletionAllocator> CCAllocator; 686 CodeCompletionTUInfo CCTUInfo; 687 llvm::unique_function<void()> ResultsCallback; 688 }; 689 690 using ScoredSignature = 691 std::pair<SignatureQualitySignals, SignatureInformation>; 692 693 class SignatureHelpCollector final : public CodeCompleteConsumer { 694 695 public: 696 SignatureHelpCollector(const clang::CodeCompleteOptions &CodeCompleteOpts, 697 SignatureHelp &SigHelp) 698 : CodeCompleteConsumer(CodeCompleteOpts, /*OutputIsBinary=*/false), 699 SigHelp(SigHelp), 700 Allocator(std::make_shared<clang::GlobalCodeCompletionAllocator>()), 701 CCTUInfo(Allocator) {} 702 703 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg, 704 OverloadCandidate *Candidates, 705 unsigned NumCandidates) override { 706 std::vector<ScoredSignature> ScoredSignatures; 707 SigHelp.signatures.reserve(NumCandidates); 708 ScoredSignatures.reserve(NumCandidates); 709 // FIXME(rwols): How can we determine the "active overload candidate"? 710 // Right now the overloaded candidates seem to be provided in a "best fit" 711 // order, so I'm not too worried about this. 712 SigHelp.activeSignature = 0; 713 assert(CurrentArg <= (unsigned)std::numeric_limits<int>::max() && 714 "too many arguments"); 715 SigHelp.activeParameter = static_cast<int>(CurrentArg); 716 for (unsigned I = 0; I < NumCandidates; ++I) { 717 OverloadCandidate Candidate = Candidates[I]; 718 // We want to avoid showing instantiated signatures, because they may be 719 // long in some cases (e.g. when 'T' is substituted with 'std::string', we 720 // would get 'std::basic_string<char>'). 721 if (auto *Func = Candidate.getFunction()) { 722 if (auto *Pattern = Func->getTemplateInstantiationPattern()) 723 Candidate = OverloadCandidate(Pattern); 724 } 725 726 const auto *CCS = Candidate.CreateSignatureString( 727 CurrentArg, S, *Allocator, CCTUInfo, true); 728 assert(CCS && "Expected the CodeCompletionString to be non-null"); 729 // FIXME: for headers, we need to get a comment from the index. 730 ScoredSignatures.push_back(processOverloadCandidate( 731 Candidate, *CCS, 732 getParameterDocComment(S.getASTContext(), Candidate, CurrentArg, 733 /*CommentsFromHeaders=*/false))); 734 } 735 std::sort(ScoredSignatures.begin(), ScoredSignatures.end(), 736 [](const ScoredSignature &L, const ScoredSignature &R) { 737 // Ordering follows: 738 // - Less number of parameters is better. 739 // - Function is better than FunctionType which is better than 740 // Function Template. 741 // - High score is better. 742 // - Shorter signature is better. 743 // - Alphebatically smaller is better. 744 if (L.first.NumberOfParameters != R.first.NumberOfParameters) 745 return L.first.NumberOfParameters < 746 R.first.NumberOfParameters; 747 if (L.first.NumberOfOptionalParameters != 748 R.first.NumberOfOptionalParameters) 749 return L.first.NumberOfOptionalParameters < 750 R.first.NumberOfOptionalParameters; 751 if (L.first.Kind != R.first.Kind) { 752 using OC = CodeCompleteConsumer::OverloadCandidate; 753 switch (L.first.Kind) { 754 case OC::CK_Function: 755 return true; 756 case OC::CK_FunctionType: 757 return R.first.Kind != OC::CK_Function; 758 case OC::CK_FunctionTemplate: 759 return false; 760 } 761 llvm_unreachable("Unknown overload candidate type."); 762 } 763 if (L.second.label.size() != R.second.label.size()) 764 return L.second.label.size() < R.second.label.size(); 765 return L.second.label < R.second.label; 766 }); 767 for (const auto &SS : ScoredSignatures) 768 SigHelp.signatures.push_back(SS.second); 769 } 770 771 GlobalCodeCompletionAllocator &getAllocator() override { return *Allocator; } 772 773 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; } 774 775 private: 776 // FIXME(ioeric): consider moving CodeCompletionString logic here to 777 // CompletionString.h. 778 ScoredSignature processOverloadCandidate(const OverloadCandidate &Candidate, 779 const CodeCompletionString &CCS, 780 llvm::StringRef DocComment) const { 781 SignatureInformation Result; 782 SignatureQualitySignals Signal; 783 const char *ReturnType = nullptr; 784 785 Result.documentation = formatDocumentation(CCS, DocComment); 786 Signal.Kind = Candidate.getKind(); 787 788 for (const auto &Chunk : CCS) { 789 switch (Chunk.Kind) { 790 case CodeCompletionString::CK_ResultType: 791 // A piece of text that describes the type of an entity or, 792 // for functions and methods, the return type. 793 assert(!ReturnType && "Unexpected CK_ResultType"); 794 ReturnType = Chunk.Text; 795 break; 796 case CodeCompletionString::CK_Placeholder: 797 // A string that acts as a placeholder for, e.g., a function call 798 // argument. 799 // Intentional fallthrough here. 800 case CodeCompletionString::CK_CurrentParameter: { 801 // A piece of text that describes the parameter that corresponds to 802 // the code-completion location within a function call, message send, 803 // macro invocation, etc. 804 Result.label += Chunk.Text; 805 ParameterInformation Info; 806 Info.label = Chunk.Text; 807 Result.parameters.push_back(std::move(Info)); 808 Signal.NumberOfParameters++; 809 Signal.ContainsActiveParameter = true; 810 break; 811 } 812 case CodeCompletionString::CK_Optional: { 813 // The rest of the parameters are defaulted/optional. 814 assert(Chunk.Optional && 815 "Expected the optional code completion string to be non-null."); 816 Result.label += 817 getOptionalParameters(*Chunk.Optional, Result.parameters, Signal); 818 break; 819 } 820 case CodeCompletionString::CK_VerticalSpace: 821 break; 822 default: 823 Result.label += Chunk.Text; 824 break; 825 } 826 } 827 if (ReturnType) { 828 Result.label += " -> "; 829 Result.label += ReturnType; 830 } 831 dlog("Signal for {0}: {1}", Result, Signal); 832 return {Signal, Result}; 833 } 834 835 SignatureHelp &SigHelp; 836 std::shared_ptr<clang::GlobalCodeCompletionAllocator> Allocator; 837 CodeCompletionTUInfo CCTUInfo; 838 839 }; // SignatureHelpCollector 840 841 struct SemaCompleteInput { 842 PathRef FileName; 843 const tooling::CompileCommand &Command; 844 PrecompiledPreamble const *Preamble; 845 StringRef Contents; 846 Position Pos; 847 IntrusiveRefCntPtr<vfs::FileSystem> VFS; 848 std::shared_ptr<PCHContainerOperations> PCHs; 849 }; 850 851 // Invokes Sema code completion on a file. 852 // If \p Includes is set, it will be updated based on the compiler invocation. 853 bool semaCodeComplete(std::unique_ptr<CodeCompleteConsumer> Consumer, 854 const clang::CodeCompleteOptions &Options, 855 const SemaCompleteInput &Input, 856 IncludeStructure *Includes = nullptr) { 857 trace::Span Tracer("Sema completion"); 858 std::vector<const char *> ArgStrs; 859 for (const auto &S : Input.Command.CommandLine) 860 ArgStrs.push_back(S.c_str()); 861 862 if (Input.VFS->setCurrentWorkingDirectory(Input.Command.Directory)) { 863 log("Couldn't set working directory"); 864 // We run parsing anyway, our lit-tests rely on results for non-existing 865 // working dirs. 866 } 867 868 IgnoreDiagnostics DummyDiagsConsumer; 869 auto CI = createInvocationFromCommandLine( 870 ArgStrs, 871 CompilerInstance::createDiagnostics(new DiagnosticOptions, 872 &DummyDiagsConsumer, false), 873 Input.VFS); 874 if (!CI) { 875 elog("Couldn't create CompilerInvocation"); 876 return false; 877 } 878 auto &FrontendOpts = CI->getFrontendOpts(); 879 FrontendOpts.DisableFree = false; 880 FrontendOpts.SkipFunctionBodies = true; 881 CI->getLangOpts()->CommentOpts.ParseAllComments = true; 882 // Disable typo correction in Sema. 883 CI->getLangOpts()->SpellChecking = false; 884 // Setup code completion. 885 FrontendOpts.CodeCompleteOpts = Options; 886 FrontendOpts.CodeCompletionAt.FileName = Input.FileName; 887 auto Offset = positionToOffset(Input.Contents, Input.Pos); 888 if (!Offset) { 889 elog("Code completion position was invalid {0}", Offset.takeError()); 890 return false; 891 } 892 std::tie(FrontendOpts.CodeCompletionAt.Line, 893 FrontendOpts.CodeCompletionAt.Column) = 894 offsetToClangLineColumn(Input.Contents, *Offset); 895 896 std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer = 897 llvm::MemoryBuffer::getMemBufferCopy(Input.Contents, Input.FileName); 898 // The diagnostic options must be set before creating a CompilerInstance. 899 CI->getDiagnosticOpts().IgnoreWarnings = true; 900 // We reuse the preamble whether it's valid or not. This is a 901 // correctness/performance tradeoff: building without a preamble is slow, and 902 // completion is latency-sensitive. 903 // NOTE: we must call BeginSourceFile after prepareCompilerInstance. Otherwise 904 // the remapped buffers do not get freed. 905 auto Clang = prepareCompilerInstance( 906 std::move(CI), Input.Preamble, std::move(ContentsBuffer), 907 std::move(Input.PCHs), std::move(Input.VFS), DummyDiagsConsumer); 908 Clang->setCodeCompletionConsumer(Consumer.release()); 909 910 SyntaxOnlyAction Action; 911 if (!Action.BeginSourceFile(*Clang, Clang->getFrontendOpts().Inputs[0])) { 912 log("BeginSourceFile() failed when running codeComplete for {0}", 913 Input.FileName); 914 return false; 915 } 916 if (Includes) 917 Clang->getPreprocessor().addPPCallbacks( 918 collectIncludeStructureCallback(Clang->getSourceManager(), Includes)); 919 if (!Action.Execute()) { 920 log("Execute() failed when running codeComplete for {0}", Input.FileName); 921 return false; 922 } 923 Action.EndSourceFile(); 924 925 return true; 926 } 927 928 // Should we allow index completions in the specified context? 929 bool allowIndex(CodeCompletionContext &CC) { 930 if (!contextAllowsIndex(CC.getKind())) 931 return false; 932 // We also avoid ClassName::bar (but allow namespace::bar). 933 auto Scope = CC.getCXXScopeSpecifier(); 934 if (!Scope) 935 return true; 936 NestedNameSpecifier *NameSpec = (*Scope)->getScopeRep(); 937 if (!NameSpec) 938 return true; 939 // We only query the index when qualifier is a namespace. 940 // If it's a class, we rely solely on sema completions. 941 switch (NameSpec->getKind()) { 942 case NestedNameSpecifier::Global: 943 case NestedNameSpecifier::Namespace: 944 case NestedNameSpecifier::NamespaceAlias: 945 return true; 946 case NestedNameSpecifier::Super: 947 case NestedNameSpecifier::TypeSpec: 948 case NestedNameSpecifier::TypeSpecWithTemplate: 949 // Unresolved inside a template. 950 case NestedNameSpecifier::Identifier: 951 return false; 952 } 953 llvm_unreachable("invalid NestedNameSpecifier kind"); 954 } 955 956 } // namespace 957 958 clang::CodeCompleteOptions CodeCompleteOptions::getClangCompleteOpts() const { 959 clang::CodeCompleteOptions Result; 960 Result.IncludeCodePatterns = EnableSnippets && IncludeCodePatterns; 961 Result.IncludeMacros = IncludeMacros; 962 Result.IncludeGlobals = true; 963 // We choose to include full comments and not do doxygen parsing in 964 // completion. 965 // FIXME: ideally, we should support doxygen in some form, e.g. do markdown 966 // formatting of the comments. 967 Result.IncludeBriefComments = false; 968 969 // When an is used, Sema is responsible for completing the main file, 970 // the index can provide results from the preamble. 971 // Tell Sema not to deserialize the preamble to look for results. 972 Result.LoadExternal = !Index; 973 Result.IncludeFixIts = IncludeFixIts; 974 975 return Result; 976 } 977 978 // Runs Sema-based (AST) and Index-based completion, returns merged results. 979 // 980 // There are a few tricky considerations: 981 // - the AST provides information needed for the index query (e.g. which 982 // namespaces to search in). So Sema must start first. 983 // - we only want to return the top results (Opts.Limit). 984 // Building CompletionItems for everything else is wasteful, so we want to 985 // preserve the "native" format until we're done with scoring. 986 // - the data underlying Sema completion items is owned by the AST and various 987 // other arenas, which must stay alive for us to build CompletionItems. 988 // - we may get duplicate results from Sema and the Index, we need to merge. 989 // 990 // So we start Sema completion first, and do all our work in its callback. 991 // We use the Sema context information to query the index. 992 // Then we merge the two result sets, producing items that are Sema/Index/Both. 993 // These items are scored, and the top N are synthesized into the LSP response. 994 // Finally, we can clean up the data structures created by Sema completion. 995 // 996 // Main collaborators are: 997 // - semaCodeComplete sets up the compiler machinery to run code completion. 998 // - CompletionRecorder captures Sema completion results, including context. 999 // - SymbolIndex (Opts.Index) provides index completion results as Symbols 1000 // - CompletionCandidates are the result of merging Sema and Index results. 1001 // Each candidate points to an underlying CodeCompletionResult (Sema), a 1002 // Symbol (Index), or both. It computes the result quality score. 1003 // CompletionCandidate also does conversion to CompletionItem (at the end). 1004 // - FuzzyMatcher scores how the candidate matches the partial identifier. 1005 // This score is combined with the result quality score for the final score. 1006 // - TopN determines the results with the best score. 1007 class CodeCompleteFlow { 1008 PathRef FileName; 1009 IncludeStructure Includes; // Complete once the compiler runs. 1010 const CodeCompleteOptions &Opts; 1011 // Sema takes ownership of Recorder. Recorder is valid until Sema cleanup. 1012 CompletionRecorder *Recorder = nullptr; 1013 int NSema = 0, NIndex = 0, NBoth = 0; // Counters for logging. 1014 bool Incomplete = false; // Would more be available with a higher limit? 1015 llvm::Optional<FuzzyMatcher> Filter; // Initialized once Sema runs. 1016 std::vector<std::string> QueryScopes; // Initialized once Sema runs. 1017 // Include-insertion and proximity scoring rely on the include structure. 1018 // This is available after Sema has run. 1019 llvm::Optional<IncludeInserter> Inserter; // Available during runWithSema. 1020 llvm::Optional<URIDistance> FileProximity; // Initialized once Sema runs. 1021 1022 public: 1023 // A CodeCompleteFlow object is only useful for calling run() exactly once. 1024 CodeCompleteFlow(PathRef FileName, const IncludeStructure &Includes, 1025 const CodeCompleteOptions &Opts) 1026 : FileName(FileName), Includes(Includes), Opts(Opts) {} 1027 1028 CodeCompleteResult run(const SemaCompleteInput &SemaCCInput) && { 1029 trace::Span Tracer("CodeCompleteFlow"); 1030 1031 // We run Sema code completion first. It builds an AST and calculates: 1032 // - completion results based on the AST. 1033 // - partial identifier and context. We need these for the index query. 1034 CodeCompleteResult Output; 1035 auto RecorderOwner = llvm::make_unique<CompletionRecorder>(Opts, [&]() { 1036 assert(Recorder && "Recorder is not set"); 1037 auto Style = 1038 format::getStyle(format::DefaultFormatStyle, SemaCCInput.FileName, 1039 format::DefaultFallbackStyle, SemaCCInput.Contents, 1040 SemaCCInput.VFS.get()); 1041 if (!Style) { 1042 log("getStyle() failed for file {0}: {1}. Fallback is LLVM style.", 1043 SemaCCInput.FileName, Style.takeError()); 1044 Style = format::getLLVMStyle(); 1045 } 1046 // If preprocessor was run, inclusions from preprocessor callback should 1047 // already be added to Includes. 1048 Inserter.emplace( 1049 SemaCCInput.FileName, SemaCCInput.Contents, *Style, 1050 SemaCCInput.Command.Directory, 1051 Recorder->CCSema->getPreprocessor().getHeaderSearchInfo()); 1052 for (const auto &Inc : Includes.MainFileIncludes) 1053 Inserter->addExisting(Inc); 1054 1055 // Most of the cost of file proximity is in initializing the FileDistance 1056 // structures based on the observed includes, once per query. Conceptually 1057 // that happens here (though the per-URI-scheme initialization is lazy). 1058 // The per-result proximity scoring is (amortized) very cheap. 1059 FileDistanceOptions ProxOpts{}; // Use defaults. 1060 const auto &SM = Recorder->CCSema->getSourceManager(); 1061 llvm::StringMap<SourceParams> ProxSources; 1062 for (auto &Entry : Includes.includeDepth( 1063 SM.getFileEntryForID(SM.getMainFileID())->getName())) { 1064 auto &Source = ProxSources[Entry.getKey()]; 1065 Source.Cost = Entry.getValue() * ProxOpts.IncludeCost; 1066 // Symbols near our transitive includes are good, but only consider 1067 // things in the same directory or below it. Otherwise there can be 1068 // many false positives. 1069 if (Entry.getValue() > 0) 1070 Source.MaxUpTraversals = 1; 1071 } 1072 FileProximity.emplace(ProxSources, ProxOpts); 1073 1074 Output = runWithSema(); 1075 Inserter.reset(); // Make sure this doesn't out-live Clang. 1076 SPAN_ATTACH(Tracer, "sema_completion_kind", 1077 getCompletionKindString(Recorder->CCContext.getKind())); 1078 log("Code complete: sema context {0}, query scopes [{1}]", 1079 getCompletionKindString(Recorder->CCContext.getKind()), 1080 llvm::join(QueryScopes.begin(), QueryScopes.end(), ",")); 1081 }); 1082 1083 Recorder = RecorderOwner.get(); 1084 semaCodeComplete(std::move(RecorderOwner), Opts.getClangCompleteOpts(), 1085 SemaCCInput, &Includes); 1086 1087 SPAN_ATTACH(Tracer, "sema_results", NSema); 1088 SPAN_ATTACH(Tracer, "index_results", NIndex); 1089 SPAN_ATTACH(Tracer, "merged_results", NBoth); 1090 SPAN_ATTACH(Tracer, "returned_results", int64_t(Output.Completions.size())); 1091 SPAN_ATTACH(Tracer, "incomplete", Output.HasMore); 1092 log("Code complete: {0} results from Sema, {1} from Index, " 1093 "{2} matched, {3} returned{4}.", 1094 NSema, NIndex, NBoth, Output.Completions.size(), 1095 Output.HasMore ? " (incomplete)" : ""); 1096 assert(!Opts.Limit || Output.Completions.size() <= Opts.Limit); 1097 // We don't assert that isIncomplete means we hit a limit. 1098 // Indexes may choose to impose their own limits even if we don't have one. 1099 return Output; 1100 } 1101 1102 private: 1103 // This is called by run() once Sema code completion is done, but before the 1104 // Sema data structures are torn down. It does all the real work. 1105 CodeCompleteResult runWithSema() { 1106 const auto &CodeCompletionRange = CharSourceRange::getCharRange( 1107 Recorder->CCSema->getPreprocessor().getCodeCompletionTokenRange()); 1108 Range TextEditRange; 1109 // When we are getting completions with an empty identifier, for example 1110 // std::vector<int> asdf; 1111 // asdf.^; 1112 // Then the range will be invalid and we will be doing insertion, use 1113 // current cursor position in such cases as range. 1114 if (CodeCompletionRange.isValid()) { 1115 TextEditRange = halfOpenToRange(Recorder->CCSema->getSourceManager(), 1116 CodeCompletionRange); 1117 } else { 1118 const auto &Pos = sourceLocToPosition( 1119 Recorder->CCSema->getSourceManager(), 1120 Recorder->CCSema->getPreprocessor().getCodeCompletionLoc()); 1121 TextEditRange.start = TextEditRange.end = Pos; 1122 } 1123 Filter = FuzzyMatcher( 1124 Recorder->CCSema->getPreprocessor().getCodeCompletionFilter()); 1125 QueryScopes = getQueryScopes(Recorder->CCContext, 1126 Recorder->CCSema->getSourceManager()); 1127 // Sema provides the needed context to query the index. 1128 // FIXME: in addition to querying for extra/overlapping symbols, we should 1129 // explicitly request symbols corresponding to Sema results. 1130 // We can use their signals even if the index can't suggest them. 1131 // We must copy index results to preserve them, but there are at most Limit. 1132 auto IndexResults = (Opts.Index && allowIndex(Recorder->CCContext)) 1133 ? queryIndex() 1134 : SymbolSlab(); 1135 // Merge Sema and Index results, score them, and pick the winners. 1136 auto Top = mergeResults(Recorder->Results, IndexResults); 1137 // Convert the results to final form, assembling the expensive strings. 1138 CodeCompleteResult Output; 1139 for (auto &C : Top) { 1140 Output.Completions.push_back(toCodeCompletion(C.first)); 1141 Output.Completions.back().Score = C.second; 1142 Output.Completions.back().CompletionTokenRange = TextEditRange; 1143 } 1144 Output.HasMore = Incomplete; 1145 Output.Context = Recorder->CCContext.getKind(); 1146 return Output; 1147 } 1148 1149 SymbolSlab queryIndex() { 1150 trace::Span Tracer("Query index"); 1151 SPAN_ATTACH(Tracer, "limit", int64_t(Opts.Limit)); 1152 1153 SymbolSlab::Builder ResultsBuilder; 1154 // Build the query. 1155 FuzzyFindRequest Req; 1156 if (Opts.Limit) 1157 Req.MaxCandidateCount = Opts.Limit; 1158 Req.Query = Filter->pattern(); 1159 Req.RestrictForCodeCompletion = true; 1160 Req.Scopes = QueryScopes; 1161 // FIXME: we should send multiple weighted paths here. 1162 Req.ProximityPaths.push_back(FileName); 1163 vlog("Code complete: fuzzyFind(\"{0}\", scopes=[{1}])", Req.Query, 1164 llvm::join(Req.Scopes.begin(), Req.Scopes.end(), ",")); 1165 // Run the query against the index. 1166 if (Opts.Index->fuzzyFind( 1167 Req, [&](const Symbol &Sym) { ResultsBuilder.insert(Sym); })) 1168 Incomplete = true; 1169 return std::move(ResultsBuilder).build(); 1170 } 1171 1172 // Merges Sema and Index results where possible, to form CompletionCandidates. 1173 // Groups overloads if desired, to form CompletionCandidate::Bundles. 1174 // The bundles are scored and top results are returned, best to worst. 1175 std::vector<ScoredBundle> 1176 mergeResults(const std::vector<CodeCompletionResult> &SemaResults, 1177 const SymbolSlab &IndexResults) { 1178 trace::Span Tracer("Merge and score results"); 1179 std::vector<CompletionCandidate::Bundle> Bundles; 1180 llvm::DenseMap<size_t, size_t> BundleLookup; 1181 auto AddToBundles = [&](const CodeCompletionResult *SemaResult, 1182 const Symbol *IndexResult) { 1183 CompletionCandidate C; 1184 C.SemaResult = SemaResult; 1185 C.IndexResult = IndexResult; 1186 C.Name = IndexResult ? IndexResult->Name : Recorder->getName(*SemaResult); 1187 if (auto OverloadSet = Opts.BundleOverloads ? C.overloadSet() : 0) { 1188 auto Ret = BundleLookup.try_emplace(OverloadSet, Bundles.size()); 1189 if (Ret.second) 1190 Bundles.emplace_back(); 1191 Bundles[Ret.first->second].push_back(std::move(C)); 1192 } else { 1193 Bundles.emplace_back(); 1194 Bundles.back().push_back(std::move(C)); 1195 } 1196 }; 1197 llvm::DenseSet<const Symbol *> UsedIndexResults; 1198 auto CorrespondingIndexResult = 1199 [&](const CodeCompletionResult &SemaResult) -> const Symbol * { 1200 if (auto SymID = getSymbolID(SemaResult)) { 1201 auto I = IndexResults.find(*SymID); 1202 if (I != IndexResults.end()) { 1203 UsedIndexResults.insert(&*I); 1204 return &*I; 1205 } 1206 } 1207 return nullptr; 1208 }; 1209 // Emit all Sema results, merging them with Index results if possible. 1210 for (auto &SemaResult : Recorder->Results) 1211 AddToBundles(&SemaResult, CorrespondingIndexResult(SemaResult)); 1212 // Now emit any Index-only results. 1213 for (const auto &IndexResult : IndexResults) { 1214 if (UsedIndexResults.count(&IndexResult)) 1215 continue; 1216 AddToBundles(/*SemaResult=*/nullptr, &IndexResult); 1217 } 1218 // We only keep the best N results at any time, in "native" format. 1219 TopN<ScoredBundle, ScoredBundleGreater> Top( 1220 Opts.Limit == 0 ? std::numeric_limits<size_t>::max() : Opts.Limit); 1221 for (auto &Bundle : Bundles) 1222 addCandidate(Top, std::move(Bundle)); 1223 return std::move(Top).items(); 1224 } 1225 1226 Optional<float> fuzzyScore(const CompletionCandidate &C) { 1227 // Macros can be very spammy, so we only support prefix completion. 1228 // We won't end up with underfull index results, as macros are sema-only. 1229 if (C.SemaResult && C.SemaResult->Kind == CodeCompletionResult::RK_Macro && 1230 !C.Name.startswith_lower(Filter->pattern())) 1231 return None; 1232 return Filter->match(C.Name); 1233 } 1234 1235 // Scores a candidate and adds it to the TopN structure. 1236 void addCandidate(TopN<ScoredBundle, ScoredBundleGreater> &Candidates, 1237 CompletionCandidate::Bundle Bundle) { 1238 SymbolQualitySignals Quality; 1239 SymbolRelevanceSignals Relevance; 1240 Relevance.Context = Recorder->CCContext.getKind(); 1241 Relevance.Query = SymbolRelevanceSignals::CodeComplete; 1242 Relevance.FileProximityMatch = FileProximity.getPointer(); 1243 auto &First = Bundle.front(); 1244 if (auto FuzzyScore = fuzzyScore(First)) 1245 Relevance.NameMatch = *FuzzyScore; 1246 else 1247 return; 1248 SymbolOrigin Origin = SymbolOrigin::Unknown; 1249 bool FromIndex = false; 1250 for (const auto &Candidate : Bundle) { 1251 if (Candidate.IndexResult) { 1252 Quality.merge(*Candidate.IndexResult); 1253 Relevance.merge(*Candidate.IndexResult); 1254 Origin |= Candidate.IndexResult->Origin; 1255 FromIndex = true; 1256 } 1257 if (Candidate.SemaResult) { 1258 Quality.merge(*Candidate.SemaResult); 1259 Relevance.merge(*Candidate.SemaResult); 1260 Origin |= SymbolOrigin::AST; 1261 } 1262 } 1263 1264 CodeCompletion::Scores Scores; 1265 Scores.Quality = Quality.evaluate(); 1266 Scores.Relevance = Relevance.evaluate(); 1267 Scores.Total = evaluateSymbolAndRelevance(Scores.Quality, Scores.Relevance); 1268 // NameMatch is in fact a multiplier on total score, so rescoring is sound. 1269 Scores.ExcludingName = Relevance.NameMatch 1270 ? Scores.Total / Relevance.NameMatch 1271 : Scores.Quality; 1272 1273 dlog("CodeComplete: {0} ({1}) = {2}\n{3}{4}\n", First.Name, 1274 llvm::to_string(Origin), Scores.Total, llvm::to_string(Quality), 1275 llvm::to_string(Relevance)); 1276 1277 NSema += bool(Origin & SymbolOrigin::AST); 1278 NIndex += FromIndex; 1279 NBoth += bool(Origin & SymbolOrigin::AST) && FromIndex; 1280 if (Candidates.push({std::move(Bundle), Scores})) 1281 Incomplete = true; 1282 } 1283 1284 CodeCompletion toCodeCompletion(const CompletionCandidate::Bundle &Bundle) { 1285 llvm::Optional<CodeCompletionBuilder> Builder; 1286 for (const auto &Item : Bundle) { 1287 CodeCompletionString *SemaCCS = 1288 Item.SemaResult ? Recorder->codeCompletionString(*Item.SemaResult) 1289 : nullptr; 1290 if (!Builder) 1291 Builder.emplace(Recorder->CCSema->getASTContext(), Item, SemaCCS, 1292 *Inserter, FileName, Opts); 1293 else 1294 Builder->add(Item, SemaCCS); 1295 } 1296 return Builder->build(); 1297 } 1298 }; 1299 1300 CodeCompleteResult codeComplete(PathRef FileName, 1301 const tooling::CompileCommand &Command, 1302 PrecompiledPreamble const *Preamble, 1303 const IncludeStructure &PreambleInclusions, 1304 StringRef Contents, Position Pos, 1305 IntrusiveRefCntPtr<vfs::FileSystem> VFS, 1306 std::shared_ptr<PCHContainerOperations> PCHs, 1307 CodeCompleteOptions Opts) { 1308 return CodeCompleteFlow(FileName, PreambleInclusions, Opts) 1309 .run({FileName, Command, Preamble, Contents, Pos, VFS, PCHs}); 1310 } 1311 1312 SignatureHelp signatureHelp(PathRef FileName, 1313 const tooling::CompileCommand &Command, 1314 PrecompiledPreamble const *Preamble, 1315 StringRef Contents, Position Pos, 1316 IntrusiveRefCntPtr<vfs::FileSystem> VFS, 1317 std::shared_ptr<PCHContainerOperations> PCHs) { 1318 SignatureHelp Result; 1319 clang::CodeCompleteOptions Options; 1320 Options.IncludeGlobals = false; 1321 Options.IncludeMacros = false; 1322 Options.IncludeCodePatterns = false; 1323 Options.IncludeBriefComments = false; 1324 IncludeStructure PreambleInclusions; // Unused for signatureHelp 1325 semaCodeComplete(llvm::make_unique<SignatureHelpCollector>(Options, Result), 1326 Options, 1327 {FileName, Command, Preamble, Contents, Pos, std::move(VFS), 1328 std::move(PCHs)}); 1329 return Result; 1330 } 1331 1332 bool isIndexedForCodeCompletion(const NamedDecl &ND, ASTContext &ASTCtx) { 1333 using namespace clang::ast_matchers; 1334 auto InTopLevelScope = hasDeclContext( 1335 anyOf(namespaceDecl(), translationUnitDecl(), linkageSpecDecl())); 1336 return !match(decl(anyOf(InTopLevelScope, 1337 hasDeclContext( 1338 enumDecl(InTopLevelScope, unless(isScoped()))))), 1339 ND, ASTCtx) 1340 .empty(); 1341 } 1342 1343 CompletionItem CodeCompletion::render(const CodeCompleteOptions &Opts) const { 1344 CompletionItem LSP; 1345 LSP.label = (HeaderInsertion ? Opts.IncludeIndicator.Insert 1346 : Opts.IncludeIndicator.NoInsert) + 1347 (Opts.ShowOrigins ? "[" + llvm::to_string(Origin) + "]" : "") + 1348 RequiredQualifier + Name + Signature; 1349 1350 LSP.kind = Kind; 1351 LSP.detail = BundleSize > 1 ? llvm::formatv("[{0} overloads]", BundleSize) 1352 : ReturnType; 1353 if (!Header.empty()) 1354 LSP.detail += "\n" + Header; 1355 LSP.documentation = Documentation; 1356 LSP.sortText = sortText(Score.Total, Name); 1357 LSP.filterText = Name; 1358 LSP.textEdit = {CompletionTokenRange, RequiredQualifier + Name}; 1359 // Merge continious additionalTextEdits into main edit. The main motivation 1360 // behind this is to help LSP clients, it seems most of them are confused when 1361 // they are provided with additionalTextEdits that are consecutive to main 1362 // edit. 1363 // Note that we store additional text edits from back to front in a line. That 1364 // is mainly to help LSP clients again, so that changes do not effect each 1365 // other. 1366 for (const auto &FixIt : FixIts) { 1367 if (IsRangeConsecutive(FixIt.range, LSP.textEdit->range)) { 1368 LSP.textEdit->newText = FixIt.newText + LSP.textEdit->newText; 1369 LSP.textEdit->range.start = FixIt.range.start; 1370 } else { 1371 LSP.additionalTextEdits.push_back(FixIt); 1372 } 1373 } 1374 if (Opts.EnableSnippets) 1375 LSP.textEdit->newText += SnippetSuffix; 1376 // FIXME(kadircet): Do not even fill insertText after making sure textEdit is 1377 // compatible with most of the editors. 1378 LSP.insertText = LSP.textEdit->newText; 1379 LSP.insertTextFormat = Opts.EnableSnippets ? InsertTextFormat::Snippet 1380 : InsertTextFormat::PlainText; 1381 if (HeaderInsertion) 1382 LSP.additionalTextEdits.push_back(*HeaderInsertion); 1383 return LSP; 1384 } 1385 1386 raw_ostream &operator<<(raw_ostream &OS, const CodeCompletion &C) { 1387 // For now just lean on CompletionItem. 1388 return OS << C.render(CodeCompleteOptions()); 1389 } 1390 1391 raw_ostream &operator<<(raw_ostream &OS, const CodeCompleteResult &R) { 1392 OS << "CodeCompleteResult: " << R.Completions.size() << (R.HasMore ? "+" : "") 1393 << " (" << getCompletionKindString(R.Context) << ")" 1394 << " items:\n"; 1395 for (const auto &C : R.Completions) 1396 OS << C << "\n"; 1397 return OS; 1398 } 1399 1400 } // namespace clangd 1401 } // namespace clang 1402