Indexing.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822
  1. //===- CIndexHigh.cpp - Higher level API functions ------------------------===//
  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. #include "IndexingContext.h"
  10. #include "CXCursor.h"
  11. #include "CXSourceLocation.h"
  12. #include "CXTranslationUnit.h"
  13. #include "CXString.h"
  14. #include "CIndexDiagnostic.h"
  15. #include "CIndexer.h"
  16. #include "clang/Frontend/ASTUnit.h"
  17. #include "clang/Frontend/CompilerInvocation.h"
  18. #include "clang/Frontend/CompilerInstance.h"
  19. #include "clang/Frontend/FrontendAction.h"
  20. #include "clang/Frontend/Utils.h"
  21. #include "clang/Sema/SemaConsumer.h"
  22. #include "clang/AST/ASTConsumer.h"
  23. #include "clang/AST/DeclVisitor.h"
  24. #include "clang/Lex/Preprocessor.h"
  25. #include "clang/Lex/PPCallbacks.h"
  26. #include "llvm/Support/MemoryBuffer.h"
  27. #include "llvm/Support/CrashRecoveryContext.h"
  28. using namespace clang;
  29. using namespace cxstring;
  30. using namespace cxtu;
  31. using namespace cxindex;
  32. static void indexDiagnostics(CXTranslationUnit TU, IndexingContext &IdxCtx);
  33. namespace {
  34. //===----------------------------------------------------------------------===//
  35. // IndexPPCallbacks
  36. //===----------------------------------------------------------------------===//
  37. class IndexPPCallbacks : public PPCallbacks {
  38. Preprocessor &PP;
  39. IndexingContext &IndexCtx;
  40. bool IsMainFileEntered;
  41. public:
  42. IndexPPCallbacks(Preprocessor &PP, IndexingContext &indexCtx)
  43. : PP(PP), IndexCtx(indexCtx), IsMainFileEntered(false) { }
  44. virtual void FileChanged(SourceLocation Loc, FileChangeReason Reason,
  45. SrcMgr::CharacteristicKind FileType, FileID PrevFID) {
  46. if (IsMainFileEntered)
  47. return;
  48. SourceManager &SM = PP.getSourceManager();
  49. SourceLocation MainFileLoc = SM.getLocForStartOfFile(SM.getMainFileID());
  50. if (Loc == MainFileLoc && Reason == PPCallbacks::EnterFile) {
  51. IsMainFileEntered = true;
  52. IndexCtx.enteredMainFile(SM.getFileEntryForID(SM.getMainFileID()));
  53. }
  54. }
  55. virtual void InclusionDirective(SourceLocation HashLoc,
  56. const Token &IncludeTok,
  57. StringRef FileName,
  58. bool IsAngled,
  59. CharSourceRange FilenameRange,
  60. const FileEntry *File,
  61. StringRef SearchPath,
  62. StringRef RelativePath) {
  63. bool isImport = (IncludeTok.is(tok::identifier) &&
  64. IncludeTok.getIdentifierInfo()->getPPKeywordID() == tok::pp_import);
  65. IndexCtx.ppIncludedFile(HashLoc, FileName, File, isImport, IsAngled);
  66. }
  67. /// MacroDefined - This hook is called whenever a macro definition is seen.
  68. virtual void MacroDefined(const Token &Id, const MacroInfo *MI) {
  69. }
  70. /// MacroUndefined - This hook is called whenever a macro #undef is seen.
  71. /// MI is released immediately following this callback.
  72. virtual void MacroUndefined(const Token &MacroNameTok, const MacroInfo *MI) {
  73. }
  74. /// MacroExpands - This is called by when a macro invocation is found.
  75. virtual void MacroExpands(const Token &MacroNameTok, const MacroInfo* MI,
  76. SourceRange Range) {
  77. }
  78. /// SourceRangeSkipped - This hook is called when a source range is skipped.
  79. /// \param Range The SourceRange that was skipped. The range begins at the
  80. /// #if/#else directive and ends after the #endif/#else directive.
  81. virtual void SourceRangeSkipped(SourceRange Range) {
  82. }
  83. };
  84. //===----------------------------------------------------------------------===//
  85. // IndexingConsumer
  86. //===----------------------------------------------------------------------===//
  87. class IndexingConsumer : public ASTConsumer {
  88. IndexingContext &IndexCtx;
  89. public:
  90. explicit IndexingConsumer(IndexingContext &indexCtx)
  91. : IndexCtx(indexCtx) { }
  92. // ASTConsumer Implementation
  93. virtual void Initialize(ASTContext &Context) {
  94. IndexCtx.setASTContext(Context);
  95. IndexCtx.startedTranslationUnit();
  96. }
  97. virtual void HandleTranslationUnit(ASTContext &Ctx) {
  98. }
  99. virtual bool HandleTopLevelDecl(DeclGroupRef DG) {
  100. IndexCtx.indexDeclGroupRef(DG);
  101. return !IndexCtx.shouldAbort();
  102. }
  103. /// \brief Handle the specified top-level declaration that occurred inside
  104. /// and ObjC container.
  105. virtual void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) {
  106. // They will be handled after the interface is seen first.
  107. IndexCtx.addTUDeclInObjCContainer(D);
  108. }
  109. /// \brief This is called by the AST reader when deserializing things.
  110. /// The default implementation forwards to HandleTopLevelDecl but we don't
  111. /// care about them when indexing, so have an empty definition.
  112. virtual void HandleInterestingDecl(DeclGroupRef D) {}
  113. virtual void HandleTagDeclDefinition(TagDecl *D) {
  114. if (!IndexCtx.shouldIndexImplicitTemplateInsts())
  115. return;
  116. if (IndexCtx.isTemplateImplicitInstantiation(D))
  117. IndexCtx.indexDecl(D);
  118. }
  119. virtual void HandleCXXImplicitFunctionInstantiation(FunctionDecl *D) {
  120. if (!IndexCtx.shouldIndexImplicitTemplateInsts())
  121. return;
  122. IndexCtx.indexDecl(D);
  123. }
  124. };
  125. //===----------------------------------------------------------------------===//
  126. // CaptureDiagnosticConsumer
  127. //===----------------------------------------------------------------------===//
  128. class CaptureDiagnosticConsumer : public DiagnosticConsumer {
  129. SmallVector<StoredDiagnostic, 4> Errors;
  130. public:
  131. virtual void HandleDiagnostic(DiagnosticsEngine::Level level,
  132. const Diagnostic &Info) {
  133. if (level >= DiagnosticsEngine::Error)
  134. Errors.push_back(StoredDiagnostic(level, Info));
  135. }
  136. DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
  137. return new IgnoringDiagConsumer();
  138. }
  139. };
  140. //===----------------------------------------------------------------------===//
  141. // IndexingFrontendAction
  142. //===----------------------------------------------------------------------===//
  143. class IndexingFrontendAction : public ASTFrontendAction {
  144. IndexingContext IndexCtx;
  145. CXTranslationUnit CXTU;
  146. public:
  147. IndexingFrontendAction(CXClientData clientData,
  148. IndexerCallbacks &indexCallbacks,
  149. unsigned indexOptions,
  150. CXTranslationUnit cxTU)
  151. : IndexCtx(clientData, indexCallbacks, indexOptions, cxTU),
  152. CXTU(cxTU) { }
  153. virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
  154. StringRef InFile) {
  155. IndexCtx.setASTContext(CI.getASTContext());
  156. Preprocessor &PP = CI.getPreprocessor();
  157. PP.addPPCallbacks(new IndexPPCallbacks(PP, IndexCtx));
  158. IndexCtx.setPreprocessor(PP);
  159. return new IndexingConsumer(IndexCtx);
  160. }
  161. virtual void EndSourceFileAction() {
  162. indexDiagnostics(CXTU, IndexCtx);
  163. }
  164. virtual TranslationUnitKind getTranslationUnitKind() {
  165. if (IndexCtx.shouldIndexImplicitTemplateInsts())
  166. return TU_Complete;
  167. else
  168. return TU_Prefix;
  169. }
  170. virtual bool hasCodeCompletionSupport() const { return false; }
  171. };
  172. //===----------------------------------------------------------------------===//
  173. // clang_indexSourceFileUnit Implementation
  174. //===----------------------------------------------------------------------===//
  175. struct IndexSourceFileInfo {
  176. CXIndexAction idxAction;
  177. CXClientData client_data;
  178. IndexerCallbacks *index_callbacks;
  179. unsigned index_callbacks_size;
  180. unsigned index_options;
  181. const char *source_filename;
  182. const char *const *command_line_args;
  183. int num_command_line_args;
  184. struct CXUnsavedFile *unsaved_files;
  185. unsigned num_unsaved_files;
  186. CXTranslationUnit *out_TU;
  187. unsigned TU_options;
  188. int result;
  189. };
  190. struct MemBufferOwner {
  191. SmallVector<const llvm::MemoryBuffer *, 8> Buffers;
  192. ~MemBufferOwner() {
  193. for (SmallVectorImpl<const llvm::MemoryBuffer *>::iterator
  194. I = Buffers.begin(), E = Buffers.end(); I != E; ++I)
  195. delete *I;
  196. }
  197. };
  198. } // anonymous namespace
  199. static void clang_indexSourceFile_Impl(void *UserData) {
  200. IndexSourceFileInfo *ITUI =
  201. static_cast<IndexSourceFileInfo*>(UserData);
  202. CXIndex CIdx = (CXIndex)ITUI->idxAction;
  203. CXClientData client_data = ITUI->client_data;
  204. IndexerCallbacks *client_index_callbacks = ITUI->index_callbacks;
  205. unsigned index_callbacks_size = ITUI->index_callbacks_size;
  206. unsigned index_options = ITUI->index_options;
  207. const char *source_filename = ITUI->source_filename;
  208. const char * const *command_line_args = ITUI->command_line_args;
  209. int num_command_line_args = ITUI->num_command_line_args;
  210. struct CXUnsavedFile *unsaved_files = ITUI->unsaved_files;
  211. unsigned num_unsaved_files = ITUI->num_unsaved_files;
  212. CXTranslationUnit *out_TU = ITUI->out_TU;
  213. unsigned TU_options = ITUI->TU_options;
  214. ITUI->result = 1; // init as error.
  215. if (out_TU)
  216. *out_TU = 0;
  217. bool requestedToGetTU = (out_TU != 0);
  218. if (!CIdx)
  219. return;
  220. if (!client_index_callbacks || index_callbacks_size == 0)
  221. return;
  222. IndexerCallbacks CB;
  223. memset(&CB, 0, sizeof(CB));
  224. unsigned ClientCBSize = index_callbacks_size < sizeof(CB)
  225. ? index_callbacks_size : sizeof(CB);
  226. memcpy(&CB, client_index_callbacks, ClientCBSize);
  227. CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
  228. if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
  229. setThreadBackgroundPriority();
  230. CaptureDiagnosticConsumer *CaptureDiag = new CaptureDiagnosticConsumer();
  231. // Configure the diagnostics.
  232. DiagnosticOptions DiagOpts;
  233. IntrusiveRefCntPtr<DiagnosticsEngine>
  234. Diags(CompilerInstance::createDiagnostics(DiagOpts, num_command_line_args,
  235. command_line_args,
  236. CaptureDiag,
  237. /*ShouldOwnClient=*/true,
  238. /*ShouldCloneClient=*/false));
  239. // Recover resources if we crash before exiting this function.
  240. llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
  241. llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
  242. DiagCleanup(Diags.getPtr());
  243. OwningPtr<std::vector<const char *> >
  244. Args(new std::vector<const char*>());
  245. // Recover resources if we crash before exiting this method.
  246. llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
  247. ArgsCleanup(Args.get());
  248. Args->insert(Args->end(), command_line_args,
  249. command_line_args + num_command_line_args);
  250. // The 'source_filename' argument is optional. If the caller does not
  251. // specify it then it is assumed that the source file is specified
  252. // in the actual argument list.
  253. // Put the source file after command_line_args otherwise if '-x' flag is
  254. // present it will be unused.
  255. if (source_filename)
  256. Args->push_back(source_filename);
  257. IntrusiveRefCntPtr<CompilerInvocation>
  258. CInvok(createInvocationFromCommandLine(*Args, Diags));
  259. if (!CInvok)
  260. return;
  261. // Recover resources if we crash before exiting this function.
  262. llvm::CrashRecoveryContextCleanupRegistrar<CompilerInvocation,
  263. llvm::CrashRecoveryContextReleaseRefCleanup<CompilerInvocation> >
  264. CInvokCleanup(CInvok.getPtr());
  265. if (CInvok->getFrontendOpts().Inputs.empty())
  266. return;
  267. OwningPtr<MemBufferOwner> BufOwner(new MemBufferOwner());
  268. // Recover resources if we crash before exiting this method.
  269. llvm::CrashRecoveryContextCleanupRegistrar<MemBufferOwner>
  270. BufOwnerCleanup(BufOwner.get());
  271. for (unsigned I = 0; I != num_unsaved_files; ++I) {
  272. StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
  273. const llvm::MemoryBuffer *Buffer
  274. = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
  275. CInvok->getPreprocessorOpts().addRemappedFile(unsaved_files[I].Filename, Buffer);
  276. BufOwner->Buffers.push_back(Buffer);
  277. }
  278. // Since libclang is primarily used by batch tools dealing with
  279. // (often very broken) source code, where spell-checking can have a
  280. // significant negative impact on performance (particularly when
  281. // precompiled headers are involved), we disable it.
  282. CInvok->getLangOpts()->SpellChecking = false;
  283. if (!requestedToGetTU)
  284. CInvok->getPreprocessorOpts().DetailedRecord = false;
  285. if (index_options & CXIndexOpt_SuppressWarnings)
  286. CInvok->getDiagnosticOpts().IgnoreWarnings = true;
  287. ASTUnit *Unit = ASTUnit::create(CInvok.getPtr(), Diags,
  288. /*CaptureDiagnostics=*/true,
  289. /*UserFilesAreVolatile=*/true);
  290. OwningPtr<CXTUOwner> CXTU(new CXTUOwner(MakeCXTranslationUnit(CXXIdx, Unit)));
  291. // Recover resources if we crash before exiting this method.
  292. llvm::CrashRecoveryContextCleanupRegistrar<CXTUOwner>
  293. CXTUCleanup(CXTU.get());
  294. OwningPtr<IndexingFrontendAction> IndexAction;
  295. IndexAction.reset(new IndexingFrontendAction(client_data, CB,
  296. index_options, CXTU->getTU()));
  297. // Recover resources if we crash before exiting this method.
  298. llvm::CrashRecoveryContextCleanupRegistrar<IndexingFrontendAction>
  299. IndexActionCleanup(IndexAction.get());
  300. bool Persistent = requestedToGetTU;
  301. bool OnlyLocalDecls = false;
  302. bool PrecompilePreamble = false;
  303. bool CacheCodeCompletionResults = false;
  304. PreprocessorOptions &PPOpts = CInvok->getPreprocessorOpts();
  305. PPOpts.DetailedRecord = false;
  306. PPOpts.AllowPCHWithCompilerErrors = true;
  307. if (requestedToGetTU) {
  308. OnlyLocalDecls = CXXIdx->getOnlyLocalDecls();
  309. PrecompilePreamble = TU_options & CXTranslationUnit_PrecompiledPreamble;
  310. // FIXME: Add a flag for modules.
  311. CacheCodeCompletionResults
  312. = TU_options & CXTranslationUnit_CacheCompletionResults;
  313. if (TU_options & CXTranslationUnit_DetailedPreprocessingRecord) {
  314. PPOpts.DetailedRecord = true;
  315. }
  316. }
  317. DiagnosticErrorTrap DiagTrap(*Diags);
  318. bool Success = ASTUnit::LoadFromCompilerInvocationAction(CInvok.getPtr(), Diags,
  319. IndexAction.get(),
  320. Unit,
  321. Persistent,
  322. CXXIdx->getClangResourcesPath(),
  323. OnlyLocalDecls,
  324. /*CaptureDiagnostics=*/true,
  325. PrecompilePreamble,
  326. CacheCodeCompletionResults,
  327. /*IncludeBriefCommentsInCodeCompletion=*/false,
  328. /*UserFilesAreVolatile=*/true);
  329. if (DiagTrap.hasErrorOccurred() && CXXIdx->getDisplayDiagnostics())
  330. printDiagsToStderr(Unit);
  331. if (!Success)
  332. return;
  333. if (out_TU)
  334. *out_TU = CXTU->takeTU();
  335. ITUI->result = 0; // success.
  336. }
  337. //===----------------------------------------------------------------------===//
  338. // clang_indexTranslationUnit Implementation
  339. //===----------------------------------------------------------------------===//
  340. namespace {
  341. struct IndexTranslationUnitInfo {
  342. CXIndexAction idxAction;
  343. CXClientData client_data;
  344. IndexerCallbacks *index_callbacks;
  345. unsigned index_callbacks_size;
  346. unsigned index_options;
  347. CXTranslationUnit TU;
  348. int result;
  349. };
  350. } // anonymous namespace
  351. static void indexPreprocessingRecord(ASTUnit &Unit, IndexingContext &IdxCtx) {
  352. Preprocessor &PP = Unit.getPreprocessor();
  353. if (!PP.getPreprocessingRecord())
  354. return;
  355. PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
  356. // FIXME: Only deserialize inclusion directives.
  357. // FIXME: Only deserialize stuff from the last chained PCH, not the PCH/Module
  358. // that it depends on.
  359. bool OnlyLocal = !Unit.isMainFileAST() && Unit.getOnlyLocalDecls();
  360. PreprocessingRecord::iterator I, E;
  361. if (OnlyLocal) {
  362. I = PPRec.local_begin();
  363. E = PPRec.local_end();
  364. } else {
  365. I = PPRec.begin();
  366. E = PPRec.end();
  367. }
  368. for (; I != E; ++I) {
  369. PreprocessedEntity *PPE = *I;
  370. if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
  371. IdxCtx.ppIncludedFile(ID->getSourceRange().getBegin(), ID->getFileName(),
  372. ID->getFile(), ID->getKind() == InclusionDirective::Import,
  373. !ID->wasInQuotes());
  374. }
  375. }
  376. }
  377. static void indexTranslationUnit(ASTUnit &Unit, IndexingContext &IdxCtx) {
  378. // FIXME: Only deserialize stuff from the last chained PCH, not the PCH/Module
  379. // that it depends on.
  380. bool OnlyLocal = !Unit.isMainFileAST() && Unit.getOnlyLocalDecls();
  381. if (OnlyLocal) {
  382. for (ASTUnit::top_level_iterator TL = Unit.top_level_begin(),
  383. TLEnd = Unit.top_level_end();
  384. TL != TLEnd; ++TL) {
  385. IdxCtx.indexTopLevelDecl(*TL);
  386. if (IdxCtx.shouldAbort())
  387. return;
  388. }
  389. } else {
  390. TranslationUnitDecl *TUDecl = Unit.getASTContext().getTranslationUnitDecl();
  391. for (TranslationUnitDecl::decl_iterator
  392. I = TUDecl->decls_begin(), E = TUDecl->decls_end(); I != E; ++I) {
  393. IdxCtx.indexTopLevelDecl(*I);
  394. if (IdxCtx.shouldAbort())
  395. return;
  396. }
  397. }
  398. }
  399. static void indexDiagnostics(CXTranslationUnit TU, IndexingContext &IdxCtx) {
  400. if (!IdxCtx.hasDiagnosticCallback())
  401. return;
  402. CXDiagnosticSetImpl *DiagSet = cxdiag::lazyCreateDiags(TU);
  403. IdxCtx.handleDiagnosticSet(DiagSet);
  404. }
  405. static void clang_indexTranslationUnit_Impl(void *UserData) {
  406. IndexTranslationUnitInfo *ITUI =
  407. static_cast<IndexTranslationUnitInfo*>(UserData);
  408. CXTranslationUnit TU = ITUI->TU;
  409. CXClientData client_data = ITUI->client_data;
  410. IndexerCallbacks *client_index_callbacks = ITUI->index_callbacks;
  411. unsigned index_callbacks_size = ITUI->index_callbacks_size;
  412. unsigned index_options = ITUI->index_options;
  413. ITUI->result = 1; // init as error.
  414. if (!TU)
  415. return;
  416. if (!client_index_callbacks || index_callbacks_size == 0)
  417. return;
  418. CIndexer *CXXIdx = (CIndexer*)TU->CIdx;
  419. if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
  420. setThreadBackgroundPriority();
  421. IndexerCallbacks CB;
  422. memset(&CB, 0, sizeof(CB));
  423. unsigned ClientCBSize = index_callbacks_size < sizeof(CB)
  424. ? index_callbacks_size : sizeof(CB);
  425. memcpy(&CB, client_index_callbacks, ClientCBSize);
  426. OwningPtr<IndexingContext> IndexCtx;
  427. IndexCtx.reset(new IndexingContext(client_data, CB, index_options, TU));
  428. // Recover resources if we crash before exiting this method.
  429. llvm::CrashRecoveryContextCleanupRegistrar<IndexingContext>
  430. IndexCtxCleanup(IndexCtx.get());
  431. OwningPtr<IndexingConsumer> IndexConsumer;
  432. IndexConsumer.reset(new IndexingConsumer(*IndexCtx));
  433. // Recover resources if we crash before exiting this method.
  434. llvm::CrashRecoveryContextCleanupRegistrar<IndexingConsumer>
  435. IndexConsumerCleanup(IndexConsumer.get());
  436. ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData);
  437. if (!Unit)
  438. return;
  439. ASTUnit::ConcurrencyCheck Check(*Unit);
  440. FileManager &FileMgr = Unit->getFileManager();
  441. if (Unit->getOriginalSourceFileName().empty())
  442. IndexCtx->enteredMainFile(0);
  443. else
  444. IndexCtx->enteredMainFile(FileMgr.getFile(Unit->getOriginalSourceFileName()));
  445. IndexConsumer->Initialize(Unit->getASTContext());
  446. indexPreprocessingRecord(*Unit, *IndexCtx);
  447. indexTranslationUnit(*Unit, *IndexCtx);
  448. indexDiagnostics(TU, *IndexCtx);
  449. ITUI->result = 0;
  450. }
  451. //===----------------------------------------------------------------------===//
  452. // libclang public APIs.
  453. //===----------------------------------------------------------------------===//
  454. extern "C" {
  455. int clang_index_isEntityObjCContainerKind(CXIdxEntityKind K) {
  456. return CXIdxEntity_ObjCClass <= K && K <= CXIdxEntity_ObjCCategory;
  457. }
  458. const CXIdxObjCContainerDeclInfo *
  459. clang_index_getObjCContainerDeclInfo(const CXIdxDeclInfo *DInfo) {
  460. if (!DInfo)
  461. return 0;
  462. const DeclInfo *DI = static_cast<const DeclInfo *>(DInfo);
  463. if (const ObjCContainerDeclInfo *
  464. ContInfo = dyn_cast<ObjCContainerDeclInfo>(DI))
  465. return &ContInfo->ObjCContDeclInfo;
  466. return 0;
  467. }
  468. const CXIdxObjCInterfaceDeclInfo *
  469. clang_index_getObjCInterfaceDeclInfo(const CXIdxDeclInfo *DInfo) {
  470. if (!DInfo)
  471. return 0;
  472. const DeclInfo *DI = static_cast<const DeclInfo *>(DInfo);
  473. if (const ObjCInterfaceDeclInfo *
  474. InterInfo = dyn_cast<ObjCInterfaceDeclInfo>(DI))
  475. return &InterInfo->ObjCInterDeclInfo;
  476. return 0;
  477. }
  478. const CXIdxObjCCategoryDeclInfo *
  479. clang_index_getObjCCategoryDeclInfo(const CXIdxDeclInfo *DInfo){
  480. if (!DInfo)
  481. return 0;
  482. const DeclInfo *DI = static_cast<const DeclInfo *>(DInfo);
  483. if (const ObjCCategoryDeclInfo *
  484. CatInfo = dyn_cast<ObjCCategoryDeclInfo>(DI))
  485. return &CatInfo->ObjCCatDeclInfo;
  486. return 0;
  487. }
  488. const CXIdxObjCProtocolRefListInfo *
  489. clang_index_getObjCProtocolRefListInfo(const CXIdxDeclInfo *DInfo) {
  490. if (!DInfo)
  491. return 0;
  492. const DeclInfo *DI = static_cast<const DeclInfo *>(DInfo);
  493. if (const ObjCInterfaceDeclInfo *
  494. InterInfo = dyn_cast<ObjCInterfaceDeclInfo>(DI))
  495. return InterInfo->ObjCInterDeclInfo.protocols;
  496. if (const ObjCProtocolDeclInfo *
  497. ProtInfo = dyn_cast<ObjCProtocolDeclInfo>(DI))
  498. return &ProtInfo->ObjCProtoRefListInfo;
  499. if (const ObjCCategoryDeclInfo *CatInfo = dyn_cast<ObjCCategoryDeclInfo>(DI))
  500. return CatInfo->ObjCCatDeclInfo.protocols;
  501. return 0;
  502. }
  503. const CXIdxObjCPropertyDeclInfo *
  504. clang_index_getObjCPropertyDeclInfo(const CXIdxDeclInfo *DInfo) {
  505. if (!DInfo)
  506. return 0;
  507. const DeclInfo *DI = static_cast<const DeclInfo *>(DInfo);
  508. if (const ObjCPropertyDeclInfo *PropInfo = dyn_cast<ObjCPropertyDeclInfo>(DI))
  509. return &PropInfo->ObjCPropDeclInfo;
  510. return 0;
  511. }
  512. const CXIdxIBOutletCollectionAttrInfo *
  513. clang_index_getIBOutletCollectionAttrInfo(const CXIdxAttrInfo *AInfo) {
  514. if (!AInfo)
  515. return 0;
  516. const AttrInfo *DI = static_cast<const AttrInfo *>(AInfo);
  517. if (const IBOutletCollectionInfo *
  518. IBInfo = dyn_cast<IBOutletCollectionInfo>(DI))
  519. return &IBInfo->IBCollInfo;
  520. return 0;
  521. }
  522. const CXIdxCXXClassDeclInfo *
  523. clang_index_getCXXClassDeclInfo(const CXIdxDeclInfo *DInfo) {
  524. if (!DInfo)
  525. return 0;
  526. const DeclInfo *DI = static_cast<const DeclInfo *>(DInfo);
  527. if (const CXXClassDeclInfo *ClassInfo = dyn_cast<CXXClassDeclInfo>(DI))
  528. return &ClassInfo->CXXClassInfo;
  529. return 0;
  530. }
  531. CXIdxClientContainer
  532. clang_index_getClientContainer(const CXIdxContainerInfo *info) {
  533. if (!info)
  534. return 0;
  535. const ContainerInfo *Container = static_cast<const ContainerInfo *>(info);
  536. return Container->IndexCtx->getClientContainerForDC(Container->DC);
  537. }
  538. void clang_index_setClientContainer(const CXIdxContainerInfo *info,
  539. CXIdxClientContainer client) {
  540. if (!info)
  541. return;
  542. const ContainerInfo *Container = static_cast<const ContainerInfo *>(info);
  543. Container->IndexCtx->addContainerInMap(Container->DC, client);
  544. }
  545. CXIdxClientEntity clang_index_getClientEntity(const CXIdxEntityInfo *info) {
  546. if (!info)
  547. return 0;
  548. const EntityInfo *Entity = static_cast<const EntityInfo *>(info);
  549. return Entity->IndexCtx->getClientEntity(Entity->Dcl);
  550. }
  551. void clang_index_setClientEntity(const CXIdxEntityInfo *info,
  552. CXIdxClientEntity client) {
  553. if (!info)
  554. return;
  555. const EntityInfo *Entity = static_cast<const EntityInfo *>(info);
  556. Entity->IndexCtx->setClientEntity(Entity->Dcl, client);
  557. }
  558. CXIndexAction clang_IndexAction_create(CXIndex CIdx) {
  559. // For now, CXIndexAction is featureless.
  560. return CIdx;
  561. }
  562. void clang_IndexAction_dispose(CXIndexAction idxAction) {
  563. // For now, CXIndexAction is featureless.
  564. }
  565. int clang_indexSourceFile(CXIndexAction idxAction,
  566. CXClientData client_data,
  567. IndexerCallbacks *index_callbacks,
  568. unsigned index_callbacks_size,
  569. unsigned index_options,
  570. const char *source_filename,
  571. const char * const *command_line_args,
  572. int num_command_line_args,
  573. struct CXUnsavedFile *unsaved_files,
  574. unsigned num_unsaved_files,
  575. CXTranslationUnit *out_TU,
  576. unsigned TU_options) {
  577. IndexSourceFileInfo ITUI = { idxAction, client_data, index_callbacks,
  578. index_callbacks_size, index_options,
  579. source_filename, command_line_args,
  580. num_command_line_args, unsaved_files,
  581. num_unsaved_files, out_TU, TU_options, 0 };
  582. if (getenv("LIBCLANG_NOTHREADS")) {
  583. clang_indexSourceFile_Impl(&ITUI);
  584. return ITUI.result;
  585. }
  586. llvm::CrashRecoveryContext CRC;
  587. if (!RunSafely(CRC, clang_indexSourceFile_Impl, &ITUI)) {
  588. fprintf(stderr, "libclang: crash detected during indexing source file: {\n");
  589. fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
  590. fprintf(stderr, " 'command_line_args' : [");
  591. for (int i = 0; i != num_command_line_args; ++i) {
  592. if (i)
  593. fprintf(stderr, ", ");
  594. fprintf(stderr, "'%s'", command_line_args[i]);
  595. }
  596. fprintf(stderr, "],\n");
  597. fprintf(stderr, " 'unsaved_files' : [");
  598. for (unsigned i = 0; i != num_unsaved_files; ++i) {
  599. if (i)
  600. fprintf(stderr, ", ");
  601. fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
  602. unsaved_files[i].Length);
  603. }
  604. fprintf(stderr, "],\n");
  605. fprintf(stderr, " 'options' : %d,\n", TU_options);
  606. fprintf(stderr, "}\n");
  607. return 1;
  608. } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
  609. if (out_TU)
  610. PrintLibclangResourceUsage(*out_TU);
  611. }
  612. return ITUI.result;
  613. }
  614. int clang_indexTranslationUnit(CXIndexAction idxAction,
  615. CXClientData client_data,
  616. IndexerCallbacks *index_callbacks,
  617. unsigned index_callbacks_size,
  618. unsigned index_options,
  619. CXTranslationUnit TU) {
  620. IndexTranslationUnitInfo ITUI = { idxAction, client_data, index_callbacks,
  621. index_callbacks_size, index_options, TU,
  622. 0 };
  623. if (getenv("LIBCLANG_NOTHREADS")) {
  624. clang_indexTranslationUnit_Impl(&ITUI);
  625. return ITUI.result;
  626. }
  627. llvm::CrashRecoveryContext CRC;
  628. if (!RunSafely(CRC, clang_indexTranslationUnit_Impl, &ITUI)) {
  629. fprintf(stderr, "libclang: crash detected during indexing TU\n");
  630. return 1;
  631. }
  632. return ITUI.result;
  633. }
  634. void clang_indexLoc_getFileLocation(CXIdxLoc location,
  635. CXIdxClientFile *indexFile,
  636. CXFile *file,
  637. unsigned *line,
  638. unsigned *column,
  639. unsigned *offset) {
  640. if (indexFile) *indexFile = 0;
  641. if (file) *file = 0;
  642. if (line) *line = 0;
  643. if (column) *column = 0;
  644. if (offset) *offset = 0;
  645. SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
  646. if (!location.ptr_data[0] || Loc.isInvalid())
  647. return;
  648. IndexingContext &IndexCtx =
  649. *static_cast<IndexingContext*>(location.ptr_data[0]);
  650. IndexCtx.translateLoc(Loc, indexFile, file, line, column, offset);
  651. }
  652. CXSourceLocation clang_indexLoc_getCXSourceLocation(CXIdxLoc location) {
  653. SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
  654. if (!location.ptr_data[0] || Loc.isInvalid())
  655. return clang_getNullLocation();
  656. IndexingContext &IndexCtx =
  657. *static_cast<IndexingContext*>(location.ptr_data[0]);
  658. return cxloc::translateSourceLocation(IndexCtx.getASTContext(), Loc);
  659. }
  660. } // end: extern "C"