CodeCompleteConsumer.cpp 23 KB

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