CodeCompleteConsumer.cpp 22 KB

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