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