CodeCompleteConsumer.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  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/Sema/Scope.h"
  15. #include "clang/Sema/Sema.h"
  16. #include "clang/AST/DeclCXX.h"
  17. #include "clang/AST/DeclObjC.h"
  18. #include "clang/AST/DeclTemplate.h"
  19. #include "clang/Lex/Preprocessor.h"
  20. #include "clang-c/Index.h"
  21. #include "llvm/ADT/SmallString.h"
  22. #include "llvm/ADT/STLExtras.h"
  23. #include "llvm/ADT/Twine.h"
  24. #include "llvm/Support/raw_ostream.h"
  25. #include <algorithm>
  26. #include <cstring>
  27. #include <functional>
  28. using namespace clang;
  29. //===----------------------------------------------------------------------===//
  30. // Code completion context implementation
  31. //===----------------------------------------------------------------------===//
  32. bool CodeCompletionContext::wantConstructorResults() const {
  33. switch (Kind) {
  34. case CCC_Recovery:
  35. case CCC_Statement:
  36. case CCC_Expression:
  37. case CCC_ObjCMessageReceiver:
  38. case CCC_ParenthesizedExpression:
  39. return true;
  40. case CCC_TopLevel:
  41. case CCC_ObjCInterface:
  42. case CCC_ObjCImplementation:
  43. case CCC_ObjCIvarList:
  44. case CCC_ClassStructUnion:
  45. case CCC_DotMemberAccess:
  46. case CCC_ArrowMemberAccess:
  47. case CCC_ObjCPropertyAccess:
  48. case CCC_EnumTag:
  49. case CCC_UnionTag:
  50. case CCC_ClassOrStructTag:
  51. case CCC_ObjCProtocolName:
  52. case CCC_Namespace:
  53. case CCC_Type:
  54. case CCC_Name:
  55. case CCC_PotentiallyQualifiedName:
  56. case CCC_MacroName:
  57. case CCC_MacroNameUse:
  58. case CCC_PreprocessorExpression:
  59. case CCC_PreprocessorDirective:
  60. case CCC_NaturalLanguage:
  61. case CCC_SelectorName:
  62. case CCC_TypeQualifiers:
  63. case CCC_Other:
  64. case CCC_OtherWithMacros:
  65. case CCC_ObjCInstanceMessage:
  66. case CCC_ObjCClassMessage:
  67. case CCC_ObjCInterfaceName:
  68. case CCC_ObjCCategoryName:
  69. return false;
  70. }
  71. llvm_unreachable("Invalid CodeCompletionContext::Kind!");
  72. }
  73. //===----------------------------------------------------------------------===//
  74. // Code completion string implementation
  75. //===----------------------------------------------------------------------===//
  76. CodeCompletionString::Chunk::Chunk(ChunkKind Kind, const char *Text)
  77. : Kind(Kind), Text("")
  78. {
  79. switch (Kind) {
  80. case CK_TypedText:
  81. case CK_Text:
  82. case CK_Placeholder:
  83. case CK_Informative:
  84. case CK_ResultType:
  85. case CK_CurrentParameter:
  86. this->Text = Text;
  87. break;
  88. case CK_Optional:
  89. llvm_unreachable("Optional strings cannot be created from text");
  90. case CK_LeftParen:
  91. this->Text = "(";
  92. break;
  93. case CK_RightParen:
  94. this->Text = ")";
  95. break;
  96. case CK_LeftBracket:
  97. this->Text = "[";
  98. break;
  99. case CK_RightBracket:
  100. this->Text = "]";
  101. break;
  102. case CK_LeftBrace:
  103. this->Text = "{";
  104. break;
  105. case CK_RightBrace:
  106. this->Text = "}";
  107. break;
  108. case CK_LeftAngle:
  109. this->Text = "<";
  110. break;
  111. case CK_RightAngle:
  112. this->Text = ">";
  113. break;
  114. case CK_Comma:
  115. this->Text = ", ";
  116. break;
  117. case CK_Colon:
  118. this->Text = ":";
  119. break;
  120. case CK_SemiColon:
  121. this->Text = ";";
  122. break;
  123. case CK_Equal:
  124. this->Text = " = ";
  125. break;
  126. case CK_HorizontalSpace:
  127. this->Text = " ";
  128. break;
  129. case CK_VerticalSpace:
  130. this->Text = "\n";
  131. break;
  132. }
  133. }
  134. CodeCompletionString::Chunk
  135. CodeCompletionString::Chunk::CreateText(const char *Text) {
  136. return Chunk(CK_Text, Text);
  137. }
  138. CodeCompletionString::Chunk
  139. CodeCompletionString::Chunk::CreateOptional(CodeCompletionString *Optional) {
  140. Chunk Result;
  141. Result.Kind = CK_Optional;
  142. Result.Optional = Optional;
  143. return Result;
  144. }
  145. CodeCompletionString::Chunk
  146. CodeCompletionString::Chunk::CreatePlaceholder(const char *Placeholder) {
  147. return Chunk(CK_Placeholder, Placeholder);
  148. }
  149. CodeCompletionString::Chunk
  150. CodeCompletionString::Chunk::CreateInformative(const char *Informative) {
  151. return Chunk(CK_Informative, Informative);
  152. }
  153. CodeCompletionString::Chunk
  154. CodeCompletionString::Chunk::CreateResultType(const char *ResultType) {
  155. return Chunk(CK_ResultType, ResultType);
  156. }
  157. CodeCompletionString::Chunk
  158. CodeCompletionString::Chunk::CreateCurrentParameter(
  159. const char *CurrentParameter) {
  160. return Chunk(CK_CurrentParameter, CurrentParameter);
  161. }
  162. CodeCompletionString::CodeCompletionString(const Chunk *Chunks,
  163. unsigned NumChunks,
  164. unsigned Priority,
  165. CXAvailabilityKind Availability,
  166. const char **Annotations,
  167. unsigned NumAnnotations)
  168. : NumChunks(NumChunks), NumAnnotations(NumAnnotations)
  169. , Priority(Priority), Availability(Availability)
  170. {
  171. assert(NumChunks <= 0xffff);
  172. assert(NumAnnotations <= 0xffff);
  173. Chunk *StoredChunks = reinterpret_cast<Chunk *>(this + 1);
  174. for (unsigned I = 0; I != NumChunks; ++I)
  175. StoredChunks[I] = Chunks[I];
  176. const char **StoredAnnotations = reinterpret_cast<const char **>(StoredChunks + NumChunks);
  177. for (unsigned I = 0; I != NumAnnotations; ++I)
  178. StoredAnnotations[I] = Annotations[I];
  179. }
  180. unsigned CodeCompletionString::getAnnotationCount() const {
  181. return NumAnnotations;
  182. }
  183. const char *CodeCompletionString::getAnnotation(unsigned AnnotationNr) const {
  184. if (AnnotationNr < NumAnnotations)
  185. return reinterpret_cast<const char * const*>(end())[AnnotationNr];
  186. else
  187. return 0;
  188. }
  189. std::string CodeCompletionString::getAsString() const {
  190. std::string Result;
  191. llvm::raw_string_ostream OS(Result);
  192. for (iterator C = begin(), CEnd = end(); C != CEnd; ++C) {
  193. switch (C->Kind) {
  194. case CK_Optional: OS << "{#" << C->Optional->getAsString() << "#}"; break;
  195. case CK_Placeholder: OS << "<#" << C->Text << "#>"; break;
  196. case CK_Informative:
  197. case CK_ResultType:
  198. OS << "[#" << C->Text << "#]";
  199. break;
  200. case CK_CurrentParameter: OS << "<#" << C->Text << "#>"; break;
  201. default: OS << C->Text; break;
  202. }
  203. }
  204. return OS.str();
  205. }
  206. const char *CodeCompletionString::getTypedText() const {
  207. for (iterator C = begin(), CEnd = end(); C != CEnd; ++C)
  208. if (C->Kind == CK_TypedText)
  209. return C->Text;
  210. return 0;
  211. }
  212. const char *CodeCompletionAllocator::CopyString(StringRef String) {
  213. char *Mem = (char *)Allocate(String.size() + 1, 1);
  214. std::copy(String.begin(), String.end(), Mem);
  215. Mem[String.size()] = 0;
  216. return Mem;
  217. }
  218. const char *CodeCompletionAllocator::CopyString(Twine String) {
  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. llvm::SmallString<128> Data;
  223. return CopyString(String.toStringRef(Data));
  224. }
  225. CodeCompletionString *CodeCompletionBuilder::TakeString() {
  226. void *Mem = Allocator.Allocate(
  227. sizeof(CodeCompletionString) + sizeof(Chunk) * Chunks.size()
  228. + sizeof(const char *) * Annotations.size(),
  229. llvm::alignOf<CodeCompletionString>());
  230. CodeCompletionString *Result
  231. = new (Mem) CodeCompletionString(Chunks.data(), Chunks.size(),
  232. Priority, Availability,
  233. Annotations.data(), Annotations.size());
  234. Chunks.clear();
  235. return Result;
  236. }
  237. unsigned CodeCompletionResult::getPriorityFromDecl(NamedDecl *ND) {
  238. if (!ND)
  239. return CCP_Unlikely;
  240. // Context-based decisions.
  241. DeclContext *DC = ND->getDeclContext()->getRedeclContext();
  242. if (DC->isFunctionOrMethod() || isa<BlockDecl>(DC)) {
  243. // _cmd is relatively rare
  244. if (ImplicitParamDecl *ImplicitParam = dyn_cast<ImplicitParamDecl>(ND))
  245. if (ImplicitParam->getIdentifier() &&
  246. ImplicitParam->getIdentifier()->isStr("_cmd"))
  247. return CCP_ObjC_cmd;
  248. return CCP_LocalDeclaration;
  249. }
  250. if (DC->isRecord() || isa<ObjCContainerDecl>(DC))
  251. return CCP_MemberDeclaration;
  252. // Content-based decisions.
  253. if (isa<EnumConstantDecl>(ND))
  254. return CCP_Constant;
  255. if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND))
  256. return CCP_Type;
  257. return CCP_Declaration;
  258. }
  259. //===----------------------------------------------------------------------===//
  260. // Code completion overload candidate implementation
  261. //===----------------------------------------------------------------------===//
  262. FunctionDecl *
  263. CodeCompleteConsumer::OverloadCandidate::getFunction() const {
  264. if (getKind() == CK_Function)
  265. return Function;
  266. else if (getKind() == CK_FunctionTemplate)
  267. return FunctionTemplate->getTemplatedDecl();
  268. else
  269. return 0;
  270. }
  271. const FunctionType *
  272. CodeCompleteConsumer::OverloadCandidate::getFunctionType() const {
  273. switch (Kind) {
  274. case CK_Function:
  275. return Function->getType()->getAs<FunctionType>();
  276. case CK_FunctionTemplate:
  277. return FunctionTemplate->getTemplatedDecl()->getType()
  278. ->getAs<FunctionType>();
  279. case CK_FunctionType:
  280. return Type;
  281. }
  282. llvm_unreachable("Invalid CandidateKind!");
  283. }
  284. //===----------------------------------------------------------------------===//
  285. // Code completion consumer implementation
  286. //===----------------------------------------------------------------------===//
  287. CodeCompleteConsumer::~CodeCompleteConsumer() { }
  288. void
  289. PrintingCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &SemaRef,
  290. CodeCompletionContext Context,
  291. CodeCompletionResult *Results,
  292. unsigned NumResults) {
  293. std::stable_sort(Results, Results + NumResults);
  294. // Print the results.
  295. for (unsigned I = 0; I != NumResults; ++I) {
  296. OS << "COMPLETION: ";
  297. switch (Results[I].Kind) {
  298. case CodeCompletionResult::RK_Declaration:
  299. OS << *Results[I].Declaration;
  300. if (Results[I].Hidden)
  301. OS << " (Hidden)";
  302. if (CodeCompletionString *CCS
  303. = Results[I].CreateCodeCompletionString(SemaRef, Allocator)) {
  304. OS << " : " << CCS->getAsString();
  305. }
  306. OS << '\n';
  307. break;
  308. case CodeCompletionResult::RK_Keyword:
  309. OS << Results[I].Keyword << '\n';
  310. break;
  311. case CodeCompletionResult::RK_Macro: {
  312. OS << Results[I].Macro->getName();
  313. if (CodeCompletionString *CCS
  314. = Results[I].CreateCodeCompletionString(SemaRef, Allocator)) {
  315. OS << " : " << CCS->getAsString();
  316. }
  317. OS << '\n';
  318. break;
  319. }
  320. case CodeCompletionResult::RK_Pattern: {
  321. OS << "Pattern : "
  322. << Results[I].Pattern->getAsString() << '\n';
  323. break;
  324. }
  325. }
  326. }
  327. }
  328. void
  329. PrintingCodeCompleteConsumer::ProcessOverloadCandidates(Sema &SemaRef,
  330. unsigned CurrentArg,
  331. OverloadCandidate *Candidates,
  332. unsigned NumCandidates) {
  333. for (unsigned I = 0; I != NumCandidates; ++I) {
  334. if (CodeCompletionString *CCS
  335. = Candidates[I].CreateSignatureString(CurrentArg, SemaRef,
  336. Allocator)) {
  337. OS << "OVERLOAD: " << CCS->getAsString() << "\n";
  338. }
  339. }
  340. }
  341. void CodeCompletionResult::computeCursorKindAndAvailability(bool Accessible) {
  342. switch (Kind) {
  343. case RK_Declaration:
  344. // Set the availability based on attributes.
  345. switch (Declaration->getAvailability()) {
  346. case AR_Available:
  347. case AR_NotYetIntroduced:
  348. Availability = CXAvailability_Available;
  349. break;
  350. case AR_Deprecated:
  351. Availability = CXAvailability_Deprecated;
  352. break;
  353. case AR_Unavailable:
  354. Availability = CXAvailability_NotAvailable;
  355. break;
  356. }
  357. if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Declaration))
  358. if (Function->isDeleted())
  359. Availability = CXAvailability_NotAvailable;
  360. CursorKind = getCursorKindForDecl(Declaration);
  361. if (CursorKind == CXCursor_UnexposedDecl) {
  362. // FIXME: Forward declarations of Objective-C classes and protocols
  363. // are not directly exposed, but we want code completion to treat them
  364. // like a definition.
  365. if (isa<ObjCInterfaceDecl>(Declaration))
  366. CursorKind = CXCursor_ObjCInterfaceDecl;
  367. else if (isa<ObjCProtocolDecl>(Declaration))
  368. CursorKind = CXCursor_ObjCProtocolDecl;
  369. else
  370. CursorKind = CXCursor_NotImplemented;
  371. }
  372. break;
  373. case RK_Macro:
  374. Availability = CXAvailability_Available;
  375. CursorKind = CXCursor_MacroDefinition;
  376. break;
  377. case RK_Keyword:
  378. Availability = CXAvailability_Available;
  379. CursorKind = CXCursor_NotImplemented;
  380. break;
  381. case RK_Pattern:
  382. // Do nothing: Patterns can come with cursor kinds!
  383. break;
  384. }
  385. if (!Accessible)
  386. Availability = CXAvailability_NotAccessible;
  387. }
  388. /// \brief Retrieve the name that should be used to order a result.
  389. ///
  390. /// If the name needs to be constructed as a string, that string will be
  391. /// saved into Saved and the returned StringRef will refer to it.
  392. static StringRef getOrderedName(const CodeCompletionResult &R,
  393. std::string &Saved) {
  394. switch (R.Kind) {
  395. case CodeCompletionResult::RK_Keyword:
  396. return R.Keyword;
  397. case CodeCompletionResult::RK_Pattern:
  398. return R.Pattern->getTypedText();
  399. case CodeCompletionResult::RK_Macro:
  400. return R.Macro->getName();
  401. case CodeCompletionResult::RK_Declaration:
  402. // Handle declarations below.
  403. break;
  404. }
  405. DeclarationName Name = R.Declaration->getDeclName();
  406. // If the name is a simple identifier (by far the common case), or a
  407. // zero-argument selector, just return a reference to that identifier.
  408. if (IdentifierInfo *Id = Name.getAsIdentifierInfo())
  409. return Id->getName();
  410. if (Name.isObjCZeroArgSelector())
  411. if (IdentifierInfo *Id
  412. = Name.getObjCSelector().getIdentifierInfoForSlot(0))
  413. return Id->getName();
  414. Saved = Name.getAsString();
  415. return Saved;
  416. }
  417. bool clang::operator<(const CodeCompletionResult &X,
  418. const CodeCompletionResult &Y) {
  419. std::string XSaved, YSaved;
  420. StringRef XStr = getOrderedName(X, XSaved);
  421. StringRef YStr = getOrderedName(Y, YSaved);
  422. int cmp = XStr.compare_lower(YStr);
  423. if (cmp)
  424. return cmp < 0;
  425. // If case-insensitive comparison fails, try case-sensitive comparison.
  426. cmp = XStr.compare(YStr);
  427. if (cmp)
  428. return cmp < 0;
  429. return false;
  430. }