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