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