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 // AST-based completions are provided using the completion hooks in Sema. 11 // 12 // Signature help works in a similar way as code completion, but it is simpler 13 // as there are typically fewer candidates. 14 // 15 //===---------------------------------------------------------------------===// 16 17 #include "CodeComplete.h" 18 #include "CodeCompletionStrings.h" 19 #include "Compiler.h" 20 #include "FuzzyMatch.h" 21 #include "Logger.h" 22 #include "Trace.h" 23 #include "index/Index.h" 24 #include "clang/Frontend/CompilerInstance.h" 25 #include "clang/Frontend/FrontendActions.h" 26 #include "clang/Index/USRGeneration.h" 27 #include "clang/Sema/CodeCompleteConsumer.h" 28 #include "clang/Sema/Sema.h" 29 #include "llvm/Support/Format.h" 30 #include <queue> 31 32 namespace clang { 33 namespace clangd { 34 namespace { 35 36 CompletionItemKind toCompletionItemKind(CXCursorKind CursorKind) { 37 switch (CursorKind) { 38 case CXCursor_MacroInstantiation: 39 case CXCursor_MacroDefinition: 40 return CompletionItemKind::Text; 41 case CXCursor_CXXMethod: 42 case CXCursor_Destructor: 43 return CompletionItemKind::Method; 44 case CXCursor_FunctionDecl: 45 case CXCursor_FunctionTemplate: 46 return CompletionItemKind::Function; 47 case CXCursor_Constructor: 48 return CompletionItemKind::Constructor; 49 case CXCursor_FieldDecl: 50 return CompletionItemKind::Field; 51 case CXCursor_VarDecl: 52 case CXCursor_ParmDecl: 53 return CompletionItemKind::Variable; 54 // FIXME(ioeric): use LSP struct instead of class when it is suppoted in the 55 // protocol. 56 case CXCursor_StructDecl: 57 case CXCursor_ClassDecl: 58 case CXCursor_UnionDecl: 59 case CXCursor_ClassTemplate: 60 case CXCursor_ClassTemplatePartialSpecialization: 61 return CompletionItemKind::Class; 62 case CXCursor_Namespace: 63 case CXCursor_NamespaceAlias: 64 case CXCursor_NamespaceRef: 65 return CompletionItemKind::Module; 66 case CXCursor_EnumConstantDecl: 67 return CompletionItemKind::Value; 68 case CXCursor_EnumDecl: 69 return CompletionItemKind::Enum; 70 // FIXME(ioeric): figure out whether reference is the right type for aliases. 71 case CXCursor_TypeAliasDecl: 72 case CXCursor_TypeAliasTemplateDecl: 73 case CXCursor_TypedefDecl: 74 case CXCursor_MemberRef: 75 case CXCursor_TypeRef: 76 return CompletionItemKind::Reference; 77 default: 78 return CompletionItemKind::Missing; 79 } 80 } 81 82 CompletionItemKind 83 toCompletionItemKind(CodeCompletionResult::ResultKind ResKind, 84 CXCursorKind CursorKind) { 85 switch (ResKind) { 86 case CodeCompletionResult::RK_Declaration: 87 return toCompletionItemKind(CursorKind); 88 case CodeCompletionResult::RK_Keyword: 89 return CompletionItemKind::Keyword; 90 case CodeCompletionResult::RK_Macro: 91 return CompletionItemKind::Text; // unfortunately, there's no 'Macro' 92 // completion items in LSP. 93 case CodeCompletionResult::RK_Pattern: 94 return CompletionItemKind::Snippet; 95 } 96 llvm_unreachable("Unhandled CodeCompletionResult::ResultKind."); 97 } 98 99 CompletionItemKind toCompletionItemKind(index::SymbolKind Kind) { 100 using SK = index::SymbolKind; 101 switch (Kind) { 102 case SK::Unknown: 103 return CompletionItemKind::Missing; 104 case SK::Module: 105 case SK::Namespace: 106 case SK::NamespaceAlias: 107 return CompletionItemKind::Module; 108 case SK::Macro: 109 return CompletionItemKind::Text; 110 case SK::Enum: 111 return CompletionItemKind::Enum; 112 // FIXME(ioeric): use LSP struct instead of class when it is suppoted in the 113 // protocol. 114 case SK::Struct: 115 case SK::Class: 116 case SK::Protocol: 117 case SK::Extension: 118 case SK::Union: 119 return CompletionItemKind::Class; 120 // FIXME(ioeric): figure out whether reference is the right type for aliases. 121 case SK::TypeAlias: 122 case SK::Using: 123 return CompletionItemKind::Reference; 124 case SK::Function: 125 // FIXME(ioeric): this should probably be an operator. This should be fixed 126 // when `Operator` is support type in the protocol. 127 case SK::ConversionFunction: 128 return CompletionItemKind::Function; 129 case SK::Variable: 130 case SK::Parameter: 131 return CompletionItemKind::Variable; 132 case SK::Field: 133 return CompletionItemKind::Field; 134 // FIXME(ioeric): use LSP enum constant when it is supported in the protocol. 135 case SK::EnumConstant: 136 return CompletionItemKind::Value; 137 case SK::InstanceMethod: 138 case SK::ClassMethod: 139 case SK::StaticMethod: 140 case SK::Destructor: 141 return CompletionItemKind::Method; 142 case SK::InstanceProperty: 143 case SK::ClassProperty: 144 case SK::StaticProperty: 145 return CompletionItemKind::Property; 146 case SK::Constructor: 147 return CompletionItemKind::Constructor; 148 } 149 llvm_unreachable("Unhandled clang::index::SymbolKind."); 150 } 151 152 /// Get the optional chunk as a string. This function is possibly recursive. 153 /// 154 /// The parameter info for each parameter is appended to the Parameters. 155 std::string 156 getOptionalParameters(const CodeCompletionString &CCS, 157 std::vector<ParameterInformation> &Parameters) { 158 std::string Result; 159 for (const auto &Chunk : CCS) { 160 switch (Chunk.Kind) { 161 case CodeCompletionString::CK_Optional: 162 assert(Chunk.Optional && 163 "Expected the optional code completion string to be non-null."); 164 Result += getOptionalParameters(*Chunk.Optional, Parameters); 165 break; 166 case CodeCompletionString::CK_VerticalSpace: 167 break; 168 case CodeCompletionString::CK_Placeholder: 169 // A string that acts as a placeholder for, e.g., a function call 170 // argument. 171 // Intentional fallthrough here. 172 case CodeCompletionString::CK_CurrentParameter: { 173 // A piece of text that describes the parameter that corresponds to 174 // the code-completion location within a function call, message send, 175 // macro invocation, etc. 176 Result += Chunk.Text; 177 ParameterInformation Info; 178 Info.label = Chunk.Text; 179 Parameters.push_back(std::move(Info)); 180 break; 181 } 182 default: 183 Result += Chunk.Text; 184 break; 185 } 186 } 187 return Result; 188 } 189 190 // Produces an integer that sorts in the same order as F. 191 // That is: a < b <==> encodeFloat(a) < encodeFloat(b). 192 uint32_t encodeFloat(float F) { 193 static_assert(std::numeric_limits<float>::is_iec559, ""); 194 static_assert(sizeof(float) == sizeof(uint32_t), ""); 195 constexpr uint32_t TopBit = ~(~uint32_t{0} >> 1); 196 197 // Get the bits of the float. Endianness is the same as for integers. 198 uint32_t U; 199 memcpy(&U, &F, sizeof(float)); 200 // IEEE 754 floats compare like sign-magnitude integers. 201 if (U & TopBit) // Negative float. 202 return 0 - U; // Map onto the low half of integers, order reversed. 203 return U + TopBit; // Positive floats map onto the high half of integers. 204 } 205 206 // Returns a string that sorts in the same order as (-Score, Name), for LSP. 207 std::string sortText(float Score, llvm::StringRef Name) { 208 // We convert -Score to an integer, and hex-encode for readability. 209 // Example: [0.5, "foo"] -> "41000000foo" 210 std::string S; 211 llvm::raw_string_ostream OS(S); 212 write_hex(OS, encodeFloat(-Score), llvm::HexPrintStyle::Lower, 213 /*Width=*/2 * sizeof(Score)); 214 OS << Name; 215 OS.flush(); 216 return S; 217 } 218 219 /// A code completion result, in clang-native form. 220 /// It may be promoted to a CompletionItem if it's among the top-ranked results. 221 struct CompletionCandidate { 222 llvm::StringRef Name; // Used for filtering and sorting. 223 // We may have a result from Sema, from the index, or both. 224 const CodeCompletionResult *SemaResult = nullptr; 225 const Symbol *IndexResult = nullptr; 226 227 // Computes the "symbol quality" score for this completion. Higher is better. 228 float score() const { 229 // For now we just use the Sema priority, mapping it onto a 0-1 interval. 230 if (!SemaResult) // FIXME(sammccall): better scoring for index results. 231 return 0.3f; // fixed mediocre score for index-only results. 232 233 // Priority 80 is a really bad score. 234 float Score = 1 - std::min<float>(80, SemaResult->Priority) / 80; 235 236 switch (static_cast<CXAvailabilityKind>(SemaResult->Availability)) { 237 case CXAvailability_Available: 238 // No penalty. 239 break; 240 case CXAvailability_Deprecated: 241 Score *= 0.1f; 242 break; 243 case CXAvailability_NotAccessible: 244 case CXAvailability_NotAvailable: 245 Score = 0; 246 break; 247 } 248 return Score; 249 } 250 251 // Builds an LSP completion item. 252 CompletionItem build(const CompletionItemScores &Scores, 253 const CodeCompleteOptions &Opts, 254 CodeCompletionString *SemaCCS) const { 255 assert(bool(SemaResult) == bool(SemaCCS)); 256 CompletionItem I; 257 if (SemaResult) { 258 I.kind = toCompletionItemKind(SemaResult->Kind, SemaResult->CursorKind); 259 getLabelAndInsertText(*SemaCCS, &I.label, &I.insertText, 260 Opts.EnableSnippets); 261 I.filterText = getFilterText(*SemaCCS); 262 I.documentation = getDocumentation(*SemaCCS); 263 I.detail = getDetail(*SemaCCS); 264 } 265 if (IndexResult) { 266 if (I.kind == CompletionItemKind::Missing) 267 I.kind = toCompletionItemKind(IndexResult->SymInfo.Kind); 268 // FIXME: reintroduce a way to show the index source for debugging. 269 if (I.label.empty()) 270 I.label = IndexResult->CompletionLabel; 271 if (I.filterText.empty()) 272 I.filterText = IndexResult->Name; 273 274 // FIXME(ioeric): support inserting/replacing scope qualifiers. 275 if (I.insertText.empty()) 276 I.insertText = Opts.EnableSnippets 277 ? IndexResult->CompletionSnippetInsertText 278 : IndexResult->CompletionPlainInsertText; 279 280 if (auto *D = IndexResult->Detail) { 281 if (I.documentation.empty()) 282 I.documentation = D->Documentation; 283 if (I.detail.empty()) 284 I.detail = D->CompletionDetail; 285 } 286 } 287 I.scoreInfo = Scores; 288 I.sortText = sortText(Scores.finalScore, Name); 289 I.insertTextFormat = Opts.EnableSnippets ? InsertTextFormat::Snippet 290 : InsertTextFormat::PlainText; 291 return I; 292 } 293 }; 294 295 // Determine the symbol ID for a Sema code completion result, if possible. 296 llvm::Optional<SymbolID> getSymbolID(const CodeCompletionResult &R) { 297 switch (R.Kind) { 298 case CodeCompletionResult::RK_Declaration: 299 case CodeCompletionResult::RK_Pattern: { 300 llvm::SmallString<128> USR; 301 if (/*Ignore=*/clang::index::generateUSRForDecl(R.Declaration, USR)) 302 return None; 303 return SymbolID(USR); 304 } 305 case CodeCompletionResult::RK_Macro: 306 // FIXME: Macros do have USRs, but the CCR doesn't contain enough info. 307 case CodeCompletionResult::RK_Keyword: 308 return None; 309 } 310 llvm_unreachable("unknown CodeCompletionResult kind"); 311 } 312 313 // Scopes of the paritial identifier we're trying to complete. 314 // It is used when we query the index for more completion results. 315 struct SpecifiedScope { 316 // The scopes we should look in, determined by Sema. 317 // 318 // If the qualifier was fully resolved, we look for completions in these 319 // scopes; if there is an unresolved part of the qualifier, it should be 320 // resolved within these scopes. 321 // 322 // Examples of qualified completion: 323 // 324 // "::vec" => {""} 325 // "using namespace std; ::vec^" => {"", "std::"} 326 // "namespace ns {using namespace std;} ns::^" => {"ns::", "std::"} 327 // "std::vec^" => {""} // "std" unresolved 328 // 329 // Examples of unqualified completion: 330 // 331 // "vec^" => {""} 332 // "using namespace std; vec^" => {"", "std::"} 333 // "using namespace std; namespace ns { vec^ }" => {"ns::", "std::", ""} 334 // 335 // "" for global namespace, "ns::" for normal namespace. 336 std::vector<std::string> AccessibleScopes; 337 // The full scope qualifier as typed by the user (without the leading "::"). 338 // Set if the qualifier is not fully resolved by Sema. 339 llvm::Optional<std::string> UnresolvedQualifier; 340 341 // Construct scopes being queried in indexes. 342 // This method format the scopes to match the index request representation. 343 std::vector<std::string> scopesForIndexQuery() { 344 std::vector<std::string> Results; 345 for (llvm::StringRef AS : AccessibleScopes) { 346 Results.push_back(AS); 347 if (UnresolvedQualifier) 348 Results.back() += *UnresolvedQualifier; 349 } 350 return Results; 351 } 352 }; 353 354 // Get all scopes that will be queried in indexes. 355 std::vector<std::string> getQueryScopes(CodeCompletionContext &CCContext, 356 const SourceManager& SM) { 357 auto GetAllAccessibleScopes = [](CodeCompletionContext& CCContext) { 358 SpecifiedScope Info; 359 for (auto* Context : CCContext.getVisitedContexts()) { 360 if (isa<TranslationUnitDecl>(Context)) 361 Info.AccessibleScopes.push_back(""); // global namespace 362 else if (const auto*NS = dyn_cast<NamespaceDecl>(Context)) 363 Info.AccessibleScopes.push_back(NS->getQualifiedNameAsString() + "::"); 364 } 365 return Info; 366 }; 367 368 auto SS = CCContext.getCXXScopeSpecifier(); 369 370 // Unqualified completion (e.g. "vec^"). 371 if (!SS) { 372 // FIXME: Once we can insert namespace qualifiers and use the in-scope 373 // namespaces for scoring, search in all namespaces. 374 // FIXME: Capture scopes and use for scoring, for example, 375 // "using namespace std; namespace foo {v^}" => 376 // foo::value > std::vector > boost::variant 377 return GetAllAccessibleScopes(CCContext).scopesForIndexQuery(); 378 } 379 380 // Qualified completion ("std::vec^"), we have two cases depending on whether 381 // the qualifier can be resolved by Sema. 382 if ((*SS)->isValid()) { // Resolved qualifier. 383 return GetAllAccessibleScopes(CCContext).scopesForIndexQuery(); 384 } 385 386 // Unresolved qualifier. 387 // FIXME: When Sema can resolve part of a scope chain (e.g. 388 // "known::unknown::id"), we should expand the known part ("known::") rather 389 // than treating the whole thing as unknown. 390 SpecifiedScope Info; 391 Info.AccessibleScopes.push_back(""); // global namespace 392 393 Info.UnresolvedQualifier = 394 Lexer::getSourceText(CharSourceRange::getCharRange((*SS)->getRange()), 395 SM, clang::LangOptions()).ltrim("::"); 396 // Sema excludes the trailing "::". 397 if (!Info.UnresolvedQualifier->empty()) 398 *Info.UnresolvedQualifier += "::"; 399 400 return Info.scopesForIndexQuery(); 401 } 402 403 // The CompletionRecorder captures Sema code-complete output, including context. 404 // It filters out ignored results (but doesn't apply fuzzy-filtering yet). 405 // It doesn't do scoring or conversion to CompletionItem yet, as we want to 406 // merge with index results first. 407 struct CompletionRecorder : public CodeCompleteConsumer { 408 CompletionRecorder(const CodeCompleteOptions &Opts) 409 : CodeCompleteConsumer(Opts.getClangCompleteOpts(), 410 /*OutputIsBinary=*/false), 411 CCContext(CodeCompletionContext::CCC_Other), Opts(Opts), 412 CCAllocator(std::make_shared<GlobalCodeCompletionAllocator>()), 413 CCTUInfo(CCAllocator) {} 414 std::vector<CodeCompletionResult> Results; 415 CodeCompletionContext CCContext; 416 Sema *CCSema = nullptr; // Sema that created the results. 417 // FIXME: Sema is scary. Can we store ASTContext and Preprocessor, instead? 418 419 void ProcessCodeCompleteResults(class Sema &S, CodeCompletionContext Context, 420 CodeCompletionResult *InResults, 421 unsigned NumResults) override final { 422 // Record the completion context. 423 assert(!CCSema && "ProcessCodeCompleteResults called multiple times!"); 424 CCSema = &S; 425 CCContext = Context; 426 427 // Retain the results we might want. 428 for (unsigned I = 0; I < NumResults; ++I) { 429 auto &Result = InResults[I]; 430 // Drop hidden items which cannot be found by lookup after completion. 431 // Exception: some items can be named by using a qualifier. 432 if (Result.Hidden && (!Result.Qualifier || Result.QualifierIsInformative)) 433 continue; 434 if (!Opts.IncludeIneligibleResults && 435 (Result.Availability == CXAvailability_NotAvailable || 436 Result.Availability == CXAvailability_NotAccessible)) 437 continue; 438 // Destructor completion is rarely useful, and works inconsistently. 439 // (s.^ completes ~string, but s.~st^ is an error). 440 if (dyn_cast_or_null<CXXDestructorDecl>(Result.Declaration)) 441 continue; 442 Results.push_back(Result); 443 } 444 } 445 446 CodeCompletionAllocator &getAllocator() override { return *CCAllocator; } 447 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; } 448 449 // Returns the filtering/sorting name for Result, which must be from Results. 450 // Returned string is owned by this recorder (or the AST). 451 llvm::StringRef getName(const CodeCompletionResult &Result) { 452 switch (Result.Kind) { 453 case CodeCompletionResult::RK_Declaration: 454 if (auto *ID = Result.Declaration->getIdentifier()) 455 return ID->getName(); 456 break; 457 case CodeCompletionResult::RK_Keyword: 458 return Result.Keyword; 459 case CodeCompletionResult::RK_Macro: 460 return Result.Macro->getName(); 461 case CodeCompletionResult::RK_Pattern: 462 return Result.Pattern->getTypedText(); 463 } 464 auto *CCS = codeCompletionString(Result, /*IncludeBriefComments=*/false); 465 return CCS->getTypedText(); 466 } 467 468 // Build a CodeCompletion string for R, which must be from Results. 469 // The CCS will be owned by this recorder. 470 CodeCompletionString *codeCompletionString(const CodeCompletionResult &R, 471 bool IncludeBriefComments) { 472 // CodeCompletionResult doesn't seem to be const-correct. We own it, anyway. 473 return const_cast<CodeCompletionResult &>(R).CreateCodeCompletionString( 474 *CCSema, CCContext, *CCAllocator, CCTUInfo, IncludeBriefComments); 475 } 476 477 private: 478 CodeCompleteOptions Opts; 479 std::shared_ptr<GlobalCodeCompletionAllocator> CCAllocator; 480 CodeCompletionTUInfo CCTUInfo; 481 }; 482 483 // Tracks a bounded number of candidates with the best scores. 484 class TopN { 485 public: 486 using value_type = std::pair<CompletionCandidate, CompletionItemScores>; 487 static constexpr size_t Unbounded = std::numeric_limits<size_t>::max(); 488 489 TopN(size_t N) : N(N) {} 490 491 // Adds a candidate to the set. 492 // Returns true if a candidate was dropped to get back under N. 493 bool push(value_type &&V) { 494 bool Dropped = false; 495 if (Heap.size() >= N) { 496 Dropped = true; 497 if (N > 0 && greater(V, Heap.front())) { 498 std::pop_heap(Heap.begin(), Heap.end(), greater); 499 Heap.back() = std::move(V); 500 std::push_heap(Heap.begin(), Heap.end(), greater); 501 } 502 } else { 503 Heap.push_back(std::move(V)); 504 std::push_heap(Heap.begin(), Heap.end(), greater); 505 } 506 assert(Heap.size() <= N); 507 assert(std::is_heap(Heap.begin(), Heap.end(), greater)); 508 return Dropped; 509 } 510 511 // Returns candidates from best to worst. 512 std::vector<value_type> items() && { 513 std::sort_heap(Heap.begin(), Heap.end(), greater); 514 assert(Heap.size() <= N); 515 return std::move(Heap); 516 } 517 518 private: 519 static bool greater(const value_type &L, const value_type &R) { 520 if (L.second.finalScore != R.second.finalScore) 521 return L.second.finalScore > R.second.finalScore; 522 return L.first.Name < R.first.Name; // Earlier name is better. 523 } 524 525 const size_t N; 526 std::vector<value_type> Heap; // Min-heap, comparator is greater(). 527 }; 528 529 class SignatureHelpCollector final : public CodeCompleteConsumer { 530 531 public: 532 SignatureHelpCollector(const clang::CodeCompleteOptions &CodeCompleteOpts, 533 SignatureHelp &SigHelp) 534 : CodeCompleteConsumer(CodeCompleteOpts, /*OutputIsBinary=*/false), 535 SigHelp(SigHelp), 536 Allocator(std::make_shared<clang::GlobalCodeCompletionAllocator>()), 537 CCTUInfo(Allocator) {} 538 539 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg, 540 OverloadCandidate *Candidates, 541 unsigned NumCandidates) override { 542 SigHelp.signatures.reserve(NumCandidates); 543 // FIXME(rwols): How can we determine the "active overload candidate"? 544 // Right now the overloaded candidates seem to be provided in a "best fit" 545 // order, so I'm not too worried about this. 546 SigHelp.activeSignature = 0; 547 assert(CurrentArg <= (unsigned)std::numeric_limits<int>::max() && 548 "too many arguments"); 549 SigHelp.activeParameter = static_cast<int>(CurrentArg); 550 for (unsigned I = 0; I < NumCandidates; ++I) { 551 const auto &Candidate = Candidates[I]; 552 const auto *CCS = Candidate.CreateSignatureString( 553 CurrentArg, S, *Allocator, CCTUInfo, true); 554 assert(CCS && "Expected the CodeCompletionString to be non-null"); 555 SigHelp.signatures.push_back(ProcessOverloadCandidate(Candidate, *CCS)); 556 } 557 } 558 559 GlobalCodeCompletionAllocator &getAllocator() override { return *Allocator; } 560 561 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; } 562 563 private: 564 // FIXME(ioeric): consider moving CodeCompletionString logic here to 565 // CompletionString.h. 566 SignatureInformation 567 ProcessOverloadCandidate(const OverloadCandidate &Candidate, 568 const CodeCompletionString &CCS) const { 569 SignatureInformation Result; 570 const char *ReturnType = nullptr; 571 572 Result.documentation = getDocumentation(CCS); 573 574 for (const auto &Chunk : CCS) { 575 switch (Chunk.Kind) { 576 case CodeCompletionString::CK_ResultType: 577 // A piece of text that describes the type of an entity or, 578 // for functions and methods, the return type. 579 assert(!ReturnType && "Unexpected CK_ResultType"); 580 ReturnType = Chunk.Text; 581 break; 582 case CodeCompletionString::CK_Placeholder: 583 // A string that acts as a placeholder for, e.g., a function call 584 // argument. 585 // Intentional fallthrough here. 586 case CodeCompletionString::CK_CurrentParameter: { 587 // A piece of text that describes the parameter that corresponds to 588 // the code-completion location within a function call, message send, 589 // macro invocation, etc. 590 Result.label += Chunk.Text; 591 ParameterInformation Info; 592 Info.label = Chunk.Text; 593 Result.parameters.push_back(std::move(Info)); 594 break; 595 } 596 case CodeCompletionString::CK_Optional: { 597 // The rest of the parameters are defaulted/optional. 598 assert(Chunk.Optional && 599 "Expected the optional code completion string to be non-null."); 600 Result.label += 601 getOptionalParameters(*Chunk.Optional, Result.parameters); 602 break; 603 } 604 case CodeCompletionString::CK_VerticalSpace: 605 break; 606 default: 607 Result.label += Chunk.Text; 608 break; 609 } 610 } 611 if (ReturnType) { 612 Result.label += " -> "; 613 Result.label += ReturnType; 614 } 615 return Result; 616 } 617 618 SignatureHelp &SigHelp; 619 std::shared_ptr<clang::GlobalCodeCompletionAllocator> Allocator; 620 CodeCompletionTUInfo CCTUInfo; 621 622 }; // SignatureHelpCollector 623 624 struct SemaCompleteInput { 625 PathRef FileName; 626 const tooling::CompileCommand &Command; 627 PrecompiledPreamble const *Preamble; 628 StringRef Contents; 629 Position Pos; 630 IntrusiveRefCntPtr<vfs::FileSystem> VFS; 631 std::shared_ptr<PCHContainerOperations> PCHs; 632 }; 633 634 // Invokes Sema code completion on a file. 635 // Callback will be invoked once completion is done, but before cleaning up. 636 bool semaCodeComplete(std::unique_ptr<CodeCompleteConsumer> Consumer, 637 const clang::CodeCompleteOptions &Options, 638 const SemaCompleteInput &Input, 639 llvm::function_ref<void()> Callback = nullptr) { 640 auto Tracer = llvm::make_unique<trace::Span>("Sema completion"); 641 std::vector<const char *> ArgStrs; 642 for (const auto &S : Input.Command.CommandLine) 643 ArgStrs.push_back(S.c_str()); 644 645 Input.VFS->setCurrentWorkingDirectory(Input.Command.Directory); 646 647 IgnoreDiagnostics DummyDiagsConsumer; 648 auto CI = createInvocationFromCommandLine( 649 ArgStrs, 650 CompilerInstance::createDiagnostics(new DiagnosticOptions, 651 &DummyDiagsConsumer, false), 652 Input.VFS); 653 if (!CI) { 654 log("Couldn't create CompilerInvocation");; 655 return false; 656 } 657 CI->getFrontendOpts().DisableFree = false; 658 659 std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer = 660 llvm::MemoryBuffer::getMemBufferCopy(Input.Contents, Input.FileName); 661 662 // We reuse the preamble whether it's valid or not. This is a 663 // correctness/performance tradeoff: building without a preamble is slow, and 664 // completion is latency-sensitive. 665 if (Input.Preamble) { 666 auto Bounds = 667 ComputePreambleBounds(*CI->getLangOpts(), ContentsBuffer.get(), 0); 668 // FIXME(ibiryukov): Remove this call to CanReuse() after we'll fix 669 // clients relying on getting stats for preamble files during code 670 // completion. 671 // Note that results of CanReuse() are ignored, see the comment above. 672 Input.Preamble->CanReuse(*CI, ContentsBuffer.get(), Bounds, 673 Input.VFS.get()); 674 } 675 auto Clang = prepareCompilerInstance( 676 std::move(CI), Input.Preamble, std::move(ContentsBuffer), 677 std::move(Input.PCHs), std::move(Input.VFS), DummyDiagsConsumer); 678 auto &DiagOpts = Clang->getDiagnosticOpts(); 679 DiagOpts.IgnoreWarnings = true; 680 681 // Disable typo correction in Sema. 682 Clang->getLangOpts().SpellChecking = false; 683 684 auto &FrontendOpts = Clang->getFrontendOpts(); 685 FrontendOpts.SkipFunctionBodies = true; 686 FrontendOpts.CodeCompleteOpts = Options; 687 FrontendOpts.CodeCompletionAt.FileName = Input.FileName; 688 FrontendOpts.CodeCompletionAt.Line = Input.Pos.line + 1; 689 FrontendOpts.CodeCompletionAt.Column = Input.Pos.character + 1; 690 691 Clang->setCodeCompletionConsumer(Consumer.release()); 692 693 SyntaxOnlyAction Action; 694 if (!Action.BeginSourceFile(*Clang, Clang->getFrontendOpts().Inputs[0])) { 695 log("BeginSourceFile() failed when running codeComplete for " + 696 Input.FileName); 697 return false; 698 } 699 if (!Action.Execute()) { 700 log("Execute() failed when running codeComplete for " + Input.FileName); 701 return false; 702 } 703 Tracer.reset(); 704 705 if (Callback) 706 Callback(); 707 708 Tracer = llvm::make_unique<trace::Span>("Sema completion cleanup"); 709 Action.EndSourceFile(); 710 711 return true; 712 } 713 714 // Should we perform index-based completion in this context? 715 // FIXME: consider allowing completion, but restricting the result types. 716 bool allowIndex(enum CodeCompletionContext::Kind K) { 717 switch (K) { 718 case CodeCompletionContext::CCC_TopLevel: 719 case CodeCompletionContext::CCC_ObjCInterface: 720 case CodeCompletionContext::CCC_ObjCImplementation: 721 case CodeCompletionContext::CCC_ObjCIvarList: 722 case CodeCompletionContext::CCC_ClassStructUnion: 723 case CodeCompletionContext::CCC_Statement: 724 case CodeCompletionContext::CCC_Expression: 725 case CodeCompletionContext::CCC_ObjCMessageReceiver: 726 case CodeCompletionContext::CCC_EnumTag: 727 case CodeCompletionContext::CCC_UnionTag: 728 case CodeCompletionContext::CCC_ClassOrStructTag: 729 case CodeCompletionContext::CCC_ObjCProtocolName: 730 case CodeCompletionContext::CCC_Namespace: 731 case CodeCompletionContext::CCC_Type: 732 case CodeCompletionContext::CCC_Name: // FIXME: why does ns::^ give this? 733 case CodeCompletionContext::CCC_PotentiallyQualifiedName: 734 case CodeCompletionContext::CCC_ParenthesizedExpression: 735 case CodeCompletionContext::CCC_ObjCInterfaceName: 736 case CodeCompletionContext::CCC_ObjCCategoryName: 737 return true; 738 case CodeCompletionContext::CCC_Other: // Be conservative. 739 case CodeCompletionContext::CCC_OtherWithMacros: 740 case CodeCompletionContext::CCC_DotMemberAccess: 741 case CodeCompletionContext::CCC_ArrowMemberAccess: 742 case CodeCompletionContext::CCC_ObjCPropertyAccess: 743 case CodeCompletionContext::CCC_MacroName: 744 case CodeCompletionContext::CCC_MacroNameUse: 745 case CodeCompletionContext::CCC_PreprocessorExpression: 746 case CodeCompletionContext::CCC_PreprocessorDirective: 747 case CodeCompletionContext::CCC_NaturalLanguage: 748 case CodeCompletionContext::CCC_SelectorName: 749 case CodeCompletionContext::CCC_TypeQualifiers: 750 case CodeCompletionContext::CCC_ObjCInstanceMessage: 751 case CodeCompletionContext::CCC_ObjCClassMessage: 752 case CodeCompletionContext::CCC_Recovery: 753 return false; 754 } 755 llvm_unreachable("unknown code completion context"); 756 } 757 758 } // namespace 759 760 clang::CodeCompleteOptions CodeCompleteOptions::getClangCompleteOpts() const { 761 clang::CodeCompleteOptions Result; 762 Result.IncludeCodePatterns = EnableSnippets && IncludeCodePatterns; 763 Result.IncludeMacros = IncludeMacros; 764 Result.IncludeGlobals = true; 765 Result.IncludeBriefComments = IncludeBriefComments; 766 767 // When an is used, Sema is responsible for completing the main file, 768 // the index can provide results from the preamble. 769 // Tell Sema not to deserialize the preamble to look for results. 770 Result.LoadExternal = !Index; 771 772 return Result; 773 } 774 775 // Runs Sema-based (AST) and Index-based completion, returns merged results. 776 // 777 // There are a few tricky considerations: 778 // - the AST provides information needed for the index query (e.g. which 779 // namespaces to search in). So Sema must start first. 780 // - we only want to return the top results (Opts.Limit). 781 // Building CompletionItems for everything else is wasteful, so we want to 782 // preserve the "native" format until we're done with scoring. 783 // - the data underlying Sema completion items is owned by the AST and various 784 // other arenas, which must stay alive for us to build CompletionItems. 785 // - we may get duplicate results from Sema and the Index, we need to merge. 786 // 787 // So we start Sema completion first, but defer its cleanup until we're done. 788 // We use the Sema context information to query the index. 789 // Then we merge the two result sets, producing items that are Sema/Index/Both. 790 // These items are scored, and the top N are synthesized into the LSP response. 791 // Finally, we can clean up the data structures created by Sema completion. 792 // 793 // Main collaborators are: 794 // - semaCodeComplete sets up the compiler machinery to run code completion. 795 // - CompletionRecorder captures Sema completion results, including context. 796 // - SymbolIndex (Opts.Index) provides index completion results as Symbols 797 // - CompletionCandidates are the result of merging Sema and Index results. 798 // Each candidate points to an underlying CodeCompletionResult (Sema), a 799 // Symbol (Index), or both. It computes the result quality score. 800 // CompletionCandidate also does conversion to CompletionItem (at the end). 801 // - FuzzyMatcher scores how the candidate matches the partial identifier. 802 // This score is combined with the result quality score for the final score. 803 // - TopN determines the results with the best score. 804 class CodeCompleteFlow { 805 const CodeCompleteOptions &Opts; 806 // Sema takes ownership of Recorder. Recorder is valid until Sema cleanup. 807 std::unique_ptr<CompletionRecorder> RecorderOwner; 808 CompletionRecorder &Recorder; 809 int NSema = 0, NIndex = 0, NBoth = 0; // Counters for logging. 810 bool Incomplete = false; // Would more be available with a higher limit? 811 llvm::Optional<FuzzyMatcher> Filter; // Initialized once Sema runs. 812 813 public: 814 // A CodeCompleteFlow object is only useful for calling run() exactly once. 815 CodeCompleteFlow(const CodeCompleteOptions &Opts) 816 : Opts(Opts), RecorderOwner(new CompletionRecorder(Opts)), 817 Recorder(*RecorderOwner) {} 818 819 CompletionList run(const SemaCompleteInput &SemaCCInput) && { 820 trace::Span Tracer("CodeCompleteFlow"); 821 // We run Sema code completion first. It builds an AST and calculates: 822 // - completion results based on the AST. These are saved for merging. 823 // - partial identifier and context. We need these for the index query. 824 CompletionList Output; 825 semaCodeComplete(std::move(RecorderOwner), Opts.getClangCompleteOpts(), 826 SemaCCInput, [&] { 827 if (Recorder.CCSema) 828 Output = runWithSema(); 829 else 830 log("Code complete: no Sema callback, 0 results"); 831 }); 832 833 SPAN_ATTACH(Tracer, "sema_results", NSema); 834 SPAN_ATTACH(Tracer, "index_results", NIndex); 835 SPAN_ATTACH(Tracer, "merged_results", NBoth); 836 SPAN_ATTACH(Tracer, "returned_results", Output.items.size()); 837 SPAN_ATTACH(Tracer, "incomplete", Output.isIncomplete); 838 log(llvm::formatv("Code complete: {0} results from Sema, {1} from Index, " 839 "{2} matched, {3} returned{4}.", 840 NSema, NIndex, NBoth, Output.items.size(), 841 Output.isIncomplete ? " (incomplete)" : "")); 842 assert(!Opts.Limit || Output.items.size() <= Opts.Limit); 843 // We don't assert that isIncomplete means we hit a limit. 844 // Indexes may choose to impose their own limits even if we don't have one. 845 return Output; 846 } 847 848 private: 849 // This is called by run() once Sema code completion is done, but before the 850 // Sema data structures are torn down. It does all the real work. 851 CompletionList runWithSema() { 852 Filter = FuzzyMatcher( 853 Recorder.CCSema->getPreprocessor().getCodeCompletionFilter()); 854 // Sema provides the needed context to query the index. 855 // FIXME: in addition to querying for extra/overlapping symbols, we should 856 // explicitly request symbols corresponding to Sema results. 857 // We can use their signals even if the index can't suggest them. 858 // We must copy index results to preserve them, but there are at most Limit. 859 auto IndexResults = queryIndex(); 860 // Merge Sema and Index results, score them, and pick the winners. 861 auto Top = mergeResults(Recorder.Results, IndexResults); 862 // Convert the results to the desired LSP structs. 863 CompletionList Output; 864 for (auto &C : Top) 865 Output.items.push_back(toCompletionItem(C.first, C.second)); 866 Output.isIncomplete = Incomplete; 867 return Output; 868 } 869 870 SymbolSlab queryIndex() { 871 if (!Opts.Index || !allowIndex(Recorder.CCContext.getKind())) 872 return SymbolSlab(); 873 trace::Span Tracer("Query index"); 874 SPAN_ATTACH(Tracer, "limit", Opts.Limit); 875 876 SymbolSlab::Builder ResultsBuilder; 877 // Build the query. 878 FuzzyFindRequest Req; 879 if (Opts.Limit) 880 Req.MaxCandidateCount = Opts.Limit; 881 Req.Query = Filter->pattern(); 882 Req.Scopes = 883 getQueryScopes(Recorder.CCContext, Recorder.CCSema->getSourceManager()); 884 log(llvm::formatv("Code complete: fuzzyFind(\"{0}\", scopes=[{1}])", 885 Req.Query, 886 llvm::join(Req.Scopes.begin(), Req.Scopes.end(), ","))); 887 // Run the query against the index. 888 Incomplete |= !Opts.Index->fuzzyFind( 889 Req, [&](const Symbol &Sym) { ResultsBuilder.insert(Sym); }); 890 return std::move(ResultsBuilder).build(); 891 } 892 893 // Merges the Sema and Index results where possible, scores them, and 894 // returns the top results from best to worst. 895 std::vector<std::pair<CompletionCandidate, CompletionItemScores>> 896 mergeResults(const std::vector<CodeCompletionResult> &SemaResults, 897 const SymbolSlab &IndexResults) { 898 trace::Span Tracer("Merge and score results"); 899 // We only keep the best N results at any time, in "native" format. 900 TopN Top(Opts.Limit == 0 ? TopN::Unbounded : Opts.Limit); 901 llvm::DenseSet<const Symbol *> UsedIndexResults; 902 auto CorrespondingIndexResult = 903 [&](const CodeCompletionResult &SemaResult) -> const Symbol * { 904 if (auto SymID = getSymbolID(SemaResult)) { 905 auto I = IndexResults.find(*SymID); 906 if (I != IndexResults.end()) { 907 UsedIndexResults.insert(&*I); 908 return &*I; 909 } 910 } 911 return nullptr; 912 }; 913 // Emit all Sema results, merging them with Index results if possible. 914 for (auto &SemaResult : Recorder.Results) 915 addCandidate(Top, &SemaResult, CorrespondingIndexResult(SemaResult)); 916 // Now emit any Index-only results. 917 for (const auto &IndexResult : IndexResults) { 918 if (UsedIndexResults.count(&IndexResult)) 919 continue; 920 addCandidate(Top, /*SemaResult=*/nullptr, &IndexResult); 921 } 922 return std::move(Top).items(); 923 } 924 925 // Scores a candidate and adds it to the TopN structure. 926 void addCandidate(TopN &Candidates, const CodeCompletionResult *SemaResult, 927 const Symbol *IndexResult) { 928 CompletionCandidate C; 929 C.SemaResult = SemaResult; 930 C.IndexResult = IndexResult; 931 C.Name = IndexResult ? IndexResult->Name : Recorder.getName(*SemaResult); 932 933 CompletionItemScores Scores; 934 if (auto FuzzyScore = Filter->match(C.Name)) 935 Scores.filterScore = *FuzzyScore; 936 else 937 return; 938 Scores.symbolScore = C.score(); 939 // We score candidates by multiplying symbolScore ("quality" of the result) 940 // with filterScore (how well it matched the query). 941 // This is sensitive to the distribution of both component scores! 942 Scores.finalScore = Scores.filterScore * Scores.symbolScore; 943 944 NSema += bool(SemaResult); 945 NIndex += bool(IndexResult); 946 NBoth += SemaResult && IndexResult; 947 Incomplete |= Candidates.push({C, Scores}); 948 } 949 950 CompletionItem toCompletionItem(const CompletionCandidate &Candidate, 951 const CompletionItemScores &Scores) { 952 CodeCompletionString *SemaCCS = nullptr; 953 if (auto *SR = Candidate.SemaResult) 954 SemaCCS = Recorder.codeCompletionString(*SR, Opts.IncludeBriefComments); 955 return Candidate.build(Scores, Opts, SemaCCS); 956 } 957 }; 958 959 CompletionList codeComplete(PathRef FileName, 960 const tooling::CompileCommand &Command, 961 PrecompiledPreamble const *Preamble, 962 StringRef Contents, Position Pos, 963 IntrusiveRefCntPtr<vfs::FileSystem> VFS, 964 std::shared_ptr<PCHContainerOperations> PCHs, 965 CodeCompleteOptions Opts) { 966 return CodeCompleteFlow(Opts).run( 967 {FileName, Command, Preamble, Contents, Pos, VFS, PCHs}); 968 } 969 970 SignatureHelp signatureHelp(PathRef FileName, 971 const tooling::CompileCommand &Command, 972 PrecompiledPreamble const *Preamble, 973 StringRef Contents, Position Pos, 974 IntrusiveRefCntPtr<vfs::FileSystem> VFS, 975 std::shared_ptr<PCHContainerOperations> PCHs) { 976 SignatureHelp Result; 977 clang::CodeCompleteOptions Options; 978 Options.IncludeGlobals = false; 979 Options.IncludeMacros = false; 980 Options.IncludeCodePatterns = false; 981 Options.IncludeBriefComments = true; 982 semaCodeComplete(llvm::make_unique<SignatureHelpCollector>(Options, Result), 983 Options, 984 {FileName, Command, Preamble, Contents, Pos, std::move(VFS), 985 std::move(PCHs)}); 986 return Result; 987 } 988 989 } // namespace clangd 990 } // namespace clang 991