CodeCompleteConsumer.cpp 18 KB

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