CIndexCodeCompletion.cpp 33 KB

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