1*67e74705SXin Li //===- CIndexHigh.cpp - Higher level API functions ------------------------===//
2*67e74705SXin Li //
3*67e74705SXin Li // The LLVM Compiler Infrastructure
4*67e74705SXin Li //
5*67e74705SXin Li // This file is distributed under the University of Illinois Open Source
6*67e74705SXin Li // License. See LICENSE.TXT for details.
7*67e74705SXin Li //
8*67e74705SXin Li //===----------------------------------------------------------------------===//
9*67e74705SXin Li
10*67e74705SXin Li #include "CIndexDiagnostic.h"
11*67e74705SXin Li #include "CIndexer.h"
12*67e74705SXin Li #include "CLog.h"
13*67e74705SXin Li #include "CXCursor.h"
14*67e74705SXin Li #include "CXIndexDataConsumer.h"
15*67e74705SXin Li #include "CXSourceLocation.h"
16*67e74705SXin Li #include "CXString.h"
17*67e74705SXin Li #include "CXTranslationUnit.h"
18*67e74705SXin Li #include "clang/AST/ASTConsumer.h"
19*67e74705SXin Li #include "clang/Frontend/ASTUnit.h"
20*67e74705SXin Li #include "clang/Frontend/CompilerInstance.h"
21*67e74705SXin Li #include "clang/Frontend/CompilerInvocation.h"
22*67e74705SXin Li #include "clang/Frontend/FrontendAction.h"
23*67e74705SXin Li #include "clang/Frontend/Utils.h"
24*67e74705SXin Li #include "clang/Index/IndexingAction.h"
25*67e74705SXin Li #include "clang/Lex/HeaderSearch.h"
26*67e74705SXin Li #include "clang/Lex/PPCallbacks.h"
27*67e74705SXin Li #include "clang/Lex/PPConditionalDirectiveRecord.h"
28*67e74705SXin Li #include "clang/Lex/Preprocessor.h"
29*67e74705SXin Li #include "clang/Sema/SemaConsumer.h"
30*67e74705SXin Li #include "llvm/Support/CrashRecoveryContext.h"
31*67e74705SXin Li #include "llvm/Support/MemoryBuffer.h"
32*67e74705SXin Li #include "llvm/Support/Mutex.h"
33*67e74705SXin Li #include "llvm/Support/MutexGuard.h"
34*67e74705SXin Li #include <cstdio>
35*67e74705SXin Li #include <utility>
36*67e74705SXin Li
37*67e74705SXin Li using namespace clang;
38*67e74705SXin Li using namespace clang::index;
39*67e74705SXin Li using namespace cxtu;
40*67e74705SXin Li using namespace cxindex;
41*67e74705SXin Li
42*67e74705SXin Li namespace {
43*67e74705SXin Li
44*67e74705SXin Li //===----------------------------------------------------------------------===//
45*67e74705SXin Li // Skip Parsed Bodies
46*67e74705SXin Li //===----------------------------------------------------------------------===//
47*67e74705SXin Li
48*67e74705SXin Li /// \brief A "region" in source code identified by the file/offset of the
49*67e74705SXin Li /// preprocessor conditional directive that it belongs to.
50*67e74705SXin Li /// Multiple, non-consecutive ranges can be parts of the same region.
51*67e74705SXin Li ///
52*67e74705SXin Li /// As an example of different regions separated by preprocessor directives:
53*67e74705SXin Li ///
54*67e74705SXin Li /// \code
55*67e74705SXin Li /// #1
56*67e74705SXin Li /// #ifdef BLAH
57*67e74705SXin Li /// #2
58*67e74705SXin Li /// #ifdef CAKE
59*67e74705SXin Li /// #3
60*67e74705SXin Li /// #endif
61*67e74705SXin Li /// #2
62*67e74705SXin Li /// #endif
63*67e74705SXin Li /// #1
64*67e74705SXin Li /// \endcode
65*67e74705SXin Li ///
66*67e74705SXin Li /// There are 3 regions, with non-consecutive parts:
67*67e74705SXin Li /// #1 is identified as the beginning of the file
68*67e74705SXin Li /// #2 is identified as the location of "#ifdef BLAH"
69*67e74705SXin Li /// #3 is identified as the location of "#ifdef CAKE"
70*67e74705SXin Li ///
71*67e74705SXin Li class PPRegion {
72*67e74705SXin Li llvm::sys::fs::UniqueID UniqueID;
73*67e74705SXin Li time_t ModTime;
74*67e74705SXin Li unsigned Offset;
75*67e74705SXin Li public:
PPRegion()76*67e74705SXin Li PPRegion() : UniqueID(0, 0), ModTime(), Offset() {}
PPRegion(llvm::sys::fs::UniqueID UniqueID,unsigned offset,time_t modTime)77*67e74705SXin Li PPRegion(llvm::sys::fs::UniqueID UniqueID, unsigned offset, time_t modTime)
78*67e74705SXin Li : UniqueID(UniqueID), ModTime(modTime), Offset(offset) {}
79*67e74705SXin Li
getUniqueID() const80*67e74705SXin Li const llvm::sys::fs::UniqueID &getUniqueID() const { return UniqueID; }
getOffset() const81*67e74705SXin Li unsigned getOffset() const { return Offset; }
getModTime() const82*67e74705SXin Li time_t getModTime() const { return ModTime; }
83*67e74705SXin Li
isInvalid() const84*67e74705SXin Li bool isInvalid() const { return *this == PPRegion(); }
85*67e74705SXin Li
operator ==(const PPRegion & lhs,const PPRegion & rhs)86*67e74705SXin Li friend bool operator==(const PPRegion &lhs, const PPRegion &rhs) {
87*67e74705SXin Li return lhs.UniqueID == rhs.UniqueID && lhs.Offset == rhs.Offset &&
88*67e74705SXin Li lhs.ModTime == rhs.ModTime;
89*67e74705SXin Li }
90*67e74705SXin Li };
91*67e74705SXin Li
92*67e74705SXin Li typedef llvm::DenseSet<PPRegion> PPRegionSetTy;
93*67e74705SXin Li
94*67e74705SXin Li } // end anonymous namespace
95*67e74705SXin Li
96*67e74705SXin Li namespace llvm {
97*67e74705SXin Li template <> struct isPodLike<PPRegion> {
98*67e74705SXin Li static const bool value = true;
99*67e74705SXin Li };
100*67e74705SXin Li
101*67e74705SXin Li template <>
102*67e74705SXin Li struct DenseMapInfo<PPRegion> {
getEmptyKeyllvm::DenseMapInfo103*67e74705SXin Li static inline PPRegion getEmptyKey() {
104*67e74705SXin Li return PPRegion(llvm::sys::fs::UniqueID(0, 0), unsigned(-1), 0);
105*67e74705SXin Li }
getTombstoneKeyllvm::DenseMapInfo106*67e74705SXin Li static inline PPRegion getTombstoneKey() {
107*67e74705SXin Li return PPRegion(llvm::sys::fs::UniqueID(0, 0), unsigned(-2), 0);
108*67e74705SXin Li }
109*67e74705SXin Li
getHashValuellvm::DenseMapInfo110*67e74705SXin Li static unsigned getHashValue(const PPRegion &S) {
111*67e74705SXin Li llvm::FoldingSetNodeID ID;
112*67e74705SXin Li const llvm::sys::fs::UniqueID &UniqueID = S.getUniqueID();
113*67e74705SXin Li ID.AddInteger(UniqueID.getFile());
114*67e74705SXin Li ID.AddInteger(UniqueID.getDevice());
115*67e74705SXin Li ID.AddInteger(S.getOffset());
116*67e74705SXin Li ID.AddInteger(S.getModTime());
117*67e74705SXin Li return ID.ComputeHash();
118*67e74705SXin Li }
119*67e74705SXin Li
isEqualllvm::DenseMapInfo120*67e74705SXin Li static bool isEqual(const PPRegion &LHS, const PPRegion &RHS) {
121*67e74705SXin Li return LHS == RHS;
122*67e74705SXin Li }
123*67e74705SXin Li };
124*67e74705SXin Li }
125*67e74705SXin Li
126*67e74705SXin Li namespace {
127*67e74705SXin Li
128*67e74705SXin Li class SessionSkipBodyData {
129*67e74705SXin Li llvm::sys::Mutex Mux;
130*67e74705SXin Li PPRegionSetTy ParsedRegions;
131*67e74705SXin Li
132*67e74705SXin Li public:
SessionSkipBodyData()133*67e74705SXin Li SessionSkipBodyData() : Mux(/*recursive=*/false) {}
~SessionSkipBodyData()134*67e74705SXin Li ~SessionSkipBodyData() {
135*67e74705SXin Li //llvm::errs() << "RegionData: " << Skipped.size() << " - " << Skipped.getMemorySize() << "\n";
136*67e74705SXin Li }
137*67e74705SXin Li
copyTo(PPRegionSetTy & Set)138*67e74705SXin Li void copyTo(PPRegionSetTy &Set) {
139*67e74705SXin Li llvm::MutexGuard MG(Mux);
140*67e74705SXin Li Set = ParsedRegions;
141*67e74705SXin Li }
142*67e74705SXin Li
update(ArrayRef<PPRegion> Regions)143*67e74705SXin Li void update(ArrayRef<PPRegion> Regions) {
144*67e74705SXin Li llvm::MutexGuard MG(Mux);
145*67e74705SXin Li ParsedRegions.insert(Regions.begin(), Regions.end());
146*67e74705SXin Li }
147*67e74705SXin Li };
148*67e74705SXin Li
149*67e74705SXin Li class TUSkipBodyControl {
150*67e74705SXin Li SessionSkipBodyData &SessionData;
151*67e74705SXin Li PPConditionalDirectiveRecord &PPRec;
152*67e74705SXin Li Preprocessor &PP;
153*67e74705SXin Li
154*67e74705SXin Li PPRegionSetTy ParsedRegions;
155*67e74705SXin Li SmallVector<PPRegion, 32> NewParsedRegions;
156*67e74705SXin Li PPRegion LastRegion;
157*67e74705SXin Li bool LastIsParsed;
158*67e74705SXin Li
159*67e74705SXin Li public:
TUSkipBodyControl(SessionSkipBodyData & sessionData,PPConditionalDirectiveRecord & ppRec,Preprocessor & pp)160*67e74705SXin Li TUSkipBodyControl(SessionSkipBodyData &sessionData,
161*67e74705SXin Li PPConditionalDirectiveRecord &ppRec,
162*67e74705SXin Li Preprocessor &pp)
163*67e74705SXin Li : SessionData(sessionData), PPRec(ppRec), PP(pp) {
164*67e74705SXin Li SessionData.copyTo(ParsedRegions);
165*67e74705SXin Li }
166*67e74705SXin Li
isParsed(SourceLocation Loc,FileID FID,const FileEntry * FE)167*67e74705SXin Li bool isParsed(SourceLocation Loc, FileID FID, const FileEntry *FE) {
168*67e74705SXin Li PPRegion region = getRegion(Loc, FID, FE);
169*67e74705SXin Li if (region.isInvalid())
170*67e74705SXin Li return false;
171*67e74705SXin Li
172*67e74705SXin Li // Check common case, consecutive functions in the same region.
173*67e74705SXin Li if (LastRegion == region)
174*67e74705SXin Li return LastIsParsed;
175*67e74705SXin Li
176*67e74705SXin Li LastRegion = region;
177*67e74705SXin Li LastIsParsed = ParsedRegions.count(region);
178*67e74705SXin Li if (!LastIsParsed)
179*67e74705SXin Li NewParsedRegions.push_back(region);
180*67e74705SXin Li return LastIsParsed;
181*67e74705SXin Li }
182*67e74705SXin Li
finished()183*67e74705SXin Li void finished() {
184*67e74705SXin Li SessionData.update(NewParsedRegions);
185*67e74705SXin Li }
186*67e74705SXin Li
187*67e74705SXin Li private:
getRegion(SourceLocation Loc,FileID FID,const FileEntry * FE)188*67e74705SXin Li PPRegion getRegion(SourceLocation Loc, FileID FID, const FileEntry *FE) {
189*67e74705SXin Li SourceLocation RegionLoc = PPRec.findConditionalDirectiveRegionLoc(Loc);
190*67e74705SXin Li if (RegionLoc.isInvalid()) {
191*67e74705SXin Li if (isParsedOnceInclude(FE)) {
192*67e74705SXin Li const llvm::sys::fs::UniqueID &ID = FE->getUniqueID();
193*67e74705SXin Li return PPRegion(ID, 0, FE->getModificationTime());
194*67e74705SXin Li }
195*67e74705SXin Li return PPRegion();
196*67e74705SXin Li }
197*67e74705SXin Li
198*67e74705SXin Li const SourceManager &SM = PPRec.getSourceManager();
199*67e74705SXin Li assert(RegionLoc.isFileID());
200*67e74705SXin Li FileID RegionFID;
201*67e74705SXin Li unsigned RegionOffset;
202*67e74705SXin Li std::tie(RegionFID, RegionOffset) = SM.getDecomposedLoc(RegionLoc);
203*67e74705SXin Li
204*67e74705SXin Li if (RegionFID != FID) {
205*67e74705SXin Li if (isParsedOnceInclude(FE)) {
206*67e74705SXin Li const llvm::sys::fs::UniqueID &ID = FE->getUniqueID();
207*67e74705SXin Li return PPRegion(ID, 0, FE->getModificationTime());
208*67e74705SXin Li }
209*67e74705SXin Li return PPRegion();
210*67e74705SXin Li }
211*67e74705SXin Li
212*67e74705SXin Li const llvm::sys::fs::UniqueID &ID = FE->getUniqueID();
213*67e74705SXin Li return PPRegion(ID, RegionOffset, FE->getModificationTime());
214*67e74705SXin Li }
215*67e74705SXin Li
isParsedOnceInclude(const FileEntry * FE)216*67e74705SXin Li bool isParsedOnceInclude(const FileEntry *FE) {
217*67e74705SXin Li return PP.getHeaderSearchInfo().isFileMultipleIncludeGuarded(FE);
218*67e74705SXin Li }
219*67e74705SXin Li };
220*67e74705SXin Li
221*67e74705SXin Li //===----------------------------------------------------------------------===//
222*67e74705SXin Li // IndexPPCallbacks
223*67e74705SXin Li //===----------------------------------------------------------------------===//
224*67e74705SXin Li
225*67e74705SXin Li class IndexPPCallbacks : public PPCallbacks {
226*67e74705SXin Li Preprocessor &PP;
227*67e74705SXin Li CXIndexDataConsumer &DataConsumer;
228*67e74705SXin Li bool IsMainFileEntered;
229*67e74705SXin Li
230*67e74705SXin Li public:
IndexPPCallbacks(Preprocessor & PP,CXIndexDataConsumer & dataConsumer)231*67e74705SXin Li IndexPPCallbacks(Preprocessor &PP, CXIndexDataConsumer &dataConsumer)
232*67e74705SXin Li : PP(PP), DataConsumer(dataConsumer), IsMainFileEntered(false) { }
233*67e74705SXin Li
FileChanged(SourceLocation Loc,FileChangeReason Reason,SrcMgr::CharacteristicKind FileType,FileID PrevFID)234*67e74705SXin Li void FileChanged(SourceLocation Loc, FileChangeReason Reason,
235*67e74705SXin Li SrcMgr::CharacteristicKind FileType, FileID PrevFID) override {
236*67e74705SXin Li if (IsMainFileEntered)
237*67e74705SXin Li return;
238*67e74705SXin Li
239*67e74705SXin Li SourceManager &SM = PP.getSourceManager();
240*67e74705SXin Li SourceLocation MainFileLoc = SM.getLocForStartOfFile(SM.getMainFileID());
241*67e74705SXin Li
242*67e74705SXin Li if (Loc == MainFileLoc && Reason == PPCallbacks::EnterFile) {
243*67e74705SXin Li IsMainFileEntered = true;
244*67e74705SXin Li DataConsumer.enteredMainFile(SM.getFileEntryForID(SM.getMainFileID()));
245*67e74705SXin Li }
246*67e74705SXin Li }
247*67e74705SXin Li
InclusionDirective(SourceLocation HashLoc,const Token & IncludeTok,StringRef FileName,bool IsAngled,CharSourceRange FilenameRange,const FileEntry * File,StringRef SearchPath,StringRef RelativePath,const Module * Imported)248*67e74705SXin Li void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok,
249*67e74705SXin Li StringRef FileName, bool IsAngled,
250*67e74705SXin Li CharSourceRange FilenameRange, const FileEntry *File,
251*67e74705SXin Li StringRef SearchPath, StringRef RelativePath,
252*67e74705SXin Li const Module *Imported) override {
253*67e74705SXin Li bool isImport = (IncludeTok.is(tok::identifier) &&
254*67e74705SXin Li IncludeTok.getIdentifierInfo()->getPPKeywordID() == tok::pp_import);
255*67e74705SXin Li DataConsumer.ppIncludedFile(HashLoc, FileName, File, isImport, IsAngled,
256*67e74705SXin Li Imported);
257*67e74705SXin Li }
258*67e74705SXin Li
259*67e74705SXin Li /// MacroDefined - This hook is called whenever a macro definition is seen.
MacroDefined(const Token & Id,const MacroDirective * MD)260*67e74705SXin Li void MacroDefined(const Token &Id, const MacroDirective *MD) override {}
261*67e74705SXin Li
262*67e74705SXin Li /// MacroUndefined - This hook is called whenever a macro #undef is seen.
263*67e74705SXin Li /// MI is released immediately following this callback.
MacroUndefined(const Token & MacroNameTok,const MacroDefinition & MD)264*67e74705SXin Li void MacroUndefined(const Token &MacroNameTok,
265*67e74705SXin Li const MacroDefinition &MD) override {}
266*67e74705SXin Li
267*67e74705SXin Li /// MacroExpands - This is called by when a macro invocation is found.
MacroExpands(const Token & MacroNameTok,const MacroDefinition & MD,SourceRange Range,const MacroArgs * Args)268*67e74705SXin Li void MacroExpands(const Token &MacroNameTok, const MacroDefinition &MD,
269*67e74705SXin Li SourceRange Range, const MacroArgs *Args) override {}
270*67e74705SXin Li
271*67e74705SXin Li /// SourceRangeSkipped - This hook is called when a source range is skipped.
272*67e74705SXin Li /// \param Range The SourceRange that was skipped. The range begins at the
273*67e74705SXin Li /// #if/#else directive and ends after the #endif/#else directive.
SourceRangeSkipped(SourceRange Range)274*67e74705SXin Li void SourceRangeSkipped(SourceRange Range) override {}
275*67e74705SXin Li };
276*67e74705SXin Li
277*67e74705SXin Li //===----------------------------------------------------------------------===//
278*67e74705SXin Li // IndexingConsumer
279*67e74705SXin Li //===----------------------------------------------------------------------===//
280*67e74705SXin Li
281*67e74705SXin Li class IndexingConsumer : public ASTConsumer {
282*67e74705SXin Li CXIndexDataConsumer &DataConsumer;
283*67e74705SXin Li TUSkipBodyControl *SKCtrl;
284*67e74705SXin Li
285*67e74705SXin Li public:
IndexingConsumer(CXIndexDataConsumer & dataConsumer,TUSkipBodyControl * skCtrl)286*67e74705SXin Li IndexingConsumer(CXIndexDataConsumer &dataConsumer, TUSkipBodyControl *skCtrl)
287*67e74705SXin Li : DataConsumer(dataConsumer), SKCtrl(skCtrl) { }
288*67e74705SXin Li
289*67e74705SXin Li // ASTConsumer Implementation
290*67e74705SXin Li
Initialize(ASTContext & Context)291*67e74705SXin Li void Initialize(ASTContext &Context) override {
292*67e74705SXin Li DataConsumer.setASTContext(Context);
293*67e74705SXin Li DataConsumer.startedTranslationUnit();
294*67e74705SXin Li }
295*67e74705SXin Li
HandleTranslationUnit(ASTContext & Ctx)296*67e74705SXin Li void HandleTranslationUnit(ASTContext &Ctx) override {
297*67e74705SXin Li if (SKCtrl)
298*67e74705SXin Li SKCtrl->finished();
299*67e74705SXin Li }
300*67e74705SXin Li
HandleTopLevelDecl(DeclGroupRef DG)301*67e74705SXin Li bool HandleTopLevelDecl(DeclGroupRef DG) override {
302*67e74705SXin Li return !DataConsumer.shouldAbort();
303*67e74705SXin Li }
304*67e74705SXin Li
shouldSkipFunctionBody(Decl * D)305*67e74705SXin Li bool shouldSkipFunctionBody(Decl *D) override {
306*67e74705SXin Li if (!SKCtrl) {
307*67e74705SXin Li // Always skip bodies.
308*67e74705SXin Li return true;
309*67e74705SXin Li }
310*67e74705SXin Li
311*67e74705SXin Li const SourceManager &SM = DataConsumer.getASTContext().getSourceManager();
312*67e74705SXin Li SourceLocation Loc = D->getLocation();
313*67e74705SXin Li if (Loc.isMacroID())
314*67e74705SXin Li return false;
315*67e74705SXin Li if (SM.isInSystemHeader(Loc))
316*67e74705SXin Li return true; // always skip bodies from system headers.
317*67e74705SXin Li
318*67e74705SXin Li FileID FID;
319*67e74705SXin Li unsigned Offset;
320*67e74705SXin Li std::tie(FID, Offset) = SM.getDecomposedLoc(Loc);
321*67e74705SXin Li // Don't skip bodies from main files; this may be revisited.
322*67e74705SXin Li if (SM.getMainFileID() == FID)
323*67e74705SXin Li return false;
324*67e74705SXin Li const FileEntry *FE = SM.getFileEntryForID(FID);
325*67e74705SXin Li if (!FE)
326*67e74705SXin Li return false;
327*67e74705SXin Li
328*67e74705SXin Li return SKCtrl->isParsed(Loc, FID, FE);
329*67e74705SXin Li }
330*67e74705SXin Li };
331*67e74705SXin Li
332*67e74705SXin Li //===----------------------------------------------------------------------===//
333*67e74705SXin Li // CaptureDiagnosticConsumer
334*67e74705SXin Li //===----------------------------------------------------------------------===//
335*67e74705SXin Li
336*67e74705SXin Li class CaptureDiagnosticConsumer : public DiagnosticConsumer {
337*67e74705SXin Li SmallVector<StoredDiagnostic, 4> Errors;
338*67e74705SXin Li public:
339*67e74705SXin Li
HandleDiagnostic(DiagnosticsEngine::Level level,const Diagnostic & Info)340*67e74705SXin Li void HandleDiagnostic(DiagnosticsEngine::Level level,
341*67e74705SXin Li const Diagnostic &Info) override {
342*67e74705SXin Li if (level >= DiagnosticsEngine::Error)
343*67e74705SXin Li Errors.push_back(StoredDiagnostic(level, Info));
344*67e74705SXin Li }
345*67e74705SXin Li };
346*67e74705SXin Li
347*67e74705SXin Li //===----------------------------------------------------------------------===//
348*67e74705SXin Li // IndexingFrontendAction
349*67e74705SXin Li //===----------------------------------------------------------------------===//
350*67e74705SXin Li
351*67e74705SXin Li class IndexingFrontendAction : public ASTFrontendAction {
352*67e74705SXin Li std::shared_ptr<CXIndexDataConsumer> DataConsumer;
353*67e74705SXin Li
354*67e74705SXin Li SessionSkipBodyData *SKData;
355*67e74705SXin Li std::unique_ptr<TUSkipBodyControl> SKCtrl;
356*67e74705SXin Li
357*67e74705SXin Li public:
IndexingFrontendAction(std::shared_ptr<CXIndexDataConsumer> dataConsumer,SessionSkipBodyData * skData)358*67e74705SXin Li IndexingFrontendAction(std::shared_ptr<CXIndexDataConsumer> dataConsumer,
359*67e74705SXin Li SessionSkipBodyData *skData)
360*67e74705SXin Li : DataConsumer(std::move(dataConsumer)), SKData(skData) {}
361*67e74705SXin Li
CreateASTConsumer(CompilerInstance & CI,StringRef InFile)362*67e74705SXin Li std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
363*67e74705SXin Li StringRef InFile) override {
364*67e74705SXin Li PreprocessorOptions &PPOpts = CI.getPreprocessorOpts();
365*67e74705SXin Li
366*67e74705SXin Li if (!PPOpts.ImplicitPCHInclude.empty()) {
367*67e74705SXin Li DataConsumer->importedPCH(
368*67e74705SXin Li CI.getFileManager().getFile(PPOpts.ImplicitPCHInclude));
369*67e74705SXin Li }
370*67e74705SXin Li
371*67e74705SXin Li DataConsumer->setASTContext(CI.getASTContext());
372*67e74705SXin Li Preprocessor &PP = CI.getPreprocessor();
373*67e74705SXin Li PP.addPPCallbacks(llvm::make_unique<IndexPPCallbacks>(PP, *DataConsumer));
374*67e74705SXin Li DataConsumer->setPreprocessor(PP);
375*67e74705SXin Li
376*67e74705SXin Li if (SKData) {
377*67e74705SXin Li auto *PPRec = new PPConditionalDirectiveRecord(PP.getSourceManager());
378*67e74705SXin Li PP.addPPCallbacks(std::unique_ptr<PPCallbacks>(PPRec));
379*67e74705SXin Li SKCtrl = llvm::make_unique<TUSkipBodyControl>(*SKData, *PPRec, PP);
380*67e74705SXin Li }
381*67e74705SXin Li
382*67e74705SXin Li return llvm::make_unique<IndexingConsumer>(*DataConsumer, SKCtrl.get());
383*67e74705SXin Li }
384*67e74705SXin Li
getTranslationUnitKind()385*67e74705SXin Li TranslationUnitKind getTranslationUnitKind() override {
386*67e74705SXin Li if (DataConsumer->shouldIndexImplicitTemplateInsts())
387*67e74705SXin Li return TU_Complete;
388*67e74705SXin Li else
389*67e74705SXin Li return TU_Prefix;
390*67e74705SXin Li }
hasCodeCompletionSupport() const391*67e74705SXin Li bool hasCodeCompletionSupport() const override { return false; }
392*67e74705SXin Li };
393*67e74705SXin Li
394*67e74705SXin Li //===----------------------------------------------------------------------===//
395*67e74705SXin Li // clang_indexSourceFileUnit Implementation
396*67e74705SXin Li //===----------------------------------------------------------------------===//
397*67e74705SXin Li
getIndexingOptionsFromCXOptions(unsigned index_options)398*67e74705SXin Li static IndexingOptions getIndexingOptionsFromCXOptions(unsigned index_options) {
399*67e74705SXin Li IndexingOptions IdxOpts;
400*67e74705SXin Li if (index_options & CXIndexOpt_IndexFunctionLocalSymbols)
401*67e74705SXin Li IdxOpts.IndexFunctionLocals = true;
402*67e74705SXin Li return IdxOpts;
403*67e74705SXin Li }
404*67e74705SXin Li
405*67e74705SXin Li struct IndexSessionData {
406*67e74705SXin Li CXIndex CIdx;
407*67e74705SXin Li std::unique_ptr<SessionSkipBodyData> SkipBodyData;
408*67e74705SXin Li
IndexSessionData__anon757d5f4d0211::IndexSessionData409*67e74705SXin Li explicit IndexSessionData(CXIndex cIdx)
410*67e74705SXin Li : CIdx(cIdx), SkipBodyData(new SessionSkipBodyData) {}
411*67e74705SXin Li };
412*67e74705SXin Li
413*67e74705SXin Li } // anonymous namespace
414*67e74705SXin Li
clang_indexSourceFile_Impl(CXIndexAction cxIdxAction,CXClientData client_data,IndexerCallbacks * client_index_callbacks,unsigned index_callbacks_size,unsigned index_options,const char * source_filename,const char * const * command_line_args,int num_command_line_args,ArrayRef<CXUnsavedFile> unsaved_files,CXTranslationUnit * out_TU,unsigned TU_options)415*67e74705SXin Li static CXErrorCode clang_indexSourceFile_Impl(
416*67e74705SXin Li CXIndexAction cxIdxAction, CXClientData client_data,
417*67e74705SXin Li IndexerCallbacks *client_index_callbacks, unsigned index_callbacks_size,
418*67e74705SXin Li unsigned index_options, const char *source_filename,
419*67e74705SXin Li const char *const *command_line_args, int num_command_line_args,
420*67e74705SXin Li ArrayRef<CXUnsavedFile> unsaved_files, CXTranslationUnit *out_TU,
421*67e74705SXin Li unsigned TU_options) {
422*67e74705SXin Li if (out_TU)
423*67e74705SXin Li *out_TU = nullptr;
424*67e74705SXin Li bool requestedToGetTU = (out_TU != nullptr);
425*67e74705SXin Li
426*67e74705SXin Li if (!cxIdxAction) {
427*67e74705SXin Li return CXError_InvalidArguments;
428*67e74705SXin Li }
429*67e74705SXin Li if (!client_index_callbacks || index_callbacks_size == 0) {
430*67e74705SXin Li return CXError_InvalidArguments;
431*67e74705SXin Li }
432*67e74705SXin Li
433*67e74705SXin Li IndexerCallbacks CB;
434*67e74705SXin Li memset(&CB, 0, sizeof(CB));
435*67e74705SXin Li unsigned ClientCBSize = index_callbacks_size < sizeof(CB)
436*67e74705SXin Li ? index_callbacks_size : sizeof(CB);
437*67e74705SXin Li memcpy(&CB, client_index_callbacks, ClientCBSize);
438*67e74705SXin Li
439*67e74705SXin Li IndexSessionData *IdxSession = static_cast<IndexSessionData *>(cxIdxAction);
440*67e74705SXin Li CIndexer *CXXIdx = static_cast<CIndexer *>(IdxSession->CIdx);
441*67e74705SXin Li
442*67e74705SXin Li if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
443*67e74705SXin Li setThreadBackgroundPriority();
444*67e74705SXin Li
445*67e74705SXin Li bool CaptureDiagnostics = !Logger::isLoggingEnabled();
446*67e74705SXin Li
447*67e74705SXin Li CaptureDiagnosticConsumer *CaptureDiag = nullptr;
448*67e74705SXin Li if (CaptureDiagnostics)
449*67e74705SXin Li CaptureDiag = new CaptureDiagnosticConsumer();
450*67e74705SXin Li
451*67e74705SXin Li // Configure the diagnostics.
452*67e74705SXin Li IntrusiveRefCntPtr<DiagnosticsEngine>
453*67e74705SXin Li Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions,
454*67e74705SXin Li CaptureDiag,
455*67e74705SXin Li /*ShouldOwnClient=*/true));
456*67e74705SXin Li
457*67e74705SXin Li // Recover resources if we crash before exiting this function.
458*67e74705SXin Li llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
459*67e74705SXin Li llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
460*67e74705SXin Li DiagCleanup(Diags.get());
461*67e74705SXin Li
462*67e74705SXin Li std::unique_ptr<std::vector<const char *>> Args(
463*67e74705SXin Li new std::vector<const char *>());
464*67e74705SXin Li
465*67e74705SXin Li // Recover resources if we crash before exiting this method.
466*67e74705SXin Li llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
467*67e74705SXin Li ArgsCleanup(Args.get());
468*67e74705SXin Li
469*67e74705SXin Li Args->insert(Args->end(), command_line_args,
470*67e74705SXin Li command_line_args + num_command_line_args);
471*67e74705SXin Li
472*67e74705SXin Li // The 'source_filename' argument is optional. If the caller does not
473*67e74705SXin Li // specify it then it is assumed that the source file is specified
474*67e74705SXin Li // in the actual argument list.
475*67e74705SXin Li // Put the source file after command_line_args otherwise if '-x' flag is
476*67e74705SXin Li // present it will be unused.
477*67e74705SXin Li if (source_filename)
478*67e74705SXin Li Args->push_back(source_filename);
479*67e74705SXin Li
480*67e74705SXin Li IntrusiveRefCntPtr<CompilerInvocation>
481*67e74705SXin Li CInvok(createInvocationFromCommandLine(*Args, Diags));
482*67e74705SXin Li
483*67e74705SXin Li if (!CInvok)
484*67e74705SXin Li return CXError_Failure;
485*67e74705SXin Li
486*67e74705SXin Li // Recover resources if we crash before exiting this function.
487*67e74705SXin Li llvm::CrashRecoveryContextCleanupRegistrar<CompilerInvocation,
488*67e74705SXin Li llvm::CrashRecoveryContextReleaseRefCleanup<CompilerInvocation> >
489*67e74705SXin Li CInvokCleanup(CInvok.get());
490*67e74705SXin Li
491*67e74705SXin Li if (CInvok->getFrontendOpts().Inputs.empty())
492*67e74705SXin Li return CXError_Failure;
493*67e74705SXin Li
494*67e74705SXin Li typedef SmallVector<std::unique_ptr<llvm::MemoryBuffer>, 8> MemBufferOwner;
495*67e74705SXin Li std::unique_ptr<MemBufferOwner> BufOwner(new MemBufferOwner);
496*67e74705SXin Li
497*67e74705SXin Li // Recover resources if we crash before exiting this method.
498*67e74705SXin Li llvm::CrashRecoveryContextCleanupRegistrar<MemBufferOwner> BufOwnerCleanup(
499*67e74705SXin Li BufOwner.get());
500*67e74705SXin Li
501*67e74705SXin Li for (auto &UF : unsaved_files) {
502*67e74705SXin Li std::unique_ptr<llvm::MemoryBuffer> MB =
503*67e74705SXin Li llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
504*67e74705SXin Li CInvok->getPreprocessorOpts().addRemappedFile(UF.Filename, MB.get());
505*67e74705SXin Li BufOwner->push_back(std::move(MB));
506*67e74705SXin Li }
507*67e74705SXin Li
508*67e74705SXin Li // Since libclang is primarily used by batch tools dealing with
509*67e74705SXin Li // (often very broken) source code, where spell-checking can have a
510*67e74705SXin Li // significant negative impact on performance (particularly when
511*67e74705SXin Li // precompiled headers are involved), we disable it.
512*67e74705SXin Li CInvok->getLangOpts()->SpellChecking = false;
513*67e74705SXin Li
514*67e74705SXin Li if (index_options & CXIndexOpt_SuppressWarnings)
515*67e74705SXin Li CInvok->getDiagnosticOpts().IgnoreWarnings = true;
516*67e74705SXin Li
517*67e74705SXin Li // Make sure to use the raw module format.
518*67e74705SXin Li CInvok->getHeaderSearchOpts().ModuleFormat =
519*67e74705SXin Li CXXIdx->getPCHContainerOperations()->getRawReader().getFormat();
520*67e74705SXin Li
521*67e74705SXin Li ASTUnit *Unit = ASTUnit::create(CInvok.get(), Diags, CaptureDiagnostics,
522*67e74705SXin Li /*UserFilesAreVolatile=*/true);
523*67e74705SXin Li if (!Unit)
524*67e74705SXin Li return CXError_InvalidArguments;
525*67e74705SXin Li
526*67e74705SXin Li std::unique_ptr<CXTUOwner> CXTU(
527*67e74705SXin Li new CXTUOwner(MakeCXTranslationUnit(CXXIdx, Unit)));
528*67e74705SXin Li
529*67e74705SXin Li // Recover resources if we crash before exiting this method.
530*67e74705SXin Li llvm::CrashRecoveryContextCleanupRegistrar<CXTUOwner>
531*67e74705SXin Li CXTUCleanup(CXTU.get());
532*67e74705SXin Li
533*67e74705SXin Li // Enable the skip-parsed-bodies optimization only for C++; this may be
534*67e74705SXin Li // revisited.
535*67e74705SXin Li bool SkipBodies = (index_options & CXIndexOpt_SkipParsedBodiesInSession) &&
536*67e74705SXin Li CInvok->getLangOpts()->CPlusPlus;
537*67e74705SXin Li if (SkipBodies)
538*67e74705SXin Li CInvok->getFrontendOpts().SkipFunctionBodies = true;
539*67e74705SXin Li
540*67e74705SXin Li auto DataConsumer =
541*67e74705SXin Li std::make_shared<CXIndexDataConsumer>(client_data, CB, index_options,
542*67e74705SXin Li CXTU->getTU());
543*67e74705SXin Li auto InterAction = llvm::make_unique<IndexingFrontendAction>(DataConsumer,
544*67e74705SXin Li SkipBodies ? IdxSession->SkipBodyData.get() : nullptr);
545*67e74705SXin Li std::unique_ptr<FrontendAction> IndexAction;
546*67e74705SXin Li IndexAction = createIndexingAction(DataConsumer,
547*67e74705SXin Li getIndexingOptionsFromCXOptions(index_options),
548*67e74705SXin Li std::move(InterAction));
549*67e74705SXin Li
550*67e74705SXin Li // Recover resources if we crash before exiting this method.
551*67e74705SXin Li llvm::CrashRecoveryContextCleanupRegistrar<FrontendAction>
552*67e74705SXin Li IndexActionCleanup(IndexAction.get());
553*67e74705SXin Li
554*67e74705SXin Li bool Persistent = requestedToGetTU;
555*67e74705SXin Li bool OnlyLocalDecls = false;
556*67e74705SXin Li bool PrecompilePreamble = false;
557*67e74705SXin Li bool CreatePreambleOnFirstParse = false;
558*67e74705SXin Li bool CacheCodeCompletionResults = false;
559*67e74705SXin Li PreprocessorOptions &PPOpts = CInvok->getPreprocessorOpts();
560*67e74705SXin Li PPOpts.AllowPCHWithCompilerErrors = true;
561*67e74705SXin Li
562*67e74705SXin Li if (requestedToGetTU) {
563*67e74705SXin Li OnlyLocalDecls = CXXIdx->getOnlyLocalDecls();
564*67e74705SXin Li PrecompilePreamble = TU_options & CXTranslationUnit_PrecompiledPreamble;
565*67e74705SXin Li CreatePreambleOnFirstParse =
566*67e74705SXin Li TU_options & CXTranslationUnit_CreatePreambleOnFirstParse;
567*67e74705SXin Li // FIXME: Add a flag for modules.
568*67e74705SXin Li CacheCodeCompletionResults
569*67e74705SXin Li = TU_options & CXTranslationUnit_CacheCompletionResults;
570*67e74705SXin Li }
571*67e74705SXin Li
572*67e74705SXin Li if (TU_options & CXTranslationUnit_DetailedPreprocessingRecord) {
573*67e74705SXin Li PPOpts.DetailedRecord = true;
574*67e74705SXin Li }
575*67e74705SXin Li
576*67e74705SXin Li if (!requestedToGetTU && !CInvok->getLangOpts()->Modules)
577*67e74705SXin Li PPOpts.DetailedRecord = false;
578*67e74705SXin Li
579*67e74705SXin Li // Unless the user specified that they want the preamble on the first parse
580*67e74705SXin Li // set it up to be created on the first reparse. This makes the first parse
581*67e74705SXin Li // faster, trading for a slower (first) reparse.
582*67e74705SXin Li unsigned PrecompilePreambleAfterNParses =
583*67e74705SXin Li !PrecompilePreamble ? 0 : 2 - CreatePreambleOnFirstParse;
584*67e74705SXin Li DiagnosticErrorTrap DiagTrap(*Diags);
585*67e74705SXin Li bool Success = ASTUnit::LoadFromCompilerInvocationAction(
586*67e74705SXin Li CInvok.get(), CXXIdx->getPCHContainerOperations(), Diags,
587*67e74705SXin Li IndexAction.get(), Unit, Persistent, CXXIdx->getClangResourcesPath(),
588*67e74705SXin Li OnlyLocalDecls, CaptureDiagnostics, PrecompilePreambleAfterNParses,
589*67e74705SXin Li CacheCodeCompletionResults,
590*67e74705SXin Li /*IncludeBriefCommentsInCodeCompletion=*/false,
591*67e74705SXin Li /*UserFilesAreVolatile=*/true);
592*67e74705SXin Li if (DiagTrap.hasErrorOccurred() && CXXIdx->getDisplayDiagnostics())
593*67e74705SXin Li printDiagsToStderr(Unit);
594*67e74705SXin Li
595*67e74705SXin Li if (isASTReadError(Unit))
596*67e74705SXin Li return CXError_ASTReadError;
597*67e74705SXin Li
598*67e74705SXin Li if (!Success)
599*67e74705SXin Li return CXError_Failure;
600*67e74705SXin Li
601*67e74705SXin Li if (out_TU)
602*67e74705SXin Li *out_TU = CXTU->takeTU();
603*67e74705SXin Li
604*67e74705SXin Li return CXError_Success;
605*67e74705SXin Li }
606*67e74705SXin Li
607*67e74705SXin Li //===----------------------------------------------------------------------===//
608*67e74705SXin Li // clang_indexTranslationUnit Implementation
609*67e74705SXin Li //===----------------------------------------------------------------------===//
610*67e74705SXin Li
indexPreprocessingRecord(ASTUnit & Unit,CXIndexDataConsumer & IdxCtx)611*67e74705SXin Li static void indexPreprocessingRecord(ASTUnit &Unit, CXIndexDataConsumer &IdxCtx) {
612*67e74705SXin Li Preprocessor &PP = Unit.getPreprocessor();
613*67e74705SXin Li if (!PP.getPreprocessingRecord())
614*67e74705SXin Li return;
615*67e74705SXin Li
616*67e74705SXin Li // FIXME: Only deserialize inclusion directives.
617*67e74705SXin Li
618*67e74705SXin Li bool isModuleFile = Unit.isModuleFile();
619*67e74705SXin Li for (PreprocessedEntity *PPE : Unit.getLocalPreprocessingEntities()) {
620*67e74705SXin Li if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
621*67e74705SXin Li SourceLocation Loc = ID->getSourceRange().getBegin();
622*67e74705SXin Li // Modules have synthetic main files as input, give an invalid location
623*67e74705SXin Li // if the location points to such a file.
624*67e74705SXin Li if (isModuleFile && Unit.isInMainFileID(Loc))
625*67e74705SXin Li Loc = SourceLocation();
626*67e74705SXin Li IdxCtx.ppIncludedFile(Loc, ID->getFileName(),
627*67e74705SXin Li ID->getFile(),
628*67e74705SXin Li ID->getKind() == InclusionDirective::Import,
629*67e74705SXin Li !ID->wasInQuotes(), ID->importedModule());
630*67e74705SXin Li }
631*67e74705SXin Li }
632*67e74705SXin Li }
633*67e74705SXin Li
clang_indexTranslationUnit_Impl(CXIndexAction idxAction,CXClientData client_data,IndexerCallbacks * client_index_callbacks,unsigned index_callbacks_size,unsigned index_options,CXTranslationUnit TU)634*67e74705SXin Li static CXErrorCode clang_indexTranslationUnit_Impl(
635*67e74705SXin Li CXIndexAction idxAction, CXClientData client_data,
636*67e74705SXin Li IndexerCallbacks *client_index_callbacks, unsigned index_callbacks_size,
637*67e74705SXin Li unsigned index_options, CXTranslationUnit TU) {
638*67e74705SXin Li // Check arguments.
639*67e74705SXin Li if (isNotUsableTU(TU)) {
640*67e74705SXin Li LOG_BAD_TU(TU);
641*67e74705SXin Li return CXError_InvalidArguments;
642*67e74705SXin Li }
643*67e74705SXin Li if (!client_index_callbacks || index_callbacks_size == 0) {
644*67e74705SXin Li return CXError_InvalidArguments;
645*67e74705SXin Li }
646*67e74705SXin Li
647*67e74705SXin Li CIndexer *CXXIdx = TU->CIdx;
648*67e74705SXin Li if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
649*67e74705SXin Li setThreadBackgroundPriority();
650*67e74705SXin Li
651*67e74705SXin Li IndexerCallbacks CB;
652*67e74705SXin Li memset(&CB, 0, sizeof(CB));
653*67e74705SXin Li unsigned ClientCBSize = index_callbacks_size < sizeof(CB)
654*67e74705SXin Li ? index_callbacks_size : sizeof(CB);
655*67e74705SXin Li memcpy(&CB, client_index_callbacks, ClientCBSize);
656*67e74705SXin Li
657*67e74705SXin Li auto DataConsumer = std::make_shared<CXIndexDataConsumer>(client_data, CB,
658*67e74705SXin Li index_options, TU);
659*67e74705SXin Li
660*67e74705SXin Li ASTUnit *Unit = cxtu::getASTUnit(TU);
661*67e74705SXin Li if (!Unit)
662*67e74705SXin Li return CXError_Failure;
663*67e74705SXin Li
664*67e74705SXin Li ASTUnit::ConcurrencyCheck Check(*Unit);
665*67e74705SXin Li
666*67e74705SXin Li if (const FileEntry *PCHFile = Unit->getPCHFile())
667*67e74705SXin Li DataConsumer->importedPCH(PCHFile);
668*67e74705SXin Li
669*67e74705SXin Li FileManager &FileMgr = Unit->getFileManager();
670*67e74705SXin Li
671*67e74705SXin Li if (Unit->getOriginalSourceFileName().empty())
672*67e74705SXin Li DataConsumer->enteredMainFile(nullptr);
673*67e74705SXin Li else
674*67e74705SXin Li DataConsumer->enteredMainFile(FileMgr.getFile(Unit->getOriginalSourceFileName()));
675*67e74705SXin Li
676*67e74705SXin Li DataConsumer->setASTContext(Unit->getASTContext());
677*67e74705SXin Li DataConsumer->startedTranslationUnit();
678*67e74705SXin Li
679*67e74705SXin Li indexPreprocessingRecord(*Unit, *DataConsumer);
680*67e74705SXin Li indexASTUnit(*Unit, DataConsumer, getIndexingOptionsFromCXOptions(index_options));
681*67e74705SXin Li DataConsumer->indexDiagnostics();
682*67e74705SXin Li
683*67e74705SXin Li return CXError_Success;
684*67e74705SXin Li }
685*67e74705SXin Li
686*67e74705SXin Li //===----------------------------------------------------------------------===//
687*67e74705SXin Li // libclang public APIs.
688*67e74705SXin Li //===----------------------------------------------------------------------===//
689*67e74705SXin Li
690*67e74705SXin Li extern "C" {
691*67e74705SXin Li
clang_index_isEntityObjCContainerKind(CXIdxEntityKind K)692*67e74705SXin Li int clang_index_isEntityObjCContainerKind(CXIdxEntityKind K) {
693*67e74705SXin Li return CXIdxEntity_ObjCClass <= K && K <= CXIdxEntity_ObjCCategory;
694*67e74705SXin Li }
695*67e74705SXin Li
696*67e74705SXin Li const CXIdxObjCContainerDeclInfo *
clang_index_getObjCContainerDeclInfo(const CXIdxDeclInfo * DInfo)697*67e74705SXin Li clang_index_getObjCContainerDeclInfo(const CXIdxDeclInfo *DInfo) {
698*67e74705SXin Li if (!DInfo)
699*67e74705SXin Li return nullptr;
700*67e74705SXin Li
701*67e74705SXin Li const DeclInfo *DI = static_cast<const DeclInfo *>(DInfo);
702*67e74705SXin Li if (const ObjCContainerDeclInfo *
703*67e74705SXin Li ContInfo = dyn_cast<ObjCContainerDeclInfo>(DI))
704*67e74705SXin Li return &ContInfo->ObjCContDeclInfo;
705*67e74705SXin Li
706*67e74705SXin Li return nullptr;
707*67e74705SXin Li }
708*67e74705SXin Li
709*67e74705SXin Li const CXIdxObjCInterfaceDeclInfo *
clang_index_getObjCInterfaceDeclInfo(const CXIdxDeclInfo * DInfo)710*67e74705SXin Li clang_index_getObjCInterfaceDeclInfo(const CXIdxDeclInfo *DInfo) {
711*67e74705SXin Li if (!DInfo)
712*67e74705SXin Li return nullptr;
713*67e74705SXin Li
714*67e74705SXin Li const DeclInfo *DI = static_cast<const DeclInfo *>(DInfo);
715*67e74705SXin Li if (const ObjCInterfaceDeclInfo *
716*67e74705SXin Li InterInfo = dyn_cast<ObjCInterfaceDeclInfo>(DI))
717*67e74705SXin Li return &InterInfo->ObjCInterDeclInfo;
718*67e74705SXin Li
719*67e74705SXin Li return nullptr;
720*67e74705SXin Li }
721*67e74705SXin Li
722*67e74705SXin Li const CXIdxObjCCategoryDeclInfo *
clang_index_getObjCCategoryDeclInfo(const CXIdxDeclInfo * DInfo)723*67e74705SXin Li clang_index_getObjCCategoryDeclInfo(const CXIdxDeclInfo *DInfo){
724*67e74705SXin Li if (!DInfo)
725*67e74705SXin Li return nullptr;
726*67e74705SXin Li
727*67e74705SXin Li const DeclInfo *DI = static_cast<const DeclInfo *>(DInfo);
728*67e74705SXin Li if (const ObjCCategoryDeclInfo *
729*67e74705SXin Li CatInfo = dyn_cast<ObjCCategoryDeclInfo>(DI))
730*67e74705SXin Li return &CatInfo->ObjCCatDeclInfo;
731*67e74705SXin Li
732*67e74705SXin Li return nullptr;
733*67e74705SXin Li }
734*67e74705SXin Li
735*67e74705SXin Li const CXIdxObjCProtocolRefListInfo *
clang_index_getObjCProtocolRefListInfo(const CXIdxDeclInfo * DInfo)736*67e74705SXin Li clang_index_getObjCProtocolRefListInfo(const CXIdxDeclInfo *DInfo) {
737*67e74705SXin Li if (!DInfo)
738*67e74705SXin Li return nullptr;
739*67e74705SXin Li
740*67e74705SXin Li const DeclInfo *DI = static_cast<const DeclInfo *>(DInfo);
741*67e74705SXin Li
742*67e74705SXin Li if (const ObjCInterfaceDeclInfo *
743*67e74705SXin Li InterInfo = dyn_cast<ObjCInterfaceDeclInfo>(DI))
744*67e74705SXin Li return InterInfo->ObjCInterDeclInfo.protocols;
745*67e74705SXin Li
746*67e74705SXin Li if (const ObjCProtocolDeclInfo *
747*67e74705SXin Li ProtInfo = dyn_cast<ObjCProtocolDeclInfo>(DI))
748*67e74705SXin Li return &ProtInfo->ObjCProtoRefListInfo;
749*67e74705SXin Li
750*67e74705SXin Li if (const ObjCCategoryDeclInfo *CatInfo = dyn_cast<ObjCCategoryDeclInfo>(DI))
751*67e74705SXin Li return CatInfo->ObjCCatDeclInfo.protocols;
752*67e74705SXin Li
753*67e74705SXin Li return nullptr;
754*67e74705SXin Li }
755*67e74705SXin Li
756*67e74705SXin Li const CXIdxObjCPropertyDeclInfo *
clang_index_getObjCPropertyDeclInfo(const CXIdxDeclInfo * DInfo)757*67e74705SXin Li clang_index_getObjCPropertyDeclInfo(const CXIdxDeclInfo *DInfo) {
758*67e74705SXin Li if (!DInfo)
759*67e74705SXin Li return nullptr;
760*67e74705SXin Li
761*67e74705SXin Li const DeclInfo *DI = static_cast<const DeclInfo *>(DInfo);
762*67e74705SXin Li if (const ObjCPropertyDeclInfo *PropInfo = dyn_cast<ObjCPropertyDeclInfo>(DI))
763*67e74705SXin Li return &PropInfo->ObjCPropDeclInfo;
764*67e74705SXin Li
765*67e74705SXin Li return nullptr;
766*67e74705SXin Li }
767*67e74705SXin Li
768*67e74705SXin Li const CXIdxIBOutletCollectionAttrInfo *
clang_index_getIBOutletCollectionAttrInfo(const CXIdxAttrInfo * AInfo)769*67e74705SXin Li clang_index_getIBOutletCollectionAttrInfo(const CXIdxAttrInfo *AInfo) {
770*67e74705SXin Li if (!AInfo)
771*67e74705SXin Li return nullptr;
772*67e74705SXin Li
773*67e74705SXin Li const AttrInfo *DI = static_cast<const AttrInfo *>(AInfo);
774*67e74705SXin Li if (const IBOutletCollectionInfo *
775*67e74705SXin Li IBInfo = dyn_cast<IBOutletCollectionInfo>(DI))
776*67e74705SXin Li return &IBInfo->IBCollInfo;
777*67e74705SXin Li
778*67e74705SXin Li return nullptr;
779*67e74705SXin Li }
780*67e74705SXin Li
781*67e74705SXin Li const CXIdxCXXClassDeclInfo *
clang_index_getCXXClassDeclInfo(const CXIdxDeclInfo * DInfo)782*67e74705SXin Li clang_index_getCXXClassDeclInfo(const CXIdxDeclInfo *DInfo) {
783*67e74705SXin Li if (!DInfo)
784*67e74705SXin Li return nullptr;
785*67e74705SXin Li
786*67e74705SXin Li const DeclInfo *DI = static_cast<const DeclInfo *>(DInfo);
787*67e74705SXin Li if (const CXXClassDeclInfo *ClassInfo = dyn_cast<CXXClassDeclInfo>(DI))
788*67e74705SXin Li return &ClassInfo->CXXClassInfo;
789*67e74705SXin Li
790*67e74705SXin Li return nullptr;
791*67e74705SXin Li }
792*67e74705SXin Li
793*67e74705SXin Li CXIdxClientContainer
clang_index_getClientContainer(const CXIdxContainerInfo * info)794*67e74705SXin Li clang_index_getClientContainer(const CXIdxContainerInfo *info) {
795*67e74705SXin Li if (!info)
796*67e74705SXin Li return nullptr;
797*67e74705SXin Li const ContainerInfo *Container = static_cast<const ContainerInfo *>(info);
798*67e74705SXin Li return Container->IndexCtx->getClientContainerForDC(Container->DC);
799*67e74705SXin Li }
800*67e74705SXin Li
clang_index_setClientContainer(const CXIdxContainerInfo * info,CXIdxClientContainer client)801*67e74705SXin Li void clang_index_setClientContainer(const CXIdxContainerInfo *info,
802*67e74705SXin Li CXIdxClientContainer client) {
803*67e74705SXin Li if (!info)
804*67e74705SXin Li return;
805*67e74705SXin Li const ContainerInfo *Container = static_cast<const ContainerInfo *>(info);
806*67e74705SXin Li Container->IndexCtx->addContainerInMap(Container->DC, client);
807*67e74705SXin Li }
808*67e74705SXin Li
clang_index_getClientEntity(const CXIdxEntityInfo * info)809*67e74705SXin Li CXIdxClientEntity clang_index_getClientEntity(const CXIdxEntityInfo *info) {
810*67e74705SXin Li if (!info)
811*67e74705SXin Li return nullptr;
812*67e74705SXin Li const EntityInfo *Entity = static_cast<const EntityInfo *>(info);
813*67e74705SXin Li return Entity->IndexCtx->getClientEntity(Entity->Dcl);
814*67e74705SXin Li }
815*67e74705SXin Li
clang_index_setClientEntity(const CXIdxEntityInfo * info,CXIdxClientEntity client)816*67e74705SXin Li void clang_index_setClientEntity(const CXIdxEntityInfo *info,
817*67e74705SXin Li CXIdxClientEntity client) {
818*67e74705SXin Li if (!info)
819*67e74705SXin Li return;
820*67e74705SXin Li const EntityInfo *Entity = static_cast<const EntityInfo *>(info);
821*67e74705SXin Li Entity->IndexCtx->setClientEntity(Entity->Dcl, client);
822*67e74705SXin Li }
823*67e74705SXin Li
clang_IndexAction_create(CXIndex CIdx)824*67e74705SXin Li CXIndexAction clang_IndexAction_create(CXIndex CIdx) {
825*67e74705SXin Li return new IndexSessionData(CIdx);
826*67e74705SXin Li }
827*67e74705SXin Li
clang_IndexAction_dispose(CXIndexAction idxAction)828*67e74705SXin Li void clang_IndexAction_dispose(CXIndexAction idxAction) {
829*67e74705SXin Li if (idxAction)
830*67e74705SXin Li delete static_cast<IndexSessionData *>(idxAction);
831*67e74705SXin Li }
832*67e74705SXin Li
clang_indexSourceFile(CXIndexAction idxAction,CXClientData client_data,IndexerCallbacks * index_callbacks,unsigned index_callbacks_size,unsigned index_options,const char * source_filename,const char * const * command_line_args,int num_command_line_args,struct CXUnsavedFile * unsaved_files,unsigned num_unsaved_files,CXTranslationUnit * out_TU,unsigned TU_options)833*67e74705SXin Li int clang_indexSourceFile(CXIndexAction idxAction,
834*67e74705SXin Li CXClientData client_data,
835*67e74705SXin Li IndexerCallbacks *index_callbacks,
836*67e74705SXin Li unsigned index_callbacks_size,
837*67e74705SXin Li unsigned index_options,
838*67e74705SXin Li const char *source_filename,
839*67e74705SXin Li const char * const *command_line_args,
840*67e74705SXin Li int num_command_line_args,
841*67e74705SXin Li struct CXUnsavedFile *unsaved_files,
842*67e74705SXin Li unsigned num_unsaved_files,
843*67e74705SXin Li CXTranslationUnit *out_TU,
844*67e74705SXin Li unsigned TU_options) {
845*67e74705SXin Li SmallVector<const char *, 4> Args;
846*67e74705SXin Li Args.push_back("clang");
847*67e74705SXin Li Args.append(command_line_args, command_line_args + num_command_line_args);
848*67e74705SXin Li return clang_indexSourceFileFullArgv(
849*67e74705SXin Li idxAction, client_data, index_callbacks, index_callbacks_size,
850*67e74705SXin Li index_options, source_filename, Args.data(), Args.size(), unsaved_files,
851*67e74705SXin Li num_unsaved_files, out_TU, TU_options);
852*67e74705SXin Li }
853*67e74705SXin Li
clang_indexSourceFileFullArgv(CXIndexAction idxAction,CXClientData client_data,IndexerCallbacks * index_callbacks,unsigned index_callbacks_size,unsigned index_options,const char * source_filename,const char * const * command_line_args,int num_command_line_args,struct CXUnsavedFile * unsaved_files,unsigned num_unsaved_files,CXTranslationUnit * out_TU,unsigned TU_options)854*67e74705SXin Li int clang_indexSourceFileFullArgv(
855*67e74705SXin Li CXIndexAction idxAction, CXClientData client_data,
856*67e74705SXin Li IndexerCallbacks *index_callbacks, unsigned index_callbacks_size,
857*67e74705SXin Li unsigned index_options, const char *source_filename,
858*67e74705SXin Li const char *const *command_line_args, int num_command_line_args,
859*67e74705SXin Li struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
860*67e74705SXin Li CXTranslationUnit *out_TU, unsigned TU_options) {
861*67e74705SXin Li LOG_FUNC_SECTION {
862*67e74705SXin Li *Log << source_filename << ": ";
863*67e74705SXin Li for (int i = 0; i != num_command_line_args; ++i)
864*67e74705SXin Li *Log << command_line_args[i] << " ";
865*67e74705SXin Li }
866*67e74705SXin Li
867*67e74705SXin Li if (num_unsaved_files && !unsaved_files)
868*67e74705SXin Li return CXError_InvalidArguments;
869*67e74705SXin Li
870*67e74705SXin Li CXErrorCode result = CXError_Failure;
871*67e74705SXin Li auto IndexSourceFileImpl = [=, &result]() {
872*67e74705SXin Li result = clang_indexSourceFile_Impl(
873*67e74705SXin Li idxAction, client_data, index_callbacks, index_callbacks_size,
874*67e74705SXin Li index_options, source_filename, command_line_args,
875*67e74705SXin Li num_command_line_args,
876*67e74705SXin Li llvm::makeArrayRef(unsaved_files, num_unsaved_files), out_TU,
877*67e74705SXin Li TU_options);
878*67e74705SXin Li };
879*67e74705SXin Li
880*67e74705SXin Li if (getenv("LIBCLANG_NOTHREADS")) {
881*67e74705SXin Li IndexSourceFileImpl();
882*67e74705SXin Li return result;
883*67e74705SXin Li }
884*67e74705SXin Li
885*67e74705SXin Li llvm::CrashRecoveryContext CRC;
886*67e74705SXin Li
887*67e74705SXin Li if (!RunSafely(CRC, IndexSourceFileImpl)) {
888*67e74705SXin Li fprintf(stderr, "libclang: crash detected during indexing source file: {\n");
889*67e74705SXin Li fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
890*67e74705SXin Li fprintf(stderr, " 'command_line_args' : [");
891*67e74705SXin Li for (int i = 0; i != num_command_line_args; ++i) {
892*67e74705SXin Li if (i)
893*67e74705SXin Li fprintf(stderr, ", ");
894*67e74705SXin Li fprintf(stderr, "'%s'", command_line_args[i]);
895*67e74705SXin Li }
896*67e74705SXin Li fprintf(stderr, "],\n");
897*67e74705SXin Li fprintf(stderr, " 'unsaved_files' : [");
898*67e74705SXin Li for (unsigned i = 0; i != num_unsaved_files; ++i) {
899*67e74705SXin Li if (i)
900*67e74705SXin Li fprintf(stderr, ", ");
901*67e74705SXin Li fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
902*67e74705SXin Li unsaved_files[i].Length);
903*67e74705SXin Li }
904*67e74705SXin Li fprintf(stderr, "],\n");
905*67e74705SXin Li fprintf(stderr, " 'options' : %d,\n", TU_options);
906*67e74705SXin Li fprintf(stderr, "}\n");
907*67e74705SXin Li
908*67e74705SXin Li return 1;
909*67e74705SXin Li } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
910*67e74705SXin Li if (out_TU)
911*67e74705SXin Li PrintLibclangResourceUsage(*out_TU);
912*67e74705SXin Li }
913*67e74705SXin Li
914*67e74705SXin Li return result;
915*67e74705SXin Li }
916*67e74705SXin Li
clang_indexTranslationUnit(CXIndexAction idxAction,CXClientData client_data,IndexerCallbacks * index_callbacks,unsigned index_callbacks_size,unsigned index_options,CXTranslationUnit TU)917*67e74705SXin Li int clang_indexTranslationUnit(CXIndexAction idxAction,
918*67e74705SXin Li CXClientData client_data,
919*67e74705SXin Li IndexerCallbacks *index_callbacks,
920*67e74705SXin Li unsigned index_callbacks_size,
921*67e74705SXin Li unsigned index_options,
922*67e74705SXin Li CXTranslationUnit TU) {
923*67e74705SXin Li LOG_FUNC_SECTION {
924*67e74705SXin Li *Log << TU;
925*67e74705SXin Li }
926*67e74705SXin Li
927*67e74705SXin Li CXErrorCode result;
928*67e74705SXin Li auto IndexTranslationUnitImpl = [=, &result]() {
929*67e74705SXin Li result = clang_indexTranslationUnit_Impl(
930*67e74705SXin Li idxAction, client_data, index_callbacks, index_callbacks_size,
931*67e74705SXin Li index_options, TU);
932*67e74705SXin Li };
933*67e74705SXin Li
934*67e74705SXin Li if (getenv("LIBCLANG_NOTHREADS")) {
935*67e74705SXin Li IndexTranslationUnitImpl();
936*67e74705SXin Li return result;
937*67e74705SXin Li }
938*67e74705SXin Li
939*67e74705SXin Li llvm::CrashRecoveryContext CRC;
940*67e74705SXin Li
941*67e74705SXin Li if (!RunSafely(CRC, IndexTranslationUnitImpl)) {
942*67e74705SXin Li fprintf(stderr, "libclang: crash detected during indexing TU\n");
943*67e74705SXin Li
944*67e74705SXin Li return 1;
945*67e74705SXin Li }
946*67e74705SXin Li
947*67e74705SXin Li return result;
948*67e74705SXin Li }
949*67e74705SXin Li
clang_indexLoc_getFileLocation(CXIdxLoc location,CXIdxClientFile * indexFile,CXFile * file,unsigned * line,unsigned * column,unsigned * offset)950*67e74705SXin Li void clang_indexLoc_getFileLocation(CXIdxLoc location,
951*67e74705SXin Li CXIdxClientFile *indexFile,
952*67e74705SXin Li CXFile *file,
953*67e74705SXin Li unsigned *line,
954*67e74705SXin Li unsigned *column,
955*67e74705SXin Li unsigned *offset) {
956*67e74705SXin Li if (indexFile) *indexFile = nullptr;
957*67e74705SXin Li if (file) *file = nullptr;
958*67e74705SXin Li if (line) *line = 0;
959*67e74705SXin Li if (column) *column = 0;
960*67e74705SXin Li if (offset) *offset = 0;
961*67e74705SXin Li
962*67e74705SXin Li SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
963*67e74705SXin Li if (!location.ptr_data[0] || Loc.isInvalid())
964*67e74705SXin Li return;
965*67e74705SXin Li
966*67e74705SXin Li CXIndexDataConsumer &DataConsumer =
967*67e74705SXin Li *static_cast<CXIndexDataConsumer*>(location.ptr_data[0]);
968*67e74705SXin Li DataConsumer.translateLoc(Loc, indexFile, file, line, column, offset);
969*67e74705SXin Li }
970*67e74705SXin Li
clang_indexLoc_getCXSourceLocation(CXIdxLoc location)971*67e74705SXin Li CXSourceLocation clang_indexLoc_getCXSourceLocation(CXIdxLoc location) {
972*67e74705SXin Li SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
973*67e74705SXin Li if (!location.ptr_data[0] || Loc.isInvalid())
974*67e74705SXin Li return clang_getNullLocation();
975*67e74705SXin Li
976*67e74705SXin Li CXIndexDataConsumer &DataConsumer =
977*67e74705SXin Li *static_cast<CXIndexDataConsumer*>(location.ptr_data[0]);
978*67e74705SXin Li return cxloc::translateSourceLocation(DataConsumer.getASTContext(), Loc);
979*67e74705SXin Li }
980*67e74705SXin Li
981*67e74705SXin Li } // end: extern "C"
982*67e74705SXin Li
983