1 //===- CIndexHigh.cpp - Higher level API functions ------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "CIndexDiagnostic.h"
14 #include "CXIndexDataConsumer.h"
15 #include "CXSourceLocation.h"
17 #include "CXTranslationUnit.h"
18 #include "clang/AST/ASTConsumer.h"
19 #include "clang/Frontend/ASTUnit.h"
20 #include "clang/Frontend/CompilerInstance.h"
21 #include "clang/Frontend/CompilerInvocation.h"
22 #include "clang/Frontend/FrontendAction.h"
23 #include "clang/Frontend/Utils.h"
24 #include "clang/Index/IndexingAction.h"
25 #include "clang/Lex/HeaderSearch.h"
26 #include "clang/Lex/PPCallbacks.h"
27 #include "clang/Lex/PPConditionalDirectiveRecord.h"
28 #include "clang/Lex/Preprocessor.h"
29 #include "clang/Lex/PreprocessorOptions.h"
30 #include "llvm/Support/CrashRecoveryContext.h"
31 #include "llvm/Support/MemoryBuffer.h"
32 #include "llvm/Support/Mutex.h"
33 #include "llvm/Support/MutexGuard.h"
37 using namespace clang;
38 using namespace clang::index;
40 using namespace cxindex;
44 //===----------------------------------------------------------------------===//
46 //===----------------------------------------------------------------------===//
48 /// A "region" in source code identified by the file/offset of the
49 /// preprocessor conditional directive that it belongs to.
50 /// Multiple, non-consecutive ranges can be parts of the same region.
52 /// As an example of different regions separated by preprocessor directives:
66 /// There are 3 regions, with non-consecutive parts:
67 /// #1 is identified as the beginning of the file
68 /// #2 is identified as the location of "#ifdef BLAH"
69 /// #3 is identified as the location of "#ifdef CAKE"
72 llvm::sys::fs::UniqueID UniqueID;
76 PPRegion() : UniqueID(0, 0), ModTime(), Offset() {}
77 PPRegion(llvm::sys::fs::UniqueID UniqueID, unsigned offset, time_t modTime)
78 : UniqueID(UniqueID), ModTime(modTime), Offset(offset) {}
80 const llvm::sys::fs::UniqueID &getUniqueID() const { return UniqueID; }
81 unsigned getOffset() const { return Offset; }
82 time_t getModTime() const { return ModTime; }
84 bool isInvalid() const { return *this == PPRegion(); }
86 friend bool operator==(const PPRegion &lhs, const PPRegion &rhs) {
87 return lhs.UniqueID == rhs.UniqueID && lhs.Offset == rhs.Offset &&
88 lhs.ModTime == rhs.ModTime;
92 typedef llvm::DenseSet<PPRegion> PPRegionSetTy;
94 } // end anonymous namespace
97 template <> struct isPodLike<PPRegion> {
98 static const bool value = true;
102 struct DenseMapInfo<PPRegion> {
103 static inline PPRegion getEmptyKey() {
104 return PPRegion(llvm::sys::fs::UniqueID(0, 0), unsigned(-1), 0);
106 static inline PPRegion getTombstoneKey() {
107 return PPRegion(llvm::sys::fs::UniqueID(0, 0), unsigned(-2), 0);
110 static unsigned getHashValue(const PPRegion &S) {
111 llvm::FoldingSetNodeID ID;
112 const llvm::sys::fs::UniqueID &UniqueID = S.getUniqueID();
113 ID.AddInteger(UniqueID.getFile());
114 ID.AddInteger(UniqueID.getDevice());
115 ID.AddInteger(S.getOffset());
116 ID.AddInteger(S.getModTime());
117 return ID.ComputeHash();
120 static bool isEqual(const PPRegion &LHS, const PPRegion &RHS) {
128 class SessionSkipBodyData {
129 llvm::sys::Mutex Mux;
130 PPRegionSetTy ParsedRegions;
133 SessionSkipBodyData() : Mux(/*recursive=*/false) {}
134 ~SessionSkipBodyData() {
135 //llvm::errs() << "RegionData: " << Skipped.size() << " - " << Skipped.getMemorySize() << "\n";
138 void copyTo(PPRegionSetTy &Set) {
139 llvm::MutexGuard MG(Mux);
143 void update(ArrayRef<PPRegion> Regions) {
144 llvm::MutexGuard MG(Mux);
145 ParsedRegions.insert(Regions.begin(), Regions.end());
149 class TUSkipBodyControl {
150 SessionSkipBodyData &SessionData;
151 PPConditionalDirectiveRecord &PPRec;
154 PPRegionSetTy ParsedRegions;
155 SmallVector<PPRegion, 32> NewParsedRegions;
160 TUSkipBodyControl(SessionSkipBodyData &sessionData,
161 PPConditionalDirectiveRecord &ppRec,
163 : SessionData(sessionData), PPRec(ppRec), PP(pp) {
164 SessionData.copyTo(ParsedRegions);
167 bool isParsed(SourceLocation Loc, FileID FID, const FileEntry *FE) {
168 PPRegion region = getRegion(Loc, FID, FE);
169 if (region.isInvalid())
172 // Check common case, consecutive functions in the same region.
173 if (LastRegion == region)
177 LastIsParsed = ParsedRegions.count(region);
179 NewParsedRegions.push_back(region);
184 SessionData.update(NewParsedRegions);
188 PPRegion getRegion(SourceLocation Loc, FileID FID, const FileEntry *FE) {
189 SourceLocation RegionLoc = PPRec.findConditionalDirectiveRegionLoc(Loc);
190 if (RegionLoc.isInvalid()) {
191 if (isParsedOnceInclude(FE)) {
192 const llvm::sys::fs::UniqueID &ID = FE->getUniqueID();
193 return PPRegion(ID, 0, FE->getModificationTime());
198 const SourceManager &SM = PPRec.getSourceManager();
199 assert(RegionLoc.isFileID());
201 unsigned RegionOffset;
202 std::tie(RegionFID, RegionOffset) = SM.getDecomposedLoc(RegionLoc);
204 if (RegionFID != FID) {
205 if (isParsedOnceInclude(FE)) {
206 const llvm::sys::fs::UniqueID &ID = FE->getUniqueID();
207 return PPRegion(ID, 0, FE->getModificationTime());
212 const llvm::sys::fs::UniqueID &ID = FE->getUniqueID();
213 return PPRegion(ID, RegionOffset, FE->getModificationTime());
216 bool isParsedOnceInclude(const FileEntry *FE) {
217 return PP.getHeaderSearchInfo().isFileMultipleIncludeGuarded(FE);
221 //===----------------------------------------------------------------------===//
223 //===----------------------------------------------------------------------===//
225 class IndexPPCallbacks : public PPCallbacks {
227 CXIndexDataConsumer &DataConsumer;
228 bool IsMainFileEntered;
231 IndexPPCallbacks(Preprocessor &PP, CXIndexDataConsumer &dataConsumer)
232 : PP(PP), DataConsumer(dataConsumer), IsMainFileEntered(false) { }
234 void FileChanged(SourceLocation Loc, FileChangeReason Reason,
235 SrcMgr::CharacteristicKind FileType, FileID PrevFID) override {
236 if (IsMainFileEntered)
239 SourceManager &SM = PP.getSourceManager();
240 SourceLocation MainFileLoc = SM.getLocForStartOfFile(SM.getMainFileID());
242 if (Loc == MainFileLoc && Reason == PPCallbacks::EnterFile) {
243 IsMainFileEntered = true;
244 DataConsumer.enteredMainFile(SM.getFileEntryForID(SM.getMainFileID()));
248 void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok,
249 StringRef FileName, bool IsAngled,
250 CharSourceRange FilenameRange, const FileEntry *File,
251 StringRef SearchPath, StringRef RelativePath,
252 const Module *Imported,
253 SrcMgr::CharacteristicKind FileType) override {
254 bool isImport = (IncludeTok.is(tok::identifier) &&
255 IncludeTok.getIdentifierInfo()->getPPKeywordID() == tok::pp_import);
256 DataConsumer.ppIncludedFile(HashLoc, FileName, File, isImport, IsAngled,
260 /// MacroDefined - This hook is called whenever a macro definition is seen.
261 void MacroDefined(const Token &Id, const MacroDirective *MD) override {}
263 /// MacroUndefined - This hook is called whenever a macro #undef is seen.
264 /// MI is released immediately following this callback.
265 void MacroUndefined(const Token &MacroNameTok,
266 const MacroDefinition &MD,
267 const MacroDirective *UD) override {}
269 /// MacroExpands - This is called by when a macro invocation is found.
270 void MacroExpands(const Token &MacroNameTok, const MacroDefinition &MD,
271 SourceRange Range, const MacroArgs *Args) override {}
273 /// SourceRangeSkipped - This hook is called when a source range is skipped.
274 /// \param Range The SourceRange that was skipped. The range begins at the
275 /// #if/#else directive and ends after the #endif/#else directive.
276 void SourceRangeSkipped(SourceRange Range, SourceLocation EndifLoc) override {
280 //===----------------------------------------------------------------------===//
282 //===----------------------------------------------------------------------===//
284 class IndexingConsumer : public ASTConsumer {
285 CXIndexDataConsumer &DataConsumer;
286 TUSkipBodyControl *SKCtrl;
289 IndexingConsumer(CXIndexDataConsumer &dataConsumer, TUSkipBodyControl *skCtrl)
290 : DataConsumer(dataConsumer), SKCtrl(skCtrl) { }
292 // ASTConsumer Implementation
294 void Initialize(ASTContext &Context) override {
295 DataConsumer.setASTContext(Context);
296 DataConsumer.startedTranslationUnit();
299 void HandleTranslationUnit(ASTContext &Ctx) override {
304 bool HandleTopLevelDecl(DeclGroupRef DG) override {
305 return !DataConsumer.shouldAbort();
308 bool shouldSkipFunctionBody(Decl *D) override {
310 // Always skip bodies.
314 const SourceManager &SM = DataConsumer.getASTContext().getSourceManager();
315 SourceLocation Loc = D->getLocation();
318 if (SM.isInSystemHeader(Loc))
319 return true; // always skip bodies from system headers.
323 std::tie(FID, Offset) = SM.getDecomposedLoc(Loc);
324 // Don't skip bodies from main files; this may be revisited.
325 if (SM.getMainFileID() == FID)
327 const FileEntry *FE = SM.getFileEntryForID(FID);
331 return SKCtrl->isParsed(Loc, FID, FE);
335 //===----------------------------------------------------------------------===//
336 // CaptureDiagnosticConsumer
337 //===----------------------------------------------------------------------===//
339 class CaptureDiagnosticConsumer : public DiagnosticConsumer {
340 SmallVector<StoredDiagnostic, 4> Errors;
343 void HandleDiagnostic(DiagnosticsEngine::Level level,
344 const Diagnostic &Info) override {
345 if (level >= DiagnosticsEngine::Error)
346 Errors.push_back(StoredDiagnostic(level, Info));
350 //===----------------------------------------------------------------------===//
351 // IndexingFrontendAction
352 //===----------------------------------------------------------------------===//
354 class IndexingFrontendAction : public ASTFrontendAction {
355 std::shared_ptr<CXIndexDataConsumer> DataConsumer;
357 SessionSkipBodyData *SKData;
358 std::unique_ptr<TUSkipBodyControl> SKCtrl;
361 IndexingFrontendAction(std::shared_ptr<CXIndexDataConsumer> dataConsumer,
362 SessionSkipBodyData *skData)
363 : DataConsumer(std::move(dataConsumer)), SKData(skData) {}
365 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
366 StringRef InFile) override {
367 PreprocessorOptions &PPOpts = CI.getPreprocessorOpts();
369 if (!PPOpts.ImplicitPCHInclude.empty()) {
370 DataConsumer->importedPCH(
371 CI.getFileManager().getFile(PPOpts.ImplicitPCHInclude));
374 DataConsumer->setASTContext(CI.getASTContext());
375 Preprocessor &PP = CI.getPreprocessor();
376 PP.addPPCallbacks(llvm::make_unique<IndexPPCallbacks>(PP, *DataConsumer));
377 DataConsumer->setPreprocessor(CI.getPreprocessorPtr());
380 auto *PPRec = new PPConditionalDirectiveRecord(PP.getSourceManager());
381 PP.addPPCallbacks(std::unique_ptr<PPCallbacks>(PPRec));
382 SKCtrl = llvm::make_unique<TUSkipBodyControl>(*SKData, *PPRec, PP);
385 return llvm::make_unique<IndexingConsumer>(*DataConsumer, SKCtrl.get());
388 TranslationUnitKind getTranslationUnitKind() override {
389 if (DataConsumer->shouldIndexImplicitTemplateInsts())
394 bool hasCodeCompletionSupport() const override { return false; }
397 //===----------------------------------------------------------------------===//
398 // clang_indexSourceFileUnit Implementation
399 //===----------------------------------------------------------------------===//
401 static IndexingOptions getIndexingOptionsFromCXOptions(unsigned index_options) {
402 IndexingOptions IdxOpts;
403 if (index_options & CXIndexOpt_IndexFunctionLocalSymbols)
404 IdxOpts.IndexFunctionLocals = true;
405 if (index_options & CXIndexOpt_IndexImplicitTemplateInstantiations)
406 IdxOpts.IndexImplicitInstantiation = true;
410 struct IndexSessionData {
412 std::unique_ptr<SessionSkipBodyData> SkipBodyData;
414 explicit IndexSessionData(CXIndex cIdx)
415 : CIdx(cIdx), SkipBodyData(new SessionSkipBodyData) {}
418 } // anonymous namespace
420 static CXErrorCode clang_indexSourceFile_Impl(
421 CXIndexAction cxIdxAction, CXClientData client_data,
422 IndexerCallbacks *client_index_callbacks, unsigned index_callbacks_size,
423 unsigned index_options, const char *source_filename,
424 const char *const *command_line_args, int num_command_line_args,
425 ArrayRef<CXUnsavedFile> unsaved_files, CXTranslationUnit *out_TU,
426 unsigned TU_options) {
429 bool requestedToGetTU = (out_TU != nullptr);
432 return CXError_InvalidArguments;
434 if (!client_index_callbacks || index_callbacks_size == 0) {
435 return CXError_InvalidArguments;
439 memset(&CB, 0, sizeof(CB));
440 unsigned ClientCBSize = index_callbacks_size < sizeof(CB)
441 ? index_callbacks_size : sizeof(CB);
442 memcpy(&CB, client_index_callbacks, ClientCBSize);
444 IndexSessionData *IdxSession = static_cast<IndexSessionData *>(cxIdxAction);
445 CIndexer *CXXIdx = static_cast<CIndexer *>(IdxSession->CIdx);
447 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
448 setThreadBackgroundPriority();
450 bool CaptureDiagnostics = !Logger::isLoggingEnabled();
452 CaptureDiagnosticConsumer *CaptureDiag = nullptr;
453 if (CaptureDiagnostics)
454 CaptureDiag = new CaptureDiagnosticConsumer();
456 // Configure the diagnostics.
457 IntrusiveRefCntPtr<DiagnosticsEngine>
458 Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions,
460 /*ShouldOwnClient=*/true));
462 // Recover resources if we crash before exiting this function.
463 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
464 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
465 DiagCleanup(Diags.get());
467 std::unique_ptr<std::vector<const char *>> Args(
468 new std::vector<const char *>());
470 // Recover resources if we crash before exiting this method.
471 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
472 ArgsCleanup(Args.get());
474 Args->insert(Args->end(), command_line_args,
475 command_line_args + num_command_line_args);
477 // The 'source_filename' argument is optional. If the caller does not
478 // specify it then it is assumed that the source file is specified
479 // in the actual argument list.
480 // Put the source file after command_line_args otherwise if '-x' flag is
481 // present it will be unused.
483 Args->push_back(source_filename);
485 std::shared_ptr<CompilerInvocation> CInvok =
486 createInvocationFromCommandLine(*Args, Diags);
489 return CXError_Failure;
491 // Recover resources if we crash before exiting this function.
492 llvm::CrashRecoveryContextCleanupRegistrar<
493 std::shared_ptr<CompilerInvocation>,
494 llvm::CrashRecoveryContextDestructorCleanup<
495 std::shared_ptr<CompilerInvocation>>>
496 CInvokCleanup(&CInvok);
498 if (CInvok->getFrontendOpts().Inputs.empty())
499 return CXError_Failure;
501 typedef SmallVector<std::unique_ptr<llvm::MemoryBuffer>, 8> MemBufferOwner;
502 std::unique_ptr<MemBufferOwner> BufOwner(new MemBufferOwner);
504 // Recover resources if we crash before exiting this method.
505 llvm::CrashRecoveryContextCleanupRegistrar<MemBufferOwner> BufOwnerCleanup(
508 for (auto &UF : unsaved_files) {
509 std::unique_ptr<llvm::MemoryBuffer> MB =
510 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
511 CInvok->getPreprocessorOpts().addRemappedFile(UF.Filename, MB.get());
512 BufOwner->push_back(std::move(MB));
515 // Since libclang is primarily used by batch tools dealing with
516 // (often very broken) source code, where spell-checking can have a
517 // significant negative impact on performance (particularly when
518 // precompiled headers are involved), we disable it.
519 CInvok->getLangOpts()->SpellChecking = false;
521 if (index_options & CXIndexOpt_SuppressWarnings)
522 CInvok->getDiagnosticOpts().IgnoreWarnings = true;
524 // Make sure to use the raw module format.
525 CInvok->getHeaderSearchOpts().ModuleFormat =
526 CXXIdx->getPCHContainerOperations()->getRawReader().getFormat();
528 auto Unit = ASTUnit::create(CInvok, Diags, CaptureDiagnostics,
529 /*UserFilesAreVolatile=*/true);
531 return CXError_InvalidArguments;
533 auto *UPtr = Unit.get();
534 std::unique_ptr<CXTUOwner> CXTU(
535 new CXTUOwner(MakeCXTranslationUnit(CXXIdx, std::move(Unit))));
537 // Recover resources if we crash before exiting this method.
538 llvm::CrashRecoveryContextCleanupRegistrar<CXTUOwner>
539 CXTUCleanup(CXTU.get());
541 // Enable the skip-parsed-bodies optimization only for C++; this may be
543 bool SkipBodies = (index_options & CXIndexOpt_SkipParsedBodiesInSession) &&
544 CInvok->getLangOpts()->CPlusPlus;
546 CInvok->getFrontendOpts().SkipFunctionBodies = true;
549 std::make_shared<CXIndexDataConsumer>(client_data, CB, index_options,
551 auto InterAction = llvm::make_unique<IndexingFrontendAction>(DataConsumer,
552 SkipBodies ? IdxSession->SkipBodyData.get() : nullptr);
553 std::unique_ptr<FrontendAction> IndexAction;
554 IndexAction = createIndexingAction(DataConsumer,
555 getIndexingOptionsFromCXOptions(index_options),
556 std::move(InterAction));
558 // Recover resources if we crash before exiting this method.
559 llvm::CrashRecoveryContextCleanupRegistrar<FrontendAction>
560 IndexActionCleanup(IndexAction.get());
562 bool Persistent = requestedToGetTU;
563 bool OnlyLocalDecls = false;
564 bool PrecompilePreamble = false;
565 bool CreatePreambleOnFirstParse = false;
566 bool CacheCodeCompletionResults = false;
567 PreprocessorOptions &PPOpts = CInvok->getPreprocessorOpts();
568 PPOpts.AllowPCHWithCompilerErrors = true;
570 if (requestedToGetTU) {
571 OnlyLocalDecls = CXXIdx->getOnlyLocalDecls();
572 PrecompilePreamble = TU_options & CXTranslationUnit_PrecompiledPreamble;
573 CreatePreambleOnFirstParse =
574 TU_options & CXTranslationUnit_CreatePreambleOnFirstParse;
575 // FIXME: Add a flag for modules.
576 CacheCodeCompletionResults
577 = TU_options & CXTranslationUnit_CacheCompletionResults;
580 if (TU_options & CXTranslationUnit_DetailedPreprocessingRecord) {
581 PPOpts.DetailedRecord = true;
584 if (!requestedToGetTU && !CInvok->getLangOpts()->Modules)
585 PPOpts.DetailedRecord = false;
587 // Unless the user specified that they want the preamble on the first parse
588 // set it up to be created on the first reparse. This makes the first parse
589 // faster, trading for a slower (first) reparse.
590 unsigned PrecompilePreambleAfterNParses =
591 !PrecompilePreamble ? 0 : 2 - CreatePreambleOnFirstParse;
592 DiagnosticErrorTrap DiagTrap(*Diags);
593 bool Success = ASTUnit::LoadFromCompilerInvocationAction(
594 std::move(CInvok), CXXIdx->getPCHContainerOperations(), Diags,
595 IndexAction.get(), UPtr, Persistent, CXXIdx->getClangResourcesPath(),
596 OnlyLocalDecls, CaptureDiagnostics, PrecompilePreambleAfterNParses,
597 CacheCodeCompletionResults,
598 /*IncludeBriefCommentsInCodeCompletion=*/false,
599 /*UserFilesAreVolatile=*/true);
600 if (DiagTrap.hasErrorOccurred() && CXXIdx->getDisplayDiagnostics())
601 printDiagsToStderr(UPtr);
603 if (isASTReadError(UPtr))
604 return CXError_ASTReadError;
607 return CXError_Failure;
610 *out_TU = CXTU->takeTU();
612 return CXError_Success;
615 //===----------------------------------------------------------------------===//
616 // clang_indexTranslationUnit Implementation
617 //===----------------------------------------------------------------------===//
619 static void indexPreprocessingRecord(ASTUnit &Unit, CXIndexDataConsumer &IdxCtx) {
620 Preprocessor &PP = Unit.getPreprocessor();
621 if (!PP.getPreprocessingRecord())
624 // FIXME: Only deserialize inclusion directives.
626 bool isModuleFile = Unit.isModuleFile();
627 for (PreprocessedEntity *PPE : Unit.getLocalPreprocessingEntities()) {
628 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
629 SourceLocation Loc = ID->getSourceRange().getBegin();
630 // Modules have synthetic main files as input, give an invalid location
631 // if the location points to such a file.
632 if (isModuleFile && Unit.isInMainFileID(Loc))
633 Loc = SourceLocation();
634 IdxCtx.ppIncludedFile(Loc, ID->getFileName(),
636 ID->getKind() == InclusionDirective::Import,
637 !ID->wasInQuotes(), ID->importedModule());
642 static CXErrorCode clang_indexTranslationUnit_Impl(
643 CXIndexAction idxAction, CXClientData client_data,
644 IndexerCallbacks *client_index_callbacks, unsigned index_callbacks_size,
645 unsigned index_options, CXTranslationUnit TU) {
647 if (isNotUsableTU(TU)) {
649 return CXError_InvalidArguments;
651 if (!client_index_callbacks || index_callbacks_size == 0) {
652 return CXError_InvalidArguments;
655 CIndexer *CXXIdx = TU->CIdx;
656 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
657 setThreadBackgroundPriority();
660 memset(&CB, 0, sizeof(CB));
661 unsigned ClientCBSize = index_callbacks_size < sizeof(CB)
662 ? index_callbacks_size : sizeof(CB);
663 memcpy(&CB, client_index_callbacks, ClientCBSize);
665 CXIndexDataConsumer DataConsumer(client_data, CB, index_options, TU);
667 ASTUnit *Unit = cxtu::getASTUnit(TU);
669 return CXError_Failure;
671 ASTUnit::ConcurrencyCheck Check(*Unit);
673 if (const FileEntry *PCHFile = Unit->getPCHFile())
674 DataConsumer.importedPCH(PCHFile);
676 FileManager &FileMgr = Unit->getFileManager();
678 if (Unit->getOriginalSourceFileName().empty())
679 DataConsumer.enteredMainFile(nullptr);
681 DataConsumer.enteredMainFile(
682 FileMgr.getFile(Unit->getOriginalSourceFileName()));
684 DataConsumer.setASTContext(Unit->getASTContext());
685 DataConsumer.startedTranslationUnit();
687 indexPreprocessingRecord(*Unit, DataConsumer);
688 indexASTUnit(*Unit, DataConsumer, getIndexingOptionsFromCXOptions(index_options));
689 DataConsumer.indexDiagnostics();
691 return CXError_Success;
694 //===----------------------------------------------------------------------===//
695 // libclang public APIs.
696 //===----------------------------------------------------------------------===//
698 int clang_index_isEntityObjCContainerKind(CXIdxEntityKind K) {
699 return CXIdxEntity_ObjCClass <= K && K <= CXIdxEntity_ObjCCategory;
702 const CXIdxObjCContainerDeclInfo *
703 clang_index_getObjCContainerDeclInfo(const CXIdxDeclInfo *DInfo) {
707 const DeclInfo *DI = static_cast<const DeclInfo *>(DInfo);
708 if (const ObjCContainerDeclInfo *
709 ContInfo = dyn_cast<ObjCContainerDeclInfo>(DI))
710 return &ContInfo->ObjCContDeclInfo;
715 const CXIdxObjCInterfaceDeclInfo *
716 clang_index_getObjCInterfaceDeclInfo(const CXIdxDeclInfo *DInfo) {
720 const DeclInfo *DI = static_cast<const DeclInfo *>(DInfo);
721 if (const ObjCInterfaceDeclInfo *
722 InterInfo = dyn_cast<ObjCInterfaceDeclInfo>(DI))
723 return &InterInfo->ObjCInterDeclInfo;
728 const CXIdxObjCCategoryDeclInfo *
729 clang_index_getObjCCategoryDeclInfo(const CXIdxDeclInfo *DInfo){
733 const DeclInfo *DI = static_cast<const DeclInfo *>(DInfo);
734 if (const ObjCCategoryDeclInfo *
735 CatInfo = dyn_cast<ObjCCategoryDeclInfo>(DI))
736 return &CatInfo->ObjCCatDeclInfo;
741 const CXIdxObjCProtocolRefListInfo *
742 clang_index_getObjCProtocolRefListInfo(const CXIdxDeclInfo *DInfo) {
746 const DeclInfo *DI = static_cast<const DeclInfo *>(DInfo);
748 if (const ObjCInterfaceDeclInfo *
749 InterInfo = dyn_cast<ObjCInterfaceDeclInfo>(DI))
750 return InterInfo->ObjCInterDeclInfo.protocols;
752 if (const ObjCProtocolDeclInfo *
753 ProtInfo = dyn_cast<ObjCProtocolDeclInfo>(DI))
754 return &ProtInfo->ObjCProtoRefListInfo;
756 if (const ObjCCategoryDeclInfo *CatInfo = dyn_cast<ObjCCategoryDeclInfo>(DI))
757 return CatInfo->ObjCCatDeclInfo.protocols;
762 const CXIdxObjCPropertyDeclInfo *
763 clang_index_getObjCPropertyDeclInfo(const CXIdxDeclInfo *DInfo) {
767 const DeclInfo *DI = static_cast<const DeclInfo *>(DInfo);
768 if (const ObjCPropertyDeclInfo *PropInfo = dyn_cast<ObjCPropertyDeclInfo>(DI))
769 return &PropInfo->ObjCPropDeclInfo;
774 const CXIdxIBOutletCollectionAttrInfo *
775 clang_index_getIBOutletCollectionAttrInfo(const CXIdxAttrInfo *AInfo) {
779 const AttrInfo *DI = static_cast<const AttrInfo *>(AInfo);
780 if (const IBOutletCollectionInfo *
781 IBInfo = dyn_cast<IBOutletCollectionInfo>(DI))
782 return &IBInfo->IBCollInfo;
787 const CXIdxCXXClassDeclInfo *
788 clang_index_getCXXClassDeclInfo(const CXIdxDeclInfo *DInfo) {
792 const DeclInfo *DI = static_cast<const DeclInfo *>(DInfo);
793 if (const CXXClassDeclInfo *ClassInfo = dyn_cast<CXXClassDeclInfo>(DI))
794 return &ClassInfo->CXXClassInfo;
800 clang_index_getClientContainer(const CXIdxContainerInfo *info) {
803 const ContainerInfo *Container = static_cast<const ContainerInfo *>(info);
804 return Container->IndexCtx->getClientContainerForDC(Container->DC);
807 void clang_index_setClientContainer(const CXIdxContainerInfo *info,
808 CXIdxClientContainer client) {
811 const ContainerInfo *Container = static_cast<const ContainerInfo *>(info);
812 Container->IndexCtx->addContainerInMap(Container->DC, client);
815 CXIdxClientEntity clang_index_getClientEntity(const CXIdxEntityInfo *info) {
818 const EntityInfo *Entity = static_cast<const EntityInfo *>(info);
819 return Entity->IndexCtx->getClientEntity(Entity->Dcl);
822 void clang_index_setClientEntity(const CXIdxEntityInfo *info,
823 CXIdxClientEntity client) {
826 const EntityInfo *Entity = static_cast<const EntityInfo *>(info);
827 Entity->IndexCtx->setClientEntity(Entity->Dcl, client);
830 CXIndexAction clang_IndexAction_create(CXIndex CIdx) {
831 return new IndexSessionData(CIdx);
834 void clang_IndexAction_dispose(CXIndexAction idxAction) {
836 delete static_cast<IndexSessionData *>(idxAction);
839 int clang_indexSourceFile(CXIndexAction idxAction,
840 CXClientData client_data,
841 IndexerCallbacks *index_callbacks,
842 unsigned index_callbacks_size,
843 unsigned index_options,
844 const char *source_filename,
845 const char * const *command_line_args,
846 int num_command_line_args,
847 struct CXUnsavedFile *unsaved_files,
848 unsigned num_unsaved_files,
849 CXTranslationUnit *out_TU,
850 unsigned TU_options) {
851 SmallVector<const char *, 4> Args;
852 Args.push_back("clang");
853 Args.append(command_line_args, command_line_args + num_command_line_args);
854 return clang_indexSourceFileFullArgv(
855 idxAction, client_data, index_callbacks, index_callbacks_size,
856 index_options, source_filename, Args.data(), Args.size(), unsaved_files,
857 num_unsaved_files, out_TU, TU_options);
860 int clang_indexSourceFileFullArgv(
861 CXIndexAction idxAction, CXClientData client_data,
862 IndexerCallbacks *index_callbacks, unsigned index_callbacks_size,
863 unsigned index_options, const char *source_filename,
864 const char *const *command_line_args, int num_command_line_args,
865 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
866 CXTranslationUnit *out_TU, unsigned TU_options) {
868 *Log << source_filename << ": ";
869 for (int i = 0; i != num_command_line_args; ++i)
870 *Log << command_line_args[i] << " ";
873 if (num_unsaved_files && !unsaved_files)
874 return CXError_InvalidArguments;
876 CXErrorCode result = CXError_Failure;
877 auto IndexSourceFileImpl = [=, &result]() {
878 result = clang_indexSourceFile_Impl(
879 idxAction, client_data, index_callbacks, index_callbacks_size,
880 index_options, source_filename, command_line_args,
881 num_command_line_args,
882 llvm::makeArrayRef(unsaved_files, num_unsaved_files), out_TU,
886 llvm::CrashRecoveryContext CRC;
888 if (!RunSafely(CRC, IndexSourceFileImpl)) {
889 fprintf(stderr, "libclang: crash detected during indexing source file: {\n");
890 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
891 fprintf(stderr, " 'command_line_args' : [");
892 for (int i = 0; i != num_command_line_args; ++i) {
894 fprintf(stderr, ", ");
895 fprintf(stderr, "'%s'", command_line_args[i]);
897 fprintf(stderr, "],\n");
898 fprintf(stderr, " 'unsaved_files' : [");
899 for (unsigned i = 0; i != num_unsaved_files; ++i) {
901 fprintf(stderr, ", ");
902 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
903 unsaved_files[i].Length);
905 fprintf(stderr, "],\n");
906 fprintf(stderr, " 'options' : %d,\n", TU_options);
907 fprintf(stderr, "}\n");
910 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
912 PrintLibclangResourceUsage(*out_TU);
918 int clang_indexTranslationUnit(CXIndexAction idxAction,
919 CXClientData client_data,
920 IndexerCallbacks *index_callbacks,
921 unsigned index_callbacks_size,
922 unsigned index_options,
923 CXTranslationUnit TU) {
929 auto IndexTranslationUnitImpl = [=, &result]() {
930 result = clang_indexTranslationUnit_Impl(
931 idxAction, client_data, index_callbacks, index_callbacks_size,
935 llvm::CrashRecoveryContext CRC;
937 if (!RunSafely(CRC, IndexTranslationUnitImpl)) {
938 fprintf(stderr, "libclang: crash detected during indexing TU\n");
946 void clang_indexLoc_getFileLocation(CXIdxLoc location,
947 CXIdxClientFile *indexFile,
952 if (indexFile) *indexFile = nullptr;
953 if (file) *file = nullptr;
955 if (column) *column = 0;
956 if (offset) *offset = 0;
958 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
959 if (!location.ptr_data[0] || Loc.isInvalid())
962 CXIndexDataConsumer &DataConsumer =
963 *static_cast<CXIndexDataConsumer*>(location.ptr_data[0]);
964 DataConsumer.translateLoc(Loc, indexFile, file, line, column, offset);
967 CXSourceLocation clang_indexLoc_getCXSourceLocation(CXIdxLoc location) {
968 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
969 if (!location.ptr_data[0] || Loc.isInvalid())
970 return clang_getNullLocation();
972 CXIndexDataConsumer &DataConsumer =
973 *static_cast<CXIndexDataConsumer*>(location.ptr_data[0]);
974 return cxloc::translateSourceLocation(DataConsumer.getASTContext(), Loc);