CodeCompleteConsumer.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733
  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. #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/Sema/Sema.h"
  23. #include "clang/Lex/Preprocessor.h"
  24. #include "llvm/ADT/SmallString.h"
  25. #include "llvm/ADT/SmallVector.h"
  26. #include "llvm/ADT/StringRef.h"
  27. #include "llvm/ADT/Twine.h"
  28. #include "llvm/Support/Casting.h"
  29. #include "llvm/Support/Compiler.h"
  30. #include "llvm/Support/ErrorHandling.h"
  31. #include "llvm/Support/raw_ostream.h"
  32. #include <algorithm>
  33. #include <cassert>
  34. #include <cstdint>
  35. #include <string>
  36. using namespace clang;
  37. //===----------------------------------------------------------------------===//
  38. // Code completion context implementation
  39. //===----------------------------------------------------------------------===//
  40. bool CodeCompletionContext::wantConstructorResults() const {
  41. switch (CCKind) {
  42. case CCC_Recovery:
  43. case CCC_Statement:
  44. case CCC_Expression:
  45. case CCC_ObjCMessageReceiver:
  46. case CCC_ParenthesizedExpression:
  47. return true;
  48. case CCC_TopLevel:
  49. case CCC_ObjCInterface:
  50. case CCC_ObjCImplementation:
  51. case CCC_ObjCIvarList:
  52. case CCC_ClassStructUnion:
  53. case CCC_DotMemberAccess:
  54. case CCC_ArrowMemberAccess:
  55. case CCC_ObjCPropertyAccess:
  56. case CCC_EnumTag:
  57. case CCC_UnionTag:
  58. case CCC_ClassOrStructTag:
  59. case CCC_ObjCProtocolName:
  60. case CCC_Namespace:
  61. case CCC_Type:
  62. case CCC_Name:
  63. case CCC_PotentiallyQualifiedName:
  64. case CCC_MacroName:
  65. case CCC_MacroNameUse:
  66. case CCC_PreprocessorExpression:
  67. case CCC_PreprocessorDirective:
  68. case CCC_NaturalLanguage:
  69. case CCC_SelectorName:
  70. case CCC_TypeQualifiers:
  71. case CCC_Other:
  72. case CCC_OtherWithMacros:
  73. case CCC_ObjCInstanceMessage:
  74. case CCC_ObjCClassMessage:
  75. case CCC_ObjCInterfaceName:
  76. case CCC_ObjCCategoryName:
  77. return false;
  78. }
  79. llvm_unreachable("Invalid CodeCompletionContext::Kind!");
  80. }
  81. StringRef clang::getCompletionKindString(CodeCompletionContext::Kind Kind) {
  82. using CCKind = CodeCompletionContext::Kind;
  83. switch (Kind) {
  84. case CCKind::CCC_Other:
  85. return "Other";
  86. case CCKind::CCC_OtherWithMacros:
  87. return "OtherWithMacros";
  88. case CCKind::CCC_TopLevel:
  89. return "TopLevel";
  90. case CCKind::CCC_ObjCInterface:
  91. return "ObjCInterface";
  92. case CCKind::CCC_ObjCImplementation:
  93. return "ObjCImplementation";
  94. case CCKind::CCC_ObjCIvarList:
  95. return "ObjCIvarList";
  96. case CCKind::CCC_ClassStructUnion:
  97. return "ClassStructUnion";
  98. case CCKind::CCC_Statement:
  99. return "Statement";
  100. case CCKind::CCC_Expression:
  101. return "Expression";
  102. case CCKind::CCC_ObjCMessageReceiver:
  103. return "ObjCMessageReceiver";
  104. case CCKind::CCC_DotMemberAccess:
  105. return "DotMemberAccess";
  106. case CCKind::CCC_ArrowMemberAccess:
  107. return "ArrowMemberAccess";
  108. case CCKind::CCC_ObjCPropertyAccess:
  109. return "ObjCPropertyAccess";
  110. case CCKind::CCC_EnumTag:
  111. return "EnumTag";
  112. case CCKind::CCC_UnionTag:
  113. return "UnionTag";
  114. case CCKind::CCC_ClassOrStructTag:
  115. return "ClassOrStructTag";
  116. case CCKind::CCC_ObjCProtocolName:
  117. return "ObjCProtocolName";
  118. case CCKind::CCC_Namespace:
  119. return "Namespace";
  120. case CCKind::CCC_Type:
  121. return "Type";
  122. case CCKind::CCC_Name:
  123. return "Name";
  124. case CCKind::CCC_PotentiallyQualifiedName:
  125. return "PotentiallyQualifiedName";
  126. case CCKind::CCC_MacroName:
  127. return "MacroName";
  128. case CCKind::CCC_MacroNameUse:
  129. return "MacroNameUse";
  130. case CCKind::CCC_PreprocessorExpression:
  131. return "PreprocessorExpression";
  132. case CCKind::CCC_PreprocessorDirective:
  133. return "PreprocessorDirective";
  134. case CCKind::CCC_NaturalLanguage:
  135. return "NaturalLanguage";
  136. case CCKind::CCC_SelectorName:
  137. return "SelectorName";
  138. case CCKind::CCC_TypeQualifiers:
  139. return "TypeQualifiers";
  140. case CCKind::CCC_ParenthesizedExpression:
  141. return "ParenthesizedExpression";
  142. case CCKind::CCC_ObjCInstanceMessage:
  143. return "ObjCInstanceMessage";
  144. case CCKind::CCC_ObjCClassMessage:
  145. return "ObjCClassMessage";
  146. case CCKind::CCC_ObjCInterfaceName:
  147. return "ObjCInterfaceName";
  148. case CCKind::CCC_ObjCCategoryName:
  149. return "ObjCCategoryName";
  150. case CCKind::CCC_Recovery:
  151. return "Recovery";
  152. }
  153. llvm_unreachable("Invalid CodeCompletionContext::Kind!");
  154. }
  155. //===----------------------------------------------------------------------===//
  156. // Code completion string implementation
  157. //===----------------------------------------------------------------------===//
  158. CodeCompletionString::Chunk::Chunk(ChunkKind Kind, const char *Text)
  159. : Kind(Kind), Text("") {
  160. switch (Kind) {
  161. case CK_TypedText:
  162. case CK_Text:
  163. case CK_Placeholder:
  164. case CK_Informative:
  165. case CK_ResultType:
  166. case CK_CurrentParameter:
  167. this->Text = Text;
  168. break;
  169. case CK_Optional:
  170. llvm_unreachable("Optional strings cannot be created from text");
  171. case CK_LeftParen:
  172. this->Text = "(";
  173. break;
  174. case CK_RightParen:
  175. this->Text = ")";
  176. break;
  177. case CK_LeftBracket:
  178. this->Text = "[";
  179. break;
  180. case CK_RightBracket:
  181. this->Text = "]";
  182. break;
  183. case CK_LeftBrace:
  184. this->Text = "{";
  185. break;
  186. case CK_RightBrace:
  187. this->Text = "}";
  188. break;
  189. case CK_LeftAngle:
  190. this->Text = "<";
  191. break;
  192. case CK_RightAngle:
  193. this->Text = ">";
  194. break;
  195. case CK_Comma:
  196. this->Text = ", ";
  197. break;
  198. case CK_Colon:
  199. this->Text = ":";
  200. break;
  201. case CK_SemiColon:
  202. this->Text = ";";
  203. break;
  204. case CK_Equal:
  205. this->Text = " = ";
  206. break;
  207. case CK_HorizontalSpace:
  208. this->Text = " ";
  209. break;
  210. case CK_VerticalSpace:
  211. this->Text = "\n";
  212. break;
  213. }
  214. }
  215. CodeCompletionString::Chunk
  216. CodeCompletionString::Chunk::CreateText(const char *Text) {
  217. return Chunk(CK_Text, Text);
  218. }
  219. CodeCompletionString::Chunk
  220. CodeCompletionString::Chunk::CreateOptional(CodeCompletionString *Optional) {
  221. Chunk Result;
  222. Result.Kind = CK_Optional;
  223. Result.Optional = Optional;
  224. return Result;
  225. }
  226. CodeCompletionString::Chunk
  227. CodeCompletionString::Chunk::CreatePlaceholder(const char *Placeholder) {
  228. return Chunk(CK_Placeholder, Placeholder);
  229. }
  230. CodeCompletionString::Chunk
  231. CodeCompletionString::Chunk::CreateInformative(const char *Informative) {
  232. return Chunk(CK_Informative, Informative);
  233. }
  234. CodeCompletionString::Chunk
  235. CodeCompletionString::Chunk::CreateResultType(const char *ResultType) {
  236. return Chunk(CK_ResultType, ResultType);
  237. }
  238. CodeCompletionString::Chunk
  239. CodeCompletionString::Chunk::CreateCurrentParameter(
  240. const char *CurrentParameter) {
  241. return Chunk(CK_CurrentParameter, CurrentParameter);
  242. }
  243. CodeCompletionString::CodeCompletionString(const Chunk *Chunks,
  244. unsigned NumChunks,
  245. unsigned Priority,
  246. CXAvailabilityKind Availability,
  247. const char **Annotations,
  248. unsigned NumAnnotations,
  249. StringRef ParentName,
  250. const char *BriefComment)
  251. : NumChunks(NumChunks), NumAnnotations(NumAnnotations),
  252. Priority(Priority), Availability(Availability),
  253. ParentName(ParentName), BriefComment(BriefComment) {
  254. assert(NumChunks <= 0xffff);
  255. assert(NumAnnotations <= 0xffff);
  256. auto *StoredChunks = reinterpret_cast<Chunk *>(this + 1);
  257. for (unsigned I = 0; I != NumChunks; ++I)
  258. StoredChunks[I] = Chunks[I];
  259. const auto **StoredAnnotations = reinterpret_cast<const char **>(StoredChunks + NumChunks);
  260. for (unsigned I = 0; I != NumAnnotations; ++I)
  261. StoredAnnotations[I] = Annotations[I];
  262. }
  263. unsigned CodeCompletionString::getAnnotationCount() const {
  264. return NumAnnotations;
  265. }
  266. const char *CodeCompletionString::getAnnotation(unsigned AnnotationNr) const {
  267. if (AnnotationNr < NumAnnotations)
  268. return reinterpret_cast<const char * const*>(end())[AnnotationNr];
  269. else
  270. return nullptr;
  271. }
  272. std::string CodeCompletionString::getAsString() const {
  273. std::string Result;
  274. llvm::raw_string_ostream OS(Result);
  275. for (iterator C = begin(), CEnd = end(); C != CEnd; ++C) {
  276. switch (C->Kind) {
  277. case CK_Optional: OS << "{#" << C->Optional->getAsString() << "#}"; break;
  278. case CK_Placeholder: OS << "<#" << C->Text << "#>"; break;
  279. case CK_Informative:
  280. case CK_ResultType:
  281. OS << "[#" << C->Text << "#]";
  282. break;
  283. case CK_CurrentParameter: OS << "<#" << C->Text << "#>"; break;
  284. default: OS << C->Text; break;
  285. }
  286. }
  287. return OS.str();
  288. }
  289. const char *CodeCompletionString::getTypedText() const {
  290. for (iterator C = begin(), CEnd = end(); C != CEnd; ++C)
  291. if (C->Kind == CK_TypedText)
  292. return C->Text;
  293. return nullptr;
  294. }
  295. const char *CodeCompletionAllocator::CopyString(const Twine &String) {
  296. SmallString<128> Data;
  297. StringRef Ref = String.toStringRef(Data);
  298. // FIXME: It would be more efficient to teach Twine to tell us its size and
  299. // then add a routine there to fill in an allocated char* with the contents
  300. // of the string.
  301. auto *Mem = (char *)Allocate(Ref.size() + 1, 1);
  302. std::copy(Ref.begin(), Ref.end(), Mem);
  303. Mem[Ref.size()] = 0;
  304. return Mem;
  305. }
  306. StringRef CodeCompletionTUInfo::getParentName(const DeclContext *DC) {
  307. const auto *ND = dyn_cast<NamedDecl>(DC);
  308. if (!ND)
  309. return {};
  310. // Check whether we've already cached the parent name.
  311. StringRef &CachedParentName = ParentNames[DC];
  312. if (!CachedParentName.empty())
  313. return CachedParentName;
  314. // If we already processed this DeclContext and assigned empty to it, the
  315. // data pointer will be non-null.
  316. if (CachedParentName.data() != nullptr)
  317. return {};
  318. // Find the interesting names.
  319. SmallVector<const DeclContext *, 2> Contexts;
  320. while (DC && !DC->isFunctionOrMethod()) {
  321. if (const auto *ND = dyn_cast<NamedDecl>(DC)) {
  322. if (ND->getIdentifier())
  323. Contexts.push_back(DC);
  324. }
  325. DC = DC->getParent();
  326. }
  327. {
  328. SmallString<128> S;
  329. llvm::raw_svector_ostream OS(S);
  330. bool First = true;
  331. for (unsigned I = Contexts.size(); I != 0; --I) {
  332. if (First)
  333. First = false;
  334. else {
  335. OS << "::";
  336. }
  337. const DeclContext *CurDC = Contexts[I-1];
  338. if (const auto *CatImpl = dyn_cast<ObjCCategoryImplDecl>(CurDC))
  339. CurDC = CatImpl->getCategoryDecl();
  340. if (const auto *Cat = dyn_cast<ObjCCategoryDecl>(CurDC)) {
  341. const ObjCInterfaceDecl *Interface = Cat->getClassInterface();
  342. if (!Interface) {
  343. // Assign an empty StringRef but with non-null data to distinguish
  344. // between empty because we didn't process the DeclContext yet.
  345. CachedParentName = StringRef((const char *)(uintptr_t)~0U, 0);
  346. return {};
  347. }
  348. OS << Interface->getName() << '(' << Cat->getName() << ')';
  349. } else {
  350. OS << cast<NamedDecl>(CurDC)->getName();
  351. }
  352. }
  353. CachedParentName = AllocatorRef->CopyString(OS.str());
  354. }
  355. return CachedParentName;
  356. }
  357. CodeCompletionString *CodeCompletionBuilder::TakeString() {
  358. void *Mem = getAllocator().Allocate(
  359. sizeof(CodeCompletionString) + sizeof(Chunk) * Chunks.size() +
  360. sizeof(const char *) * Annotations.size(),
  361. alignof(CodeCompletionString));
  362. auto *Result
  363. = new (Mem) CodeCompletionString(Chunks.data(), Chunks.size(),
  364. Priority, Availability,
  365. Annotations.data(), Annotations.size(),
  366. ParentName, BriefComment);
  367. Chunks.clear();
  368. return Result;
  369. }
  370. void CodeCompletionBuilder::AddTypedTextChunk(const char *Text) {
  371. Chunks.push_back(Chunk(CodeCompletionString::CK_TypedText, Text));
  372. }
  373. void CodeCompletionBuilder::AddTextChunk(const char *Text) {
  374. Chunks.push_back(Chunk::CreateText(Text));
  375. }
  376. void CodeCompletionBuilder::AddOptionalChunk(CodeCompletionString *Optional) {
  377. Chunks.push_back(Chunk::CreateOptional(Optional));
  378. }
  379. void CodeCompletionBuilder::AddPlaceholderChunk(const char *Placeholder) {
  380. Chunks.push_back(Chunk::CreatePlaceholder(Placeholder));
  381. }
  382. void CodeCompletionBuilder::AddInformativeChunk(const char *Text) {
  383. Chunks.push_back(Chunk::CreateInformative(Text));
  384. }
  385. void CodeCompletionBuilder::AddResultTypeChunk(const char *ResultType) {
  386. Chunks.push_back(Chunk::CreateResultType(ResultType));
  387. }
  388. void
  389. CodeCompletionBuilder::AddCurrentParameterChunk(const char *CurrentParameter) {
  390. Chunks.push_back(Chunk::CreateCurrentParameter(CurrentParameter));
  391. }
  392. void CodeCompletionBuilder::AddChunk(CodeCompletionString::ChunkKind CK,
  393. const char *Text) {
  394. Chunks.push_back(Chunk(CK, Text));
  395. }
  396. void CodeCompletionBuilder::addParentContext(const DeclContext *DC) {
  397. if (DC->isTranslationUnit())
  398. return;
  399. if (DC->isFunctionOrMethod())
  400. return;
  401. const auto *ND = dyn_cast<NamedDecl>(DC);
  402. if (!ND)
  403. return;
  404. ParentName = getCodeCompletionTUInfo().getParentName(DC);
  405. }
  406. void CodeCompletionBuilder::addBriefComment(StringRef Comment) {
  407. BriefComment = Allocator.CopyString(Comment);
  408. }
  409. //===----------------------------------------------------------------------===//
  410. // Code completion overload candidate implementation
  411. //===----------------------------------------------------------------------===//
  412. FunctionDecl *
  413. CodeCompleteConsumer::OverloadCandidate::getFunction() const {
  414. if (getKind() == CK_Function)
  415. return Function;
  416. else if (getKind() == CK_FunctionTemplate)
  417. return FunctionTemplate->getTemplatedDecl();
  418. else
  419. return nullptr;
  420. }
  421. const FunctionType *
  422. CodeCompleteConsumer::OverloadCandidate::getFunctionType() const {
  423. switch (Kind) {
  424. case CK_Function:
  425. return Function->getType()->getAs<FunctionType>();
  426. case CK_FunctionTemplate:
  427. return FunctionTemplate->getTemplatedDecl()->getType()
  428. ->getAs<FunctionType>();
  429. case CK_FunctionType:
  430. return Type;
  431. }
  432. llvm_unreachable("Invalid CandidateKind!");
  433. }
  434. //===----------------------------------------------------------------------===//
  435. // Code completion consumer implementation
  436. //===----------------------------------------------------------------------===//
  437. CodeCompleteConsumer::~CodeCompleteConsumer() = default;
  438. bool PrintingCodeCompleteConsumer::isResultFilteredOut(StringRef Filter,
  439. CodeCompletionResult Result) {
  440. switch (Result.Kind) {
  441. case CodeCompletionResult::RK_Declaration:
  442. return !(Result.Declaration->getIdentifier() &&
  443. Result.Declaration->getIdentifier()->getName().startswith(Filter));
  444. case CodeCompletionResult::RK_Keyword:
  445. return !StringRef(Result.Keyword).startswith(Filter);
  446. case CodeCompletionResult::RK_Macro:
  447. return !Result.Macro->getName().startswith(Filter);
  448. case CodeCompletionResult::RK_Pattern:
  449. return !StringRef(Result.Pattern->getAsString()).startswith(Filter);
  450. }
  451. llvm_unreachable("Unknown code completion result Kind.");
  452. }
  453. void
  454. PrintingCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &SemaRef,
  455. CodeCompletionContext Context,
  456. CodeCompletionResult *Results,
  457. unsigned NumResults) {
  458. std::stable_sort(Results, Results + NumResults);
  459. StringRef Filter = SemaRef.getPreprocessor().getCodeCompletionFilter();
  460. // Print the results.
  461. for (unsigned I = 0; I != NumResults; ++I) {
  462. if(!Filter.empty() && isResultFilteredOut(Filter, Results[I]))
  463. continue;
  464. OS << "COMPLETION: ";
  465. switch (Results[I].Kind) {
  466. case CodeCompletionResult::RK_Declaration:
  467. OS << *Results[I].Declaration;
  468. if (Results[I].Hidden)
  469. OS << " (Hidden)";
  470. if (CodeCompletionString *CCS
  471. = Results[I].CreateCodeCompletionString(SemaRef, Context,
  472. getAllocator(),
  473. CCTUInfo,
  474. includeBriefComments())) {
  475. OS << " : " << CCS->getAsString();
  476. if (const char *BriefComment = CCS->getBriefComment())
  477. OS << " : " << BriefComment;
  478. }
  479. OS << '\n';
  480. break;
  481. case CodeCompletionResult::RK_Keyword:
  482. OS << Results[I].Keyword << '\n';
  483. break;
  484. case CodeCompletionResult::RK_Macro:
  485. OS << Results[I].Macro->getName();
  486. if (CodeCompletionString *CCS
  487. = Results[I].CreateCodeCompletionString(SemaRef, Context,
  488. getAllocator(),
  489. CCTUInfo,
  490. includeBriefComments())) {
  491. OS << " : " << CCS->getAsString();
  492. }
  493. OS << '\n';
  494. break;
  495. case CodeCompletionResult::RK_Pattern:
  496. OS << "Pattern : "
  497. << Results[I].Pattern->getAsString() << '\n';
  498. break;
  499. }
  500. }
  501. }
  502. // This function is used solely to preserve the former presentation of overloads
  503. // by "clang -cc1 -code-completion-at", since CodeCompletionString::getAsString
  504. // needs to be improved for printing the newer and more detailed overload
  505. // chunks.
  506. static std::string getOverloadAsString(const CodeCompletionString &CCS) {
  507. std::string Result;
  508. llvm::raw_string_ostream OS(Result);
  509. for (auto &C : CCS) {
  510. switch (C.Kind) {
  511. case CodeCompletionString::CK_Informative:
  512. case CodeCompletionString::CK_ResultType:
  513. OS << "[#" << C.Text << "#]";
  514. break;
  515. case CodeCompletionString::CK_CurrentParameter:
  516. OS << "<#" << C.Text << "#>";
  517. break;
  518. default: OS << C.Text; break;
  519. }
  520. }
  521. return OS.str();
  522. }
  523. void
  524. PrintingCodeCompleteConsumer::ProcessOverloadCandidates(Sema &SemaRef,
  525. unsigned CurrentArg,
  526. OverloadCandidate *Candidates,
  527. unsigned NumCandidates) {
  528. for (unsigned I = 0; I != NumCandidates; ++I) {
  529. if (CodeCompletionString *CCS
  530. = Candidates[I].CreateSignatureString(CurrentArg, SemaRef,
  531. getAllocator(), CCTUInfo,
  532. includeBriefComments())) {
  533. OS << "OVERLOAD: " << getOverloadAsString(*CCS) << "\n";
  534. }
  535. }
  536. }
  537. /// \brief Retrieve the effective availability of the given declaration.
  538. static AvailabilityResult getDeclAvailability(const Decl *D) {
  539. AvailabilityResult AR = D->getAvailability();
  540. if (isa<EnumConstantDecl>(D))
  541. AR = std::max(AR, cast<Decl>(D->getDeclContext())->getAvailability());
  542. return AR;
  543. }
  544. void CodeCompletionResult::computeCursorKindAndAvailability(bool Accessible) {
  545. switch (Kind) {
  546. case RK_Pattern:
  547. if (!Declaration) {
  548. // Do nothing: Patterns can come with cursor kinds!
  549. break;
  550. }
  551. LLVM_FALLTHROUGH;
  552. case RK_Declaration: {
  553. // Set the availability based on attributes.
  554. switch (getDeclAvailability(Declaration)) {
  555. case AR_Available:
  556. case AR_NotYetIntroduced:
  557. Availability = CXAvailability_Available;
  558. break;
  559. case AR_Deprecated:
  560. Availability = CXAvailability_Deprecated;
  561. break;
  562. case AR_Unavailable:
  563. Availability = CXAvailability_NotAvailable;
  564. break;
  565. }
  566. if (const auto *Function = dyn_cast<FunctionDecl>(Declaration))
  567. if (Function->isDeleted())
  568. Availability = CXAvailability_NotAvailable;
  569. CursorKind = getCursorKindForDecl(Declaration);
  570. if (CursorKind == CXCursor_UnexposedDecl) {
  571. // FIXME: Forward declarations of Objective-C classes and protocols
  572. // are not directly exposed, but we want code completion to treat them
  573. // like a definition.
  574. if (isa<ObjCInterfaceDecl>(Declaration))
  575. CursorKind = CXCursor_ObjCInterfaceDecl;
  576. else if (isa<ObjCProtocolDecl>(Declaration))
  577. CursorKind = CXCursor_ObjCProtocolDecl;
  578. else
  579. CursorKind = CXCursor_NotImplemented;
  580. }
  581. break;
  582. }
  583. case RK_Macro:
  584. case RK_Keyword:
  585. llvm_unreachable("Macro and keyword kinds are handled by the constructors");
  586. }
  587. if (!Accessible)
  588. Availability = CXAvailability_NotAccessible;
  589. }
  590. /// \brief Retrieve the name that should be used to order a result.
  591. ///
  592. /// If the name needs to be constructed as a string, that string will be
  593. /// saved into Saved and the returned StringRef will refer to it.
  594. StringRef CodeCompletionResult::getOrderedName(std::string &Saved) const {
  595. switch (Kind) {
  596. case RK_Keyword:
  597. return Keyword;
  598. case RK_Pattern:
  599. return Pattern->getTypedText();
  600. case RK_Macro:
  601. return Macro->getName();
  602. case RK_Declaration:
  603. // Handle declarations below.
  604. break;
  605. }
  606. DeclarationName Name = Declaration->getDeclName();
  607. // If the name is a simple identifier (by far the common case), or a
  608. // zero-argument selector, just return a reference to that identifier.
  609. if (IdentifierInfo *Id = Name.getAsIdentifierInfo())
  610. return Id->getName();
  611. if (Name.isObjCZeroArgSelector())
  612. if (IdentifierInfo *Id
  613. = Name.getObjCSelector().getIdentifierInfoForSlot(0))
  614. return Id->getName();
  615. Saved = Name.getAsString();
  616. return Saved;
  617. }
  618. bool clang::operator<(const CodeCompletionResult &X,
  619. const CodeCompletionResult &Y) {
  620. std::string XSaved, YSaved;
  621. StringRef XStr = X.getOrderedName(XSaved);
  622. StringRef YStr = Y.getOrderedName(YSaved);
  623. int cmp = XStr.compare_lower(YStr);
  624. if (cmp)
  625. return cmp < 0;
  626. // If case-insensitive comparison fails, try case-sensitive comparison.
  627. cmp = XStr.compare(YStr);
  628. if (cmp)
  629. return cmp < 0;
  630. return false;
  631. }