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