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