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