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