CodeCompleteConsumer.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640
  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. // //
  28. ///////////////////////////////////////////////////////////////////////////////
  29. using namespace clang;
  30. //===----------------------------------------------------------------------===//
  31. // Code completion context implementation
  32. //===----------------------------------------------------------------------===//
  33. bool CodeCompletionContext::wantConstructorResults() const {
  34. switch (Kind) {
  35. case CCC_Recovery:
  36. case CCC_Statement:
  37. case CCC_Expression:
  38. case CCC_ObjCMessageReceiver:
  39. case CCC_ParenthesizedExpression:
  40. return true;
  41. case CCC_TopLevel:
  42. case CCC_ObjCInterface:
  43. case CCC_ObjCImplementation:
  44. case CCC_ObjCIvarList:
  45. case CCC_ClassStructUnion:
  46. case CCC_DotMemberAccess:
  47. case CCC_ArrowMemberAccess:
  48. case CCC_ObjCPropertyAccess:
  49. case CCC_EnumTag:
  50. case CCC_UnionTag:
  51. case CCC_ClassOrStructTag:
  52. case CCC_ObjCProtocolName:
  53. case CCC_Namespace:
  54. case CCC_Type:
  55. case CCC_Name:
  56. case CCC_PotentiallyQualifiedName:
  57. case CCC_MacroName:
  58. case CCC_MacroNameUse:
  59. case CCC_PreprocessorExpression:
  60. case CCC_PreprocessorDirective:
  61. case CCC_NaturalLanguage:
  62. case CCC_SelectorName:
  63. case CCC_TypeQualifiers:
  64. case CCC_Other:
  65. case CCC_OtherWithMacros:
  66. case CCC_ObjCInstanceMessage:
  67. case CCC_ObjCClassMessage:
  68. case CCC_ObjCInterfaceName:
  69. case CCC_ObjCCategoryName:
  70. return false;
  71. }
  72. llvm_unreachable("Invalid CodeCompletionContext::Kind!");
  73. }
  74. //===----------------------------------------------------------------------===//
  75. // Code completion string implementation
  76. //===----------------------------------------------------------------------===//
  77. CodeCompletionString::Chunk::Chunk(ChunkKind Kind, const char *Text)
  78. : Kind(Kind), Text("")
  79. {
  80. switch (Kind) {
  81. case CK_TypedText:
  82. case CK_Text:
  83. case CK_Placeholder:
  84. case CK_Informative:
  85. case CK_ResultType:
  86. case CK_CurrentParameter:
  87. this->Text = Text;
  88. break;
  89. case CK_Optional:
  90. llvm_unreachable("Optional strings cannot be created from text");
  91. case CK_LeftParen:
  92. this->Text = "(";
  93. break;
  94. case CK_RightParen:
  95. this->Text = ")";
  96. break;
  97. case CK_LeftBracket:
  98. this->Text = "[";
  99. break;
  100. case CK_RightBracket:
  101. this->Text = "]";
  102. break;
  103. case CK_LeftBrace:
  104. this->Text = "{";
  105. break;
  106. case CK_RightBrace:
  107. this->Text = "}";
  108. break;
  109. case CK_LeftAngle:
  110. this->Text = "<";
  111. break;
  112. case CK_RightAngle:
  113. this->Text = ">";
  114. break;
  115. case CK_Comma:
  116. this->Text = ", ";
  117. break;
  118. case CK_Colon:
  119. this->Text = ":";
  120. break;
  121. case CK_SemiColon:
  122. this->Text = ";";
  123. break;
  124. case CK_Equal:
  125. this->Text = " = ";
  126. break;
  127. case CK_HorizontalSpace:
  128. this->Text = " ";
  129. break;
  130. case CK_VerticalSpace:
  131. this->Text = "\n";
  132. break;
  133. }
  134. }
  135. CodeCompletionString::Chunk
  136. CodeCompletionString::Chunk::CreateText(const char *Text) {
  137. return Chunk(CK_Text, Text);
  138. }
  139. CodeCompletionString::Chunk
  140. CodeCompletionString::Chunk::CreateOptional(CodeCompletionString *Optional) {
  141. Chunk Result;
  142. Result.Kind = CK_Optional;
  143. Result.Optional = Optional;
  144. return Result;
  145. }
  146. CodeCompletionString::Chunk
  147. CodeCompletionString::Chunk::CreatePlaceholder(const char *Placeholder) {
  148. return Chunk(CK_Placeholder, Placeholder);
  149. }
  150. CodeCompletionString::Chunk
  151. CodeCompletionString::Chunk::CreateInformative(const char *Informative) {
  152. return Chunk(CK_Informative, Informative);
  153. }
  154. CodeCompletionString::Chunk
  155. CodeCompletionString::Chunk::CreateResultType(const char *ResultType) {
  156. return Chunk(CK_ResultType, ResultType);
  157. }
  158. CodeCompletionString::Chunk
  159. CodeCompletionString::Chunk::CreateCurrentParameter(
  160. const char *CurrentParameter) {
  161. return Chunk(CK_CurrentParameter, CurrentParameter);
  162. }
  163. CodeCompletionString::CodeCompletionString(const Chunk *Chunks,
  164. unsigned NumChunks,
  165. unsigned Priority,
  166. CXAvailabilityKind Availability,
  167. const char **Annotations,
  168. unsigned NumAnnotations,
  169. StringRef ParentName,
  170. const char *BriefComment)
  171. : NumChunks(NumChunks), NumAnnotations(NumAnnotations),
  172. Priority(Priority), Availability(Availability),
  173. ParentName(ParentName), BriefComment(BriefComment)
  174. {
  175. assert(NumChunks <= 0xffff);
  176. assert(NumAnnotations <= 0xffff);
  177. Chunk *StoredChunks = reinterpret_cast<Chunk *>(this + 1);
  178. for (unsigned I = 0; I != NumChunks; ++I)
  179. StoredChunks[I] = Chunks[I];
  180. const char **StoredAnnotations = reinterpret_cast<const char **>(StoredChunks + NumChunks);
  181. for (unsigned I = 0; I != NumAnnotations; ++I)
  182. StoredAnnotations[I] = Annotations[I];
  183. }
  184. unsigned CodeCompletionString::getAnnotationCount() const {
  185. return NumAnnotations;
  186. }
  187. const char *CodeCompletionString::getAnnotation(unsigned AnnotationNr) const {
  188. if (AnnotationNr < NumAnnotations)
  189. return reinterpret_cast<const char * const*>(end())[AnnotationNr];
  190. else
  191. return nullptr;
  192. }
  193. std::string CodeCompletionString::getAsString() const {
  194. std::string Result;
  195. llvm::raw_string_ostream OS(Result);
  196. for (iterator C = begin(), CEnd = end(); C != CEnd; ++C) {
  197. switch (C->Kind) {
  198. case CK_Optional: OS << "{#" << C->Optional->getAsString() << "#}"; break;
  199. case CK_Placeholder: OS << "<#" << C->Text << "#>"; break;
  200. case CK_Informative:
  201. case CK_ResultType:
  202. OS << "[#" << C->Text << "#]";
  203. break;
  204. case CK_CurrentParameter: OS << "<#" << C->Text << "#>"; break;
  205. default: OS << C->Text; break;
  206. }
  207. }
  208. return OS.str();
  209. }
  210. const char *CodeCompletionString::getTypedText() const {
  211. for (iterator C = begin(), CEnd = end(); C != CEnd; ++C)
  212. if (C->Kind == CK_TypedText)
  213. return C->Text;
  214. return nullptr;
  215. }
  216. const char *CodeCompletionAllocator::CopyString(const Twine &String) {
  217. SmallString<128> Data;
  218. StringRef Ref = String.toStringRef(Data);
  219. // FIXME: It would be more efficient to teach Twine to tell us its size and
  220. // then add a routine there to fill in an allocated char* with the contents
  221. // of the string.
  222. char *Mem = (char *)Allocate(Ref.size() + 1, 1);
  223. std::copy(Ref.begin(), Ref.end(), Mem);
  224. Mem[Ref.size()] = 0;
  225. return Mem;
  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 *)~(uintptr_t)0U, 0); // HLSL Change
  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, Context,
  376. getAllocator(),
  377. CCTUInfo,
  378. includeBriefComments())) {
  379. OS << " : " << CCS->getAsString();
  380. if (const char *BriefComment = CCS->getBriefComment())
  381. OS << " : " << BriefComment;
  382. }
  383. OS << '\n';
  384. break;
  385. case CodeCompletionResult::RK_Keyword:
  386. OS << Results[I].Keyword << '\n';
  387. break;
  388. case CodeCompletionResult::RK_Macro: {
  389. OS << Results[I].Macro->getName();
  390. if (CodeCompletionString *CCS
  391. = Results[I].CreateCodeCompletionString(SemaRef, Context,
  392. getAllocator(),
  393. CCTUInfo,
  394. includeBriefComments())) {
  395. OS << " : " << CCS->getAsString();
  396. }
  397. OS << '\n';
  398. break;
  399. }
  400. case CodeCompletionResult::RK_Pattern: {
  401. OS << "Pattern : "
  402. << Results[I].Pattern->getAsString() << '\n';
  403. break;
  404. }
  405. }
  406. }
  407. }
  408. // This function is used solely to preserve the former presentation of overloads
  409. // by "clang -cc1 -code-completion-at", since CodeCompletionString::getAsString
  410. // needs to be improved for printing the newer and more detailed overload
  411. // chunks.
  412. static std::string getOverloadAsString(const CodeCompletionString &CCS) {
  413. std::string Result;
  414. llvm::raw_string_ostream OS(Result);
  415. for (auto &C : CCS) {
  416. switch (C.Kind) {
  417. case CodeCompletionString::CK_Informative:
  418. case CodeCompletionString::CK_ResultType:
  419. OS << "[#" << C.Text << "#]";
  420. break;
  421. case CodeCompletionString::CK_CurrentParameter:
  422. OS << "<#" << C.Text << "#>";
  423. break;
  424. default: OS << C.Text; break;
  425. }
  426. }
  427. return OS.str();
  428. }
  429. void
  430. PrintingCodeCompleteConsumer::ProcessOverloadCandidates(Sema &SemaRef,
  431. unsigned CurrentArg,
  432. OverloadCandidate *Candidates,
  433. unsigned NumCandidates) {
  434. for (unsigned I = 0; I != NumCandidates; ++I) {
  435. if (CodeCompletionString *CCS
  436. = Candidates[I].CreateSignatureString(CurrentArg, SemaRef,
  437. getAllocator(), CCTUInfo,
  438. includeBriefComments())) {
  439. OS << "OVERLOAD: " << getOverloadAsString(*CCS) << "\n";
  440. }
  441. }
  442. }
  443. /// \brief Retrieve the effective availability of the given declaration.
  444. static AvailabilityResult getDeclAvailability(const Decl *D) {
  445. AvailabilityResult AR = D->getAvailability();
  446. if (isa<EnumConstantDecl>(D))
  447. AR = std::max(AR, cast<Decl>(D->getDeclContext())->getAvailability());
  448. return AR;
  449. }
  450. void CodeCompletionResult::computeCursorKindAndAvailability(bool Accessible) {
  451. switch (Kind) {
  452. case RK_Pattern:
  453. if (!Declaration) {
  454. // Do nothing: Patterns can come with cursor kinds!
  455. break;
  456. }
  457. // Fall through
  458. case RK_Declaration: {
  459. // Set the availability based on attributes.
  460. switch (getDeclAvailability(Declaration)) {
  461. case AR_Available:
  462. case AR_NotYetIntroduced:
  463. Availability = CXAvailability_Available;
  464. break;
  465. case AR_Deprecated:
  466. Availability = CXAvailability_Deprecated;
  467. break;
  468. case AR_Unavailable:
  469. Availability = CXAvailability_NotAvailable;
  470. break;
  471. }
  472. if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(Declaration))
  473. if (Function->isDeleted())
  474. Availability = CXAvailability_NotAvailable;
  475. CursorKind = getCursorKindForDecl(Declaration);
  476. if (CursorKind == CXCursor_UnexposedDecl) {
  477. // FIXME: Forward declarations of Objective-C classes and protocols
  478. // are not directly exposed, but we want code completion to treat them
  479. // like a definition.
  480. if (isa<ObjCInterfaceDecl>(Declaration))
  481. CursorKind = CXCursor_ObjCInterfaceDecl;
  482. else if (isa<ObjCProtocolDecl>(Declaration))
  483. CursorKind = CXCursor_ObjCProtocolDecl;
  484. else
  485. CursorKind = CXCursor_NotImplemented;
  486. }
  487. break;
  488. }
  489. case RK_Macro:
  490. case RK_Keyword:
  491. llvm_unreachable("Macro and keyword kinds are handled by the constructors");
  492. }
  493. if (!Accessible)
  494. Availability = CXAvailability_NotAccessible;
  495. }
  496. /// \brief Retrieve the name that should be used to order a result.
  497. ///
  498. /// If the name needs to be constructed as a string, that string will be
  499. /// saved into Saved and the returned StringRef will refer to it.
  500. static StringRef getOrderedName(const CodeCompletionResult &R,
  501. std::string &Saved) {
  502. switch (R.Kind) {
  503. case CodeCompletionResult::RK_Keyword:
  504. return R.Keyword;
  505. case CodeCompletionResult::RK_Pattern:
  506. return R.Pattern->getTypedText();
  507. case CodeCompletionResult::RK_Macro:
  508. return R.Macro->getName();
  509. case CodeCompletionResult::RK_Declaration:
  510. // Handle declarations below.
  511. break;
  512. }
  513. DeclarationName Name = R.Declaration->getDeclName();
  514. // If the name is a simple identifier (by far the common case), or a
  515. // zero-argument selector, just return a reference to that identifier.
  516. if (IdentifierInfo *Id = Name.getAsIdentifierInfo())
  517. return Id->getName();
  518. if (Name.isObjCZeroArgSelector())
  519. if (IdentifierInfo *Id
  520. = Name.getObjCSelector().getIdentifierInfoForSlot(0))
  521. return Id->getName();
  522. Saved = Name.getAsString();
  523. return Saved;
  524. }
  525. bool clang::operator<(const CodeCompletionResult &X,
  526. const CodeCompletionResult &Y) {
  527. std::string XSaved, YSaved;
  528. StringRef XStr = getOrderedName(X, XSaved);
  529. StringRef YStr = getOrderedName(Y, YSaved);
  530. int cmp = XStr.compare_lower(YStr);
  531. if (cmp)
  532. return cmp < 0;
  533. // If case-insensitive comparison fails, try case-sensitive comparison.
  534. cmp = XStr.compare(YStr);
  535. if (cmp)
  536. return cmp < 0;
  537. return false;
  538. }