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