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 /// \brief 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) override {
253 bool isImport = (IncludeTok.is(tok::identifier) &&
254 IncludeTok.getIdentifierInfo()->getPPKeywordID() == tok::pp_import);
255 DataConsumer.ppIncludedFile(HashLoc, FileName, File, isImport, IsAngled,
259 /// MacroDefined - This hook is called whenever a macro definition is seen.
260 void MacroDefined(const Token &Id, const MacroDirective *MD) override {}
262 /// MacroUndefined - This hook is called whenever a macro #undef is seen.
263 /// MI is released immediately following this callback.
264 void MacroUndefined(const Token &MacroNameTok,
265 const MacroDefinition &MD) override {}
267 /// MacroExpands - This is called by when a macro invocation is found.
268 void MacroExpands(const Token &MacroNameTok, const MacroDefinition &MD,
269 SourceRange Range, const MacroArgs *Args) override {}
271 /// SourceRangeSkipped - This hook is called when a source range is skipped.
272 /// \param Range The SourceRange that was skipped. The range begins at the
273 /// #if/#else directive and ends after the #endif/#else directive.
274 void SourceRangeSkipped(SourceRange Range) override {}
277 //===----------------------------------------------------------------------===//
279 //===----------------------------------------------------------------------===//
281 class IndexingConsumer : public ASTConsumer {
282 CXIndexDataConsumer &DataConsumer;
283 TUSkipBodyControl *SKCtrl;
286 IndexingConsumer(CXIndexDataConsumer &dataConsumer, TUSkipBodyControl *skCtrl)
287 : DataConsumer(dataConsumer), SKCtrl(skCtrl) { }
289 // ASTConsumer Implementation
291 void Initialize(ASTContext &Context) override {
292 DataConsumer.setASTContext(Context);
293 DataConsumer.startedTranslationUnit();
296 void HandleTranslationUnit(ASTContext &Ctx) override {
301 bool HandleTopLevelDecl(DeclGroupRef DG) override {
302 return !DataConsumer.shouldAbort();
305 bool shouldSkipFunctionBody(Decl *D) override {
307 // Always skip bodies.
311 const SourceManager &SM = DataConsumer.getASTContext().getSourceManager();
312 SourceLocation Loc = D->getLocation();
315 if (SM.isInSystemHeader(Loc))
316 return true; // always skip bodies from system headers.
320 std::tie(FID, Offset) = SM.getDecomposedLoc(Loc);
321 // Don't skip bodies from main files; this may be revisited.
322 if (SM.getMainFileID() == FID)
324 const FileEntry *FE = SM.getFileEntryForID(FID);
328 return SKCtrl->isParsed(Loc, FID, FE);
332 //===----------------------------------------------------------------------===//
333 // CaptureDiagnosticConsumer
334 //===----------------------------------------------------------------------===//
336 class CaptureDiagnosticConsumer : public DiagnosticConsumer {
337 SmallVector<StoredDiagnostic, 4> Errors;
340 void HandleDiagnostic(DiagnosticsEngine::Level level,
341 const Diagnostic &Info) override {
342 if (level >= DiagnosticsEngine::Error)
343 Errors.push_back(StoredDiagnostic(level, Info));
347 //===----------------------------------------------------------------------===//
348 // IndexingFrontendAction
349 //===----------------------------------------------------------------------===//
351 class IndexingFrontendAction : public ASTFrontendAction {
352 std::shared_ptr<CXIndexDataConsumer> DataConsumer;
354 SessionSkipBodyData *SKData;
355 std::unique_ptr<TUSkipBodyControl> SKCtrl;
358 IndexingFrontendAction(std::shared_ptr<CXIndexDataConsumer> dataConsumer,
359 SessionSkipBodyData *skData)
360 : DataConsumer(std::move(dataConsumer)), SKData(skData) {}
362 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
363 StringRef InFile) override {
364 PreprocessorOptions &PPOpts = CI.getPreprocessorOpts();
366 if (!PPOpts.ImplicitPCHInclude.empty()) {
367 DataConsumer->importedPCH(
368 CI.getFileManager().getFile(PPOpts.ImplicitPCHInclude));
371 DataConsumer->setASTContext(CI.getASTContext());
372 Preprocessor &PP = CI.getPreprocessor();
373 PP.addPPCallbacks(llvm::make_unique<IndexPPCallbacks>(PP, *DataConsumer));
374 DataConsumer->setPreprocessor(PP);
377 auto *PPRec = new PPConditionalDirectiveRecord(PP.getSourceManager());
378 PP.addPPCallbacks(std::unique_ptr<PPCallbacks>(PPRec));
379 SKCtrl = llvm::make_unique<TUSkipBodyControl>(*SKData, *PPRec, PP);
382 return llvm::make_unique<IndexingConsumer>(*DataConsumer, SKCtrl.get());
385 TranslationUnitKind getTranslationUnitKind() override {
386 if (DataConsumer->shouldIndexImplicitTemplateInsts())
391 bool hasCodeCompletionSupport() const override { return false; }
394 //===----------------------------------------------------------------------===//
395 // clang_indexSourceFileUnit Implementation
396 //===----------------------------------------------------------------------===//
398 static IndexingOptions getIndexingOptionsFromCXOptions(unsigned index_options) {
399 IndexingOptions IdxOpts;
400 if (index_options & CXIndexOpt_IndexFunctionLocalSymbols)
401 IdxOpts.IndexFunctionLocals = true;
405 struct IndexSessionData {
407 std::unique_ptr<SessionSkipBodyData> SkipBodyData;
409 explicit IndexSessionData(CXIndex cIdx)
410 : CIdx(cIdx), SkipBodyData(new SessionSkipBodyData) {}
413 } // anonymous namespace
415 static CXErrorCode clang_indexSourceFile_Impl(
416 CXIndexAction cxIdxAction, CXClientData client_data,
417 IndexerCallbacks *client_index_callbacks, unsigned index_callbacks_size,
418 unsigned index_options, const char *source_filename,
419 const char *const *command_line_args, int num_command_line_args,
420 ArrayRef<CXUnsavedFile> unsaved_files, CXTranslationUnit *out_TU,
421 unsigned TU_options) {
424 bool requestedToGetTU = (out_TU != nullptr);
427 return CXError_InvalidArguments;
429 if (!client_index_callbacks || index_callbacks_size == 0) {
430 return CXError_InvalidArguments;
434 memset(&CB, 0, sizeof(CB));
435 unsigned ClientCBSize = index_callbacks_size < sizeof(CB)
436 ? index_callbacks_size : sizeof(CB);
437 memcpy(&CB, client_index_callbacks, ClientCBSize);
439 IndexSessionData *IdxSession = static_cast<IndexSessionData *>(cxIdxAction);
440 CIndexer *CXXIdx = static_cast<CIndexer *>(IdxSession->CIdx);
442 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
443 setThreadBackgroundPriority();
445 bool CaptureDiagnostics = !Logger::isLoggingEnabled();
447 CaptureDiagnosticConsumer *CaptureDiag = nullptr;
448 if (CaptureDiagnostics)
449 CaptureDiag = new CaptureDiagnosticConsumer();
451 // Configure the diagnostics.
452 IntrusiveRefCntPtr<DiagnosticsEngine>
453 Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions,
455 /*ShouldOwnClient=*/true));
457 // Recover resources if we crash before exiting this function.
458 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
459 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
460 DiagCleanup(Diags.get());
462 std::unique_ptr<std::vector<const char *>> Args(
463 new std::vector<const char *>());
465 // Recover resources if we crash before exiting this method.
466 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
467 ArgsCleanup(Args.get());
469 Args->insert(Args->end(), command_line_args,
470 command_line_args + num_command_line_args);
472 // The 'source_filename' argument is optional. If the caller does not
473 // specify it then it is assumed that the source file is specified
474 // in the actual argument list.
475 // Put the source file after command_line_args otherwise if '-x' flag is
476 // present it will be unused.
478 Args->push_back(source_filename);
480 IntrusiveRefCntPtr<CompilerInvocation>
481 CInvok(createInvocationFromCommandLine(*Args, Diags));
484 return CXError_Failure;
486 // Recover resources if we crash before exiting this function.
487 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInvocation,
488 llvm::CrashRecoveryContextReleaseRefCleanup<CompilerInvocation> >
489 CInvokCleanup(CInvok.get());
491 if (CInvok->getFrontendOpts().Inputs.empty())
492 return CXError_Failure;
494 typedef SmallVector<std::unique_ptr<llvm::MemoryBuffer>, 8> MemBufferOwner;
495 std::unique_ptr<MemBufferOwner> BufOwner(new MemBufferOwner);
497 // Recover resources if we crash before exiting this method.
498 llvm::CrashRecoveryContextCleanupRegistrar<MemBufferOwner> BufOwnerCleanup(
501 for (auto &UF : unsaved_files) {
502 std::unique_ptr<llvm::MemoryBuffer> MB =
503 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
504 CInvok->getPreprocessorOpts().addRemappedFile(UF.Filename, MB.get());
505 BufOwner->push_back(std::move(MB));
508 // Since libclang is primarily used by batch tools dealing with
509 // (often very broken) source code, where spell-checking can have a
510 // significant negative impact on performance (particularly when
511 // precompiled headers are involved), we disable it.
512 CInvok->getLangOpts()->SpellChecking = false;
514 if (index_options & CXIndexOpt_SuppressWarnings)
515 CInvok->getDiagnosticOpts().IgnoreWarnings = true;
517 // Make sure to use the raw module format.
518 CInvok->getHeaderSearchOpts().ModuleFormat =
519 CXXIdx->getPCHContainerOperations()->getRawReader().getFormat();
521 ASTUnit *Unit = ASTUnit::create(CInvok.get(), Diags, CaptureDiagnostics,
522 /*UserFilesAreVolatile=*/true);
524 return CXError_InvalidArguments;
526 std::unique_ptr<CXTUOwner> CXTU(
527 new CXTUOwner(MakeCXTranslationUnit(CXXIdx, Unit)));
529 // Recover resources if we crash before exiting this method.
530 llvm::CrashRecoveryContextCleanupRegistrar<CXTUOwner>
531 CXTUCleanup(CXTU.get());
533 // Enable the skip-parsed-bodies optimization only for C++; this may be
535 bool SkipBodies = (index_options & CXIndexOpt_SkipParsedBodiesInSession) &&
536 CInvok->getLangOpts()->CPlusPlus;
538 CInvok->getFrontendOpts().SkipFunctionBodies = true;
541 std::make_shared<CXIndexDataConsumer>(client_data, CB, index_options,
543 auto InterAction = llvm::make_unique<IndexingFrontendAction>(DataConsumer,
544 SkipBodies ? IdxSession->SkipBodyData.get() : nullptr);
545 std::unique_ptr<FrontendAction> IndexAction;
546 IndexAction = createIndexingAction(DataConsumer,
547 getIndexingOptionsFromCXOptions(index_options),
548 std::move(InterAction));
550 // Recover resources if we crash before exiting this method.
551 llvm::CrashRecoveryContextCleanupRegistrar<FrontendAction>
552 IndexActionCleanup(IndexAction.get());
554 bool Persistent = requestedToGetTU;
555 bool OnlyLocalDecls = false;
556 bool PrecompilePreamble = false;
557 bool CreatePreambleOnFirstParse = false;
558 bool CacheCodeCompletionResults = false;
559 PreprocessorOptions &PPOpts = CInvok->getPreprocessorOpts();
560 PPOpts.AllowPCHWithCompilerErrors = true;
562 if (requestedToGetTU) {
563 OnlyLocalDecls = CXXIdx->getOnlyLocalDecls();
564 PrecompilePreamble = TU_options & CXTranslationUnit_PrecompiledPreamble;
565 CreatePreambleOnFirstParse =
566 TU_options & CXTranslationUnit_CreatePreambleOnFirstParse;
567 // FIXME: Add a flag for modules.
568 CacheCodeCompletionResults
569 = TU_options & CXTranslationUnit_CacheCompletionResults;
572 if (TU_options & CXTranslationUnit_DetailedPreprocessingRecord) {
573 PPOpts.DetailedRecord = true;
576 if (!requestedToGetTU && !CInvok->getLangOpts()->Modules)
577 PPOpts.DetailedRecord = false;
579 // Unless the user specified that they want the preamble on the first parse
580 // set it up to be created on the first reparse. This makes the first parse
581 // faster, trading for a slower (first) reparse.
582 unsigned PrecompilePreambleAfterNParses =
583 !PrecompilePreamble ? 0 : 2 - CreatePreambleOnFirstParse;
584 DiagnosticErrorTrap DiagTrap(*Diags);
585 bool Success = ASTUnit::LoadFromCompilerInvocationAction(
586 CInvok.get(), CXXIdx->getPCHContainerOperations(), Diags,
587 IndexAction.get(), Unit, Persistent, CXXIdx->getClangResourcesPath(),
588 OnlyLocalDecls, CaptureDiagnostics, PrecompilePreambleAfterNParses,
589 CacheCodeCompletionResults,
590 /*IncludeBriefCommentsInCodeCompletion=*/false,
591 /*UserFilesAreVolatile=*/true);
592 if (DiagTrap.hasErrorOccurred() && CXXIdx->getDisplayDiagnostics())
593 printDiagsToStderr(Unit);
595 if (isASTReadError(Unit))
596 return CXError_ASTReadError;
599 return CXError_Failure;
602 *out_TU = CXTU->takeTU();
604 return CXError_Success;
607 //===----------------------------------------------------------------------===//
608 // clang_indexTranslationUnit Implementation
609 //===----------------------------------------------------------------------===//
611 static void indexPreprocessingRecord(ASTUnit &Unit, CXIndexDataConsumer &IdxCtx) {
612 Preprocessor &PP = Unit.getPreprocessor();
613 if (!PP.getPreprocessingRecord())
616 // FIXME: Only deserialize inclusion directives.
618 bool isModuleFile = Unit.isModuleFile();
619 for (PreprocessedEntity *PPE : Unit.getLocalPreprocessingEntities()) {
620 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
621 SourceLocation Loc = ID->getSourceRange().getBegin();
622 // Modules have synthetic main files as input, give an invalid location
623 // if the location points to such a file.
624 if (isModuleFile && Unit.isInMainFileID(Loc))
625 Loc = SourceLocation();
626 IdxCtx.ppIncludedFile(Loc, ID->getFileName(),
628 ID->getKind() == InclusionDirective::Import,
629 !ID->wasInQuotes(), ID->importedModule());
634 static CXErrorCode clang_indexTranslationUnit_Impl(
635 CXIndexAction idxAction, CXClientData client_data,
636 IndexerCallbacks *client_index_callbacks, unsigned index_callbacks_size,
637 unsigned index_options, CXTranslationUnit TU) {
639 if (isNotUsableTU(TU)) {
641 return CXError_InvalidArguments;
643 if (!client_index_callbacks || index_callbacks_size == 0) {
644 return CXError_InvalidArguments;
647 CIndexer *CXXIdx = TU->CIdx;
648 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
649 setThreadBackgroundPriority();
652 memset(&CB, 0, sizeof(CB));
653 unsigned ClientCBSize = index_callbacks_size < sizeof(CB)
654 ? index_callbacks_size : sizeof(CB);
655 memcpy(&CB, client_index_callbacks, ClientCBSize);
657 auto DataConsumer = std::make_shared<CXIndexDataConsumer>(client_data, CB,
660 ASTUnit *Unit = cxtu::getASTUnit(TU);
662 return CXError_Failure;
664 ASTUnit::ConcurrencyCheck Check(*Unit);
666 if (const FileEntry *PCHFile = Unit->getPCHFile())
667 DataConsumer->importedPCH(PCHFile);
669 FileManager &FileMgr = Unit->getFileManager();
671 if (Unit->getOriginalSourceFileName().empty())
672 DataConsumer->enteredMainFile(nullptr);
674 DataConsumer->enteredMainFile(FileMgr.getFile(Unit->getOriginalSourceFileName()));
676 DataConsumer->setASTContext(Unit->getASTContext());
677 DataConsumer->startedTranslationUnit();
679 indexPreprocessingRecord(*Unit, *DataConsumer);
680 indexASTUnit(*Unit, DataConsumer, getIndexingOptionsFromCXOptions(index_options));
681 DataConsumer->indexDiagnostics();
683 return CXError_Success;
686 //===----------------------------------------------------------------------===//
687 // libclang public APIs.
688 //===----------------------------------------------------------------------===//
690 int clang_index_isEntityObjCContainerKind(CXIdxEntityKind K) {
691 return CXIdxEntity_ObjCClass <= K && K <= CXIdxEntity_ObjCCategory;
694 const CXIdxObjCContainerDeclInfo *
695 clang_index_getObjCContainerDeclInfo(const CXIdxDeclInfo *DInfo) {
699 const DeclInfo *DI = static_cast<const DeclInfo *>(DInfo);
700 if (const ObjCContainerDeclInfo *
701 ContInfo = dyn_cast<ObjCContainerDeclInfo>(DI))
702 return &ContInfo->ObjCContDeclInfo;
707 const CXIdxObjCInterfaceDeclInfo *
708 clang_index_getObjCInterfaceDeclInfo(const CXIdxDeclInfo *DInfo) {
712 const DeclInfo *DI = static_cast<const DeclInfo *>(DInfo);
713 if (const ObjCInterfaceDeclInfo *
714 InterInfo = dyn_cast<ObjCInterfaceDeclInfo>(DI))
715 return &InterInfo->ObjCInterDeclInfo;
720 const CXIdxObjCCategoryDeclInfo *
721 clang_index_getObjCCategoryDeclInfo(const CXIdxDeclInfo *DInfo){
725 const DeclInfo *DI = static_cast<const DeclInfo *>(DInfo);
726 if (const ObjCCategoryDeclInfo *
727 CatInfo = dyn_cast<ObjCCategoryDeclInfo>(DI))
728 return &CatInfo->ObjCCatDeclInfo;
733 const CXIdxObjCProtocolRefListInfo *
734 clang_index_getObjCProtocolRefListInfo(const CXIdxDeclInfo *DInfo) {
738 const DeclInfo *DI = static_cast<const DeclInfo *>(DInfo);
740 if (const ObjCInterfaceDeclInfo *
741 InterInfo = dyn_cast<ObjCInterfaceDeclInfo>(DI))
742 return InterInfo->ObjCInterDeclInfo.protocols;
744 if (const ObjCProtocolDeclInfo *
745 ProtInfo = dyn_cast<ObjCProtocolDeclInfo>(DI))
746 return &ProtInfo->ObjCProtoRefListInfo;
748 if (const ObjCCategoryDeclInfo *CatInfo = dyn_cast<ObjCCategoryDeclInfo>(DI))
749 return CatInfo->ObjCCatDeclInfo.protocols;
754 const CXIdxObjCPropertyDeclInfo *
755 clang_index_getObjCPropertyDeclInfo(const CXIdxDeclInfo *DInfo) {
759 const DeclInfo *DI = static_cast<const DeclInfo *>(DInfo);
760 if (const ObjCPropertyDeclInfo *PropInfo = dyn_cast<ObjCPropertyDeclInfo>(DI))
761 return &PropInfo->ObjCPropDeclInfo;
766 const CXIdxIBOutletCollectionAttrInfo *
767 clang_index_getIBOutletCollectionAttrInfo(const CXIdxAttrInfo *AInfo) {
771 const AttrInfo *DI = static_cast<const AttrInfo *>(AInfo);
772 if (const IBOutletCollectionInfo *
773 IBInfo = dyn_cast<IBOutletCollectionInfo>(DI))
774 return &IBInfo->IBCollInfo;
779 const CXIdxCXXClassDeclInfo *
780 clang_index_getCXXClassDeclInfo(const CXIdxDeclInfo *DInfo) {
784 const DeclInfo *DI = static_cast<const DeclInfo *>(DInfo);
785 if (const CXXClassDeclInfo *ClassInfo = dyn_cast<CXXClassDeclInfo>(DI))
786 return &ClassInfo->CXXClassInfo;
792 clang_index_getClientContainer(const CXIdxContainerInfo *info) {
795 const ContainerInfo *Container = static_cast<const ContainerInfo *>(info);
796 return Container->IndexCtx->getClientContainerForDC(Container->DC);
799 void clang_index_setClientContainer(const CXIdxContainerInfo *info,
800 CXIdxClientContainer client) {
803 const ContainerInfo *Container = static_cast<const ContainerInfo *>(info);
804 Container->IndexCtx->addContainerInMap(Container->DC, client);
807 CXIdxClientEntity clang_index_getClientEntity(const CXIdxEntityInfo *info) {
810 const EntityInfo *Entity = static_cast<const EntityInfo *>(info);
811 return Entity->IndexCtx->getClientEntity(Entity->Dcl);
814 void clang_index_setClientEntity(const CXIdxEntityInfo *info,
815 CXIdxClientEntity client) {
818 const EntityInfo *Entity = static_cast<const EntityInfo *>(info);
819 Entity->IndexCtx->setClientEntity(Entity->Dcl, client);
822 CXIndexAction clang_IndexAction_create(CXIndex CIdx) {
823 return new IndexSessionData(CIdx);
826 void clang_IndexAction_dispose(CXIndexAction idxAction) {
828 delete static_cast<IndexSessionData *>(idxAction);
831 int clang_indexSourceFile(CXIndexAction idxAction,
832 CXClientData client_data,
833 IndexerCallbacks *index_callbacks,
834 unsigned index_callbacks_size,
835 unsigned index_options,
836 const char *source_filename,
837 const char * const *command_line_args,
838 int num_command_line_args,
839 struct CXUnsavedFile *unsaved_files,
840 unsigned num_unsaved_files,
841 CXTranslationUnit *out_TU,
842 unsigned TU_options) {
843 SmallVector<const char *, 4> Args;
844 Args.push_back("clang");
845 Args.append(command_line_args, command_line_args + num_command_line_args);
846 return clang_indexSourceFileFullArgv(
847 idxAction, client_data, index_callbacks, index_callbacks_size,
848 index_options, source_filename, Args.data(), Args.size(), unsaved_files,
849 num_unsaved_files, out_TU, TU_options);
852 int clang_indexSourceFileFullArgv(
853 CXIndexAction idxAction, CXClientData client_data,
854 IndexerCallbacks *index_callbacks, unsigned index_callbacks_size,
855 unsigned index_options, const char *source_filename,
856 const char *const *command_line_args, int num_command_line_args,
857 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
858 CXTranslationUnit *out_TU, unsigned TU_options) {
860 *Log << source_filename << ": ";
861 for (int i = 0; i != num_command_line_args; ++i)
862 *Log << command_line_args[i] << " ";
865 if (num_unsaved_files && !unsaved_files)
866 return CXError_InvalidArguments;
868 CXErrorCode result = CXError_Failure;
869 auto IndexSourceFileImpl = [=, &result]() {
870 result = clang_indexSourceFile_Impl(
871 idxAction, client_data, index_callbacks, index_callbacks_size,
872 index_options, source_filename, command_line_args,
873 num_command_line_args,
874 llvm::makeArrayRef(unsaved_files, num_unsaved_files), out_TU,
878 if (getenv("LIBCLANG_NOTHREADS")) {
879 IndexSourceFileImpl();
883 llvm::CrashRecoveryContext CRC;
885 if (!RunSafely(CRC, IndexSourceFileImpl)) {
886 fprintf(stderr, "libclang: crash detected during indexing source file: {\n");
887 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
888 fprintf(stderr, " 'command_line_args' : [");
889 for (int i = 0; i != num_command_line_args; ++i) {
891 fprintf(stderr, ", ");
892 fprintf(stderr, "'%s'", command_line_args[i]);
894 fprintf(stderr, "],\n");
895 fprintf(stderr, " 'unsaved_files' : [");
896 for (unsigned i = 0; i != num_unsaved_files; ++i) {
898 fprintf(stderr, ", ");
899 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
900 unsaved_files[i].Length);
902 fprintf(stderr, "],\n");
903 fprintf(stderr, " 'options' : %d,\n", TU_options);
904 fprintf(stderr, "}\n");
907 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
909 PrintLibclangResourceUsage(*out_TU);
915 int clang_indexTranslationUnit(CXIndexAction idxAction,
916 CXClientData client_data,
917 IndexerCallbacks *index_callbacks,
918 unsigned index_callbacks_size,
919 unsigned index_options,
920 CXTranslationUnit TU) {
926 auto IndexTranslationUnitImpl = [=, &result]() {
927 result = clang_indexTranslationUnit_Impl(
928 idxAction, client_data, index_callbacks, index_callbacks_size,
932 if (getenv("LIBCLANG_NOTHREADS")) {
933 IndexTranslationUnitImpl();
937 llvm::CrashRecoveryContext CRC;
939 if (!RunSafely(CRC, IndexTranslationUnitImpl)) {
940 fprintf(stderr, "libclang: crash detected during indexing TU\n");
948 void clang_indexLoc_getFileLocation(CXIdxLoc location,
949 CXIdxClientFile *indexFile,
954 if (indexFile) *indexFile = nullptr;
955 if (file) *file = nullptr;
957 if (column) *column = 0;
958 if (offset) *offset = 0;
960 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
961 if (!location.ptr_data[0] || Loc.isInvalid())
964 CXIndexDataConsumer &DataConsumer =
965 *static_cast<CXIndexDataConsumer*>(location.ptr_data[0]);
966 DataConsumer.translateLoc(Loc, indexFile, file, line, column, offset);
969 CXSourceLocation clang_indexLoc_getCXSourceLocation(CXIdxLoc location) {
970 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
971 if (!location.ptr_data[0] || Loc.isInvalid())
972 return clang_getNullLocation();
974 CXIndexDataConsumer &DataConsumer =
975 *static_cast<CXIndexDataConsumer*>(location.ptr_data[0]);
976 return cxloc::translateSourceLocation(DataConsumer.getASTContext(), Loc);