CodeCompleteConsumer.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769
  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
  246. CodeCompletionString::Chunk::CreateCurrentParameter(
  247. const char *CurrentParameter) {
  248. return Chunk(CK_CurrentParameter, CurrentParameter);
  249. }
  250. CodeCompletionString::CodeCompletionString(const Chunk *Chunks,
  251. unsigned NumChunks,
  252. unsigned Priority,
  253. CXAvailabilityKind Availability,
  254. const char **Annotations,
  255. unsigned NumAnnotations,
  256. StringRef ParentName,
  257. const char *BriefComment)
  258. : NumChunks(NumChunks), NumAnnotations(NumAnnotations),
  259. Priority(Priority), Availability(Availability),
  260. ParentName(ParentName), BriefComment(BriefComment) {
  261. assert(NumChunks <= 0xffff);
  262. assert(NumAnnotations <= 0xffff);
  263. Chunk *StoredChunks = reinterpret_cast<Chunk *>(this + 1);
  264. for (unsigned I = 0; I != NumChunks; ++I)
  265. StoredChunks[I] = Chunks[I];
  266. const char **StoredAnnotations = reinterpret_cast<const char **>(StoredChunks + NumChunks);
  267. for (unsigned I = 0; I != NumAnnotations; ++I)
  268. StoredAnnotations[I] = Annotations[I];
  269. }
  270. unsigned CodeCompletionString::getAnnotationCount() const {
  271. return NumAnnotations;
  272. }
  273. const char *CodeCompletionString::getAnnotation(unsigned AnnotationNr) const {
  274. if (AnnotationNr < NumAnnotations)
  275. return reinterpret_cast<const char * const*>(end())[AnnotationNr];
  276. else
  277. return nullptr;
  278. }
  279. std::string CodeCompletionString::getAsString() const {
  280. std::string Result;
  281. llvm::raw_string_ostream OS(Result);
  282. for (iterator C = begin(), CEnd = end(); C != CEnd; ++C) {
  283. switch (C->Kind) {
  284. case CK_Optional: OS << "{#" << C->Optional->getAsString() << "#}"; break;
  285. case CK_Placeholder: OS << "<#" << C->Text << "#>"; break;
  286. case CK_Informative:
  287. case CK_ResultType:
  288. OS << "[#" << C->Text << "#]";
  289. break;
  290. case CK_CurrentParameter: OS << "<#" << C->Text << "#>"; break;
  291. default: OS << C->Text; break;
  292. }
  293. }
  294. return OS.str();
  295. }
  296. const char *CodeCompletionString::getTypedText() const {
  297. for (iterator C = begin(), CEnd = end(); C != CEnd; ++C)
  298. if (C->Kind == CK_TypedText)
  299. return C->Text;
  300. return nullptr;
  301. }
  302. const char *CodeCompletionAllocator::CopyString(const Twine &String) {
  303. SmallString<128> Data;
  304. StringRef Ref = String.toStringRef(Data);
  305. // FIXME: It would be more efficient to teach Twine to tell us its size and
  306. // then add a routine there to fill in an allocated char* with the contents
  307. // of the string.
  308. char *Mem = (char *)Allocate(Ref.size() + 1, 1);
  309. std::copy(Ref.begin(), Ref.end(), Mem);
  310. Mem[Ref.size()] = 0;
  311. return Mem;
  312. }
  313. StringRef CodeCompletionTUInfo::getParentName(const DeclContext *DC) {
  314. const NamedDecl *ND = dyn_cast<NamedDecl>(DC);
  315. if (!ND)
  316. return {};
  317. // Check whether we've already cached the parent name.
  318. StringRef &CachedParentName = ParentNames[DC];
  319. if (!CachedParentName.empty())
  320. return CachedParentName;
  321. // If we already processed this DeclContext and assigned empty to it, the
  322. // data pointer will be non-null.
  323. if (CachedParentName.data() != nullptr)
  324. return {};
  325. // Find the interesting names.
  326. SmallVector<const DeclContext *, 2> Contexts;
  327. while (DC && !DC->isFunctionOrMethod()) {
  328. if (const NamedDecl *ND = dyn_cast<NamedDecl>(DC)) {
  329. if (ND->getIdentifier())
  330. Contexts.push_back(DC);
  331. }
  332. DC = DC->getParent();
  333. }
  334. {
  335. SmallString<128> S;
  336. llvm::raw_svector_ostream OS(S);
  337. bool First = true;
  338. for (unsigned I = Contexts.size(); I != 0; --I) {
  339. if (First)
  340. First = false;
  341. else {
  342. OS << "::";
  343. }
  344. const DeclContext *CurDC = Contexts[I-1];
  345. if (const ObjCCategoryImplDecl *CatImpl = dyn_cast<ObjCCategoryImplDecl>(CurDC))
  346. CurDC = CatImpl->getCategoryDecl();
  347. if (const ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(CurDC)) {
  348. const ObjCInterfaceDecl *Interface = Cat->getClassInterface();
  349. if (!Interface) {
  350. // Assign an empty StringRef but with non-null data to distinguish
  351. // between empty because we didn't process the DeclContext yet.
  352. CachedParentName = StringRef((const char *)(uintptr_t)~0U, 0);
  353. return {};
  354. }
  355. OS << Interface->getName() << '(' << Cat->getName() << ')';
  356. } else {
  357. OS << cast<NamedDecl>(CurDC)->getName();
  358. }
  359. }
  360. CachedParentName = AllocatorRef->CopyString(OS.str());
  361. }
  362. return CachedParentName;
  363. }
  364. CodeCompletionString *CodeCompletionBuilder::TakeString() {
  365. void *Mem = getAllocator().Allocate(
  366. sizeof(CodeCompletionString) + sizeof(Chunk) * Chunks.size() +
  367. sizeof(const char *) * Annotations.size(),
  368. alignof(CodeCompletionString));
  369. CodeCompletionString *Result
  370. = new (Mem) CodeCompletionString(Chunks.data(), Chunks.size(),
  371. Priority, Availability,
  372. Annotations.data(), Annotations.size(),
  373. ParentName, BriefComment);
  374. Chunks.clear();
  375. return Result;
  376. }
  377. void CodeCompletionBuilder::AddTypedTextChunk(const char *Text) {
  378. Chunks.push_back(Chunk(CodeCompletionString::CK_TypedText, Text));
  379. }
  380. void CodeCompletionBuilder::AddTextChunk(const char *Text) {
  381. Chunks.push_back(Chunk::CreateText(Text));
  382. }
  383. void CodeCompletionBuilder::AddOptionalChunk(CodeCompletionString *Optional) {
  384. Chunks.push_back(Chunk::CreateOptional(Optional));
  385. }
  386. void CodeCompletionBuilder::AddPlaceholderChunk(const char *Placeholder) {
  387. Chunks.push_back(Chunk::CreatePlaceholder(Placeholder));
  388. }
  389. void CodeCompletionBuilder::AddInformativeChunk(const char *Text) {
  390. Chunks.push_back(Chunk::CreateInformative(Text));
  391. }
  392. void CodeCompletionBuilder::AddResultTypeChunk(const char *ResultType) {
  393. Chunks.push_back(Chunk::CreateResultType(ResultType));
  394. }
  395. void
  396. CodeCompletionBuilder::AddCurrentParameterChunk(const char *CurrentParameter) {
  397. Chunks.push_back(Chunk::CreateCurrentParameter(CurrentParameter));
  398. }
  399. void CodeCompletionBuilder::AddChunk(CodeCompletionString::ChunkKind CK,
  400. const char *Text) {
  401. Chunks.push_back(Chunk(CK, Text));
  402. }
  403. void CodeCompletionBuilder::addParentContext(const DeclContext *DC) {
  404. if (DC->isTranslationUnit())
  405. return;
  406. if (DC->isFunctionOrMethod())
  407. return;
  408. const NamedDecl *ND = dyn_cast<NamedDecl>(DC);
  409. if (!ND)
  410. return;
  411. ParentName = getCodeCompletionTUInfo().getParentName(DC);
  412. }
  413. void CodeCompletionBuilder::addBriefComment(StringRef Comment) {
  414. BriefComment = Allocator.CopyString(Comment);
  415. }
  416. //===----------------------------------------------------------------------===//
  417. // Code completion overload candidate implementation
  418. //===----------------------------------------------------------------------===//
  419. FunctionDecl *
  420. 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()->getType()
  435. ->getAs<FunctionType>();
  436. case CK_FunctionType:
  437. return Type;
  438. }
  439. llvm_unreachable("Invalid CandidateKind!");
  440. }
  441. //===----------------------------------------------------------------------===//
  442. // Code completion consumer implementation
  443. //===----------------------------------------------------------------------===//
  444. CodeCompleteConsumer::~CodeCompleteConsumer() = default;
  445. bool PrintingCodeCompleteConsumer::isResultFilteredOut(StringRef Filter,
  446. CodeCompletionResult Result) {
  447. switch (Result.Kind) {
  448. case CodeCompletionResult::RK_Declaration:
  449. return !(Result.Declaration->getIdentifier() &&
  450. Result.Declaration->getIdentifier()->getName().startswith(Filter));
  451. case CodeCompletionResult::RK_Keyword:
  452. return !StringRef(Result.Keyword).startswith(Filter);
  453. case CodeCompletionResult::RK_Macro:
  454. return !Result.Macro->getName().startswith(Filter);
  455. case CodeCompletionResult::RK_Pattern:
  456. return !(Result.Pattern->getTypedText() &&
  457. StringRef(Result.Pattern->getTypedText()).startswith(Filter));
  458. }
  459. llvm_unreachable("Unknown code completion result Kind.");
  460. }
  461. void
  462. PrintingCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &SemaRef,
  463. CodeCompletionContext Context,
  464. 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 (!Tags.empty())
  483. OS << " (" << llvm::join(Tags, ",") << ")";
  484. }
  485. if (CodeCompletionString *CCS = Results[I].CreateCodeCompletionString(
  486. SemaRef, Context, getAllocator(), CCTUInfo,
  487. includeBriefComments())) {
  488. OS << " : " << CCS->getAsString();
  489. if (const char *BriefComment = CCS->getBriefComment())
  490. OS << " : " << BriefComment;
  491. }
  492. for (const FixItHint &FixIt : Results[I].FixIts) {
  493. const SourceLocation BLoc = FixIt.RemoveRange.getBegin();
  494. const SourceLocation ELoc = FixIt.RemoveRange.getEnd();
  495. SourceManager &SM = SemaRef.SourceMgr;
  496. std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(BLoc);
  497. std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(ELoc);
  498. // Adjust for token ranges.
  499. if (FixIt.RemoveRange.isTokenRange())
  500. EInfo.second += Lexer::MeasureTokenLength(ELoc, SM, SemaRef.LangOpts);
  501. OS << " (requires fix-it:"
  502. << " {" << SM.getLineNumber(BInfo.first, BInfo.second) << ':'
  503. << SM.getColumnNumber(BInfo.first, BInfo.second) << '-'
  504. << SM.getLineNumber(EInfo.first, EInfo.second) << ':'
  505. << SM.getColumnNumber(EInfo.first, EInfo.second) << "}"
  506. << " to \"" << FixIt.CodeToInsert << "\")";
  507. }
  508. OS << '\n';
  509. break;
  510. case CodeCompletionResult::RK_Keyword:
  511. OS << Results[I].Keyword << '\n';
  512. break;
  513. case CodeCompletionResult::RK_Macro:
  514. OS << Results[I].Macro->getName();
  515. if (CodeCompletionString *CCS
  516. = Results[I].CreateCodeCompletionString(SemaRef, Context,
  517. getAllocator(),
  518. CCTUInfo,
  519. includeBriefComments())) {
  520. OS << " : " << CCS->getAsString();
  521. }
  522. OS << '\n';
  523. break;
  524. case CodeCompletionResult::RK_Pattern:
  525. OS << "Pattern : "
  526. << 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: OS << C.Text; break;
  551. }
  552. }
  553. return OS.str();
  554. }
  555. void PrintingCodeCompleteConsumer::ProcessOverloadCandidates(
  556. Sema &SemaRef, unsigned CurrentArg, OverloadCandidate *Candidates,
  557. unsigned NumCandidates, SourceLocation OpenParLoc) {
  558. OS << "OPENING_PAREN_LOC: ";
  559. OpenParLoc.print(OS, SemaRef.getSourceManager());
  560. OS << "\n";
  561. for (unsigned I = 0; I != NumCandidates; ++I) {
  562. if (CodeCompletionString *CCS = Candidates[I].CreateSignatureString(
  563. CurrentArg, SemaRef, getAllocator(), CCTUInfo,
  564. includeBriefComments())) {
  565. OS << "OVERLOAD: " << getOverloadAsString(*CCS) << "\n";
  566. }
  567. }
  568. }
  569. /// Retrieve the effective availability of the given declaration.
  570. static AvailabilityResult getDeclAvailability(const Decl *D) {
  571. AvailabilityResult AR = D->getAvailability();
  572. if (isa<EnumConstantDecl>(D))
  573. AR = std::max(AR, cast<Decl>(D->getDeclContext())->getAvailability());
  574. return AR;
  575. }
  576. void CodeCompletionResult::computeCursorKindAndAvailability(bool Accessible) {
  577. switch (Kind) {
  578. case RK_Pattern:
  579. if (!Declaration) {
  580. // Do nothing: Patterns can come with cursor kinds!
  581. break;
  582. }
  583. LLVM_FALLTHROUGH;
  584. case RK_Declaration: {
  585. // Set the availability based on attributes.
  586. switch (getDeclAvailability(Declaration)) {
  587. case AR_Available:
  588. case AR_NotYetIntroduced:
  589. Availability = CXAvailability_Available;
  590. break;
  591. case AR_Deprecated:
  592. Availability = CXAvailability_Deprecated;
  593. break;
  594. case AR_Unavailable:
  595. Availability = CXAvailability_NotAvailable;
  596. break;
  597. }
  598. if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(Declaration))
  599. if (Function->isDeleted())
  600. Availability = CXAvailability_NotAvailable;
  601. CursorKind = getCursorKindForDecl(Declaration);
  602. if (CursorKind == CXCursor_UnexposedDecl) {
  603. // FIXME: Forward declarations of Objective-C classes and protocols
  604. // are not directly exposed, but we want code completion to treat them
  605. // like a definition.
  606. if (isa<ObjCInterfaceDecl>(Declaration))
  607. CursorKind = CXCursor_ObjCInterfaceDecl;
  608. else if (isa<ObjCProtocolDecl>(Declaration))
  609. CursorKind = CXCursor_ObjCProtocolDecl;
  610. else
  611. CursorKind = CXCursor_NotImplemented;
  612. }
  613. break;
  614. }
  615. case RK_Macro:
  616. case RK_Keyword:
  617. llvm_unreachable("Macro and keyword kinds are handled by the constructors");
  618. }
  619. if (!Accessible)
  620. Availability = CXAvailability_NotAccessible;
  621. }
  622. /// Retrieve the name that should be used to order a result.
  623. ///
  624. /// If the name needs to be constructed as a string, that string will be
  625. /// saved into Saved and the returned StringRef will refer to it.
  626. StringRef CodeCompletionResult::getOrderedName(std::string &Saved) const {
  627. switch (Kind) {
  628. case RK_Keyword:
  629. return Keyword;
  630. case RK_Pattern:
  631. return Pattern->getTypedText();
  632. case RK_Macro:
  633. return Macro->getName();
  634. case RK_Declaration:
  635. // Handle declarations below.
  636. break;
  637. }
  638. DeclarationName Name = Declaration->getDeclName();
  639. // If the name is a simple identifier (by far the common case), or a
  640. // zero-argument selector, just return a reference to that identifier.
  641. if (IdentifierInfo *Id = Name.getAsIdentifierInfo())
  642. return Id->getName();
  643. if (Name.isObjCZeroArgSelector())
  644. if (IdentifierInfo *Id
  645. = Name.getObjCSelector().getIdentifierInfoForSlot(0))
  646. return Id->getName();
  647. Saved = Name.getAsString();
  648. return Saved;
  649. }
  650. bool clang::operator<(const CodeCompletionResult &X,
  651. const CodeCompletionResult &Y) {
  652. std::string XSaved, YSaved;
  653. StringRef XStr = X.getOrderedName(XSaved);
  654. StringRef YStr = Y.getOrderedName(YSaved);
  655. int cmp = XStr.compare_lower(YStr);
  656. if (cmp)
  657. return cmp < 0;
  658. // If case-insensitive comparison fails, try case-sensitive comparison.
  659. cmp = XStr.compare(YStr);
  660. if (cmp)
  661. return cmp < 0;
  662. return false;
  663. }