CodeCompleteConsumer.cpp 25 KB

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