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