1 //===- CodeCompleteConsumer.cpp - Code Completion Interface ---------------===// 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 // This file implements the CodeCompleteConsumer class. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "clang/Sema/CodeCompleteConsumer.h" 14 #include "clang-c/Index.h" 15 #include "clang/AST/Decl.h" 16 #include "clang/AST/DeclBase.h" 17 #include "clang/AST/DeclObjC.h" 18 #include "clang/AST/DeclTemplate.h" 19 #include "clang/AST/DeclarationName.h" 20 #include "clang/AST/Type.h" 21 #include "clang/Basic/IdentifierTable.h" 22 #include "clang/Lex/Preprocessor.h" 23 #include "clang/Sema/Sema.h" 24 #include "llvm/ADT/SmallString.h" 25 #include "llvm/ADT/SmallVector.h" 26 #include "llvm/ADT/StringExtras.h" 27 #include "llvm/ADT/StringRef.h" 28 #include "llvm/ADT/Twine.h" 29 #include "llvm/Support/Casting.h" 30 #include "llvm/Support/Compiler.h" 31 #include "llvm/Support/ErrorHandling.h" 32 #include "llvm/Support/FormatVariadic.h" 33 #include "llvm/Support/raw_ostream.h" 34 #include <algorithm> 35 #include <cassert> 36 #include <cstdint> 37 #include <string> 38 39 using namespace clang; 40 41 //===----------------------------------------------------------------------===// 42 // Code completion context implementation 43 //===----------------------------------------------------------------------===// 44 45 bool CodeCompletionContext::wantConstructorResults() const { 46 switch (CCKind) { 47 case CCC_Recovery: 48 case CCC_Statement: 49 case CCC_Expression: 50 case CCC_ObjCMessageReceiver: 51 case CCC_ParenthesizedExpression: 52 case CCC_Symbol: 53 case CCC_SymbolOrNewName: 54 return true; 55 56 case CCC_TopLevel: 57 case CCC_ObjCInterface: 58 case CCC_ObjCImplementation: 59 case CCC_ObjCIvarList: 60 case CCC_ClassStructUnion: 61 case CCC_DotMemberAccess: 62 case CCC_ArrowMemberAccess: 63 case CCC_ObjCPropertyAccess: 64 case CCC_EnumTag: 65 case CCC_UnionTag: 66 case CCC_ClassOrStructTag: 67 case CCC_ObjCProtocolName: 68 case CCC_Namespace: 69 case CCC_Type: 70 case CCC_NewName: 71 case CCC_MacroName: 72 case CCC_MacroNameUse: 73 case CCC_PreprocessorExpression: 74 case CCC_PreprocessorDirective: 75 case CCC_NaturalLanguage: 76 case CCC_SelectorName: 77 case CCC_TypeQualifiers: 78 case CCC_Other: 79 case CCC_OtherWithMacros: 80 case CCC_ObjCInstanceMessage: 81 case CCC_ObjCClassMessage: 82 case CCC_ObjCInterfaceName: 83 case CCC_ObjCCategoryName: 84 case CCC_IncludedFile: 85 case CCC_Attribute: 86 return false; 87 } 88 89 llvm_unreachable("Invalid CodeCompletionContext::Kind!"); 90 } 91 92 StringRef clang::getCompletionKindString(CodeCompletionContext::Kind Kind) { 93 using CCKind = CodeCompletionContext::Kind; 94 switch (Kind) { 95 case CCKind::CCC_Other: 96 return "Other"; 97 case CCKind::CCC_OtherWithMacros: 98 return "OtherWithMacros"; 99 case CCKind::CCC_TopLevel: 100 return "TopLevel"; 101 case CCKind::CCC_ObjCInterface: 102 return "ObjCInterface"; 103 case CCKind::CCC_ObjCImplementation: 104 return "ObjCImplementation"; 105 case CCKind::CCC_ObjCIvarList: 106 return "ObjCIvarList"; 107 case CCKind::CCC_ClassStructUnion: 108 return "ClassStructUnion"; 109 case CCKind::CCC_Statement: 110 return "Statement"; 111 case CCKind::CCC_Expression: 112 return "Expression"; 113 case CCKind::CCC_ObjCMessageReceiver: 114 return "ObjCMessageReceiver"; 115 case CCKind::CCC_DotMemberAccess: 116 return "DotMemberAccess"; 117 case CCKind::CCC_ArrowMemberAccess: 118 return "ArrowMemberAccess"; 119 case CCKind::CCC_ObjCPropertyAccess: 120 return "ObjCPropertyAccess"; 121 case CCKind::CCC_EnumTag: 122 return "EnumTag"; 123 case CCKind::CCC_UnionTag: 124 return "UnionTag"; 125 case CCKind::CCC_ClassOrStructTag: 126 return "ClassOrStructTag"; 127 case CCKind::CCC_ObjCProtocolName: 128 return "ObjCProtocolName"; 129 case CCKind::CCC_Namespace: 130 return "Namespace"; 131 case CCKind::CCC_Type: 132 return "Type"; 133 case CCKind::CCC_NewName: 134 return "NewName"; 135 case CCKind::CCC_Symbol: 136 return "Symbol"; 137 case CCKind::CCC_SymbolOrNewName: 138 return "SymbolOrNewName"; 139 case CCKind::CCC_MacroName: 140 return "MacroName"; 141 case CCKind::CCC_MacroNameUse: 142 return "MacroNameUse"; 143 case CCKind::CCC_PreprocessorExpression: 144 return "PreprocessorExpression"; 145 case CCKind::CCC_PreprocessorDirective: 146 return "PreprocessorDirective"; 147 case CCKind::CCC_NaturalLanguage: 148 return "NaturalLanguage"; 149 case CCKind::CCC_SelectorName: 150 return "SelectorName"; 151 case CCKind::CCC_TypeQualifiers: 152 return "TypeQualifiers"; 153 case CCKind::CCC_ParenthesizedExpression: 154 return "ParenthesizedExpression"; 155 case CCKind::CCC_ObjCInstanceMessage: 156 return "ObjCInstanceMessage"; 157 case CCKind::CCC_ObjCClassMessage: 158 return "ObjCClassMessage"; 159 case CCKind::CCC_ObjCInterfaceName: 160 return "ObjCInterfaceName"; 161 case CCKind::CCC_ObjCCategoryName: 162 return "ObjCCategoryName"; 163 case CCKind::CCC_IncludedFile: 164 return "IncludedFile"; 165 case CCKind::CCC_Attribute: 166 return "Attribute"; 167 case CCKind::CCC_Recovery: 168 return "Recovery"; 169 } 170 llvm_unreachable("Invalid CodeCompletionContext::Kind!"); 171 } 172 173 //===----------------------------------------------------------------------===// 174 // Code completion string implementation 175 //===----------------------------------------------------------------------===// 176 177 CodeCompletionString::Chunk::Chunk(ChunkKind Kind, const char *Text) 178 : Kind(Kind), Text("") { 179 switch (Kind) { 180 case CK_TypedText: 181 case CK_Text: 182 case CK_Placeholder: 183 case CK_Informative: 184 case CK_ResultType: 185 case CK_CurrentParameter: 186 this->Text = Text; 187 break; 188 189 case CK_Optional: 190 llvm_unreachable("Optional strings cannot be created from text"); 191 192 case CK_LeftParen: 193 this->Text = "("; 194 break; 195 196 case CK_RightParen: 197 this->Text = ")"; 198 break; 199 200 case CK_LeftBracket: 201 this->Text = "["; 202 break; 203 204 case CK_RightBracket: 205 this->Text = "]"; 206 break; 207 208 case CK_LeftBrace: 209 this->Text = "{"; 210 break; 211 212 case CK_RightBrace: 213 this->Text = "}"; 214 break; 215 216 case CK_LeftAngle: 217 this->Text = "<"; 218 break; 219 220 case CK_RightAngle: 221 this->Text = ">"; 222 break; 223 224 case CK_Comma: 225 this->Text = ", "; 226 break; 227 228 case CK_Colon: 229 this->Text = ":"; 230 break; 231 232 case CK_SemiColon: 233 this->Text = ";"; 234 break; 235 236 case CK_Equal: 237 this->Text = " = "; 238 break; 239 240 case CK_HorizontalSpace: 241 this->Text = " "; 242 break; 243 244 case CK_VerticalSpace: 245 this->Text = "\n"; 246 break; 247 } 248 } 249 250 CodeCompletionString::Chunk 251 CodeCompletionString::Chunk::CreateText(const char *Text) { 252 return Chunk(CK_Text, Text); 253 } 254 255 CodeCompletionString::Chunk 256 CodeCompletionString::Chunk::CreateOptional(CodeCompletionString *Optional) { 257 Chunk Result; 258 Result.Kind = CK_Optional; 259 Result.Optional = Optional; 260 return Result; 261 } 262 263 CodeCompletionString::Chunk 264 CodeCompletionString::Chunk::CreatePlaceholder(const char *Placeholder) { 265 return Chunk(CK_Placeholder, Placeholder); 266 } 267 268 CodeCompletionString::Chunk 269 CodeCompletionString::Chunk::CreateInformative(const char *Informative) { 270 return Chunk(CK_Informative, Informative); 271 } 272 273 CodeCompletionString::Chunk 274 CodeCompletionString::Chunk::CreateResultType(const char *ResultType) { 275 return Chunk(CK_ResultType, ResultType); 276 } 277 278 CodeCompletionString::Chunk CodeCompletionString::Chunk::CreateCurrentParameter( 279 const char *CurrentParameter) { 280 return Chunk(CK_CurrentParameter, CurrentParameter); 281 } 282 283 CodeCompletionString::CodeCompletionString( 284 const Chunk *Chunks, unsigned NumChunks, unsigned Priority, 285 CXAvailabilityKind Availability, const char **Annotations, 286 unsigned NumAnnotations, StringRef ParentName, const char *BriefComment) 287 : NumChunks(NumChunks), NumAnnotations(NumAnnotations), Priority(Priority), 288 Availability(Availability), ParentName(ParentName), 289 BriefComment(BriefComment) { 290 assert(NumChunks <= 0xffff); 291 assert(NumAnnotations <= 0xffff); 292 293 Chunk *StoredChunks = reinterpret_cast<Chunk *>(this + 1); 294 for (unsigned I = 0; I != NumChunks; ++I) 295 StoredChunks[I] = Chunks[I]; 296 297 const char **StoredAnnotations = 298 reinterpret_cast<const char **>(StoredChunks + NumChunks); 299 for (unsigned I = 0; I != NumAnnotations; ++I) 300 StoredAnnotations[I] = Annotations[I]; 301 } 302 303 unsigned CodeCompletionString::getAnnotationCount() const { 304 return NumAnnotations; 305 } 306 307 const char *CodeCompletionString::getAnnotation(unsigned AnnotationNr) const { 308 if (AnnotationNr < NumAnnotations) 309 return reinterpret_cast<const char *const *>(end())[AnnotationNr]; 310 else 311 return nullptr; 312 } 313 314 std::string CodeCompletionString::getAsString() const { 315 std::string Result; 316 llvm::raw_string_ostream OS(Result); 317 318 for (const Chunk &C : *this) { 319 switch (C.Kind) { 320 case CK_Optional: 321 OS << "{#" << C.Optional->getAsString() << "#}"; 322 break; 323 case CK_Placeholder: 324 OS << "<#" << C.Text << "#>"; 325 break; 326 case CK_Informative: 327 case CK_ResultType: 328 OS << "[#" << C.Text << "#]"; 329 break; 330 case CK_CurrentParameter: 331 OS << "<#" << C.Text << "#>"; 332 break; 333 default: 334 OS << C.Text; 335 break; 336 } 337 } 338 return Result; 339 } 340 341 const char *CodeCompletionString::getTypedText() const { 342 for (const Chunk &C : *this) 343 if (C.Kind == CK_TypedText) 344 return C.Text; 345 346 return nullptr; 347 } 348 349 const char *CodeCompletionAllocator::CopyString(const Twine &String) { 350 SmallString<128> Data; 351 StringRef Ref = String.toStringRef(Data); 352 // FIXME: It would be more efficient to teach Twine to tell us its size and 353 // then add a routine there to fill in an allocated char* with the contents 354 // of the string. 355 char *Mem = (char *)Allocate(Ref.size() + 1, 1); 356 std::copy(Ref.begin(), Ref.end(), Mem); 357 Mem[Ref.size()] = 0; 358 return Mem; 359 } 360 361 StringRef CodeCompletionTUInfo::getParentName(const DeclContext *DC) { 362 if (!isa<NamedDecl>(DC)) 363 return {}; 364 365 // Check whether we've already cached the parent name. 366 StringRef &CachedParentName = ParentNames[DC]; 367 if (!CachedParentName.empty()) 368 return CachedParentName; 369 370 // If we already processed this DeclContext and assigned empty to it, the 371 // data pointer will be non-null. 372 if (CachedParentName.data() != nullptr) 373 return {}; 374 375 // Find the interesting names. 376 SmallVector<const DeclContext *, 2> Contexts; 377 while (DC && !DC->isFunctionOrMethod()) { 378 if (const auto *ND = dyn_cast<NamedDecl>(DC)) { 379 if (ND->getIdentifier()) 380 Contexts.push_back(DC); 381 } 382 383 DC = DC->getParent(); 384 } 385 386 { 387 SmallString<128> S; 388 llvm::raw_svector_ostream OS(S); 389 bool First = true; 390 for (const DeclContext *CurDC : llvm::reverse(Contexts)) { 391 if (First) 392 First = false; 393 else { 394 OS << "::"; 395 } 396 397 if (const auto *CatImpl = dyn_cast<ObjCCategoryImplDecl>(CurDC)) 398 CurDC = CatImpl->getCategoryDecl(); 399 400 if (const auto *Cat = dyn_cast<ObjCCategoryDecl>(CurDC)) { 401 const ObjCInterfaceDecl *Interface = Cat->getClassInterface(); 402 if (!Interface) { 403 // Assign an empty StringRef but with non-null data to distinguish 404 // between empty because we didn't process the DeclContext yet. 405 CachedParentName = StringRef((const char *)(uintptr_t)~0U, 0); 406 return {}; 407 } 408 409 OS << Interface->getName() << '(' << Cat->getName() << ')'; 410 } else { 411 OS << cast<NamedDecl>(CurDC)->getName(); 412 } 413 } 414 415 CachedParentName = AllocatorRef->CopyString(OS.str()); 416 } 417 418 return CachedParentName; 419 } 420 421 CodeCompletionString *CodeCompletionBuilder::TakeString() { 422 void *Mem = getAllocator().Allocate( 423 sizeof(CodeCompletionString) + sizeof(Chunk) * Chunks.size() + 424 sizeof(const char *) * Annotations.size(), 425 alignof(CodeCompletionString)); 426 CodeCompletionString *Result = new (Mem) CodeCompletionString( 427 Chunks.data(), Chunks.size(), Priority, Availability, Annotations.data(), 428 Annotations.size(), ParentName, BriefComment); 429 Chunks.clear(); 430 return Result; 431 } 432 433 void CodeCompletionBuilder::AddTypedTextChunk(const char *Text) { 434 Chunks.push_back(Chunk(CodeCompletionString::CK_TypedText, Text)); 435 } 436 437 void CodeCompletionBuilder::AddTextChunk(const char *Text) { 438 Chunks.push_back(Chunk::CreateText(Text)); 439 } 440 441 void CodeCompletionBuilder::AddOptionalChunk(CodeCompletionString *Optional) { 442 Chunks.push_back(Chunk::CreateOptional(Optional)); 443 } 444 445 void CodeCompletionBuilder::AddPlaceholderChunk(const char *Placeholder) { 446 Chunks.push_back(Chunk::CreatePlaceholder(Placeholder)); 447 } 448 449 void CodeCompletionBuilder::AddInformativeChunk(const char *Text) { 450 Chunks.push_back(Chunk::CreateInformative(Text)); 451 } 452 453 void CodeCompletionBuilder::AddResultTypeChunk(const char *ResultType) { 454 Chunks.push_back(Chunk::CreateResultType(ResultType)); 455 } 456 457 void CodeCompletionBuilder::AddCurrentParameterChunk( 458 const char *CurrentParameter) { 459 Chunks.push_back(Chunk::CreateCurrentParameter(CurrentParameter)); 460 } 461 462 void CodeCompletionBuilder::AddChunk(CodeCompletionString::ChunkKind CK, 463 const char *Text) { 464 Chunks.push_back(Chunk(CK, Text)); 465 } 466 467 void CodeCompletionBuilder::addParentContext(const DeclContext *DC) { 468 if (DC->isTranslationUnit()) 469 return; 470 471 if (DC->isFunctionOrMethod()) 472 return; 473 474 if (!isa<NamedDecl>(DC)) 475 return; 476 477 ParentName = getCodeCompletionTUInfo().getParentName(DC); 478 } 479 480 void CodeCompletionBuilder::addBriefComment(StringRef Comment) { 481 BriefComment = Allocator.CopyString(Comment); 482 } 483 484 //===----------------------------------------------------------------------===// 485 // Code completion overload candidate implementation 486 //===----------------------------------------------------------------------===// 487 FunctionDecl *CodeCompleteConsumer::OverloadCandidate::getFunction() const { 488 if (getKind() == CK_Function) 489 return Function; 490 else if (getKind() == CK_FunctionTemplate) 491 return FunctionTemplate->getTemplatedDecl(); 492 else 493 return nullptr; 494 } 495 496 const FunctionType * 497 CodeCompleteConsumer::OverloadCandidate::getFunctionType() const { 498 switch (Kind) { 499 case CK_Function: 500 return Function->getType()->getAs<FunctionType>(); 501 502 case CK_FunctionTemplate: 503 return FunctionTemplate->getTemplatedDecl() 504 ->getType() 505 ->getAs<FunctionType>(); 506 507 case CK_FunctionType: 508 return Type; 509 510 case CK_Template: 511 case CK_Aggregate: 512 return nullptr; 513 } 514 515 llvm_unreachable("Invalid CandidateKind!"); 516 } 517 518 unsigned CodeCompleteConsumer::OverloadCandidate::getNumParams() const { 519 if (Kind == CK_Template) 520 return Template->getTemplateParameters()->size(); 521 522 if (Kind == CK_Aggregate) { 523 unsigned Count = 524 std::distance(AggregateType->field_begin(), AggregateType->field_end()); 525 if (const auto *CRD = dyn_cast<CXXRecordDecl>(AggregateType)) 526 Count += CRD->getNumBases(); 527 return Count; 528 } 529 530 if (const auto *FT = getFunctionType()) 531 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) 532 return FPT->getNumParams(); 533 534 return 0; 535 } 536 537 QualType 538 CodeCompleteConsumer::OverloadCandidate::getParamType(unsigned N) const { 539 if (Kind == CK_Aggregate) { 540 if (const auto *CRD = dyn_cast<CXXRecordDecl>(AggregateType)) { 541 if (N < CRD->getNumBases()) 542 return std::next(CRD->bases_begin(), N)->getType(); 543 N -= CRD->getNumBases(); 544 } 545 for (const auto *Field : AggregateType->fields()) 546 if (N-- == 0) 547 return Field->getType(); 548 return QualType(); 549 } 550 551 if (Kind == CK_Template) { 552 TemplateParameterList *TPL = getTemplate()->getTemplateParameters(); 553 if (N < TPL->size()) 554 if (const auto *D = dyn_cast<NonTypeTemplateParmDecl>(TPL->getParam(N))) 555 return D->getType(); 556 return QualType(); 557 } 558 559 if (const auto *FT = getFunctionType()) 560 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) 561 if (N < FPT->getNumParams()) 562 return FPT->getParamType(N); 563 return QualType(); 564 } 565 566 const NamedDecl * 567 CodeCompleteConsumer::OverloadCandidate::getParamDecl(unsigned N) const { 568 if (Kind == CK_Aggregate) { 569 if (const auto *CRD = dyn_cast<CXXRecordDecl>(AggregateType)) { 570 if (N < CRD->getNumBases()) 571 return std::next(CRD->bases_begin(), N)->getType()->getAsTagDecl(); 572 N -= CRD->getNumBases(); 573 } 574 for (const auto *Field : AggregateType->fields()) 575 if (N-- == 0) 576 return Field; 577 return nullptr; 578 } 579 580 if (Kind == CK_Template) { 581 TemplateParameterList *TPL = getTemplate()->getTemplateParameters(); 582 if (N < TPL->size()) 583 return TPL->getParam(N); 584 return nullptr; 585 } 586 587 // Note that if we only have a FunctionProtoType, we don't have param decls. 588 if (const auto *FD = getFunction()) { 589 if (N < FD->param_size()) 590 return FD->getParamDecl(N); 591 } 592 return nullptr; 593 } 594 595 //===----------------------------------------------------------------------===// 596 // Code completion consumer implementation 597 //===----------------------------------------------------------------------===// 598 599 CodeCompleteConsumer::~CodeCompleteConsumer() = default; 600 601 bool PrintingCodeCompleteConsumer::isResultFilteredOut( 602 StringRef Filter, CodeCompletionResult Result) { 603 switch (Result.Kind) { 604 case CodeCompletionResult::RK_Declaration: 605 return !(Result.Declaration->getIdentifier() && 606 Result.Declaration->getIdentifier()->getName().startswith(Filter)); 607 case CodeCompletionResult::RK_Keyword: 608 return !StringRef(Result.Keyword).startswith(Filter); 609 case CodeCompletionResult::RK_Macro: 610 return !Result.Macro->getName().startswith(Filter); 611 case CodeCompletionResult::RK_Pattern: 612 return !(Result.Pattern->getTypedText() && 613 StringRef(Result.Pattern->getTypedText()).startswith(Filter)); 614 } 615 llvm_unreachable("Unknown code completion result Kind."); 616 } 617 618 void PrintingCodeCompleteConsumer::ProcessCodeCompleteResults( 619 Sema &SemaRef, CodeCompletionContext Context, CodeCompletionResult *Results, 620 unsigned NumResults) { 621 std::stable_sort(Results, Results + NumResults); 622 623 if (!Context.getPreferredType().isNull()) 624 OS << "PREFERRED-TYPE: " << Context.getPreferredType().getAsString() 625 << "\n"; 626 627 StringRef Filter = SemaRef.getPreprocessor().getCodeCompletionFilter(); 628 // Print the completions. 629 for (unsigned I = 0; I != NumResults; ++I) { 630 if (!Filter.empty() && isResultFilteredOut(Filter, Results[I])) 631 continue; 632 OS << "COMPLETION: "; 633 switch (Results[I].Kind) { 634 case CodeCompletionResult::RK_Declaration: 635 OS << *Results[I].Declaration; 636 { 637 std::vector<std::string> Tags; 638 if (Results[I].Hidden) 639 Tags.push_back("Hidden"); 640 if (Results[I].InBaseClass) 641 Tags.push_back("InBase"); 642 if (Results[I].Availability == 643 CXAvailabilityKind::CXAvailability_NotAccessible) 644 Tags.push_back("Inaccessible"); 645 if (!Tags.empty()) 646 OS << " (" << llvm::join(Tags, ",") << ")"; 647 } 648 if (CodeCompletionString *CCS = Results[I].CreateCodeCompletionString( 649 SemaRef, Context, getAllocator(), CCTUInfo, 650 includeBriefComments())) { 651 OS << " : " << CCS->getAsString(); 652 if (const char *BriefComment = CCS->getBriefComment()) 653 OS << " : " << BriefComment; 654 } 655 break; 656 657 case CodeCompletionResult::RK_Keyword: 658 OS << Results[I].Keyword; 659 break; 660 661 case CodeCompletionResult::RK_Macro: 662 OS << Results[I].Macro->getName(); 663 if (CodeCompletionString *CCS = Results[I].CreateCodeCompletionString( 664 SemaRef, Context, getAllocator(), CCTUInfo, 665 includeBriefComments())) { 666 OS << " : " << CCS->getAsString(); 667 } 668 break; 669 670 case CodeCompletionResult::RK_Pattern: 671 OS << "Pattern : " << Results[I].Pattern->getAsString(); 672 break; 673 } 674 for (const FixItHint &FixIt : Results[I].FixIts) { 675 const SourceLocation BLoc = FixIt.RemoveRange.getBegin(); 676 const SourceLocation ELoc = FixIt.RemoveRange.getEnd(); 677 678 SourceManager &SM = SemaRef.SourceMgr; 679 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(BLoc); 680 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(ELoc); 681 // Adjust for token ranges. 682 if (FixIt.RemoveRange.isTokenRange()) 683 EInfo.second += Lexer::MeasureTokenLength(ELoc, SM, SemaRef.LangOpts); 684 685 OS << " (requires fix-it:" 686 << " {" << SM.getLineNumber(BInfo.first, BInfo.second) << ':' 687 << SM.getColumnNumber(BInfo.first, BInfo.second) << '-' 688 << SM.getLineNumber(EInfo.first, EInfo.second) << ':' 689 << SM.getColumnNumber(EInfo.first, EInfo.second) << "}" 690 << " to \"" << FixIt.CodeToInsert << "\")"; 691 } 692 OS << '\n'; 693 } 694 } 695 696 // This function is used solely to preserve the former presentation of overloads 697 // by "clang -cc1 -code-completion-at", since CodeCompletionString::getAsString 698 // needs to be improved for printing the newer and more detailed overload 699 // chunks. 700 static std::string getOverloadAsString(const CodeCompletionString &CCS) { 701 std::string Result; 702 llvm::raw_string_ostream OS(Result); 703 704 for (auto &C : CCS) { 705 switch (C.Kind) { 706 case CodeCompletionString::CK_Informative: 707 case CodeCompletionString::CK_ResultType: 708 OS << "[#" << C.Text << "#]"; 709 break; 710 711 case CodeCompletionString::CK_CurrentParameter: 712 OS << "<#" << C.Text << "#>"; 713 break; 714 715 // FIXME: We can also print optional parameters of an overload. 716 case CodeCompletionString::CK_Optional: 717 break; 718 719 default: 720 OS << C.Text; 721 break; 722 } 723 } 724 return Result; 725 } 726 727 void PrintingCodeCompleteConsumer::ProcessOverloadCandidates( 728 Sema &SemaRef, unsigned CurrentArg, OverloadCandidate *Candidates, 729 unsigned NumCandidates, SourceLocation OpenParLoc, bool Braced) { 730 OS << "OPENING_PAREN_LOC: "; 731 OpenParLoc.print(OS, SemaRef.getSourceManager()); 732 OS << "\n"; 733 734 for (unsigned I = 0; I != NumCandidates; ++I) { 735 if (CodeCompletionString *CCS = Candidates[I].CreateSignatureString( 736 CurrentArg, SemaRef, getAllocator(), CCTUInfo, 737 includeBriefComments(), Braced)) { 738 OS << "OVERLOAD: " << getOverloadAsString(*CCS) << "\n"; 739 } 740 } 741 } 742 743 /// Retrieve the effective availability of the given declaration. 744 static AvailabilityResult getDeclAvailability(const Decl *D) { 745 AvailabilityResult AR = D->getAvailability(); 746 if (isa<EnumConstantDecl>(D)) 747 AR = std::max(AR, cast<Decl>(D->getDeclContext())->getAvailability()); 748 return AR; 749 } 750 751 void CodeCompletionResult::computeCursorKindAndAvailability(bool Accessible) { 752 switch (Kind) { 753 case RK_Pattern: 754 if (!Declaration) { 755 // Do nothing: Patterns can come with cursor kinds! 756 break; 757 } 758 LLVM_FALLTHROUGH; 759 760 case RK_Declaration: { 761 // Set the availability based on attributes. 762 switch (getDeclAvailability(Declaration)) { 763 case AR_Available: 764 case AR_NotYetIntroduced: 765 Availability = CXAvailability_Available; 766 break; 767 768 case AR_Deprecated: 769 Availability = CXAvailability_Deprecated; 770 break; 771 772 case AR_Unavailable: 773 Availability = CXAvailability_NotAvailable; 774 break; 775 } 776 777 if (const auto *Function = dyn_cast<FunctionDecl>(Declaration)) 778 if (Function->isDeleted()) 779 Availability = CXAvailability_NotAvailable; 780 781 CursorKind = getCursorKindForDecl(Declaration); 782 if (CursorKind == CXCursor_UnexposedDecl) { 783 // FIXME: Forward declarations of Objective-C classes and protocols 784 // are not directly exposed, but we want code completion to treat them 785 // like a definition. 786 if (isa<ObjCInterfaceDecl>(Declaration)) 787 CursorKind = CXCursor_ObjCInterfaceDecl; 788 else if (isa<ObjCProtocolDecl>(Declaration)) 789 CursorKind = CXCursor_ObjCProtocolDecl; 790 else 791 CursorKind = CXCursor_NotImplemented; 792 } 793 break; 794 } 795 796 case RK_Macro: 797 case RK_Keyword: 798 llvm_unreachable("Macro and keyword kinds are handled by the constructors"); 799 } 800 801 if (!Accessible) 802 Availability = CXAvailability_NotAccessible; 803 } 804 805 /// Retrieve the name that should be used to order a result. 806 /// 807 /// If the name needs to be constructed as a string, that string will be 808 /// saved into Saved and the returned StringRef will refer to it. 809 StringRef CodeCompletionResult::getOrderedName(std::string &Saved) const { 810 switch (Kind) { 811 case RK_Keyword: 812 return Keyword; 813 case RK_Pattern: 814 return Pattern->getTypedText(); 815 case RK_Macro: 816 return Macro->getName(); 817 case RK_Declaration: 818 // Handle declarations below. 819 break; 820 } 821 822 DeclarationName Name = Declaration->getDeclName(); 823 824 // If the name is a simple identifier (by far the common case), or a 825 // zero-argument selector, just return a reference to that identifier. 826 if (IdentifierInfo *Id = Name.getAsIdentifierInfo()) 827 return Id->getName(); 828 if (Name.isObjCZeroArgSelector()) 829 if (IdentifierInfo *Id = Name.getObjCSelector().getIdentifierInfoForSlot(0)) 830 return Id->getName(); 831 832 Saved = Name.getAsString(); 833 return Saved; 834 } 835 836 bool clang::operator<(const CodeCompletionResult &X, 837 const CodeCompletionResult &Y) { 838 std::string XSaved, YSaved; 839 StringRef XStr = X.getOrderedName(XSaved); 840 StringRef YStr = Y.getOrderedName(YSaved); 841 int cmp = XStr.compare_insensitive(YStr); 842 if (cmp) 843 return cmp < 0; 844 845 // If case-insensitive comparison fails, try case-sensitive comparison. 846 return XStr.compare(YStr) < 0; 847 } 848