CIndexCodeCompletion.cpp 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043
  1. //===- CIndexCodeCompletion.cpp - Code Completion API hooks ---------------===//
  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 Clang-C Source Indexing library hooks for
  10. // code completion.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "CIndexer.h"
  14. #include "CIndexDiagnostic.h"
  15. #include "CLog.h"
  16. #include "CXCursor.h"
  17. #include "CXSourceLocation.h"
  18. #include "CXString.h"
  19. #include "CXTranslationUnit.h"
  20. #include "clang/AST/Decl.h"
  21. #include "clang/AST/DeclObjC.h"
  22. #include "clang/AST/Type.h"
  23. #include "clang/Basic/FileManager.h"
  24. #include "clang/Basic/SourceManager.h"
  25. #include "clang/Frontend/ASTUnit.h"
  26. #include "clang/Frontend/CompilerInstance.h"
  27. #include "clang/Sema/CodeCompleteConsumer.h"
  28. #include "clang/Sema/Sema.h"
  29. #include "llvm/ADT/SmallString.h"
  30. #include "llvm/ADT/StringExtras.h"
  31. #include "llvm/Support/CrashRecoveryContext.h"
  32. #include "llvm/Support/FileSystem.h"
  33. #include "llvm/Support/FormatVariadic.h"
  34. #include "llvm/Support/MemoryBuffer.h"
  35. #include "llvm/Support/Program.h"
  36. #include "llvm/Support/Timer.h"
  37. #include "llvm/Support/raw_ostream.h"
  38. #include <atomic>
  39. #include <cstdio>
  40. #include <cstdlib>
  41. #include <string>
  42. #ifdef UDP_CODE_COMPLETION_LOGGER
  43. #include "clang/Basic/Version.h"
  44. #include <arpa/inet.h>
  45. #include <sys/socket.h>
  46. #include <sys/types.h>
  47. #include <unistd.h>
  48. #endif
  49. using namespace clang;
  50. using namespace clang::cxindex;
  51. enum CXCompletionChunkKind
  52. clang_getCompletionChunkKind(CXCompletionString completion_string,
  53. unsigned chunk_number) {
  54. CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
  55. if (!CCStr || chunk_number >= CCStr->size())
  56. return CXCompletionChunk_Text;
  57. switch ((*CCStr)[chunk_number].Kind) {
  58. case CodeCompletionString::CK_TypedText:
  59. return CXCompletionChunk_TypedText;
  60. case CodeCompletionString::CK_Text:
  61. return CXCompletionChunk_Text;
  62. case CodeCompletionString::CK_Optional:
  63. return CXCompletionChunk_Optional;
  64. case CodeCompletionString::CK_Placeholder:
  65. return CXCompletionChunk_Placeholder;
  66. case CodeCompletionString::CK_Informative:
  67. return CXCompletionChunk_Informative;
  68. case CodeCompletionString::CK_ResultType:
  69. return CXCompletionChunk_ResultType;
  70. case CodeCompletionString::CK_CurrentParameter:
  71. return CXCompletionChunk_CurrentParameter;
  72. case CodeCompletionString::CK_LeftParen:
  73. return CXCompletionChunk_LeftParen;
  74. case CodeCompletionString::CK_RightParen:
  75. return CXCompletionChunk_RightParen;
  76. case CodeCompletionString::CK_LeftBracket:
  77. return CXCompletionChunk_LeftBracket;
  78. case CodeCompletionString::CK_RightBracket:
  79. return CXCompletionChunk_RightBracket;
  80. case CodeCompletionString::CK_LeftBrace:
  81. return CXCompletionChunk_LeftBrace;
  82. case CodeCompletionString::CK_RightBrace:
  83. return CXCompletionChunk_RightBrace;
  84. case CodeCompletionString::CK_LeftAngle:
  85. return CXCompletionChunk_LeftAngle;
  86. case CodeCompletionString::CK_RightAngle:
  87. return CXCompletionChunk_RightAngle;
  88. case CodeCompletionString::CK_Comma:
  89. return CXCompletionChunk_Comma;
  90. case CodeCompletionString::CK_Colon:
  91. return CXCompletionChunk_Colon;
  92. case CodeCompletionString::CK_SemiColon:
  93. return CXCompletionChunk_SemiColon;
  94. case CodeCompletionString::CK_Equal:
  95. return CXCompletionChunk_Equal;
  96. case CodeCompletionString::CK_HorizontalSpace:
  97. return CXCompletionChunk_HorizontalSpace;
  98. case CodeCompletionString::CK_VerticalSpace:
  99. return CXCompletionChunk_VerticalSpace;
  100. }
  101. llvm_unreachable("Invalid CompletionKind!");
  102. }
  103. CXString clang_getCompletionChunkText(CXCompletionString completion_string,
  104. unsigned chunk_number) {
  105. CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
  106. if (!CCStr || chunk_number >= CCStr->size())
  107. return cxstring::createNull();
  108. switch ((*CCStr)[chunk_number].Kind) {
  109. case CodeCompletionString::CK_TypedText:
  110. case CodeCompletionString::CK_Text:
  111. case CodeCompletionString::CK_Placeholder:
  112. case CodeCompletionString::CK_CurrentParameter:
  113. case CodeCompletionString::CK_Informative:
  114. case CodeCompletionString::CK_LeftParen:
  115. case CodeCompletionString::CK_RightParen:
  116. case CodeCompletionString::CK_LeftBracket:
  117. case CodeCompletionString::CK_RightBracket:
  118. case CodeCompletionString::CK_LeftBrace:
  119. case CodeCompletionString::CK_RightBrace:
  120. case CodeCompletionString::CK_LeftAngle:
  121. case CodeCompletionString::CK_RightAngle:
  122. case CodeCompletionString::CK_Comma:
  123. case CodeCompletionString::CK_ResultType:
  124. case CodeCompletionString::CK_Colon:
  125. case CodeCompletionString::CK_SemiColon:
  126. case CodeCompletionString::CK_Equal:
  127. case CodeCompletionString::CK_HorizontalSpace:
  128. case CodeCompletionString::CK_VerticalSpace:
  129. return cxstring::createRef((*CCStr)[chunk_number].Text);
  130. case CodeCompletionString::CK_Optional:
  131. // Note: treated as an empty text block.
  132. return cxstring::createEmpty();
  133. }
  134. llvm_unreachable("Invalid CodeCompletionString Kind!");
  135. }
  136. CXCompletionString
  137. clang_getCompletionChunkCompletionString(CXCompletionString completion_string,
  138. unsigned chunk_number) {
  139. CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
  140. if (!CCStr || chunk_number >= CCStr->size())
  141. return nullptr;
  142. switch ((*CCStr)[chunk_number].Kind) {
  143. case CodeCompletionString::CK_TypedText:
  144. case CodeCompletionString::CK_Text:
  145. case CodeCompletionString::CK_Placeholder:
  146. case CodeCompletionString::CK_CurrentParameter:
  147. case CodeCompletionString::CK_Informative:
  148. case CodeCompletionString::CK_LeftParen:
  149. case CodeCompletionString::CK_RightParen:
  150. case CodeCompletionString::CK_LeftBracket:
  151. case CodeCompletionString::CK_RightBracket:
  152. case CodeCompletionString::CK_LeftBrace:
  153. case CodeCompletionString::CK_RightBrace:
  154. case CodeCompletionString::CK_LeftAngle:
  155. case CodeCompletionString::CK_RightAngle:
  156. case CodeCompletionString::CK_Comma:
  157. case CodeCompletionString::CK_ResultType:
  158. case CodeCompletionString::CK_Colon:
  159. case CodeCompletionString::CK_SemiColon:
  160. case CodeCompletionString::CK_Equal:
  161. case CodeCompletionString::CK_HorizontalSpace:
  162. case CodeCompletionString::CK_VerticalSpace:
  163. return nullptr;
  164. case CodeCompletionString::CK_Optional:
  165. // Note: treated as an empty text block.
  166. return (*CCStr)[chunk_number].Optional;
  167. }
  168. llvm_unreachable("Invalid CompletionKind!");
  169. }
  170. unsigned clang_getNumCompletionChunks(CXCompletionString completion_string) {
  171. CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
  172. return CCStr? CCStr->size() : 0;
  173. }
  174. unsigned clang_getCompletionPriority(CXCompletionString completion_string) {
  175. CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
  176. return CCStr? CCStr->getPriority() : unsigned(CCP_Unlikely);
  177. }
  178. enum CXAvailabilityKind
  179. clang_getCompletionAvailability(CXCompletionString completion_string) {
  180. CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
  181. return CCStr? static_cast<CXAvailabilityKind>(CCStr->getAvailability())
  182. : CXAvailability_Available;
  183. }
  184. unsigned clang_getCompletionNumAnnotations(CXCompletionString completion_string)
  185. {
  186. CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
  187. return CCStr ? CCStr->getAnnotationCount() : 0;
  188. }
  189. CXString clang_getCompletionAnnotation(CXCompletionString completion_string,
  190. unsigned annotation_number) {
  191. CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
  192. return CCStr ? cxstring::createRef(CCStr->getAnnotation(annotation_number))
  193. : cxstring::createNull();
  194. }
  195. CXString
  196. clang_getCompletionParent(CXCompletionString completion_string,
  197. CXCursorKind *kind) {
  198. if (kind)
  199. *kind = CXCursor_NotImplemented;
  200. CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
  201. if (!CCStr)
  202. return cxstring::createNull();
  203. return cxstring::createRef(CCStr->getParentContextName());
  204. }
  205. CXString
  206. clang_getCompletionBriefComment(CXCompletionString completion_string) {
  207. CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
  208. if (!CCStr)
  209. return cxstring::createNull();
  210. return cxstring::createRef(CCStr->getBriefComment());
  211. }
  212. namespace {
  213. /// The CXCodeCompleteResults structure we allocate internally;
  214. /// the client only sees the initial CXCodeCompleteResults structure.
  215. ///
  216. /// Normally, clients of CXString shouldn't care whether or not a CXString is
  217. /// managed by a pool or by explicitly malloc'ed memory. But
  218. /// AllocatedCXCodeCompleteResults outlives the CXTranslationUnit, so we can
  219. /// not rely on the StringPool in the TU.
  220. struct AllocatedCXCodeCompleteResults : public CXCodeCompleteResults {
  221. AllocatedCXCodeCompleteResults(IntrusiveRefCntPtr<FileManager> FileMgr);
  222. ~AllocatedCXCodeCompleteResults();
  223. /// Diagnostics produced while performing code completion.
  224. SmallVector<StoredDiagnostic, 8> Diagnostics;
  225. /// Allocated API-exposed wrappters for Diagnostics.
  226. SmallVector<CXStoredDiagnostic *, 8> DiagnosticsWrappers;
  227. IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts;
  228. /// Diag object
  229. IntrusiveRefCntPtr<DiagnosticsEngine> Diag;
  230. /// Language options used to adjust source locations.
  231. LangOptions LangOpts;
  232. /// File manager, used for diagnostics.
  233. IntrusiveRefCntPtr<FileManager> FileMgr;
  234. /// Source manager, used for diagnostics.
  235. IntrusiveRefCntPtr<SourceManager> SourceMgr;
  236. /// Temporary buffers that will be deleted once we have finished with
  237. /// the code-completion results.
  238. SmallVector<const llvm::MemoryBuffer *, 1> TemporaryBuffers;
  239. /// Allocator used to store globally cached code-completion results.
  240. std::shared_ptr<clang::GlobalCodeCompletionAllocator>
  241. CachedCompletionAllocator;
  242. /// Allocator used to store code completion results.
  243. std::shared_ptr<clang::GlobalCodeCompletionAllocator> CodeCompletionAllocator;
  244. /// Context under which completion occurred.
  245. enum clang::CodeCompletionContext::Kind ContextKind;
  246. /// A bitfield representing the acceptable completions for the
  247. /// current context.
  248. unsigned long long Contexts;
  249. /// The kind of the container for the current context for completions.
  250. enum CXCursorKind ContainerKind;
  251. /// The USR of the container for the current context for completions.
  252. std::string ContainerUSR;
  253. /// a boolean value indicating whether there is complete information
  254. /// about the container
  255. unsigned ContainerIsIncomplete;
  256. /// A string containing the Objective-C selector entered thus far for a
  257. /// message send.
  258. std::string Selector;
  259. /// Vector of fix-its for each completion result that *must* be applied
  260. /// before that result for the corresponding completion item.
  261. std::vector<std::vector<FixItHint>> FixItsVector;
  262. };
  263. } // end anonymous namespace
  264. unsigned clang_getCompletionNumFixIts(CXCodeCompleteResults *results,
  265. unsigned completion_index) {
  266. AllocatedCXCodeCompleteResults *allocated_results = (AllocatedCXCodeCompleteResults *)results;
  267. if (!allocated_results || allocated_results->FixItsVector.size() <= completion_index)
  268. return 0;
  269. return static_cast<unsigned>(allocated_results->FixItsVector[completion_index].size());
  270. }
  271. CXString clang_getCompletionFixIt(CXCodeCompleteResults *results,
  272. unsigned completion_index,
  273. unsigned fixit_index,
  274. CXSourceRange *replacement_range) {
  275. AllocatedCXCodeCompleteResults *allocated_results = (AllocatedCXCodeCompleteResults *)results;
  276. if (!allocated_results || allocated_results->FixItsVector.size() <= completion_index) {
  277. if (replacement_range)
  278. *replacement_range = clang_getNullRange();
  279. return cxstring::createNull();
  280. }
  281. ArrayRef<FixItHint> FixIts = allocated_results->FixItsVector[completion_index];
  282. if (FixIts.size() <= fixit_index) {
  283. if (replacement_range)
  284. *replacement_range = clang_getNullRange();
  285. return cxstring::createNull();
  286. }
  287. const FixItHint &FixIt = FixIts[fixit_index];
  288. if (replacement_range) {
  289. *replacement_range = cxloc::translateSourceRange(
  290. *allocated_results->SourceMgr, allocated_results->LangOpts,
  291. FixIt.RemoveRange);
  292. }
  293. return cxstring::createRef(FixIt.CodeToInsert.c_str());
  294. }
  295. /// Tracks the number of code-completion result objects that are
  296. /// currently active.
  297. ///
  298. /// Used for debugging purposes only.
  299. static std::atomic<unsigned> CodeCompletionResultObjects;
  300. AllocatedCXCodeCompleteResults::AllocatedCXCodeCompleteResults(
  301. IntrusiveRefCntPtr<FileManager> FileMgr)
  302. : CXCodeCompleteResults(), DiagOpts(new DiagnosticOptions),
  303. Diag(new DiagnosticsEngine(
  304. IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs), &*DiagOpts)),
  305. FileMgr(std::move(FileMgr)),
  306. SourceMgr(new SourceManager(*Diag, *this->FileMgr)),
  307. CodeCompletionAllocator(
  308. std::make_shared<clang::GlobalCodeCompletionAllocator>()),
  309. Contexts(CXCompletionContext_Unknown),
  310. ContainerKind(CXCursor_InvalidCode), ContainerIsIncomplete(1) {
  311. if (getenv("LIBCLANG_OBJTRACKING"))
  312. fprintf(stderr, "+++ %u completion results\n",
  313. ++CodeCompletionResultObjects);
  314. }
  315. AllocatedCXCodeCompleteResults::~AllocatedCXCodeCompleteResults() {
  316. llvm::DeleteContainerPointers(DiagnosticsWrappers);
  317. delete [] Results;
  318. for (unsigned I = 0, N = TemporaryBuffers.size(); I != N; ++I)
  319. delete TemporaryBuffers[I];
  320. if (getenv("LIBCLANG_OBJTRACKING"))
  321. fprintf(stderr, "--- %u completion results\n",
  322. --CodeCompletionResultObjects);
  323. }
  324. static unsigned long long getContextsForContextKind(
  325. enum CodeCompletionContext::Kind kind,
  326. Sema &S) {
  327. unsigned long long contexts = 0;
  328. switch (kind) {
  329. case CodeCompletionContext::CCC_OtherWithMacros: {
  330. //We can allow macros here, but we don't know what else is permissible
  331. //So we'll say the only thing permissible are macros
  332. contexts = CXCompletionContext_MacroName;
  333. break;
  334. }
  335. case CodeCompletionContext::CCC_TopLevel:
  336. case CodeCompletionContext::CCC_ObjCIvarList:
  337. case CodeCompletionContext::CCC_ClassStructUnion:
  338. case CodeCompletionContext::CCC_Type: {
  339. contexts = CXCompletionContext_AnyType |
  340. CXCompletionContext_ObjCInterface;
  341. if (S.getLangOpts().CPlusPlus) {
  342. contexts |= CXCompletionContext_EnumTag |
  343. CXCompletionContext_UnionTag |
  344. CXCompletionContext_StructTag |
  345. CXCompletionContext_ClassTag |
  346. CXCompletionContext_NestedNameSpecifier;
  347. }
  348. break;
  349. }
  350. case CodeCompletionContext::CCC_Statement: {
  351. contexts = CXCompletionContext_AnyType |
  352. CXCompletionContext_ObjCInterface |
  353. CXCompletionContext_AnyValue;
  354. if (S.getLangOpts().CPlusPlus) {
  355. contexts |= CXCompletionContext_EnumTag |
  356. CXCompletionContext_UnionTag |
  357. CXCompletionContext_StructTag |
  358. CXCompletionContext_ClassTag |
  359. CXCompletionContext_NestedNameSpecifier;
  360. }
  361. break;
  362. }
  363. case CodeCompletionContext::CCC_Expression: {
  364. contexts = CXCompletionContext_AnyValue;
  365. if (S.getLangOpts().CPlusPlus) {
  366. contexts |= CXCompletionContext_AnyType |
  367. CXCompletionContext_ObjCInterface |
  368. CXCompletionContext_EnumTag |
  369. CXCompletionContext_UnionTag |
  370. CXCompletionContext_StructTag |
  371. CXCompletionContext_ClassTag |
  372. CXCompletionContext_NestedNameSpecifier;
  373. }
  374. break;
  375. }
  376. case CodeCompletionContext::CCC_ObjCMessageReceiver: {
  377. contexts = CXCompletionContext_ObjCObjectValue |
  378. CXCompletionContext_ObjCSelectorValue |
  379. CXCompletionContext_ObjCInterface;
  380. if (S.getLangOpts().CPlusPlus) {
  381. contexts |= CXCompletionContext_CXXClassTypeValue |
  382. CXCompletionContext_AnyType |
  383. CXCompletionContext_EnumTag |
  384. CXCompletionContext_UnionTag |
  385. CXCompletionContext_StructTag |
  386. CXCompletionContext_ClassTag |
  387. CXCompletionContext_NestedNameSpecifier;
  388. }
  389. break;
  390. }
  391. case CodeCompletionContext::CCC_DotMemberAccess: {
  392. contexts = CXCompletionContext_DotMemberAccess;
  393. break;
  394. }
  395. case CodeCompletionContext::CCC_ArrowMemberAccess: {
  396. contexts = CXCompletionContext_ArrowMemberAccess;
  397. break;
  398. }
  399. case CodeCompletionContext::CCC_ObjCPropertyAccess: {
  400. contexts = CXCompletionContext_ObjCPropertyAccess;
  401. break;
  402. }
  403. case CodeCompletionContext::CCC_EnumTag: {
  404. contexts = CXCompletionContext_EnumTag |
  405. CXCompletionContext_NestedNameSpecifier;
  406. break;
  407. }
  408. case CodeCompletionContext::CCC_UnionTag: {
  409. contexts = CXCompletionContext_UnionTag |
  410. CXCompletionContext_NestedNameSpecifier;
  411. break;
  412. }
  413. case CodeCompletionContext::CCC_ClassOrStructTag: {
  414. contexts = CXCompletionContext_StructTag |
  415. CXCompletionContext_ClassTag |
  416. CXCompletionContext_NestedNameSpecifier;
  417. break;
  418. }
  419. case CodeCompletionContext::CCC_ObjCProtocolName: {
  420. contexts = CXCompletionContext_ObjCProtocol;
  421. break;
  422. }
  423. case CodeCompletionContext::CCC_Namespace: {
  424. contexts = CXCompletionContext_Namespace;
  425. break;
  426. }
  427. case CodeCompletionContext::CCC_SymbolOrNewName:
  428. case CodeCompletionContext::CCC_Symbol: {
  429. contexts = CXCompletionContext_NestedNameSpecifier;
  430. break;
  431. }
  432. case CodeCompletionContext::CCC_MacroNameUse: {
  433. contexts = CXCompletionContext_MacroName;
  434. break;
  435. }
  436. case CodeCompletionContext::CCC_NaturalLanguage: {
  437. contexts = CXCompletionContext_NaturalLanguage;
  438. break;
  439. }
  440. case CodeCompletionContext::CCC_IncludedFile: {
  441. contexts = CXCompletionContext_IncludedFile;
  442. break;
  443. }
  444. case CodeCompletionContext::CCC_SelectorName: {
  445. contexts = CXCompletionContext_ObjCSelectorName;
  446. break;
  447. }
  448. case CodeCompletionContext::CCC_ParenthesizedExpression: {
  449. contexts = CXCompletionContext_AnyType |
  450. CXCompletionContext_ObjCInterface |
  451. CXCompletionContext_AnyValue;
  452. if (S.getLangOpts().CPlusPlus) {
  453. contexts |= CXCompletionContext_EnumTag |
  454. CXCompletionContext_UnionTag |
  455. CXCompletionContext_StructTag |
  456. CXCompletionContext_ClassTag |
  457. CXCompletionContext_NestedNameSpecifier;
  458. }
  459. break;
  460. }
  461. case CodeCompletionContext::CCC_ObjCInstanceMessage: {
  462. contexts = CXCompletionContext_ObjCInstanceMessage;
  463. break;
  464. }
  465. case CodeCompletionContext::CCC_ObjCClassMessage: {
  466. contexts = CXCompletionContext_ObjCClassMessage;
  467. break;
  468. }
  469. case CodeCompletionContext::CCC_ObjCInterfaceName: {
  470. contexts = CXCompletionContext_ObjCInterface;
  471. break;
  472. }
  473. case CodeCompletionContext::CCC_ObjCCategoryName: {
  474. contexts = CXCompletionContext_ObjCCategory;
  475. break;
  476. }
  477. case CodeCompletionContext::CCC_Other:
  478. case CodeCompletionContext::CCC_ObjCInterface:
  479. case CodeCompletionContext::CCC_ObjCImplementation:
  480. case CodeCompletionContext::CCC_NewName:
  481. case CodeCompletionContext::CCC_MacroName:
  482. case CodeCompletionContext::CCC_PreprocessorExpression:
  483. case CodeCompletionContext::CCC_PreprocessorDirective:
  484. case CodeCompletionContext::CCC_TypeQualifiers: {
  485. //Only Clang results should be accepted, so we'll set all of the other
  486. //context bits to 0 (i.e. the empty set)
  487. contexts = CXCompletionContext_Unexposed;
  488. break;
  489. }
  490. case CodeCompletionContext::CCC_Recovery: {
  491. //We don't know what the current context is, so we'll return unknown
  492. //This is the equivalent of setting all of the other context bits
  493. contexts = CXCompletionContext_Unknown;
  494. break;
  495. }
  496. }
  497. return contexts;
  498. }
  499. namespace {
  500. class CaptureCompletionResults : public CodeCompleteConsumer {
  501. AllocatedCXCodeCompleteResults &AllocatedResults;
  502. CodeCompletionTUInfo CCTUInfo;
  503. SmallVector<CXCompletionResult, 16> StoredResults;
  504. CXTranslationUnit *TU;
  505. public:
  506. CaptureCompletionResults(const CodeCompleteOptions &Opts,
  507. AllocatedCXCodeCompleteResults &Results,
  508. CXTranslationUnit *TranslationUnit)
  509. : CodeCompleteConsumer(Opts), AllocatedResults(Results),
  510. CCTUInfo(Results.CodeCompletionAllocator), TU(TranslationUnit) {}
  511. ~CaptureCompletionResults() override { Finish(); }
  512. void ProcessCodeCompleteResults(Sema &S,
  513. CodeCompletionContext Context,
  514. CodeCompletionResult *Results,
  515. unsigned NumResults) override {
  516. StoredResults.reserve(StoredResults.size() + NumResults);
  517. if (includeFixIts())
  518. AllocatedResults.FixItsVector.reserve(NumResults);
  519. for (unsigned I = 0; I != NumResults; ++I) {
  520. CodeCompletionString *StoredCompletion
  521. = Results[I].CreateCodeCompletionString(S, Context, getAllocator(),
  522. getCodeCompletionTUInfo(),
  523. includeBriefComments());
  524. CXCompletionResult R;
  525. R.CursorKind = Results[I].CursorKind;
  526. R.CompletionString = StoredCompletion;
  527. StoredResults.push_back(R);
  528. if (includeFixIts())
  529. AllocatedResults.FixItsVector.emplace_back(std::move(Results[I].FixIts));
  530. }
  531. enum CodeCompletionContext::Kind contextKind = Context.getKind();
  532. AllocatedResults.ContextKind = contextKind;
  533. AllocatedResults.Contexts = getContextsForContextKind(contextKind, S);
  534. AllocatedResults.Selector = "";
  535. ArrayRef<IdentifierInfo *> SelIdents = Context.getSelIdents();
  536. for (ArrayRef<IdentifierInfo *>::iterator I = SelIdents.begin(),
  537. E = SelIdents.end();
  538. I != E; ++I) {
  539. if (IdentifierInfo *selIdent = *I)
  540. AllocatedResults.Selector += selIdent->getName();
  541. AllocatedResults.Selector += ":";
  542. }
  543. QualType baseType = Context.getBaseType();
  544. NamedDecl *D = nullptr;
  545. if (!baseType.isNull()) {
  546. // Get the declaration for a class/struct/union/enum type
  547. if (const TagType *Tag = baseType->getAs<TagType>())
  548. D = Tag->getDecl();
  549. // Get the @interface declaration for a (possibly-qualified) Objective-C
  550. // object pointer type, e.g., NSString*
  551. else if (const ObjCObjectPointerType *ObjPtr =
  552. baseType->getAs<ObjCObjectPointerType>())
  553. D = ObjPtr->getInterfaceDecl();
  554. // Get the @interface declaration for an Objective-C object type
  555. else if (const ObjCObjectType *Obj = baseType->getAs<ObjCObjectType>())
  556. D = Obj->getInterface();
  557. // Get the class for a C++ injected-class-name
  558. else if (const InjectedClassNameType *Injected =
  559. baseType->getAs<InjectedClassNameType>())
  560. D = Injected->getDecl();
  561. }
  562. if (D != nullptr) {
  563. CXCursor cursor = cxcursor::MakeCXCursor(D, *TU);
  564. AllocatedResults.ContainerKind = clang_getCursorKind(cursor);
  565. CXString CursorUSR = clang_getCursorUSR(cursor);
  566. AllocatedResults.ContainerUSR = clang_getCString(CursorUSR);
  567. clang_disposeString(CursorUSR);
  568. const Type *type = baseType.getTypePtrOrNull();
  569. if (type) {
  570. AllocatedResults.ContainerIsIncomplete = type->isIncompleteType();
  571. }
  572. else {
  573. AllocatedResults.ContainerIsIncomplete = 1;
  574. }
  575. }
  576. else {
  577. AllocatedResults.ContainerKind = CXCursor_InvalidCode;
  578. AllocatedResults.ContainerUSR.clear();
  579. AllocatedResults.ContainerIsIncomplete = 1;
  580. }
  581. }
  582. void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
  583. OverloadCandidate *Candidates,
  584. unsigned NumCandidates,
  585. SourceLocation OpenParLoc) override {
  586. StoredResults.reserve(StoredResults.size() + NumCandidates);
  587. for (unsigned I = 0; I != NumCandidates; ++I) {
  588. CodeCompletionString *StoredCompletion
  589. = Candidates[I].CreateSignatureString(CurrentArg, S, getAllocator(),
  590. getCodeCompletionTUInfo(),
  591. includeBriefComments());
  592. CXCompletionResult R;
  593. R.CursorKind = CXCursor_OverloadCandidate;
  594. R.CompletionString = StoredCompletion;
  595. StoredResults.push_back(R);
  596. }
  597. }
  598. CodeCompletionAllocator &getAllocator() override {
  599. return *AllocatedResults.CodeCompletionAllocator;
  600. }
  601. CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo;}
  602. private:
  603. void Finish() {
  604. AllocatedResults.Results = new CXCompletionResult [StoredResults.size()];
  605. AllocatedResults.NumResults = StoredResults.size();
  606. std::memcpy(AllocatedResults.Results, StoredResults.data(),
  607. StoredResults.size() * sizeof(CXCompletionResult));
  608. StoredResults.clear();
  609. }
  610. };
  611. }
  612. static CXCodeCompleteResults *
  613. clang_codeCompleteAt_Impl(CXTranslationUnit TU, const char *complete_filename,
  614. unsigned complete_line, unsigned complete_column,
  615. ArrayRef<CXUnsavedFile> unsaved_files,
  616. unsigned options) {
  617. bool IncludeBriefComments = options & CXCodeComplete_IncludeBriefComments;
  618. bool SkipPreamble = options & CXCodeComplete_SkipPreamble;
  619. bool IncludeFixIts = options & CXCodeComplete_IncludeCompletionsWithFixIts;
  620. #ifdef UDP_CODE_COMPLETION_LOGGER
  621. #ifdef UDP_CODE_COMPLETION_LOGGER_PORT
  622. const llvm::TimeRecord &StartTime = llvm::TimeRecord::getCurrentTime();
  623. #endif
  624. #endif
  625. bool EnableLogging = getenv("LIBCLANG_CODE_COMPLETION_LOGGING") != nullptr;
  626. if (cxtu::isNotUsableTU(TU)) {
  627. LOG_BAD_TU(TU);
  628. return nullptr;
  629. }
  630. ASTUnit *AST = cxtu::getASTUnit(TU);
  631. if (!AST)
  632. return nullptr;
  633. CIndexer *CXXIdx = TU->CIdx;
  634. if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
  635. setThreadBackgroundPriority();
  636. ASTUnit::ConcurrencyCheck Check(*AST);
  637. // Perform the remapping of source files.
  638. SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
  639. for (auto &UF : unsaved_files) {
  640. std::unique_ptr<llvm::MemoryBuffer> MB =
  641. llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
  642. RemappedFiles.push_back(std::make_pair(UF.Filename, MB.release()));
  643. }
  644. if (EnableLogging) {
  645. // FIXME: Add logging.
  646. }
  647. // Parse the resulting source file to find code-completion results.
  648. AllocatedCXCodeCompleteResults *Results = new AllocatedCXCodeCompleteResults(
  649. &AST->getFileManager());
  650. Results->Results = nullptr;
  651. Results->NumResults = 0;
  652. // Create a code-completion consumer to capture the results.
  653. CodeCompleteOptions Opts;
  654. Opts.IncludeBriefComments = IncludeBriefComments;
  655. Opts.LoadExternal = !SkipPreamble;
  656. Opts.IncludeFixIts = IncludeFixIts;
  657. CaptureCompletionResults Capture(Opts, *Results, &TU);
  658. // Perform completion.
  659. std::vector<const char *> CArgs;
  660. for (const auto &Arg : TU->Arguments)
  661. CArgs.push_back(Arg.c_str());
  662. std::string CompletionInvocation =
  663. llvm::formatv("-code-completion-at={0}:{1}:{2}", complete_filename,
  664. complete_line, complete_column)
  665. .str();
  666. LibclangInvocationReporter InvocationReporter(
  667. *CXXIdx, LibclangInvocationReporter::OperationKind::CompletionOperation,
  668. TU->ParsingOptions, CArgs, CompletionInvocation, unsaved_files);
  669. AST->CodeComplete(complete_filename, complete_line, complete_column,
  670. RemappedFiles, (options & CXCodeComplete_IncludeMacros),
  671. (options & CXCodeComplete_IncludeCodePatterns),
  672. IncludeBriefComments, Capture,
  673. CXXIdx->getPCHContainerOperations(), *Results->Diag,
  674. Results->LangOpts, *Results->SourceMgr, *Results->FileMgr,
  675. Results->Diagnostics, Results->TemporaryBuffers);
  676. Results->DiagnosticsWrappers.resize(Results->Diagnostics.size());
  677. // Keep a reference to the allocator used for cached global completions, so
  678. // that we can be sure that the memory used by our code completion strings
  679. // doesn't get freed due to subsequent reparses (while the code completion
  680. // results are still active).
  681. Results->CachedCompletionAllocator = AST->getCachedCompletionAllocator();
  682. #ifdef UDP_CODE_COMPLETION_LOGGER
  683. #ifdef UDP_CODE_COMPLETION_LOGGER_PORT
  684. const llvm::TimeRecord &EndTime = llvm::TimeRecord::getCurrentTime();
  685. SmallString<256> LogResult;
  686. llvm::raw_svector_ostream os(LogResult);
  687. // Figure out the language and whether or not it uses PCH.
  688. const char *lang = 0;
  689. bool usesPCH = false;
  690. for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
  691. I != E; ++I) {
  692. if (*I == 0)
  693. continue;
  694. if (strcmp(*I, "-x") == 0) {
  695. if (I + 1 != E) {
  696. lang = *(++I);
  697. continue;
  698. }
  699. }
  700. else if (strcmp(*I, "-include") == 0) {
  701. if (I+1 != E) {
  702. const char *arg = *(++I);
  703. SmallString<512> pchName;
  704. {
  705. llvm::raw_svector_ostream os(pchName);
  706. os << arg << ".pth";
  707. }
  708. pchName.push_back('\0');
  709. struct stat stat_results;
  710. if (stat(pchName.str().c_str(), &stat_results) == 0)
  711. usesPCH = true;
  712. continue;
  713. }
  714. }
  715. }
  716. os << "{ ";
  717. os << "\"wall\": " << (EndTime.getWallTime() - StartTime.getWallTime());
  718. os << ", \"numRes\": " << Results->NumResults;
  719. os << ", \"diags\": " << Results->Diagnostics.size();
  720. os << ", \"pch\": " << (usesPCH ? "true" : "false");
  721. os << ", \"lang\": \"" << (lang ? lang : "<unknown>") << '"';
  722. const char *name = getlogin();
  723. os << ", \"user\": \"" << (name ? name : "unknown") << '"';
  724. os << ", \"clangVer\": \"" << getClangFullVersion() << '"';
  725. os << " }";
  726. StringRef res = os.str();
  727. if (res.size() > 0) {
  728. do {
  729. // Setup the UDP socket.
  730. struct sockaddr_in servaddr;
  731. bzero(&servaddr, sizeof(servaddr));
  732. servaddr.sin_family = AF_INET;
  733. servaddr.sin_port = htons(UDP_CODE_COMPLETION_LOGGER_PORT);
  734. if (inet_pton(AF_INET, UDP_CODE_COMPLETION_LOGGER,
  735. &servaddr.sin_addr) <= 0)
  736. break;
  737. int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
  738. if (sockfd < 0)
  739. break;
  740. sendto(sockfd, res.data(), res.size(), 0,
  741. (struct sockaddr *)&servaddr, sizeof(servaddr));
  742. close(sockfd);
  743. }
  744. while (false);
  745. }
  746. #endif
  747. #endif
  748. return Results;
  749. }
  750. CXCodeCompleteResults *clang_codeCompleteAt(CXTranslationUnit TU,
  751. const char *complete_filename,
  752. unsigned complete_line,
  753. unsigned complete_column,
  754. struct CXUnsavedFile *unsaved_files,
  755. unsigned num_unsaved_files,
  756. unsigned options) {
  757. LOG_FUNC_SECTION {
  758. *Log << TU << ' '
  759. << complete_filename << ':' << complete_line << ':' << complete_column;
  760. }
  761. if (num_unsaved_files && !unsaved_files)
  762. return nullptr;
  763. CXCodeCompleteResults *result;
  764. auto CodeCompleteAtImpl = [=, &result]() {
  765. result = clang_codeCompleteAt_Impl(
  766. TU, complete_filename, complete_line, complete_column,
  767. llvm::makeArrayRef(unsaved_files, num_unsaved_files), options);
  768. };
  769. llvm::CrashRecoveryContext CRC;
  770. if (!RunSafely(CRC, CodeCompleteAtImpl)) {
  771. fprintf(stderr, "libclang: crash detected in code completion\n");
  772. cxtu::getASTUnit(TU)->setUnsafeToFree(true);
  773. return nullptr;
  774. } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
  775. PrintLibclangResourceUsage(TU);
  776. return result;
  777. }
  778. unsigned clang_defaultCodeCompleteOptions(void) {
  779. return CXCodeComplete_IncludeMacros;
  780. }
  781. void clang_disposeCodeCompleteResults(CXCodeCompleteResults *ResultsIn) {
  782. if (!ResultsIn)
  783. return;
  784. AllocatedCXCodeCompleteResults *Results
  785. = static_cast<AllocatedCXCodeCompleteResults*>(ResultsIn);
  786. delete Results;
  787. }
  788. unsigned
  789. clang_codeCompleteGetNumDiagnostics(CXCodeCompleteResults *ResultsIn) {
  790. AllocatedCXCodeCompleteResults *Results
  791. = static_cast<AllocatedCXCodeCompleteResults*>(ResultsIn);
  792. if (!Results)
  793. return 0;
  794. return Results->Diagnostics.size();
  795. }
  796. CXDiagnostic
  797. clang_codeCompleteGetDiagnostic(CXCodeCompleteResults *ResultsIn,
  798. unsigned Index) {
  799. AllocatedCXCodeCompleteResults *Results
  800. = static_cast<AllocatedCXCodeCompleteResults*>(ResultsIn);
  801. if (!Results || Index >= Results->Diagnostics.size())
  802. return nullptr;
  803. CXStoredDiagnostic *Diag = Results->DiagnosticsWrappers[Index];
  804. if (!Diag)
  805. Results->DiagnosticsWrappers[Index] = Diag =
  806. new CXStoredDiagnostic(Results->Diagnostics[Index], Results->LangOpts);
  807. return Diag;
  808. }
  809. unsigned long long
  810. clang_codeCompleteGetContexts(CXCodeCompleteResults *ResultsIn) {
  811. AllocatedCXCodeCompleteResults *Results
  812. = static_cast<AllocatedCXCodeCompleteResults*>(ResultsIn);
  813. if (!Results)
  814. return 0;
  815. return Results->Contexts;
  816. }
  817. enum CXCursorKind clang_codeCompleteGetContainerKind(
  818. CXCodeCompleteResults *ResultsIn,
  819. unsigned *IsIncomplete) {
  820. AllocatedCXCodeCompleteResults *Results =
  821. static_cast<AllocatedCXCodeCompleteResults *>(ResultsIn);
  822. if (!Results)
  823. return CXCursor_InvalidCode;
  824. if (IsIncomplete != nullptr) {
  825. *IsIncomplete = Results->ContainerIsIncomplete;
  826. }
  827. return Results->ContainerKind;
  828. }
  829. CXString clang_codeCompleteGetContainerUSR(CXCodeCompleteResults *ResultsIn) {
  830. AllocatedCXCodeCompleteResults *Results =
  831. static_cast<AllocatedCXCodeCompleteResults *>(ResultsIn);
  832. if (!Results)
  833. return cxstring::createEmpty();
  834. return cxstring::createRef(Results->ContainerUSR.c_str());
  835. }
  836. CXString clang_codeCompleteGetObjCSelector(CXCodeCompleteResults *ResultsIn) {
  837. AllocatedCXCodeCompleteResults *Results =
  838. static_cast<AllocatedCXCodeCompleteResults *>(ResultsIn);
  839. if (!Results)
  840. return cxstring::createEmpty();
  841. return cxstring::createDup(Results->Selector);
  842. }
  843. /// Simple utility function that appends a \p New string to the given
  844. /// \p Old string, using the \p Buffer for storage.
  845. ///
  846. /// \param Old The string to which we are appending. This parameter will be
  847. /// updated to reflect the complete string.
  848. ///
  849. ///
  850. /// \param New The string to append to \p Old.
  851. ///
  852. /// \param Buffer A buffer that stores the actual, concatenated string. It will
  853. /// be used if the old string is already-non-empty.
  854. static void AppendToString(StringRef &Old, StringRef New,
  855. SmallString<256> &Buffer) {
  856. if (Old.empty()) {
  857. Old = New;
  858. return;
  859. }
  860. if (Buffer.empty())
  861. Buffer.append(Old.begin(), Old.end());
  862. Buffer.append(New.begin(), New.end());
  863. Old = Buffer.str();
  864. }
  865. /// Get the typed-text blocks from the given code-completion string
  866. /// and return them as a single string.
  867. ///
  868. /// \param String The code-completion string whose typed-text blocks will be
  869. /// concatenated.
  870. ///
  871. /// \param Buffer A buffer used for storage of the completed name.
  872. static StringRef GetTypedName(CodeCompletionString *String,
  873. SmallString<256> &Buffer) {
  874. StringRef Result;
  875. for (CodeCompletionString::iterator C = String->begin(), CEnd = String->end();
  876. C != CEnd; ++C) {
  877. if (C->Kind == CodeCompletionString::CK_TypedText)
  878. AppendToString(Result, C->Text, Buffer);
  879. }
  880. return Result;
  881. }
  882. namespace {
  883. struct OrderCompletionResults {
  884. bool operator()(const CXCompletionResult &XR,
  885. const CXCompletionResult &YR) const {
  886. CodeCompletionString *X
  887. = (CodeCompletionString *)XR.CompletionString;
  888. CodeCompletionString *Y
  889. = (CodeCompletionString *)YR.CompletionString;
  890. SmallString<256> XBuffer;
  891. StringRef XText = GetTypedName(X, XBuffer);
  892. SmallString<256> YBuffer;
  893. StringRef YText = GetTypedName(Y, YBuffer);
  894. if (XText.empty() || YText.empty())
  895. return !XText.empty();
  896. int result = XText.compare_lower(YText);
  897. if (result < 0)
  898. return true;
  899. if (result > 0)
  900. return false;
  901. result = XText.compare(YText);
  902. return result < 0;
  903. }
  904. };
  905. }
  906. void clang_sortCodeCompletionResults(CXCompletionResult *Results,
  907. unsigned NumResults) {
  908. std::stable_sort(Results, Results + NumResults, OrderCompletionResults());
  909. }