blob: df4c8eda667ef949fcafdb489ac87a6ad1b10556 [file] [log] [blame]
Ted Kremenekd2fa5662009-08-26 22:36:44 +00001//===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00007//
Ted Kremenekd2fa5662009-08-26 22:36:44 +00008//===----------------------------------------------------------------------===//
9//
Ted Kremenekab188932010-01-05 19:32:54 +000010// This file implements the main API hooks in the Clang-C Source Indexing
11// library.
Ted Kremenekd2fa5662009-08-26 22:36:44 +000012//
13//===----------------------------------------------------------------------===//
14
Ted Kremenekab188932010-01-05 19:32:54 +000015#include "CIndexer.h"
Ted Kremenek16c440a2010-01-15 20:35:54 +000016#include "CXCursor.h"
Ted Kremenek0a90d322010-11-17 23:24:11 +000017#include "CXTranslationUnit.h"
Ted Kremeneked122732010-11-16 01:56:27 +000018#include "CXString.h"
Ted Kremenek95f33552010-08-26 01:42:22 +000019#include "CXType.h"
Ted Kremeneka297de22010-01-25 22:34:44 +000020#include "CXSourceLocation.h"
Douglas Gregor5352ac02010-01-28 00:27:43 +000021#include "CIndexDiagnostic.h"
Argyrios Kyrtzidise397bf12011-11-03 19:02:34 +000022#include "CursorVisitor.h"
Ted Kremenekab188932010-01-05 19:32:54 +000023
Ted Kremenek04bb7162010-01-22 22:44:15 +000024#include "clang/Basic/Version.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000025
Steve Narofffb570422009-09-22 19:25:29 +000026#include "clang/AST/StmtVisitor.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000027#include "clang/Basic/Diagnostic.h"
28#include "clang/Frontend/ASTUnit.h"
29#include "clang/Frontend/CompilerInstance.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000030#include "clang/Frontend/FrontendDiagnostic.h"
Ted Kremenekd8210652010-01-06 23:43:31 +000031#include "clang/Lex/Lexer.h"
Douglas Gregordd3e5542011-05-04 00:14:37 +000032#include "clang/Lex/HeaderSearch.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000033#include "clang/Lex/PreprocessingRecord.h"
Douglas Gregor33e9abd2010-01-22 19:49:59 +000034#include "clang/Lex/Preprocessor.h"
Douglas Gregora67e03f2010-09-09 21:42:20 +000035#include "llvm/ADT/STLExtras.h"
Ted Kremenekd8c370c2010-11-02 23:10:24 +000036#include "llvm/ADT/Optional.h"
Douglas Gregorf5251602011-03-08 17:10:18 +000037#include "llvm/ADT/StringSwitch.h"
Argyrios Kyrtzidisb2c60b02012-03-01 19:45:56 +000038#include "llvm/Support/SaveAndRestore.h"
Daniel Dunbarc7df4f32010-08-18 18:43:14 +000039#include "llvm/Support/CrashRecoveryContext.h"
Daniel Dunbar48615ff2010-10-08 19:30:33 +000040#include "llvm/Support/PrettyStackTrace.h"
Douglas Gregor02465752009-10-16 21:24:31 +000041#include "llvm/Support/MemoryBuffer.h"
Douglas Gregor358559d2010-10-02 22:49:11 +000042#include "llvm/Support/raw_ostream.h"
Douglas Gregor7a07fcb2010-08-09 21:00:09 +000043#include "llvm/Support/Timer.h"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000044#include "llvm/Support/Mutex.h"
45#include "llvm/Support/Program.h"
46#include "llvm/Support/Signals.h"
47#include "llvm/Support/Threading.h"
Ted Kremenek37f1ea02010-11-15 23:11:54 +000048#include "llvm/Support/Compiler.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000049
Steve Naroff50398192009-08-28 15:28:48 +000050using namespace clang;
Ted Kremenek16c440a2010-01-15 20:35:54 +000051using namespace clang::cxcursor;
Ted Kremenekee4db4f2010-02-17 00:41:08 +000052using namespace clang::cxstring;
Argyrios Kyrtzidis9049cf62011-10-12 07:07:33 +000053using namespace clang::cxtu;
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +000054using namespace clang::cxindex;
Steve Naroff50398192009-08-28 15:28:48 +000055
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +000056CXTranslationUnit cxtu::MakeCXTranslationUnit(CIndexer *CIdx, ASTUnit *TU) {
Ted Kremeneka60ed472010-11-16 08:15:36 +000057 if (!TU)
58 return 0;
59 CXTranslationUnit D = new CXTranslationUnitImpl();
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +000060 D->CIdx = CIdx;
Ted Kremeneka60ed472010-11-16 08:15:36 +000061 D->TUData = TU;
62 D->StringPool = createCXStringPool();
Ted Kremenek15322172011-11-10 08:43:12 +000063 D->Diagnostics = 0;
Ted Kremeneka60ed472010-11-16 08:15:36 +000064 return D;
65}
66
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +000067cxtu::CXTUOwner::~CXTUOwner() {
68 if (TU)
69 clang_disposeTranslationUnit(TU);
70}
71
Ted Kremenekf0e23e82010-02-17 00:41:40 +000072/// \brief Compare two source ranges to determine their relative position in
Douglas Gregor33e9abd2010-01-22 19:49:59 +000073/// the translation unit.
Ted Kremenekf0e23e82010-02-17 00:41:40 +000074static RangeComparisonResult RangeCompare(SourceManager &SM,
75 SourceRange R1,
Douglas Gregor33e9abd2010-01-22 19:49:59 +000076 SourceRange R2) {
77 assert(R1.isValid() && "First range is invalid?");
78 assert(R2.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000079 if (R1.getEnd() != R2.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000080 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000081 return RangeBefore;
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000082 if (R2.getEnd() != R1.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000083 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000084 return RangeAfter;
85 return RangeOverlap;
86}
87
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000088/// \brief Determine if a source location falls within, before, or after a
89/// a given source range.
90static RangeComparisonResult LocationCompare(SourceManager &SM,
91 SourceLocation L, SourceRange R) {
92 assert(R.isValid() && "First range is invalid?");
93 assert(L.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000094 if (L == R.getBegin() || L == R.getEnd())
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000095 return RangeOverlap;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000096 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
97 return RangeBefore;
98 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
99 return RangeAfter;
100 return RangeOverlap;
101}
102
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000103/// \brief Translate a Clang source range into a CIndex source range.
104///
105/// Clang internally represents ranges where the end location points to the
106/// start of the token at the end. However, for external clients it is more
107/// useful to have a CXSourceRange be a proper half-open interval. This routine
108/// does the appropriate translation.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000109CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000110 const LangOptions &LangOpts,
Chris Lattner0a76aae2010-06-18 22:45:06 +0000111 const CharSourceRange &R) {
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000112 // We want the last character in this location, so we will adjust the
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000113 // location accordingly.
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000114 SourceLocation EndLoc = R.getEnd();
Douglas Gregora9b06d42010-11-09 06:24:54 +0000115 if (EndLoc.isValid() && EndLoc.isMacroID())
Chandler Carruthedc3dcc2011-07-25 16:56:02 +0000116 EndLoc = SM.getExpansionRange(EndLoc).second;
Chris Lattner0a76aae2010-06-18 22:45:06 +0000117 if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) {
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000118 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000119 EndLoc = EndLoc.getLocWithOffset(Length);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000120 }
121
122 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
123 R.getBegin().getRawEncoding(),
124 EndLoc.getRawEncoding() };
125 return Result;
126}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000127
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000128//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000129// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000130//===----------------------------------------------------------------------===//
131
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000132static SourceRange getRawCursorExtent(CXCursor C);
Douglas Gregor66537982010-11-17 17:14:07 +0000133static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
134
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000135
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000136RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000137 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000138}
139
Douglas Gregorb1373d02010-01-20 20:59:29 +0000140/// \brief Visit the given cursor and, if requested by the visitor,
141/// its children.
142///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000143/// \param Cursor the cursor to visit.
144///
145/// \param CheckRegionOfInterest if true, then the caller already checked that
146/// this cursor is within the region of interest.
147///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000148/// \returns true if the visitation should be aborted, false if it
149/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000150bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000151 if (clang_isInvalid(Cursor.kind))
152 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000153
Douglas Gregorb1373d02010-01-20 20:59:29 +0000154 if (clang_isDeclaration(Cursor.kind)) {
155 Decl *D = getCursorDecl(Cursor);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +0000156 if (!D) {
157 assert(0 && "Invalid declaration cursor");
158 return true; // abort.
159 }
160
Argyrios Kyrtzidis65ab9072011-09-26 19:05:37 +0000161 // Ignore implicit declarations, unless it's an objc method because
162 // currently we should report implicit methods for properties when indexing.
163 if (D->isImplicit() && !isa<ObjCMethodDecl>(D))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000164 return false;
165 }
166
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000167 // If we have a range of interest, and this cursor doesn't intersect with it,
168 // we're done.
169 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000170 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000171 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000172 return false;
173 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000174
Douglas Gregorb1373d02010-01-20 20:59:29 +0000175 switch (Visitor(Cursor, Parent, ClientData)) {
176 case CXChildVisit_Break:
177 return true;
178
179 case CXChildVisit_Continue:
180 return false;
181
182 case CXChildVisit_Recurse:
183 return VisitChildren(Cursor);
184 }
185
David Blaikie7530c032012-01-17 06:56:22 +0000186 llvm_unreachable("Invalid CXChildVisitResult!");
Douglas Gregorb1373d02010-01-20 20:59:29 +0000187}
188
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000189static bool visitPreprocessedEntitiesInRange(SourceRange R,
190 PreprocessingRecord &PPRec,
191 CursorVisitor &Visitor) {
192 SourceManager &SM = Visitor.getASTUnit()->getSourceManager();
193 FileID FID;
194
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +0000195 if (!Visitor.shouldVisitIncludedEntities()) {
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000196 // If the begin/end of the range lie in the same FileID, do the optimization
197 // where we skip preprocessed entities that do not come from the same FileID.
Argyrios Kyrtzidisacca4112011-12-21 16:56:38 +0000198 FID = SM.getFileID(SM.getFileLoc(R.getBegin()));
199 if (FID != SM.getFileID(SM.getFileLoc(R.getEnd())))
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000200 FID = FileID();
201 }
202
203 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
204 Entities = PPRec.getPreprocessedEntitiesInRange(R);
205 return Visitor.visitPreprocessedEntities(Entities.first, Entities.second,
206 PPRec, FID);
207}
208
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000209void CursorVisitor::visitFileRegion() {
210 if (RegionOfInterest.isInvalid())
211 return;
212
213 ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData);
214 SourceManager &SM = Unit->getSourceManager();
215
216 std::pair<FileID, unsigned>
217 Begin = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getBegin())),
218 End = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getEnd()));
219
220 if (End.first != Begin.first) {
221 // If the end does not reside in the same file, try to recover by
222 // picking the end of the file of begin location.
223 End.first = Begin.first;
224 End.second = SM.getFileIDSize(Begin.first);
225 }
226
227 assert(Begin.first == End.first);
228 if (Begin.second > End.second)
229 return;
230
231 FileID File = Begin.first;
232 unsigned Offset = Begin.second;
233 unsigned Length = End.second - Begin.second;
234
Argyrios Kyrtzidisb49e7282011-11-29 03:14:11 +0000235 if (!VisitDeclsOnly && !VisitPreprocessorLast)
236 if (visitPreprocessedEntitiesInRegion())
237 return; // visitation break.
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000238
239 visitDeclsFromFileRegion(File, Offset, Length);
240
Argyrios Kyrtzidisb49e7282011-11-29 03:14:11 +0000241 if (!VisitDeclsOnly && VisitPreprocessorLast)
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000242 visitPreprocessedEntitiesInRegion();
243}
244
Argyrios Kyrtzidise2079cf2011-11-16 08:58:54 +0000245static bool isInLexicalContext(Decl *D, DeclContext *DC) {
246 if (!DC)
247 return false;
248
249 for (DeclContext *DeclDC = D->getLexicalDeclContext();
250 DeclDC; DeclDC = DeclDC->getLexicalParent()) {
251 if (DeclDC == DC)
252 return true;
253 }
254 return false;
255}
256
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000257void CursorVisitor::visitDeclsFromFileRegion(FileID File,
258 unsigned Offset, unsigned Length) {
259 ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData);
260 SourceManager &SM = Unit->getSourceManager();
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000261 SourceRange Range = RegionOfInterest;
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000262
263 SmallVector<Decl *, 16> Decls;
264 Unit->findFileRegionDecls(File, Offset, Length, Decls);
265
266 // If we didn't find any file level decls for the file, try looking at the
267 // file that it was included from.
Argyrios Kyrtzidisc14a03d2011-11-23 20:27:36 +0000268 while (Decls.empty() || Decls.front()->isTopLevelDeclInObjCContainer()) {
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000269 bool Invalid = false;
270 const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid);
271 if (Invalid)
272 return;
273
274 SourceLocation Outer;
275 if (SLEntry.isFile())
276 Outer = SLEntry.getFile().getIncludeLoc();
277 else
278 Outer = SLEntry.getExpansion().getExpansionLocStart();
279 if (Outer.isInvalid())
280 return;
281
282 llvm::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer);
283 Length = 0;
284 Unit->findFileRegionDecls(File, Offset, Length, Decls);
285 }
286
287 assert(!Decls.empty());
288
289 bool VisitedAtLeastOnce = false;
Argyrios Kyrtzidise2079cf2011-11-16 08:58:54 +0000290 DeclContext *CurDC = 0;
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000291 SmallVector<Decl *, 16>::iterator DIt = Decls.begin();
292 for (SmallVector<Decl *, 16>::iterator DE = Decls.end(); DIt != DE; ++DIt) {
293 Decl *D = *DIt;
Argyrios Kyrtzidised8bef42011-11-28 22:38:07 +0000294 if (D->getSourceRange().isInvalid())
295 continue;
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000296
Argyrios Kyrtzidise2079cf2011-11-16 08:58:54 +0000297 if (isInLexicalContext(D, CurDC))
298 continue;
299
300 CurDC = dyn_cast<DeclContext>(D);
301
Argyrios Kyrtzidise2079cf2011-11-16 08:58:54 +0000302 if (TagDecl *TD = dyn_cast<TagDecl>(D))
303 if (!TD->isFreeStanding())
304 continue;
305
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000306 RangeComparisonResult CompRes = RangeCompare(SM, D->getSourceRange(),Range);
307 if (CompRes == RangeBefore)
308 continue;
309 if (CompRes == RangeAfter)
310 break;
311
312 assert(CompRes == RangeOverlap);
313 VisitedAtLeastOnce = true;
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +0000314
315 if (isa<ObjCContainerDecl>(D)) {
316 FileDI_current = &DIt;
317 FileDE_current = DE;
318 } else {
319 FileDI_current = 0;
320 }
321
Argyrios Kyrtzidisba986172011-11-03 19:02:28 +0000322 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000323 break;
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000324 }
325
326 if (VisitedAtLeastOnce)
327 return;
328
329 // No Decls overlapped with the range. Move up the lexical context until there
330 // is a context that contains the range or we reach the translation unit
331 // level.
332 DeclContext *DC = DIt == Decls.begin() ? (*DIt)->getLexicalDeclContext()
333 : (*(DIt-1))->getLexicalDeclContext();
334
335 while (DC && !DC->isTranslationUnit()) {
336 Decl *D = cast<Decl>(DC);
337 SourceRange CurDeclRange = D->getSourceRange();
338 if (CurDeclRange.isInvalid())
339 break;
340
341 if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) {
Argyrios Kyrtzidisba986172011-11-03 19:02:28 +0000342 Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true);
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000343 break;
344 }
345
346 DC = D->getLexicalDeclContext();
347 }
348}
349
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000350bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
Argyrios Kyrtzidisb49e7282011-11-29 03:14:11 +0000351 if (!AU->getPreprocessor().getPreprocessingRecord())
352 return false;
353
Douglas Gregor788f5a12010-03-20 00:41:21 +0000354 PreprocessingRecord &PPRec
Ted Kremeneka60ed472010-11-16 08:15:36 +0000355 = *AU->getPreprocessor().getPreprocessingRecord();
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000356 SourceManager &SM = AU->getSourceManager();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000357
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000358 if (RegionOfInterest.isValid()) {
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +0000359 SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000360 SourceLocation B = MappedRange.getBegin();
361 SourceLocation E = MappedRange.getEnd();
362
363 if (AU->isInPreambleFileID(B)) {
364 if (SM.isLoadedSourceLocation(E))
365 return visitPreprocessedEntitiesInRange(SourceRange(B, E),
366 PPRec, *this);
367
368 // Beginning of range lies in the preamble but it also extends beyond
369 // it into the main file. Split the range into 2 parts, one covering
370 // the preamble and another covering the main file. This allows subsequent
371 // calls to visitPreprocessedEntitiesInRange to accept a source range that
372 // lies in the same FileID, allowing it to skip preprocessed entities that
373 // do not come from the same FileID.
374 bool breaked =
375 visitPreprocessedEntitiesInRange(
376 SourceRange(B, AU->getEndOfPreambleFileID()),
377 PPRec, *this);
378 if (breaked) return true;
379 return visitPreprocessedEntitiesInRange(
380 SourceRange(AU->getStartOfMainFileID(), E),
381 PPRec, *this);
382 }
383
384 return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this);
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000385 }
386
Douglas Gregor788f5a12010-03-20 00:41:21 +0000387 bool OnlyLocalDecls
Douglas Gregor32038bb2010-12-21 19:07:48 +0000388 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
389
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000390 if (OnlyLocalDecls)
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000391 return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(),
392 PPRec);
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000393
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000394 return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec);
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000395}
396
397template<typename InputIterator>
398bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000399 InputIterator Last,
400 PreprocessingRecord &PPRec,
401 FileID FID) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000402 for (; First != Last; ++First) {
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000403 if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID))
404 continue;
405
406 PreprocessedEntity *PPE = *First;
407 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000408 if (Visit(MakeMacroExpansionCursor(ME, TU)))
409 return true;
410
411 continue;
412 }
413
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000414 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(PPE)) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000415 if (Visit(MakeMacroDefinitionCursor(MD, TU)))
416 return true;
417
418 continue;
419 }
420
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000421 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000422 if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
423 return true;
424
425 continue;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000426 }
427 }
428
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000429 return false;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000430}
431
Douglas Gregorb1373d02010-01-20 20:59:29 +0000432/// \brief Visit the children of the given cursor.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000433///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000434/// \returns true if the visitation should be aborted, false if it
435/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000436bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregorc314aa42011-03-02 19:17:03 +0000437 if (clang_isReference(Cursor.kind) &&
438 Cursor.kind != CXCursor_CXXBaseSpecifier) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000439 // By definition, references have no children.
440 return false;
441 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000442
443 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000444 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000445 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000446
Douglas Gregorb1373d02010-01-20 20:59:29 +0000447 if (clang_isDeclaration(Cursor.kind)) {
448 Decl *D = getCursorDecl(Cursor);
Douglas Gregor06d9b1a2011-04-14 21:41:34 +0000449 if (!D)
450 return false;
451
Ted Kremenek539311e2010-02-18 18:47:01 +0000452 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000453 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000454
Douglas Gregor06d9b1a2011-04-14 21:41:34 +0000455 if (clang_isStatement(Cursor.kind)) {
456 if (Stmt *S = getCursorStmt(Cursor))
457 return Visit(S);
458
459 return false;
460 }
461
462 if (clang_isExpression(Cursor.kind)) {
463 if (Expr *E = getCursorExpr(Cursor))
464 return Visit(E);
465
466 return false;
467 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000468
Douglas Gregorb1373d02010-01-20 20:59:29 +0000469 if (clang_isTranslationUnit(Cursor.kind)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000470 CXTranslationUnit tu = getCursorTU(Cursor);
471 ASTUnit *CXXUnit = static_cast<ASTUnit*>(tu->TUData);
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000472
473 int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
474 for (unsigned I = 0; I != 2; ++I) {
475 if (VisitOrder[I]) {
476 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
477 RegionOfInterest.isInvalid()) {
478 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
479 TLEnd = CXXUnit->top_level_end();
480 TL != TLEnd; ++TL) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000481 if (Visit(MakeCXCursor(*TL, tu, RegionOfInterest), true))
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000482 return true;
483 }
484 } else if (VisitDeclContext(
485 CXXUnit->getASTContext().getTranslationUnitDecl()))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000486 return true;
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000487 continue;
Douglas Gregor7b691f332010-01-20 21:13:59 +0000488 }
Bob Wilson3178cb62010-03-19 03:57:57 +0000489
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000490 // Walk the preprocessing record.
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000491 if (CXXUnit->getPreprocessor().getPreprocessingRecord())
492 visitPreprocessedEntitiesInRegion();
Douglas Gregor0396f462010-03-19 05:22:59 +0000493 }
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000494
Douglas Gregor7b691f332010-01-20 21:13:59 +0000495 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000496 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000497
Douglas Gregorc314aa42011-03-02 19:17:03 +0000498 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
499 if (CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
500 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
501 return Visit(BaseTSInfo->getTypeLoc());
502 }
503 }
504 }
Argyrios Kyrtzidis221d5a52011-09-13 18:49:56 +0000505
506 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
507 IBOutletCollectionAttr *A =
508 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
509 if (const ObjCInterfaceType *InterT = A->getInterface()->getAs<ObjCInterfaceType>())
510 return Visit(cxcursor::MakeCursorObjCClassRef(InterT->getInterface(),
511 A->getInterfaceLoc(), TU));
512 }
513
Douglas Gregorb1373d02010-01-20 20:59:29 +0000514 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000515 return false;
516}
517
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000518bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
Douglas Gregor13c8ccb2011-04-22 23:49:24 +0000519 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
520 if (Visit(TSInfo->getTypeLoc()))
521 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000522
Ted Kremenek664cffd2010-07-22 11:30:19 +0000523 if (Stmt *Body = B->getBody())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000524 return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest));
Ted Kremenek664cffd2010-07-22 11:30:19 +0000525
526 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000527}
528
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000529llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
530 if (RegionOfInterest.isValid()) {
Douglas Gregor66537982010-11-17 17:14:07 +0000531 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000532 if (Range.isInvalid())
533 return llvm::Optional<bool>();
Douglas Gregor66537982010-11-17 17:14:07 +0000534
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000535 switch (CompareRegionOfInterest(Range)) {
536 case RangeBefore:
537 // This declaration comes before the region of interest; skip it.
538 return llvm::Optional<bool>();
539
540 case RangeAfter:
541 // This declaration comes after the region of interest; we're done.
542 return false;
543
544 case RangeOverlap:
545 // This declaration overlaps the region of interest; visit it.
546 break;
547 }
548 }
549 return true;
550}
551
552bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
553 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
554
555 // FIXME: Eventually remove. This part of a hack to support proper
556 // iteration over all Decls contained lexically within an ObjC container.
557 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
558 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
559
560 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000561 Decl *D = *I;
562 if (D->getLexicalDeclContext() != DC)
563 continue;
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000564 CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
Argyrios Kyrtzidis1836db02012-02-04 01:04:58 +0000565
566 // FIXME: ObjCClassRef/ObjCProtocolRef for forward class/protocol
567 // declarations is a mismatch with the compiler semantics.
568 if (Cursor.kind == CXCursor_ObjCInterfaceDecl) {
569 ObjCInterfaceDecl *ID = cast<ObjCInterfaceDecl>(D);
570 if (!ID->isThisDeclarationADefinition())
571 Cursor = MakeCursorObjCClassRef(ID, ID->getLocation(), TU);
572
573 } else if (Cursor.kind == CXCursor_ObjCProtocolDecl) {
574 ObjCProtocolDecl *PD = cast<ObjCProtocolDecl>(D);
575 if (!PD->isThisDeclarationADefinition())
576 Cursor = MakeCursorObjCProtocolRef(PD, PD->getLocation(), TU);
577 }
578
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000579 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
580 if (!V.hasValue())
581 continue;
582 if (!V.getValue())
583 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000584 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000585 return true;
586 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000587 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000588}
589
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000590bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
591 llvm_unreachable("Translation units are visited directly by Visit()");
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000592}
593
Richard Smith162e1c12011-04-15 14:24:37 +0000594bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
595 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
596 return Visit(TSInfo->getTypeLoc());
597
598 return false;
599}
600
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000601bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
602 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
603 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000604
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000605 return false;
606}
607
608bool CursorVisitor::VisitTagDecl(TagDecl *D) {
609 return VisitDeclContext(D);
610}
611
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000612bool CursorVisitor::VisitClassTemplateSpecializationDecl(
613 ClassTemplateSpecializationDecl *D) {
614 bool ShouldVisitBody = false;
615 switch (D->getSpecializationKind()) {
616 case TSK_Undeclared:
617 case TSK_ImplicitInstantiation:
618 // Nothing to visit
619 return false;
620
621 case TSK_ExplicitInstantiationDeclaration:
622 case TSK_ExplicitInstantiationDefinition:
623 break;
624
625 case TSK_ExplicitSpecialization:
626 ShouldVisitBody = true;
627 break;
628 }
629
630 // Visit the template arguments used in the specialization.
631 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
632 TypeLoc TL = SpecType->getTypeLoc();
633 if (TemplateSpecializationTypeLoc *TSTLoc
634 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
635 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
636 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
637 return true;
638 }
639 }
640
641 if (ShouldVisitBody && VisitCXXRecordDecl(D))
642 return true;
643
644 return false;
645}
646
Douglas Gregor74dbe642010-08-31 19:31:58 +0000647bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
648 ClassTemplatePartialSpecializationDecl *D) {
649 // FIXME: Visit the "outer" template parameter lists on the TagDecl
650 // before visiting these template parameters.
651 if (VisitTemplateParameters(D->getTemplateParameters()))
652 return true;
653
654 // Visit the partial specialization arguments.
655 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
656 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
657 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
658 return true;
659
660 return VisitCXXRecordDecl(D);
661}
662
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000663bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000664 // Visit the default argument.
665 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
666 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
667 if (Visit(DefArg->getTypeLoc()))
668 return true;
669
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000670 return false;
671}
672
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000673bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
674 if (Expr *Init = D->getInitExpr())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000675 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000676 return false;
677}
678
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000679bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
680 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
681 if (Visit(TSInfo->getTypeLoc()))
682 return true;
683
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000684 // Visit the nested-name-specifier, if present.
685 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
686 if (VisitNestedNameSpecifierLoc(QualifierLoc))
687 return true;
688
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000689 return false;
690}
691
Douglas Gregora67e03f2010-09-09 21:42:20 +0000692/// \brief Compare two base or member initializers based on their source order.
Sean Huntcbb67482011-01-08 20:30:50 +0000693static int CompareCXXCtorInitializers(const void* Xp, const void *Yp) {
694 CXXCtorInitializer const * const *X
695 = static_cast<CXXCtorInitializer const * const *>(Xp);
696 CXXCtorInitializer const * const *Y
697 = static_cast<CXXCtorInitializer const * const *>(Yp);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000698
699 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
700 return -1;
701 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
702 return 1;
703 else
704 return 0;
705}
706
Douglas Gregorb1373d02010-01-20 20:59:29 +0000707bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000708 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
709 // Visit the function declaration's syntactic components in the order
710 // written. This requires a bit of work.
Abramo Bagnara723df242010-12-14 22:11:44 +0000711 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
Douglas Gregor01829d32010-08-31 14:41:23 +0000712 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
713
714 // If we have a function declared directly (without the use of a typedef),
715 // visit just the return type. Otherwise, just visit the function's type
716 // now.
717 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
718 (!FTL && Visit(TL)))
719 return true;
720
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000721 // Visit the nested-name-specifier, if present.
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000722 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
723 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000724 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000725
726 // Visit the declaration name.
727 if (VisitDeclarationNameInfo(ND->getNameInfo()))
728 return true;
729
730 // FIXME: Visit explicitly-specified template arguments!
731
732 // Visit the function parameters, if we have a function type.
733 if (FTL && VisitFunctionTypeLoc(*FTL, true))
734 return true;
735
736 // FIXME: Attributes?
737 }
738
Sean Hunt10620eb2011-05-06 20:44:56 +0000739 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
Douglas Gregora67e03f2010-09-09 21:42:20 +0000740 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
741 // Find the initializers that were written in the source.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000742 SmallVector<CXXCtorInitializer *, 4> WrittenInits;
Douglas Gregora67e03f2010-09-09 21:42:20 +0000743 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
744 IEnd = Constructor->init_end();
745 I != IEnd; ++I) {
746 if (!(*I)->isWritten())
747 continue;
748
749 WrittenInits.push_back(*I);
750 }
751
752 // Sort the initializers in source order
753 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
Sean Huntcbb67482011-01-08 20:30:50 +0000754 &CompareCXXCtorInitializers);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000755
756 // Visit the initializers in source order
757 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
Sean Huntcbb67482011-01-08 20:30:50 +0000758 CXXCtorInitializer *Init = WrittenInits[I];
Francois Pichet00eb3f92010-12-04 09:14:42 +0000759 if (Init->isAnyMemberInitializer()) {
760 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
Douglas Gregora67e03f2010-09-09 21:42:20 +0000761 Init->getMemberLocation(), TU)))
762 return true;
Douglas Gregor76852c22011-11-01 01:16:03 +0000763 } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) {
764 if (Visit(TInfo->getTypeLoc()))
Douglas Gregora67e03f2010-09-09 21:42:20 +0000765 return true;
766 }
767
768 // Visit the initializer value.
769 if (Expr *Initializer = Init->getInit())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000770 if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
Douglas Gregora67e03f2010-09-09 21:42:20 +0000771 return true;
772 }
773 }
774
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000775 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
Douglas Gregora67e03f2010-09-09 21:42:20 +0000776 return true;
777 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000778
Douglas Gregorb1373d02010-01-20 20:59:29 +0000779 return false;
780}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000781
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000782bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
783 if (VisitDeclaratorDecl(D))
784 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000785
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000786 if (Expr *BitWidth = D->getBitWidth())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000787 return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000788
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000789 return false;
790}
791
792bool CursorVisitor::VisitVarDecl(VarDecl *D) {
793 if (VisitDeclaratorDecl(D))
794 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000795
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000796 if (Expr *Init = D->getInit())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000797 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000798
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000799 return false;
800}
801
Douglas Gregor84b51d72010-09-01 20:16:53 +0000802bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
803 if (VisitDeclaratorDecl(D))
804 return true;
805
806 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
807 if (Expr *DefArg = D->getDefaultArgument())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000808 return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
Douglas Gregor84b51d72010-09-01 20:16:53 +0000809
810 return false;
811}
812
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000813bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
814 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
815 // before visiting these template parameters.
816 if (VisitTemplateParameters(D->getTemplateParameters()))
817 return true;
818
819 return VisitFunctionDecl(D->getTemplatedDecl());
820}
821
Douglas Gregor39d6f072010-08-31 19:02:00 +0000822bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
823 // FIXME: Visit the "outer" template parameter lists on the TagDecl
824 // before visiting these template parameters.
825 if (VisitTemplateParameters(D->getTemplateParameters()))
826 return true;
827
828 return VisitCXXRecordDecl(D->getTemplatedDecl());
829}
830
Douglas Gregor84b51d72010-09-01 20:16:53 +0000831bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
832 if (VisitTemplateParameters(D->getTemplateParameters()))
833 return true;
834
835 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
836 VisitTemplateArgumentLoc(D->getDefaultArgument()))
837 return true;
838
839 return false;
840}
841
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000842bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000843 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
844 if (Visit(TSInfo->getTypeLoc()))
845 return true;
846
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000847 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000848 PEnd = ND->param_end();
849 P != PEnd; ++P) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000850 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000851 return true;
852 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000853
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000854 if (ND->isThisDeclarationADefinition() &&
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000855 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000856 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000857
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000858 return false;
859}
860
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +0000861template <typename DeclIt>
862static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current,
863 SourceManager &SM, SourceLocation EndLoc,
864 SmallVectorImpl<Decl *> &Decls) {
865 DeclIt next = *DI_current;
866 while (++next != DE_current) {
867 Decl *D_next = *next;
868 if (!D_next)
869 break;
870 SourceLocation L = D_next->getLocStart();
871 if (!L.isValid())
872 break;
873 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
874 *DI_current = next;
875 Decls.push_back(D_next);
876 continue;
877 }
878 break;
879 }
880}
881
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000882namespace {
883 struct ContainerDeclsSort {
884 SourceManager &SM;
885 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
886 bool operator()(Decl *A, Decl *B) {
887 SourceLocation L_A = A->getLocStart();
888 SourceLocation L_B = B->getLocStart();
889 assert(L_A.isValid() && L_B.isValid());
890 return SM.isBeforeInTranslationUnit(L_A, L_B);
891 }
892 };
893}
894
Douglas Gregora59e3902010-01-21 23:27:09 +0000895bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000896 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
897 // an @implementation can lexically contain Decls that are not properly
898 // nested in the AST. When we identify such cases, we need to retrofit
899 // this nesting here.
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +0000900 if (!DI_current && !FileDI_current)
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000901 return VisitDeclContext(D);
902
903 // Scan the Decls that immediately come after the container
904 // in the current DeclContext. If any fall within the
905 // container's lexical region, stash them into a vector
906 // for later processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000907 SmallVector<Decl *, 24> DeclsInContainer;
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000908 SourceLocation EndLoc = D->getSourceRange().getEnd();
Ted Kremeneka60ed472010-11-16 08:15:36 +0000909 SourceManager &SM = AU->getSourceManager();
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000910 if (EndLoc.isValid()) {
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +0000911 if (DI_current) {
912 addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc,
913 DeclsInContainer);
914 } else {
915 addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc,
916 DeclsInContainer);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000917 }
918 }
919
920 // The common case.
921 if (DeclsInContainer.empty())
922 return VisitDeclContext(D);
923
924 // Get all the Decls in the DeclContext, and sort them with the
925 // additional ones we've collected. Then visit them.
926 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
927 I!=E; ++I) {
928 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000929 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
930 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000931 continue;
932 DeclsInContainer.push_back(subDecl);
933 }
934
935 // Now sort the Decls so that they appear in lexical order.
936 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
937 ContainerDeclsSort(SM));
938
939 // Now visit the decls.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000940 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000941 E = DeclsInContainer.end(); I != E; ++I) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000942 CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000943 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
944 if (!V.hasValue())
945 continue;
946 if (!V.getValue())
947 return false;
948 if (Visit(Cursor, true))
949 return true;
950 }
951 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000952}
953
Douglas Gregorb1373d02010-01-20 20:59:29 +0000954bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000955 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
956 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000957 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000958
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000959 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
960 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
961 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000962 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000963 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000964
Douglas Gregora59e3902010-01-21 23:27:09 +0000965 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000966}
967
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000968bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000969 if (!PID->isThisDeclarationADefinition())
970 return Visit(MakeCursorObjCProtocolRef(PID, PID->getLocation(), TU));
971
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000972 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
973 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
974 E = PID->protocol_end(); I != E; ++I, ++PL)
975 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
976 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000977
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000978 return VisitObjCContainerDecl(PID);
979}
980
Ted Kremenek23173d72010-05-18 21:09:07 +0000981bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000982 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000983 return true;
984
Ted Kremenek23173d72010-05-18 21:09:07 +0000985 // FIXME: This implements a workaround with @property declarations also being
986 // installed in the DeclContext for the @interface. Eventually this code
987 // should be removed.
988 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
989 if (!CDecl || !CDecl->IsClassExtension())
990 return false;
991
992 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
993 if (!ID)
994 return false;
995
996 IdentifierInfo *PropertyId = PD->getIdentifier();
997 ObjCPropertyDecl *prevDecl =
998 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
999
1000 if (!prevDecl)
1001 return false;
1002
1003 // Visit synthesized methods since they will be skipped when visiting
1004 // the @interface.
1005 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +00001006 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001007 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
Ted Kremenek23173d72010-05-18 21:09:07 +00001008 return true;
1009
1010 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +00001011 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001012 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
Ted Kremenek23173d72010-05-18 21:09:07 +00001013 return true;
1014
1015 return false;
1016}
1017
Douglas Gregorb1373d02010-01-20 20:59:29 +00001018bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Douglas Gregor375bb142011-12-27 22:43:10 +00001019 if (!D->isThisDeclarationADefinition()) {
1020 // Forward declaration is treated like a reference.
1021 return Visit(MakeCursorObjCClassRef(D, D->getLocation(), TU));
1022 }
1023
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001024 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +00001025 if (D->getSuperClass() &&
1026 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001027 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001028 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001029 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001030
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001031 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1032 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1033 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001034 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001035 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001036
Douglas Gregora59e3902010-01-21 23:27:09 +00001037 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001038}
1039
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001040bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1041 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001042}
1043
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001044bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +00001045 // 'ID' could be null when dealing with invalid code.
1046 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1047 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1048 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001049
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001050 return VisitObjCImplDecl(D);
1051}
1052
1053bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1054#if 0
1055 // Issue callbacks for super class.
1056 // FIXME: No source location information!
1057 if (D->getSuperClass() &&
1058 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001059 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001060 TU)))
1061 return true;
1062#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001063
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001064 return VisitObjCImplDecl(D);
1065}
1066
Douglas Gregora4ffd852010-11-17 01:03:52 +00001067bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1068 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1069 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1070
1071 return false;
1072}
1073
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001074bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1075 return VisitDeclContext(D);
1076}
1077
Douglas Gregor69319002010-08-31 23:48:11 +00001078bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001079 // Visit nested-name-specifier.
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00001080 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1081 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001082 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001083
1084 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1085 D->getTargetNameLoc(), TU));
1086}
1087
Douglas Gregor7e242562010-09-01 19:52:22 +00001088bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001089 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001090 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1091 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001092 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001093 }
Douglas Gregor7e242562010-09-01 19:52:22 +00001094
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001095 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1096 return true;
1097
Douglas Gregor7e242562010-09-01 19:52:22 +00001098 return VisitDeclarationNameInfo(D->getNameInfo());
1099}
1100
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001101bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001102 // Visit nested-name-specifier.
Douglas Gregordb992412011-02-25 16:33:46 +00001103 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1104 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001105 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001106
1107 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1108 D->getIdentLocation(), TU));
1109}
1110
Douglas Gregor7e242562010-09-01 19:52:22 +00001111bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001112 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001113 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1114 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001115 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001116 }
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001117
Douglas Gregor7e242562010-09-01 19:52:22 +00001118 return VisitDeclarationNameInfo(D->getNameInfo());
1119}
1120
1121bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1122 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001123 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001124 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1125 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001126 return true;
1127
Douglas Gregor7e242562010-09-01 19:52:22 +00001128 return false;
1129}
1130
Douglas Gregor01829d32010-08-31 14:41:23 +00001131bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1132 switch (Name.getName().getNameKind()) {
1133 case clang::DeclarationName::Identifier:
1134 case clang::DeclarationName::CXXLiteralOperatorName:
1135 case clang::DeclarationName::CXXOperatorName:
1136 case clang::DeclarationName::CXXUsingDirective:
1137 return false;
1138
1139 case clang::DeclarationName::CXXConstructorName:
1140 case clang::DeclarationName::CXXDestructorName:
1141 case clang::DeclarationName::CXXConversionFunctionName:
1142 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1143 return Visit(TSInfo->getTypeLoc());
1144 return false;
1145
1146 case clang::DeclarationName::ObjCZeroArgSelector:
1147 case clang::DeclarationName::ObjCOneArgSelector:
1148 case clang::DeclarationName::ObjCMultiArgSelector:
1149 // FIXME: Per-identifier location info?
1150 return false;
1151 }
David Blaikie7530c032012-01-17 06:56:22 +00001152
1153 llvm_unreachable("Invalid DeclarationName::Kind!");
Douglas Gregor01829d32010-08-31 14:41:23 +00001154}
1155
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001156bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1157 SourceRange Range) {
1158 // FIXME: This whole routine is a hack to work around the lack of proper
1159 // source information in nested-name-specifiers (PR5791). Since we do have
1160 // a beginning source location, we can visit the first component of the
1161 // nested-name-specifier, if it's a single-token component.
1162 if (!NNS)
1163 return false;
1164
1165 // Get the first component in the nested-name-specifier.
1166 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1167 NNS = Prefix;
1168
1169 switch (NNS->getKind()) {
1170 case NestedNameSpecifier::Namespace:
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001171 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1172 TU));
1173
Douglas Gregor14aba762011-02-24 02:36:08 +00001174 case NestedNameSpecifier::NamespaceAlias:
1175 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1176 Range.getBegin(), TU));
1177
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001178 case NestedNameSpecifier::TypeSpec: {
1179 // If the type has a form where we know that the beginning of the source
1180 // range matches up with a reference cursor. Visit the appropriate reference
1181 // cursor.
John McCallf4c73712011-01-19 06:33:43 +00001182 const Type *T = NNS->getAsType();
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001183 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1184 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1185 if (const TagType *Tag = dyn_cast<TagType>(T))
1186 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1187 if (const TemplateSpecializationType *TST
1188 = dyn_cast<TemplateSpecializationType>(T))
1189 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1190 break;
1191 }
1192
1193 case NestedNameSpecifier::TypeSpecWithTemplate:
1194 case NestedNameSpecifier::Global:
1195 case NestedNameSpecifier::Identifier:
1196 break;
1197 }
1198
1199 return false;
1200}
1201
Douglas Gregordc355712011-02-25 00:36:19 +00001202bool
1203CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001204 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
Douglas Gregordc355712011-02-25 00:36:19 +00001205 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1206 Qualifiers.push_back(Qualifier);
1207
1208 while (!Qualifiers.empty()) {
1209 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1210 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1211 switch (NNS->getKind()) {
1212 case NestedNameSpecifier::Namespace:
1213 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001214 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001215 TU)))
1216 return true;
1217
1218 break;
1219
1220 case NestedNameSpecifier::NamespaceAlias:
1221 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001222 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001223 TU)))
1224 return true;
1225
1226 break;
1227
1228 case NestedNameSpecifier::TypeSpec:
1229 case NestedNameSpecifier::TypeSpecWithTemplate:
1230 if (Visit(Q.getTypeLoc()))
1231 return true;
1232
1233 break;
1234
1235 case NestedNameSpecifier::Global:
1236 case NestedNameSpecifier::Identifier:
1237 break;
1238 }
1239 }
1240
1241 return false;
1242}
1243
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001244bool CursorVisitor::VisitTemplateParameters(
1245 const TemplateParameterList *Params) {
1246 if (!Params)
1247 return false;
1248
1249 for (TemplateParameterList::const_iterator P = Params->begin(),
1250 PEnd = Params->end();
1251 P != PEnd; ++P) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001252 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001253 return true;
1254 }
1255
1256 return false;
1257}
1258
Douglas Gregor0b36e612010-08-31 20:37:03 +00001259bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1260 switch (Name.getKind()) {
1261 case TemplateName::Template:
1262 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1263
1264 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001265 // Visit the overloaded template set.
1266 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1267 return true;
1268
Douglas Gregor0b36e612010-08-31 20:37:03 +00001269 return false;
1270
1271 case TemplateName::DependentTemplate:
1272 // FIXME: Visit nested-name-specifier.
1273 return false;
1274
1275 case TemplateName::QualifiedTemplate:
1276 // FIXME: Visit nested-name-specifier.
1277 return Visit(MakeCursorTemplateRef(
1278 Name.getAsQualifiedTemplateName()->getDecl(),
1279 Loc, TU));
John McCall14606042011-06-30 08:33:18 +00001280
1281 case TemplateName::SubstTemplateTemplateParm:
1282 return Visit(MakeCursorTemplateRef(
1283 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1284 Loc, TU));
Douglas Gregor1aee05d2011-01-15 06:45:20 +00001285
1286 case TemplateName::SubstTemplateTemplateParmPack:
1287 return Visit(MakeCursorTemplateRef(
1288 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1289 Loc, TU));
Douglas Gregor0b36e612010-08-31 20:37:03 +00001290 }
David Blaikie7530c032012-01-17 06:56:22 +00001291
1292 llvm_unreachable("Invalid TemplateName::Kind!");
Douglas Gregor0b36e612010-08-31 20:37:03 +00001293}
1294
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001295bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1296 switch (TAL.getArgument().getKind()) {
1297 case TemplateArgument::Null:
1298 case TemplateArgument::Integral:
Douglas Gregor87dd6972010-12-20 16:52:59 +00001299 case TemplateArgument::Pack:
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001300 return false;
1301
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001302 case TemplateArgument::Type:
1303 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1304 return Visit(TSInfo->getTypeLoc());
1305 return false;
1306
1307 case TemplateArgument::Declaration:
1308 if (Expr *E = TAL.getSourceDeclExpression())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001309 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001310 return false;
1311
1312 case TemplateArgument::Expression:
1313 if (Expr *E = TAL.getSourceExpression())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001314 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001315 return false;
1316
1317 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001318 case TemplateArgument::TemplateExpansion:
Douglas Gregorb6744ef2011-03-02 17:09:35 +00001319 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1320 return true;
1321
Douglas Gregora7fc9012011-01-05 18:58:31 +00001322 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
Douglas Gregor0b36e612010-08-31 20:37:03 +00001323 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001324 }
David Blaikie7530c032012-01-17 06:56:22 +00001325
1326 llvm_unreachable("Invalid TemplateArgument::Kind!");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001327}
1328
Ted Kremeneka0536d82010-05-07 01:04:29 +00001329bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1330 return VisitDeclContext(D);
1331}
1332
Douglas Gregor01829d32010-08-31 14:41:23 +00001333bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1334 return Visit(TL.getUnqualifiedLoc());
1335}
1336
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001337bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00001338 ASTContext &Context = AU->getASTContext();
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001339
1340 // Some builtin types (such as Objective-C's "id", "sel", and
1341 // "Class") have associated declarations. Create cursors for those.
1342 QualType VisitType;
John McCalle0a22d02011-10-18 21:02:43 +00001343 switch (TL.getTypePtr()->getKind()) {
John McCall2dde35b2011-10-18 22:28:37 +00001344
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001345 case BuiltinType::Void:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001346 case BuiltinType::NullPtr:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001347 case BuiltinType::Dependent:
John McCall2dde35b2011-10-18 22:28:37 +00001348#define BUILTIN_TYPE(Id, SingletonId)
1349#define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1350#define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1351#define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
1352#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
1353#include "clang/AST/BuiltinTypes.def"
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001354 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001355
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001356 case BuiltinType::ObjCId:
1357 VisitType = Context.getObjCIdType();
1358 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001359
1360 case BuiltinType::ObjCClass:
1361 VisitType = Context.getObjCClassType();
1362 break;
1363
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001364 case BuiltinType::ObjCSel:
1365 VisitType = Context.getObjCSelType();
1366 break;
1367 }
1368
1369 if (!VisitType.isNull()) {
1370 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001371 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001372 TU));
1373 }
1374
1375 return false;
1376}
1377
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001378bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
Richard Smith162e1c12011-04-15 14:24:37 +00001379 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001380}
1381
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001382bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1383 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1384}
1385
1386bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
Argyrios Kyrtzidis6f155de2011-08-25 22:24:47 +00001387 if (TL.isDefinition())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001388 return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
Argyrios Kyrtzidis6f155de2011-08-25 22:24:47 +00001389
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001390 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1391}
1392
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001393bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Chandler Carruth960d13d2011-05-01 09:53:37 +00001394 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001395}
1396
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001397bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1398 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1399 return true;
1400
John McCallc12c5bb2010-05-15 11:32:37 +00001401 return false;
1402}
1403
1404bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1405 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1406 return true;
1407
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001408 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1409 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1410 TU)))
1411 return true;
1412 }
1413
1414 return false;
1415}
1416
1417bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001418 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001419}
1420
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001421bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1422 return Visit(TL.getInnerLoc());
1423}
1424
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001425bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1426 return Visit(TL.getPointeeLoc());
1427}
1428
1429bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1430 return Visit(TL.getPointeeLoc());
1431}
1432
1433bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1434 return Visit(TL.getPointeeLoc());
1435}
1436
1437bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001438 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001439}
1440
1441bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001442 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001443}
1444
Argyrios Kyrtzidis3422fbc2011-08-15 18:44:43 +00001445bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1446 return Visit(TL.getModifiedLoc());
1447}
1448
Douglas Gregor01829d32010-08-31 14:41:23 +00001449bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1450 bool SkipResultType) {
1451 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001452 return true;
1453
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001454 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001455 if (Decl *D = TL.getArg(I))
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001456 if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001457 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001458
1459 return false;
1460}
1461
1462bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1463 if (Visit(TL.getElementLoc()))
1464 return true;
1465
1466 if (Expr *Size = TL.getSizeExpr())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001467 return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001468
1469 return false;
1470}
1471
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001472bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1473 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001474 // Visit the template name.
1475 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1476 TL.getTemplateNameLoc()))
1477 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001478
1479 // Visit the template arguments.
1480 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1481 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1482 return true;
1483
1484 return false;
1485}
1486
Douglas Gregor2332c112010-01-21 20:48:56 +00001487bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1488 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1489}
1490
1491bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1492 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1493 return Visit(TSInfo->getTypeLoc());
1494
1495 return false;
1496}
1497
Sean Huntca63c202011-05-24 22:41:36 +00001498bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1499 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1500 return Visit(TSInfo->getTypeLoc());
1501
1502 return false;
1503}
1504
Douglas Gregor2494dd02011-03-01 01:34:45 +00001505bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
1506 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1507 return true;
1508
1509 return false;
1510}
1511
Douglas Gregor94fdffa2011-03-01 20:11:18 +00001512bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1513 DependentTemplateSpecializationTypeLoc TL) {
1514 // Visit the nested-name-specifier, if there is one.
1515 if (TL.getQualifierLoc() &&
1516 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1517 return true;
1518
1519 // Visit the template arguments.
1520 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1521 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1522 return true;
1523
1524 return false;
1525}
1526
Douglas Gregor9e876872011-03-01 18:12:44 +00001527bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1528 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1529 return true;
1530
1531 return Visit(TL.getNamedTypeLoc());
1532}
1533
Douglas Gregor7536dd52010-12-20 02:24:11 +00001534bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1535 return Visit(TL.getPatternLoc());
1536}
1537
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +00001538bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1539 if (Expr *E = TL.getUnderlyingExpr())
1540 return Visit(MakeCXCursor(E, StmtParent, TU));
1541
1542 return false;
1543}
1544
1545bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1546 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1547}
1548
Eli Friedmanb001de72011-10-06 23:00:33 +00001549bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1550 return Visit(TL.getValueLoc());
1551}
1552
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +00001553#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1554bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1555 return Visit##PARENT##Loc(TL); \
1556}
1557
1558DEFAULT_TYPELOC_IMPL(Complex, Type)
1559DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1560DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1561DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1562DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
1563DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1564DEFAULT_TYPELOC_IMPL(Vector, Type)
1565DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1566DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1567DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1568DEFAULT_TYPELOC_IMPL(Record, TagType)
1569DEFAULT_TYPELOC_IMPL(Enum, TagType)
1570DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1571DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1572DEFAULT_TYPELOC_IMPL(Auto, Type)
1573
Ted Kremenek3064ef92010-08-27 21:34:58 +00001574bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001575 // Visit the nested-name-specifier, if present.
1576 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1577 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1578 return true;
1579
John McCall5e1cdac2011-10-07 06:10:15 +00001580 if (D->isCompleteDefinition()) {
Ted Kremenek3064ef92010-08-27 21:34:58 +00001581 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1582 E = D->bases_end(); I != E; ++I) {
1583 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1584 return true;
1585 }
1586 }
1587
1588 return VisitTagDecl(D);
1589}
1590
Ted Kremenek09dfa372010-02-18 05:46:33 +00001591bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001592 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1593 i != e; ++i)
1594 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001595 return true;
1596
1597 return false;
1598}
1599
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001600//===----------------------------------------------------------------------===//
1601// Data-recursive visitor methods.
1602//===----------------------------------------------------------------------===//
1603
Ted Kremenek28a71942010-11-13 00:36:47 +00001604namespace {
Ted Kremenek035dc412010-11-13 00:36:50 +00001605#define DEF_JOB(NAME, DATA, KIND)\
1606class NAME : public VisitorJob {\
1607public:\
1608 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1609 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Ted Kremenekf64d8032010-11-18 00:02:32 +00001610 DATA *get() const { return static_cast<DATA*>(data[0]); }\
Ted Kremenek035dc412010-11-13 00:36:50 +00001611};
1612
1613DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1614DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001615DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001616DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001617DEF_JOB(ExplicitTemplateArgsVisit, ASTTemplateArgumentListInfo,
Ted Kremenek60608ec2010-11-17 00:50:47 +00001618 ExplicitTemplateArgsVisitKind)
Douglas Gregor94d96292011-01-19 20:34:17 +00001619DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
Douglas Gregor011d8b92012-02-15 00:54:55 +00001620DEF_JOB(LambdaExprParts, LambdaExpr, LambdaExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001621#undef DEF_JOB
1622
1623class DeclVisit : public VisitorJob {
1624public:
1625 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1626 VisitorJob(parent, VisitorJob::DeclVisitKind,
1627 d, isFirst ? (void*) 1 : (void*) 0) {}
1628 static bool classof(const VisitorJob *VJ) {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001629 return VJ->getKind() == DeclVisitKind;
Ted Kremenek035dc412010-11-13 00:36:50 +00001630 }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001631 Decl *get() const { return static_cast<Decl*>(data[0]); }
1632 bool isFirst() const { return data[1] ? true : false; }
Ted Kremenek035dc412010-11-13 00:36:50 +00001633};
Ted Kremenek035dc412010-11-13 00:36:50 +00001634class TypeLocVisit : public VisitorJob {
1635public:
1636 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1637 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1638 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1639
1640 static bool classof(const VisitorJob *VJ) {
1641 return VJ->getKind() == TypeLocVisitKind;
1642 }
1643
Ted Kremenek82f3c502010-11-15 22:23:26 +00001644 TypeLoc get() const {
Ted Kremenekf64d8032010-11-18 00:02:32 +00001645 QualType T = QualType::getFromOpaquePtr(data[0]);
1646 return TypeLoc(T, data[1]);
Ted Kremenek035dc412010-11-13 00:36:50 +00001647 }
1648};
1649
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001650class LabelRefVisit : public VisitorJob {
1651public:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001652 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1653 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001654 labelLoc.getPtrEncoding()) {}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001655
1656 static bool classof(const VisitorJob *VJ) {
1657 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1658 }
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001659 LabelDecl *get() const { return static_cast<LabelDecl*>(data[0]); }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001660 SourceLocation getLoc() const {
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001661 return SourceLocation::getFromPtrEncoding(data[1]); }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001662};
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001663
1664class NestedNameSpecifierLocVisit : public VisitorJob {
1665public:
1666 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1667 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1668 Qualifier.getNestedNameSpecifier(),
1669 Qualifier.getOpaqueData()) { }
1670
1671 static bool classof(const VisitorJob *VJ) {
1672 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1673 }
1674
1675 NestedNameSpecifierLoc get() const {
1676 return NestedNameSpecifierLoc(static_cast<NestedNameSpecifier*>(data[0]),
1677 data[1]);
1678 }
1679};
1680
Ted Kremenekf64d8032010-11-18 00:02:32 +00001681class DeclarationNameInfoVisit : public VisitorJob {
1682public:
1683 DeclarationNameInfoVisit(Stmt *S, CXCursor parent)
1684 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
1685 static bool classof(const VisitorJob *VJ) {
1686 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1687 }
1688 DeclarationNameInfo get() const {
1689 Stmt *S = static_cast<Stmt*>(data[0]);
1690 switch (S->getStmtClass()) {
1691 default:
1692 llvm_unreachable("Unhandled Stmt");
Douglas Gregorba0513d2011-10-25 01:33:02 +00001693 case clang::Stmt::MSDependentExistsStmtClass:
1694 return cast<MSDependentExistsStmt>(S)->getNameInfo();
Ted Kremenekf64d8032010-11-18 00:02:32 +00001695 case Stmt::CXXDependentScopeMemberExprClass:
1696 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1697 case Stmt::DependentScopeDeclRefExprClass:
1698 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
1699 }
1700 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001701};
Ted Kremenekcdba6592010-11-18 00:42:18 +00001702class MemberRefVisit : public VisitorJob {
1703public:
1704 MemberRefVisit(FieldDecl *D, SourceLocation L, CXCursor parent)
1705 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001706 L.getPtrEncoding()) {}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001707 static bool classof(const VisitorJob *VJ) {
1708 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1709 }
1710 FieldDecl *get() const {
1711 return static_cast<FieldDecl*>(data[0]);
1712 }
1713 SourceLocation getLoc() const {
1714 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1715 }
1716};
Ted Kremenek28a71942010-11-13 00:36:47 +00001717class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1718 VisitorWorkList &WL;
1719 CXCursor Parent;
1720public:
1721 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1722 : WL(wl), Parent(parent) {}
1723
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001724 void VisitAddrLabelExpr(AddrLabelExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001725 void VisitBlockExpr(BlockExpr *B);
Ted Kremenek28a71942010-11-13 00:36:47 +00001726 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek083c7e22010-11-13 05:38:03 +00001727 void VisitCompoundStmt(CompoundStmt *S);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001728 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
Douglas Gregorba0513d2011-10-25 01:33:02 +00001729 void VisitMSDependentExistsStmt(MSDependentExistsStmt *S);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001730 void VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001731 void VisitCXXNewExpr(CXXNewExpr *E);
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001732 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001733 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001734 void VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001735 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001736 void VisitCXXTypeidExpr(CXXTypeidExpr *E);
Ted Kremenek55b933a2010-11-17 00:50:36 +00001737 void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001738 void VisitCXXUuidofExpr(CXXUuidofExpr *E);
Argyrios Kyrtzidisdcbb2fb2011-12-03 03:49:44 +00001739 void VisitCXXCatchStmt(CXXCatchStmt *S);
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001740 void VisitDeclRefExpr(DeclRefExpr *D);
Ted Kremenek035dc412010-11-13 00:36:50 +00001741 void VisitDeclStmt(DeclStmt *S);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001742 void VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001743 void VisitDesignatedInitExpr(DesignatedInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001744 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1745 void VisitForStmt(ForStmt *FS);
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001746 void VisitGotoStmt(GotoStmt *GS);
Ted Kremenek28a71942010-11-13 00:36:47 +00001747 void VisitIfStmt(IfStmt *If);
1748 void VisitInitListExpr(InitListExpr *IE);
1749 void VisitMemberExpr(MemberExpr *M);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001750 void VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001751 void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001752 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1753 void VisitOverloadExpr(OverloadExpr *E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001754 void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001755 void VisitStmt(Stmt *S);
1756 void VisitSwitchStmt(SwitchStmt *S);
1757 void VisitWhileStmt(WhileStmt *W);
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001758 void VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Francois Pichet6ad6f282010-12-07 00:08:36 +00001759 void VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E);
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00001760 void VisitTypeTraitExpr(TypeTraitExpr *E);
John Wiegley21ff2e52011-04-28 00:16:57 +00001761 void VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E);
John Wiegley55262202011-04-25 06:54:41 +00001762 void VisitExpressionTraitExpr(ExpressionTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001763 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001764 void VisitVAArgExpr(VAArgExpr *E);
Douglas Gregor94d96292011-01-19 20:34:17 +00001765 void VisitSizeOfPackExpr(SizeOfPackExpr *E);
John McCall4b9c2d22011-11-06 09:01:30 +00001766 void VisitPseudoObjectExpr(PseudoObjectExpr *E);
1767 void VisitOpaqueValueExpr(OpaqueValueExpr *E);
Douglas Gregor011d8b92012-02-15 00:54:55 +00001768 void VisitLambdaExpr(LambdaExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00001769
Ted Kremenek28a71942010-11-13 00:36:47 +00001770private:
Ted Kremenekf64d8032010-11-18 00:02:32 +00001771 void AddDeclarationNameInfo(Stmt *S);
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001772 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001773 void AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001774 void AddMemberRef(FieldDecl *D, SourceLocation L);
Ted Kremenek28a71942010-11-13 00:36:47 +00001775 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001776 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001777 void AddTypeLoc(TypeSourceInfo *TI);
1778 void EnqueueChildren(Stmt *S);
1779};
1780} // end anonyous namespace
1781
Ted Kremenekf64d8032010-11-18 00:02:32 +00001782void EnqueueVisitor::AddDeclarationNameInfo(Stmt *S) {
1783 // 'S' should always be non-null, since it comes from the
1784 // statement we are visiting.
1785 WL.push_back(DeclarationNameInfoVisit(S, Parent));
1786}
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001787
1788void
1789EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1790 if (Qualifier)
1791 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
1792}
1793
Ted Kremenek28a71942010-11-13 00:36:47 +00001794void EnqueueVisitor::AddStmt(Stmt *S) {
1795 if (S)
1796 WL.push_back(StmtVisit(S, Parent));
1797}
Ted Kremenek035dc412010-11-13 00:36:50 +00001798void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001799 if (D)
Ted Kremenek035dc412010-11-13 00:36:50 +00001800 WL.push_back(DeclVisit(D, Parent, isFirst));
Ted Kremenek28a71942010-11-13 00:36:47 +00001801}
Ted Kremenek60608ec2010-11-17 00:50:47 +00001802void EnqueueVisitor::
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001803 AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001804 if (A)
1805 WL.push_back(ExplicitTemplateArgsVisit(
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001806 const_cast<ASTTemplateArgumentListInfo*>(A), Parent));
Ted Kremenek60608ec2010-11-17 00:50:47 +00001807}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001808void EnqueueVisitor::AddMemberRef(FieldDecl *D, SourceLocation L) {
1809 if (D)
1810 WL.push_back(MemberRefVisit(D, L, Parent));
1811}
Ted Kremenek28a71942010-11-13 00:36:47 +00001812void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1813 if (TI)
1814 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1815 }
1816void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001817 unsigned size = WL.size();
John McCall7502c1d2011-02-13 04:07:26 +00001818 for (Stmt::child_range Child = S->children(); Child; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001819 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001820 }
1821 if (size == WL.size())
1822 return;
1823 // Now reverse the entries we just added. This will match the DFS
1824 // ordering performed by the worklist.
1825 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1826 std::reverse(I, E);
1827}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001828void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1829 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
1830}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001831void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1832 AddDecl(B->getBlockDecl());
1833}
Ted Kremenek28a71942010-11-13 00:36:47 +00001834void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1835 EnqueueChildren(E);
1836 AddTypeLoc(E->getTypeSourceInfo());
1837}
Ted Kremenek083c7e22010-11-13 05:38:03 +00001838void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1839 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1840 E = S->body_rend(); I != E; ++I) {
1841 AddStmt(*I);
1842 }
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001843}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001844void EnqueueVisitor::
Douglas Gregorba0513d2011-10-25 01:33:02 +00001845VisitMSDependentExistsStmt(MSDependentExistsStmt *S) {
1846 AddStmt(S->getSubStmt());
1847 AddDeclarationNameInfo(S);
1848 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
1849 AddNestedNameSpecifierLoc(QualifierLoc);
1850}
1851
1852void EnqueueVisitor::
Ted Kremenekf64d8032010-11-18 00:02:32 +00001853VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
1854 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1855 AddDeclarationNameInfo(E);
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001856 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1857 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001858 if (!E->isImplicitAccess())
1859 AddStmt(E->getBase());
1860}
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001861void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001862 // Enqueue the initializer , if any.
1863 AddStmt(E->getInitializer());
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001864 // Enqueue the array size, if any.
1865 AddStmt(E->getArraySize());
1866 // Enqueue the allocated type.
1867 AddTypeLoc(E->getAllocatedTypeSourceInfo());
1868 // Enqueue the placement arguments.
1869 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1870 AddStmt(E->getPlacementArg(I-1));
1871}
Ted Kremenek28a71942010-11-13 00:36:47 +00001872void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
Ted Kremenek8b8d8c92010-11-13 05:55:56 +00001873 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1874 AddStmt(CE->getArg(I-1));
Ted Kremenek28a71942010-11-13 00:36:47 +00001875 AddStmt(CE->getCallee());
1876 AddStmt(CE->getArg(0));
1877}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001878void EnqueueVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1879 // Visit the name of the type being destroyed.
1880 AddTypeLoc(E->getDestroyedTypeInfo());
1881 // Visit the scope type that looks disturbingly like the nested-name-specifier
1882 // but isn't.
1883 AddTypeLoc(E->getScopeTypeInfo());
1884 // Visit the nested-name-specifier.
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001885 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1886 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001887 // Visit base expression.
1888 AddStmt(E->getBase());
1889}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001890void EnqueueVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1891 AddTypeLoc(E->getTypeSourceInfo());
1892}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001893void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1894 EnqueueChildren(E);
1895 AddTypeLoc(E->getTypeSourceInfo());
1896}
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001897void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1898 EnqueueChildren(E);
1899 if (E->isTypeOperand())
1900 AddTypeLoc(E->getTypeOperandSourceInfo());
1901}
Ted Kremenek55b933a2010-11-17 00:50:36 +00001902
1903void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
1904 *E) {
1905 EnqueueChildren(E);
1906 AddTypeLoc(E->getTypeSourceInfo());
1907}
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001908void EnqueueVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1909 EnqueueChildren(E);
1910 if (E->isTypeOperand())
1911 AddTypeLoc(E->getTypeOperandSourceInfo());
1912}
Argyrios Kyrtzidisdcbb2fb2011-12-03 03:49:44 +00001913
1914void EnqueueVisitor::VisitCXXCatchStmt(CXXCatchStmt *S) {
1915 EnqueueChildren(S);
1916 AddDecl(S->getExceptionDecl());
1917}
1918
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001919void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001920 if (DR->hasExplicitTemplateArgs()) {
1921 AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
1922 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001923 WL.push_back(DeclRefExprParts(DR, Parent));
1924}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001925void EnqueueVisitor::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
1926 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1927 AddDeclarationNameInfo(E);
Douglas Gregor00cf3cc2011-02-25 20:49:16 +00001928 AddNestedNameSpecifierLoc(E->getQualifierLoc());
Ted Kremenekf64d8032010-11-18 00:02:32 +00001929}
Ted Kremenek035dc412010-11-13 00:36:50 +00001930void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1931 unsigned size = WL.size();
1932 bool isFirst = true;
1933 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1934 D != DEnd; ++D) {
1935 AddDecl(*D, isFirst);
1936 isFirst = false;
1937 }
1938 if (size == WL.size())
1939 return;
1940 // Now reverse the entries we just added. This will match the DFS
1941 // ordering performed by the worklist.
1942 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1943 std::reverse(I, E);
1944}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001945void EnqueueVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1946 AddStmt(E->getInit());
1947 typedef DesignatedInitExpr::Designator Designator;
1948 for (DesignatedInitExpr::reverse_designators_iterator
1949 D = E->designators_rbegin(), DEnd = E->designators_rend();
1950 D != DEnd; ++D) {
1951 if (D->isFieldDesignator()) {
1952 if (FieldDecl *Field = D->getField())
1953 AddMemberRef(Field, D->getFieldLoc());
1954 continue;
1955 }
1956 if (D->isArrayDesignator()) {
1957 AddStmt(E->getArrayIndex(*D));
1958 continue;
1959 }
1960 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1961 AddStmt(E->getArrayRangeEnd(*D));
1962 AddStmt(E->getArrayRangeStart(*D));
1963 }
1964}
Ted Kremenek28a71942010-11-13 00:36:47 +00001965void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1966 EnqueueChildren(E);
1967 AddTypeLoc(E->getTypeInfoAsWritten());
1968}
1969void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1970 AddStmt(FS->getBody());
1971 AddStmt(FS->getInc());
1972 AddStmt(FS->getCond());
1973 AddDecl(FS->getConditionVariable());
1974 AddStmt(FS->getInit());
1975}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001976void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) {
1977 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
1978}
Ted Kremenek28a71942010-11-13 00:36:47 +00001979void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
1980 AddStmt(If->getElse());
1981 AddStmt(If->getThen());
1982 AddStmt(If->getCond());
1983 AddDecl(If->getConditionVariable());
1984}
1985void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
1986 // We care about the syntactic form of the initializer list, only.
1987 if (InitListExpr *Syntactic = IE->getSyntacticForm())
1988 IE = Syntactic;
1989 EnqueueChildren(IE);
1990}
1991void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
Douglas Gregor89629a72010-11-17 17:15:08 +00001992 WL.push_back(MemberExprParts(M, Parent));
1993
1994 // If the base of the member access expression is an implicit 'this', don't
1995 // visit it.
1996 // FIXME: If we ever want to show these implicit accesses, this will be
1997 // unfortunate. However, clang_getCursor() relies on this behavior.
Douglas Gregor75e85042011-03-02 21:06:53 +00001998 if (!M->isImplicitAccess())
1999 AddStmt(M->getBase());
Ted Kremenek28a71942010-11-13 00:36:47 +00002000}
Ted Kremenek73d15c42010-11-13 01:09:29 +00002001void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
2002 AddTypeLoc(E->getEncodedTypeSourceInfo());
2003}
Ted Kremenek28a71942010-11-13 00:36:47 +00002004void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
2005 EnqueueChildren(M);
2006 AddTypeLoc(M->getClassReceiverTypeInfo());
2007}
Ted Kremenekcdba6592010-11-18 00:42:18 +00002008void EnqueueVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
2009 // Visit the components of the offsetof expression.
2010 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
2011 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
2012 const OffsetOfNode &Node = E->getComponent(I-1);
2013 switch (Node.getKind()) {
2014 case OffsetOfNode::Array:
2015 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2016 break;
2017 case OffsetOfNode::Field:
Abramo Bagnara06dec892011-03-12 09:45:03 +00002018 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
Ted Kremenekcdba6592010-11-18 00:42:18 +00002019 break;
2020 case OffsetOfNode::Identifier:
2021 case OffsetOfNode::Base:
2022 continue;
2023 }
2024 }
2025 // Visit the type into which we're computing the offset.
2026 AddTypeLoc(E->getTypeSourceInfo());
2027}
Ted Kremenek28a71942010-11-13 00:36:47 +00002028void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00002029 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
Ted Kremenek60458782010-11-12 21:34:16 +00002030 WL.push_back(OverloadExprParts(E, Parent));
2031}
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002032void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
2033 UnaryExprOrTypeTraitExpr *E) {
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00002034 EnqueueChildren(E);
2035 if (E->isArgumentType())
2036 AddTypeLoc(E->getArgumentTypeInfo());
2037}
Ted Kremenek28a71942010-11-13 00:36:47 +00002038void EnqueueVisitor::VisitStmt(Stmt *S) {
2039 EnqueueChildren(S);
2040}
2041void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
2042 AddStmt(S->getBody());
2043 AddStmt(S->getCond());
2044 AddDecl(S->getConditionVariable());
2045}
Ted Kremenekfafa75a2010-11-17 00:50:39 +00002046
Ted Kremenek28a71942010-11-13 00:36:47 +00002047void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
2048 AddStmt(W->getBody());
2049 AddStmt(W->getCond());
2050 AddDecl(W->getConditionVariable());
2051}
John Wiegley21ff2e52011-04-28 00:16:57 +00002052
Ted Kremenek2939b6f2010-11-17 00:50:50 +00002053void EnqueueVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
2054 AddTypeLoc(E->getQueriedTypeSourceInfo());
2055}
Francois Pichet6ad6f282010-12-07 00:08:36 +00002056
2057void EnqueueVisitor::VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
Francois Pichet6ad6f282010-12-07 00:08:36 +00002058 AddTypeLoc(E->getRhsTypeSourceInfo());
Francois Pichet0a03a3f2010-12-08 09:11:05 +00002059 AddTypeLoc(E->getLhsTypeSourceInfo());
Francois Pichet6ad6f282010-12-07 00:08:36 +00002060}
2061
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00002062void EnqueueVisitor::VisitTypeTraitExpr(TypeTraitExpr *E) {
2063 for (unsigned I = E->getNumArgs(); I > 0; --I)
2064 AddTypeLoc(E->getArg(I-1));
2065}
2066
John Wiegley21ff2e52011-04-28 00:16:57 +00002067void EnqueueVisitor::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
2068 AddTypeLoc(E->getQueriedTypeSourceInfo());
2069}
2070
John Wiegley55262202011-04-25 06:54:41 +00002071void EnqueueVisitor::VisitExpressionTraitExpr(ExpressionTraitExpr *E) {
2072 EnqueueChildren(E);
2073}
2074
Ted Kremenek28a71942010-11-13 00:36:47 +00002075void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
2076 VisitOverloadExpr(U);
2077 if (!U->isImplicitAccess())
2078 AddStmt(U->getBase());
2079}
Ted Kremenek9d3bf792010-11-17 00:50:43 +00002080void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) {
2081 AddStmt(E->getSubExpr());
2082 AddTypeLoc(E->getWrittenTypeInfo());
2083}
Douglas Gregor94d96292011-01-19 20:34:17 +00002084void EnqueueVisitor::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
2085 WL.push_back(SizeOfPackExprParts(E, Parent));
2086}
John McCall4b9c2d22011-11-06 09:01:30 +00002087void EnqueueVisitor::VisitOpaqueValueExpr(OpaqueValueExpr *E) {
2088 // If the opaque value has a source expression, just transparently
2089 // visit that. This is useful for (e.g.) pseudo-object expressions.
2090 if (Expr *SourceExpr = E->getSourceExpr())
2091 return Visit(SourceExpr);
John McCall4b9c2d22011-11-06 09:01:30 +00002092}
Douglas Gregor011d8b92012-02-15 00:54:55 +00002093void EnqueueVisitor::VisitLambdaExpr(LambdaExpr *E) {
2094 AddStmt(E->getBody());
2095 WL.push_back(LambdaExprParts(E, Parent));
2096}
John McCall4b9c2d22011-11-06 09:01:30 +00002097void EnqueueVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *E) {
2098 // Treat the expression like its syntactic form.
2099 Visit(E->getSyntacticForm());
2100}
Ted Kremenek60458782010-11-12 21:34:16 +00002101
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002102void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002103 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002104}
2105
2106bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2107 if (RegionOfInterest.isValid()) {
2108 SourceRange Range = getRawCursorExtent(C);
2109 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2110 return false;
2111 }
2112 return true;
2113}
2114
2115bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2116 while (!WL.empty()) {
2117 // Dequeue the worklist item.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002118 VisitorJob LI = WL.back();
2119 WL.pop_back();
2120
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002121 // Set the Parent field, then back to its old value once we're done.
2122 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2123
2124 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00002125 case VisitorJob::DeclVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002126 Decl *D = cast<DeclVisit>(&LI)->get();
Ted Kremenekf1107452010-11-12 18:26:56 +00002127 if (!D)
2128 continue;
2129
2130 // For now, perform default visitation for Decls.
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002131 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2132 cast<DeclVisit>(&LI)->isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00002133 return true;
2134
2135 continue;
2136 }
Ted Kremenek60608ec2010-11-17 00:50:47 +00002137 case VisitorJob::ExplicitTemplateArgsVisitKind: {
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00002138 const ASTTemplateArgumentListInfo *ArgList =
Ted Kremenek60608ec2010-11-17 00:50:47 +00002139 cast<ExplicitTemplateArgsVisit>(&LI)->get();
2140 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2141 *ArgEnd = Arg + ArgList->NumTemplateArgs;
2142 Arg != ArgEnd; ++Arg) {
2143 if (VisitTemplateArgumentLoc(*Arg))
2144 return true;
2145 }
2146 continue;
2147 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002148 case VisitorJob::TypeLocVisitKind: {
2149 // Perform default visitation for TypeLocs.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002150 if (Visit(cast<TypeLocVisit>(&LI)->get()))
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002151 return true;
2152 continue;
2153 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002154 case VisitorJob::LabelRefVisitKind: {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002155 LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Ted Kremeneke7455012011-02-23 04:54:51 +00002156 if (LabelStmt *stmt = LS->getStmt()) {
2157 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2158 TU))) {
2159 return true;
2160 }
2161 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002162 continue;
2163 }
Ted Kremenek47695c82011-08-18 22:25:21 +00002164
Douglas Gregorf3db29f2011-02-25 18:19:59 +00002165 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2166 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2167 if (VisitNestedNameSpecifierLoc(V->get()))
2168 return true;
2169 continue;
2170 }
2171
Ted Kremenekf64d8032010-11-18 00:02:32 +00002172 case VisitorJob::DeclarationNameInfoVisitKind: {
2173 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2174 ->get()))
2175 return true;
2176 continue;
2177 }
Ted Kremenekcdba6592010-11-18 00:42:18 +00002178 case VisitorJob::MemberRefVisitKind: {
2179 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2180 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2181 return true;
2182 continue;
2183 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002184 case VisitorJob::StmtVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002185 Stmt *S = cast<StmtVisit>(&LI)->get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00002186 if (!S)
2187 continue;
2188
Ted Kremenekf1107452010-11-12 18:26:56 +00002189 // Update the current cursor.
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002190 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
Ted Kremenekcdba6592010-11-18 00:42:18 +00002191 if (!IsInRegionOfInterest(Cursor))
2192 continue;
2193 switch (Visitor(Cursor, Parent, ClientData)) {
2194 case CXChildVisit_Break: return true;
2195 case CXChildVisit_Continue: break;
2196 case CXChildVisit_Recurse:
2197 EnqueueWorkList(WL, S);
Ted Kremenek82f3c502010-11-15 22:23:26 +00002198 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002199 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00002200 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002201 }
2202 case VisitorJob::MemberExprPartsKind: {
2203 // Handle the other pieces in the MemberExpr besides the base.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002204 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002205
2206 // Visit the nested-name-specifier
Douglas Gregor40d96a62011-02-28 21:54:11 +00002207 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
2208 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002209 return true;
2210
2211 // Visit the declaration name.
2212 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2213 return true;
2214
2215 // Visit the explicitly-specified template arguments, if any.
2216 if (M->hasExplicitTemplateArgs()) {
2217 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2218 *ArgEnd = Arg + M->getNumTemplateArgs();
2219 Arg != ArgEnd; ++Arg) {
2220 if (VisitTemplateArgumentLoc(*Arg))
2221 return true;
2222 }
2223 }
2224 continue;
2225 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002226 case VisitorJob::DeclRefExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002227 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002228 // Visit nested-name-specifier, if present.
Douglas Gregor40d96a62011-02-28 21:54:11 +00002229 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
2230 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002231 return true;
2232 // Visit declaration name.
2233 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2234 return true;
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002235 continue;
2236 }
Ted Kremenek60458782010-11-12 21:34:16 +00002237 case VisitorJob::OverloadExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002238 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Ted Kremenek60458782010-11-12 21:34:16 +00002239 // Visit the nested-name-specifier.
Douglas Gregor4c9be892011-02-28 20:01:57 +00002240 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
2241 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenek60458782010-11-12 21:34:16 +00002242 return true;
2243 // Visit the declaration name.
2244 if (VisitDeclarationNameInfo(O->getNameInfo()))
2245 return true;
2246 // Visit the overloaded declaration reference.
2247 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2248 return true;
Ted Kremenek60458782010-11-12 21:34:16 +00002249 continue;
2250 }
Douglas Gregor94d96292011-01-19 20:34:17 +00002251 case VisitorJob::SizeOfPackExprPartsKind: {
2252 SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
2253 NamedDecl *Pack = E->getPack();
2254 if (isa<TemplateTypeParmDecl>(Pack)) {
2255 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
2256 E->getPackLoc(), TU)))
2257 return true;
2258
2259 continue;
2260 }
2261
2262 if (isa<TemplateTemplateParmDecl>(Pack)) {
2263 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
2264 E->getPackLoc(), TU)))
2265 return true;
2266
2267 continue;
2268 }
2269
2270 // Non-type template parameter packs and function parameter packs are
2271 // treated like DeclRefExpr cursors.
2272 continue;
2273 }
Douglas Gregor011d8b92012-02-15 00:54:55 +00002274
2275 case VisitorJob::LambdaExprPartsKind: {
2276 // Visit captures.
2277 LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
2278 for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
2279 CEnd = E->explicit_capture_end();
2280 C != CEnd; ++C) {
2281 if (C->capturesThis())
2282 continue;
2283
2284 if (Visit(MakeCursorVariableRef(C->getCapturedVar(),
2285 C->getLocation(),
2286 TU)))
2287 return true;
2288 }
2289
2290 // Visit parameters and return type, if present.
2291 if (E->hasExplicitParameters() || E->hasExplicitResultType()) {
2292 TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
2293 if (E->hasExplicitParameters() && E->hasExplicitResultType()) {
2294 // Visit the whole type.
2295 if (Visit(TL))
2296 return true;
2297 } else if (isa<FunctionProtoTypeLoc>(TL)) {
2298 FunctionProtoTypeLoc Proto = cast<FunctionProtoTypeLoc>(TL);
2299 if (E->hasExplicitParameters()) {
2300 // Visit parameters.
2301 for (unsigned I = 0, N = Proto.getNumArgs(); I != N; ++I)
2302 if (Visit(MakeCXCursor(Proto.getArg(I), TU)))
2303 return true;
2304 } else {
2305 // Visit result type.
2306 if (Visit(Proto.getResultLoc()))
2307 return true;
2308 }
2309 }
2310 }
2311 break;
2312 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002313 }
2314 }
2315 return false;
2316}
2317
Ted Kremenekcdba6592010-11-18 00:42:18 +00002318bool CursorVisitor::Visit(Stmt *S) {
Ted Kremenekd1ded662010-11-15 23:31:32 +00002319 VisitorWorkList *WL = 0;
2320 if (!WorkListFreeList.empty()) {
2321 WL = WorkListFreeList.back();
2322 WL->clear();
2323 WorkListFreeList.pop_back();
2324 }
2325 else {
2326 WL = new VisitorWorkList();
2327 WorkListCache.push_back(WL);
2328 }
2329 EnqueueWorkList(*WL, S);
2330 bool result = RunVisitorWorkList(*WL);
2331 WorkListFreeList.push_back(WL);
2332 return result;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002333}
2334
Francois Pichet48a8d142011-07-25 22:00:44 +00002335namespace {
2336typedef llvm::SmallVector<SourceRange, 4> RefNamePieces;
2337RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
2338 const DeclarationNameInfo &NI,
2339 const SourceRange &QLoc,
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00002340 const ASTTemplateArgumentListInfo *TemplateArgs = 0){
Francois Pichet48a8d142011-07-25 22:00:44 +00002341 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
2342 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
2343 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
2344
2345 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
2346
2347 RefNamePieces Pieces;
2348
2349 if (WantQualifier && QLoc.isValid())
2350 Pieces.push_back(QLoc);
2351
2352 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
2353 Pieces.push_back(NI.getLoc());
2354
2355 if (WantTemplateArgs && TemplateArgs)
2356 Pieces.push_back(SourceRange(TemplateArgs->LAngleLoc,
2357 TemplateArgs->RAngleLoc));
2358
2359 if (Kind == DeclarationName::CXXOperatorName) {
2360 Pieces.push_back(SourceLocation::getFromRawEncoding(
2361 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
2362 Pieces.push_back(SourceLocation::getFromRawEncoding(
2363 NI.getInfo().CXXOperatorName.EndOpNameLoc));
2364 }
2365
2366 if (WantSinglePiece) {
2367 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
2368 Pieces.clear();
2369 Pieces.push_back(R);
2370 }
2371
2372 return Pieces;
2373}
2374}
2375
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002376//===----------------------------------------------------------------------===//
2377// Misc. API hooks.
2378//===----------------------------------------------------------------------===//
2379
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002380static llvm::sys::Mutex EnableMultithreadingMutex;
2381static bool EnabledMultithreading;
2382
Argyrios Kyrtzidisfa39f5b2011-12-15 04:52:41 +00002383static void fatal_error_handler(void *user_data, const std::string& reason) {
Argyrios Kyrtzidisfa39f5b2011-12-15 04:52:41 +00002384 // Write the result out to stderr avoiding errs() because raw_ostreams can
2385 // call report_fatal_error.
Argyrios Kyrtzidisdb7a8002011-12-15 06:51:30 +00002386 fprintf(stderr, "LIBCLANG FATAL ERROR: %s\n", reason.c_str());
Argyrios Kyrtzidisfa39f5b2011-12-15 04:52:41 +00002387 ::abort();
2388}
2389
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002390extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002391CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2392 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002393 // Disable pretty stack trace functionality, which will otherwise be a very
2394 // poor citizen of the world and set up all sorts of signal handlers.
2395 llvm::DisablePrettyStackTrace = true;
2396
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002397 // We use crash recovery to make some of our APIs more reliable, implicitly
2398 // enable it.
2399 llvm::CrashRecoveryContext::Enable();
2400
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002401 // Enable support for multithreading in LLVM.
2402 {
2403 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2404 if (!EnabledMultithreading) {
Argyrios Kyrtzidisfa39f5b2011-12-15 04:52:41 +00002405 llvm::install_fatal_error_handler(fatal_error_handler, 0);
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002406 llvm::llvm_start_multithreaded();
2407 EnabledMultithreading = true;
2408 }
2409 }
2410
Douglas Gregora030b7c2010-01-22 20:35:53 +00002411 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002412 if (excludeDeclarationsFromPCH)
2413 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002414 if (displayDiagnostics)
2415 CIdxr->setDisplayDiagnostics();
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002416
2417 if (getenv("LIBCLANG_BGPRIO_INDEX"))
2418 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
2419 CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
2420 if (getenv("LIBCLANG_BGPRIO_EDIT"))
2421 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
2422 CXGlobalOpt_ThreadBackgroundPriorityForEditing);
2423
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002424 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002425}
2426
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002427void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002428 if (CIdx)
2429 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002430}
2431
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002432void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
2433 if (CIdx)
2434 static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
2435}
2436
2437unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
2438 if (CIdx)
2439 return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
2440 return 0;
2441}
2442
Ted Kremenekd2427dd2011-03-18 23:05:39 +00002443void clang_toggleCrashRecovery(unsigned isEnabled) {
2444 if (isEnabled)
2445 llvm::CrashRecoveryContext::Enable();
2446 else
2447 llvm::CrashRecoveryContext::Disable();
2448}
2449
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002450CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002451 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002452 if (!CIdx)
2453 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002454
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002455 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002456 FileSystemOptions FileSystemOpts;
2457 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002458
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00002459 IntrusiveRefCntPtr<DiagnosticsEngine> Diags;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002460 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002461 CXXIdx->getOnlyLocalDecls(),
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00002462 0, 0,
2463 /*CaptureDiagnostics=*/true,
2464 /*AllowPCHWithCompilerErrors=*/true);
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002465 return MakeCXTranslationUnit(CXXIdx, TU);
Steve Naroff600866c2009-08-27 19:51:58 +00002466}
2467
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002468unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002469 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregorb5af8432011-08-25 22:54:01 +00002470 CXTranslationUnit_CacheCompletionResults;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002471}
2472
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002473CXTranslationUnit
2474clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2475 const char *source_filename,
2476 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002477 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002478 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002479 struct CXUnsavedFile *unsaved_files) {
Argyrios Kyrtzidise1d43302012-02-25 02:41:16 +00002480 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
Douglas Gregor5a430212010-07-21 18:52:53 +00002481 return clang_parseTranslationUnit(CIdx, source_filename,
2482 command_line_args, num_command_line_args,
2483 unsaved_files, num_unsaved_files,
Douglas Gregordca8ee82011-05-06 16:33:08 +00002484 Options);
Douglas Gregor5a430212010-07-21 18:52:53 +00002485}
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00002486
2487void cxindex::printDiagsToStderr(ASTUnit *Unit) {
2488 if (!Unit)
2489 return;
2490
2491 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2492 DEnd = Unit->stored_diag_end();
2493 D != DEnd; ++D) {
2494 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOpts());
2495 CXString Msg = clang_formatDiagnostic(&Diag,
2496 clang_defaultDiagnosticDisplayOptions());
2497 fprintf(stderr, "%s\n", clang_getCString(Msg));
2498 clang_disposeString(Msg);
2499 }
2500#ifdef LLVM_ON_WIN32
2501 // On Windows, force a flush, since there may be multiple copies of
2502 // stderr and stdout in the file system, all with different buffers
2503 // but writing to the same device.
2504 fflush(stderr);
2505#endif
2506}
2507
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002508struct ParseTranslationUnitInfo {
2509 CXIndex CIdx;
2510 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002511 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002512 int num_command_line_args;
2513 struct CXUnsavedFile *unsaved_files;
2514 unsigned num_unsaved_files;
2515 unsigned options;
2516 CXTranslationUnit result;
2517};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002518static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002519 ParseTranslationUnitInfo *PTUI =
2520 static_cast<ParseTranslationUnitInfo*>(UserData);
2521 CXIndex CIdx = PTUI->CIdx;
2522 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002523 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002524 int num_command_line_args = PTUI->num_command_line_args;
2525 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2526 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2527 unsigned options = PTUI->options;
2528 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002529
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002530 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002531 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002532
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002533 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2534
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002535 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
Argyrios Kyrtzidis81b5ac32012-03-28 02:49:54 +00002536 setThreadBackgroundPriority();
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002537
Douglas Gregor44c181a2010-07-23 00:33:23 +00002538 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregor467dc882011-08-25 22:30:56 +00002539 // FIXME: Add a flag for modules.
2540 TranslationUnitKind TUKind
2541 = (options & CXTranslationUnit_Incomplete)? TU_Prefix : TU_Complete;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002542 bool CacheCodeCompetionResults
2543 = options & CXTranslationUnit_CacheCompletionResults;
2544
Douglas Gregor5352ac02010-01-28 00:27:43 +00002545 // Configure the diagnostics.
2546 DiagnosticOptions DiagOpts;
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00002547 IntrusiveRefCntPtr<DiagnosticsEngine>
Ted Kremenek25a11e12011-03-22 01:15:24 +00002548 Diags(CompilerInstance::createDiagnostics(DiagOpts, num_command_line_args,
2549 command_line_args));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002550
Ted Kremenek25a11e12011-03-22 01:15:24 +00002551 // Recover resources if we crash before exiting this function.
David Blaikied6471f72011-09-25 23:23:43 +00002552 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
2553 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00002554 DiagCleanup(Diags.getPtr());
2555
Dylan Noblesmith1e4c01b2012-02-13 12:32:21 +00002556 OwningPtr<std::vector<ASTUnit::RemappedFile> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00002557 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2558
2559 // Recover resources if we crash before exiting this function.
2560 llvm::CrashRecoveryContextCleanupRegistrar<
2561 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2562
Douglas Gregor4db64a42010-01-23 00:14:00 +00002563 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002564 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002565 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002566 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002567 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2568 Buffer));
Douglas Gregor4db64a42010-01-23 00:14:00 +00002569 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002570
Dylan Noblesmith1e4c01b2012-02-13 12:32:21 +00002571 OwningPtr<std::vector<const char *> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00002572 Args(new std::vector<const char*>());
2573
2574 // Recover resources if we crash before exiting this method.
2575 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
2576 ArgsCleanup(Args.get());
2577
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002578 // Since the Clang C library is primarily used by batch tools dealing with
2579 // (often very broken) source code, where spell-checking can have a
2580 // significant negative impact on performance (particularly when
2581 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002582 // Only do this if we haven't found a spell-checking-related argument.
2583 bool FoundSpellCheckingArgument = false;
2584 for (int I = 0; I != num_command_line_args; ++I) {
2585 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2586 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2587 FoundSpellCheckingArgument = true;
2588 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002589 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002590 }
2591 if (!FoundSpellCheckingArgument)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002592 Args->push_back("-fno-spell-checking");
Douglas Gregorb10daed2010-10-11 16:52:23 +00002593
Ted Kremenek25a11e12011-03-22 01:15:24 +00002594 Args->insert(Args->end(), command_line_args,
2595 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002596
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002597 // The 'source_filename' argument is optional. If the caller does not
2598 // specify it then it is assumed that the source file is specified
2599 // in the actual argument list.
2600 // Put the source file after command_line_args otherwise if '-x' flag is
2601 // present it will be unused.
2602 if (source_filename)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002603 Args->push_back(source_filename);
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002604
Douglas Gregor44c181a2010-07-23 00:33:23 +00002605 // Do we need the detailed preprocessing record?
2606 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Ted Kremenek25a11e12011-03-22 01:15:24 +00002607 Args->push_back("-Xclang");
2608 Args->push_back("-detailed-preprocessing-record");
Douglas Gregor44c181a2010-07-23 00:33:23 +00002609 }
2610
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002611 unsigned NumErrors = Diags->getClient()->getNumErrors();
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00002612 OwningPtr<ASTUnit> ErrUnit;
Dylan Noblesmith1e4c01b2012-02-13 12:32:21 +00002613 OwningPtr<ASTUnit> Unit(
Ted Kremenek4ee99262011-03-22 20:16:19 +00002614 ASTUnit::LoadFromCommandLine(Args->size() ? &(*Args)[0] : 0
2615 /* vector::data() not portable */,
2616 Args->size() ? (&(*Args)[0] + Args->size()) :0,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002617 Diags,
2618 CXXIdx->getClangResourcesPath(),
2619 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002620 /*CaptureDiagnostics=*/true,
Ted Kremenek4ee99262011-03-22 20:16:19 +00002621 RemappedFiles->size() ? &(*RemappedFiles)[0]:0,
Ted Kremenek25a11e12011-03-22 01:15:24 +00002622 RemappedFiles->size(),
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00002623 /*RemappedFilesKeepOriginalName=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002624 PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00002625 TUKind,
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00002626 CacheCodeCompetionResults,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00002627 /*AllowPCHWithCompilerErrors=*/true,
2628 &ErrUnit));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002629
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002630 if (NumErrors != Diags->getClient()->getNumErrors()) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002631 // Make sure to check that 'Unit' is non-NULL.
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00002632 if (CXXIdx->getDisplayDiagnostics())
2633 printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
Douglas Gregora88084b2010-02-18 18:08:43 +00002634 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002635
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002636 PTUI->result = MakeCXTranslationUnit(CXXIdx, Unit.take());
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002637}
2638CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2639 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002640 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002641 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002642 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002643 unsigned num_unsaved_files,
2644 unsigned options) {
2645 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002646 num_command_line_args, unsaved_files,
2647 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002648 llvm::CrashRecoveryContext CRC;
2649
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002650 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002651 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2652 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2653 fprintf(stderr, " 'command_line_args' : [");
2654 for (int i = 0; i != num_command_line_args; ++i) {
2655 if (i)
2656 fprintf(stderr, ", ");
2657 fprintf(stderr, "'%s'", command_line_args[i]);
2658 }
2659 fprintf(stderr, "],\n");
2660 fprintf(stderr, " 'unsaved_files' : [");
2661 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2662 if (i)
2663 fprintf(stderr, ", ");
2664 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2665 unsaved_files[i].Length);
2666 }
2667 fprintf(stderr, "],\n");
2668 fprintf(stderr, " 'options' : %d,\n", options);
2669 fprintf(stderr, "}\n");
2670
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002671 return 0;
Douglas Gregor6df78732011-05-05 20:27:22 +00002672 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
2673 PrintLibclangResourceUsage(PTUI.result);
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002674 }
Douglas Gregor6df78732011-05-05 20:27:22 +00002675
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002676 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002677}
2678
Douglas Gregor19998442010-08-13 15:35:05 +00002679unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2680 return CXSaveTranslationUnit_None;
2681}
Argyrios Kyrtzidis142bcb52012-03-28 02:17:59 +00002682
2683namespace {
2684
2685struct SaveTranslationUnitInfo {
2686 CXTranslationUnit TU;
2687 const char *FileName;
2688 unsigned options;
2689 CXSaveError result;
2690};
2691
2692}
2693
2694static void clang_saveTranslationUnit_Impl(void *UserData) {
2695 SaveTranslationUnitInfo *STUI =
2696 static_cast<SaveTranslationUnitInfo*>(UserData);
2697
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002698 CIndexer *CXXIdx = (CIndexer*)STUI->TU->CIdx;
2699 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
Argyrios Kyrtzidis81b5ac32012-03-28 02:49:54 +00002700 setThreadBackgroundPriority();
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002701
Argyrios Kyrtzidis142bcb52012-03-28 02:17:59 +00002702 STUI->result = static_cast<ASTUnit *>(STUI->TU->TUData)->Save(STUI->FileName);
2703}
2704
Douglas Gregor19998442010-08-13 15:35:05 +00002705int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2706 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002707 if (!TU)
Douglas Gregor39c411f2011-07-06 16:43:36 +00002708 return CXSaveError_InvalidTU;
Argyrios Kyrtzidis142bcb52012-03-28 02:17:59 +00002709
2710 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
2711 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2712
2713 SaveTranslationUnitInfo STUI = { TU, FileName, options, CXSaveError_None };
2714
2715 if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred() ||
2716 getenv("LIBCLANG_NOTHREADS")) {
2717 clang_saveTranslationUnit_Impl(&STUI);
2718
2719 if (getenv("LIBCLANG_RESOURCE_USAGE"))
2720 PrintLibclangResourceUsage(TU);
2721
2722 return STUI.result;
2723 }
2724
2725 // We have an AST that has invalid nodes due to compiler errors.
2726 // Use a crash recovery thread for protection.
2727
2728 llvm::CrashRecoveryContext CRC;
2729
2730 if (!RunSafely(CRC, clang_saveTranslationUnit_Impl, &STUI)) {
2731 fprintf(stderr, "libclang: crash detected during AST saving: {\n");
2732 fprintf(stderr, " 'filename' : '%s'\n", FileName);
2733 fprintf(stderr, " 'options' : %d,\n", options);
2734 fprintf(stderr, "}\n");
2735
2736 return CXSaveError_Unknown;
2737
2738 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
Douglas Gregor6df78732011-05-05 20:27:22 +00002739 PrintLibclangResourceUsage(TU);
Argyrios Kyrtzidis142bcb52012-03-28 02:17:59 +00002740 }
2741
2742 return STUI.result;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002743}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002744
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002745void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002746 if (CTUnit) {
2747 // If the translation unit has been marked as unsafe to free, just discard
2748 // it.
Ted Kremeneka60ed472010-11-16 08:15:36 +00002749 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002750 return;
2751
Ted Kremeneka60ed472010-11-16 08:15:36 +00002752 delete static_cast<ASTUnit *>(CTUnit->TUData);
2753 disposeCXStringPool(CTUnit->StringPool);
Ted Kremenek15322172011-11-10 08:43:12 +00002754 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002755 delete CTUnit;
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002756 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002757}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002758
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002759unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2760 return CXReparse_None;
2761}
2762
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002763struct ReparseTranslationUnitInfo {
2764 CXTranslationUnit TU;
2765 unsigned num_unsaved_files;
2766 struct CXUnsavedFile *unsaved_files;
2767 unsigned options;
2768 int result;
2769};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002770
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002771static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002772 ReparseTranslationUnitInfo *RTUI =
2773 static_cast<ReparseTranslationUnitInfo*>(UserData);
2774 CXTranslationUnit TU = RTUI->TU;
Ted Kremenek15322172011-11-10 08:43:12 +00002775
2776 // Reset the associated diagnostics.
2777 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
2778 TU->Diagnostics = 0;
2779
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002780 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2781 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2782 unsigned options = RTUI->options;
2783 (void) options;
2784 RTUI->result = 1;
2785
Douglas Gregorabc563f2010-07-19 21:46:24 +00002786 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002787 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002788
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002789 CIndexer *CXXIdx = (CIndexer*)TU->CIdx;
2790 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
Argyrios Kyrtzidis81b5ac32012-03-28 02:49:54 +00002791 setThreadBackgroundPriority();
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002792
Ted Kremeneka60ed472010-11-16 08:15:36 +00002793 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor593b0c12010-09-23 18:47:53 +00002794 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002795
Dylan Noblesmith1e4c01b2012-02-13 12:32:21 +00002796 OwningPtr<std::vector<ASTUnit::RemappedFile> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00002797 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2798
2799 // Recover resources if we crash before exiting this function.
2800 llvm::CrashRecoveryContextCleanupRegistrar<
2801 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2802
Douglas Gregorabc563f2010-07-19 21:46:24 +00002803 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002804 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002805 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002806 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002807 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2808 Buffer));
Douglas Gregorabc563f2010-07-19 21:46:24 +00002809 }
2810
Ted Kremenek4ee99262011-03-22 20:16:19 +00002811 if (!CXXUnit->Reparse(RemappedFiles->size() ? &(*RemappedFiles)[0] : 0,
2812 RemappedFiles->size()))
Douglas Gregor593b0c12010-09-23 18:47:53 +00002813 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002814}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002815
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002816int clang_reparseTranslationUnit(CXTranslationUnit TU,
2817 unsigned num_unsaved_files,
2818 struct CXUnsavedFile *unsaved_files,
2819 unsigned options) {
2820 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2821 options, 0 };
Argyrios Kyrtzidis8c4b47e2011-10-28 22:54:33 +00002822
Argyrios Kyrtzidise7de9b42011-10-29 19:32:39 +00002823 if (getenv("LIBCLANG_NOTHREADS")) {
Argyrios Kyrtzidis8c4b47e2011-10-28 22:54:33 +00002824 clang_reparseTranslationUnit_Impl(&RTUI);
2825 return RTUI.result;
2826 }
2827
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002828 llvm::CrashRecoveryContext CRC;
2829
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002830 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002831 fprintf(stderr, "libclang: crash detected during reparsing\n");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002832 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002833 return 1;
Douglas Gregor6df78732011-05-05 20:27:22 +00002834 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
2835 PrintLibclangResourceUsage(TU);
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002836
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002837 return RTUI.result;
2838}
2839
Douglas Gregordf95a132010-08-09 20:45:32 +00002840
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002841CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002842 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002843 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002844
Ted Kremeneka60ed472010-11-16 08:15:36 +00002845 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002846 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002847}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002848
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002849CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002850 CXCursor Result = { CXCursor_TranslationUnit, 0, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002851 return Result;
2852}
2853
Ted Kremenekfb480492010-01-13 21:46:36 +00002854} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002855
Ted Kremenekfb480492010-01-13 21:46:36 +00002856//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002857// CXFile Operations.
2858//===----------------------------------------------------------------------===//
2859
2860extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002861CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002862 if (!SFile)
Ted Kremeneka60ed472010-11-16 08:15:36 +00002863 return createCXString((const char*)NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002864
Steve Naroff88145032009-10-27 14:35:18 +00002865 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002866 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002867}
2868
2869time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002870 if (!SFile)
2871 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002872
Steve Naroff88145032009-10-27 14:35:18 +00002873 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2874 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002875}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002876
Douglas Gregorb9790342010-01-22 21:44:22 +00002877CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2878 if (!tu)
2879 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002880
Ted Kremeneka60ed472010-11-16 08:15:36 +00002881 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002882
Douglas Gregorb9790342010-01-22 21:44:22 +00002883 FileManager &FMgr = CXXUnit->getFileManager();
Chris Lattner39b49bc2010-11-23 08:35:12 +00002884 return const_cast<FileEntry *>(FMgr.getFile(file_name));
Douglas Gregorb9790342010-01-22 21:44:22 +00002885}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002886
Douglas Gregordd3e5542011-05-04 00:14:37 +00002887unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit tu, CXFile file) {
2888 if (!tu || !file)
2889 return 0;
2890
2891 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
2892 FileEntry *FEnt = static_cast<FileEntry *>(file);
2893 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
2894 .isFileMultipleIncludeGuarded(FEnt);
2895}
2896
Ted Kremenekfb480492010-01-13 21:46:36 +00002897} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002898
Ted Kremenekfb480492010-01-13 21:46:36 +00002899//===----------------------------------------------------------------------===//
2900// CXCursor Operations.
2901//===----------------------------------------------------------------------===//
2902
Ted Kremenekfb480492010-01-13 21:46:36 +00002903static Decl *getDeclFromExpr(Stmt *E) {
Argyrios Kyrtzidisc2954612011-09-12 22:17:26 +00002904 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Douglas Gregordb1314e2010-10-01 21:11:22 +00002905 return getDeclFromExpr(CE->getSubExpr());
2906
Ted Kremenekfb480492010-01-13 21:46:36 +00002907 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2908 return RefExpr->getDecl();
2909 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2910 return ME->getMemberDecl();
2911 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2912 return RE->getDecl();
Argyrios Kyrtzidisb085d892012-03-30 00:19:18 +00002913 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
2914 if (PRE->isExplicitProperty())
2915 return PRE->getExplicitProperty();
2916 // It could be messaging both getter and setter as in:
2917 // ++myobj.myprop;
2918 // in which case prefer to associate the setter since it is less obvious
2919 // from inspecting the source that the setter is going to get called.
2920 if (PRE->isMessagingSetter())
2921 return PRE->getImplicitPropertySetter();
2922 return PRE->getImplicitPropertyGetter();
2923 }
John McCall4b9c2d22011-11-06 09:01:30 +00002924 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
2925 return getDeclFromExpr(POE->getSyntacticForm());
2926 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
2927 if (Expr *Src = OVE->getSourceExpr())
2928 return getDeclFromExpr(Src);
Douglas Gregordb1314e2010-10-01 21:11:22 +00002929
Ted Kremenekfb480492010-01-13 21:46:36 +00002930 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2931 return getDeclFromExpr(CE->getCallee());
Chris Lattner5f9e2722011-07-23 10:55:15 +00002932 if (CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Douglas Gregor93798e22010-11-05 21:11:19 +00002933 if (!CE->isElidable())
2934 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002935 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2936 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002937
Douglas Gregordb1314e2010-10-01 21:11:22 +00002938 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2939 return PE->getProtocol();
Douglas Gregorc7793c72011-01-15 01:15:58 +00002940 if (SubstNonTypeTemplateParmPackExpr *NTTP
2941 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
2942 return NTTP->getParameterPack();
Douglas Gregor94d96292011-01-19 20:34:17 +00002943 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2944 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
2945 isa<ParmVarDecl>(SizeOfPack->getPack()))
2946 return SizeOfPack->getPack();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002947
Ted Kremenekfb480492010-01-13 21:46:36 +00002948 return 0;
2949}
2950
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002951static SourceLocation getLocationFromExpr(Expr *E) {
Argyrios Kyrtzidisc2954612011-09-12 22:17:26 +00002952 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
2953 return getLocationFromExpr(CE->getSubExpr());
2954
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002955 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2956 return /*FIXME:*/Msg->getLeftLoc();
2957 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2958 return DRE->getLocation();
2959 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2960 return Member->getMemberLoc();
2961 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2962 return Ivar->getLocation();
Douglas Gregor94d96292011-01-19 20:34:17 +00002963 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2964 return SizeOfPack->getPackLoc();
Argyrios Kyrtzidisd0469522012-03-30 00:19:13 +00002965 if (ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
2966 return PropRef->getLocation();
Douglas Gregor94d96292011-01-19 20:34:17 +00002967
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002968 return E->getLocStart();
2969}
2970
Ted Kremenekfb480492010-01-13 21:46:36 +00002971extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002972
2973unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002974 CXCursorVisitor visitor,
2975 CXClientData client_data) {
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00002976 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
2977 /*VisitPreprocessorLast=*/false);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002978 return CursorVis.VisitChildren(parent);
2979}
2980
David Chisnall3387c652010-11-03 14:12:26 +00002981#ifndef __has_feature
2982#define __has_feature(x) 0
2983#endif
2984#if __has_feature(blocks)
2985typedef enum CXChildVisitResult
2986 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2987
2988static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2989 CXClientData client_data) {
2990 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2991 return block(cursor, parent);
2992}
2993#else
2994// If we are compiled with a compiler that doesn't have native blocks support,
2995// define and call the block manually, so the
2996typedef struct _CXChildVisitResult
2997{
2998 void *isa;
2999 int flags;
3000 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003001 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
3002 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00003003} *CXCursorVisitorBlock;
3004
3005static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
3006 CXClientData client_data) {
3007 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
3008 return block->invoke(block, cursor, parent);
3009}
3010#endif
3011
3012
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003013unsigned clang_visitChildrenWithBlock(CXCursor parent,
3014 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00003015 return clang_visitChildren(parent, visitWithBlock, block);
3016}
3017
Douglas Gregor78205d42010-01-20 21:45:58 +00003018static CXString getDeclSpelling(Decl *D) {
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00003019 if (!D)
3020 return createCXString("");
3021
3022 NamedDecl *ND = dyn_cast<NamedDecl>(D);
Douglas Gregore3c60a72010-11-17 00:13:31 +00003023 if (!ND) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003024 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00003025 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3026 return createCXString(Property->getIdentifier()->getName());
3027
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003028 return createCXString("");
Douglas Gregore3c60a72010-11-17 00:13:31 +00003029 }
3030
Douglas Gregor78205d42010-01-20 21:45:58 +00003031 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003032 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003033
Douglas Gregor78205d42010-01-20 21:45:58 +00003034 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
3035 // No, this isn't the same as the code below. getIdentifier() is non-virtual
3036 // and returns different names. NamedDecl returns the class name and
3037 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003038 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003039
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003040 if (isa<UsingDirectiveDecl>(D))
3041 return createCXString("");
3042
Dylan Noblesmith36d59272012-02-13 12:32:26 +00003043 SmallString<1024> S;
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00003044 llvm::raw_svector_ostream os(S);
3045 ND->printName(os);
3046
3047 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00003048}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003049
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003050CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003051 if (clang_isTranslationUnit(C.kind))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003052 return clang_getTranslationUnitSpelling(
3053 static_cast<CXTranslationUnit>(C.data[2]));
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003054
Steve Narofff334b4e2009-09-02 18:26:48 +00003055 if (clang_isReference(C.kind)) {
3056 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00003057 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00003058 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003059 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003060 }
3061 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00003062 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003063 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003064 }
3065 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00003066 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00003067 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003068 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003069 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00003070 case CXCursor_CXXBaseSpecifier: {
3071 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
3072 return createCXString(B->getType().getAsString());
3073 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003074 case CXCursor_TypeRef: {
3075 TypeDecl *Type = getCursorTypeRef(C).first;
3076 assert(Type && "Missing type decl");
3077
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003078 return createCXString(getCursorContext(C).getTypeDeclType(Type).
3079 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003080 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003081 case CXCursor_TemplateRef: {
3082 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00003083 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003084
3085 return createCXString(Template->getNameAsString());
3086 }
Douglas Gregor69319002010-08-31 23:48:11 +00003087
3088 case CXCursor_NamespaceRef: {
3089 NamedDecl *NS = getCursorNamespaceRef(C).first;
3090 assert(NS && "Missing namespace decl");
3091
3092 return createCXString(NS->getNameAsString());
3093 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003094
Douglas Gregora67e03f2010-09-09 21:42:20 +00003095 case CXCursor_MemberRef: {
3096 FieldDecl *Field = getCursorMemberRef(C).first;
3097 assert(Field && "Missing member decl");
3098
3099 return createCXString(Field->getNameAsString());
3100 }
3101
Douglas Gregor36897b02010-09-10 00:22:18 +00003102 case CXCursor_LabelRef: {
3103 LabelStmt *Label = getCursorLabelRef(C).first;
3104 assert(Label && "Missing label");
3105
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003106 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00003107 }
3108
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003109 case CXCursor_OverloadedDeclRef: {
3110 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3111 if (Decl *D = Storage.dyn_cast<Decl *>()) {
3112 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
3113 return createCXString(ND->getNameAsString());
3114 return createCXString("");
3115 }
3116 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3117 return createCXString(E->getName().getAsString());
3118 OverloadedTemplateStorage *Ovl
3119 = Storage.get<OverloadedTemplateStorage*>();
3120 if (Ovl->size() == 0)
3121 return createCXString("");
3122 return createCXString((*Ovl->begin())->getNameAsString());
3123 }
3124
Douglas Gregor011d8b92012-02-15 00:54:55 +00003125 case CXCursor_VariableRef: {
3126 VarDecl *Var = getCursorVariableRef(C).first;
3127 assert(Var && "Missing variable decl");
3128
3129 return createCXString(Var->getNameAsString());
3130 }
3131
Daniel Dunbaracca7252009-11-30 20:42:49 +00003132 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003133 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00003134 }
3135 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003136
3137 if (clang_isExpression(C.kind)) {
3138 Decl *D = getDeclFromExpr(getCursorExpr(C));
3139 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00003140 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003141 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00003142 }
3143
Douglas Gregor36897b02010-09-10 00:22:18 +00003144 if (clang_isStatement(C.kind)) {
3145 Stmt *S = getCursorStmt(C);
3146 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003147 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00003148
3149 return createCXString("");
3150 }
3151
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003152 if (C.kind == CXCursor_MacroExpansion)
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003153 return createCXString(getCursorMacroExpansion(C)->getName()
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003154 ->getNameStart());
3155
Douglas Gregor572feb22010-03-18 18:04:21 +00003156 if (C.kind == CXCursor_MacroDefinition)
3157 return createCXString(getCursorMacroDefinition(C)->getName()
3158 ->getNameStart());
3159
Douglas Gregorecdcb882010-10-20 22:00:55 +00003160 if (C.kind == CXCursor_InclusionDirective)
3161 return createCXString(getCursorInclusionDirective(C)->getFileName());
3162
Douglas Gregor60cbfac2010-01-25 16:56:17 +00003163 if (clang_isDeclaration(C.kind))
3164 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00003165
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00003166 if (C.kind == CXCursor_AnnotateAttr) {
3167 AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
3168 return createCXString(AA->getAnnotation());
3169 }
3170
Argyrios Kyrtzidis84b79642011-12-06 22:05:01 +00003171 if (C.kind == CXCursor_AsmLabelAttr) {
3172 AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
3173 return createCXString(AA->getLabel());
3174 }
3175
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003176 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00003177}
3178
Argyrios Kyrtzidisba1da142012-03-30 20:58:35 +00003179CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C,
3180 unsigned pieceIndex,
3181 unsigned options) {
3182 if (clang_Cursor_isNull(C))
3183 return clang_getNullRange();
3184
3185 ASTContext &Ctx = getCursorContext(C);
3186
3187 if (clang_isStatement(C.kind)) {
3188 Stmt *S = getCursorStmt(C);
3189 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
3190 if (pieceIndex > 0)
3191 return clang_getNullRange();
3192 return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
3193 }
3194
3195 return clang_getNullRange();
3196 }
3197
3198 if (C.kind == CXCursor_ObjCMessageExpr) {
3199 if (ObjCMessageExpr *
3200 ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
3201 if (pieceIndex >= ME->getNumSelectorLocs())
3202 return clang_getNullRange();
3203 return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
3204 }
3205 }
3206
3207 if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
3208 C.kind == CXCursor_ObjCClassMethodDecl) {
3209 if (ObjCMethodDecl *
3210 MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
3211 if (pieceIndex >= MD->getNumSelectorLocs())
3212 return clang_getNullRange();
3213 return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
3214 }
3215 }
3216
3217 // FIXME: A CXCursor_InclusionDirective should give the location of the
3218 // filename, but we don't keep track of this.
3219
3220 // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
3221 // but we don't keep track of this.
3222
3223 // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
3224 // but we don't keep track of this.
3225
3226 // Default handling, give the location of the cursor.
3227
3228 if (pieceIndex > 0)
3229 return clang_getNullRange();
3230
3231 CXSourceLocation CXLoc = clang_getCursorLocation(C);
3232 SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
3233 return cxloc::translateSourceRange(Ctx, Loc);
3234}
3235
Douglas Gregor358559d2010-10-02 22:49:11 +00003236CXString clang_getCursorDisplayName(CXCursor C) {
3237 if (!clang_isDeclaration(C.kind))
3238 return clang_getCursorSpelling(C);
3239
3240 Decl *D = getCursorDecl(C);
3241 if (!D)
3242 return createCXString("");
3243
Douglas Gregor30c42402011-09-27 22:38:19 +00003244 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
Douglas Gregor358559d2010-10-02 22:49:11 +00003245 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
3246 D = FunTmpl->getTemplatedDecl();
3247
3248 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Dylan Noblesmith36d59272012-02-13 12:32:26 +00003249 SmallString<64> Str;
Douglas Gregor358559d2010-10-02 22:49:11 +00003250 llvm::raw_svector_ostream OS(Str);
Benjamin Kramera59d20b2012-02-07 11:57:57 +00003251 OS << *Function;
Douglas Gregor358559d2010-10-02 22:49:11 +00003252 if (Function->getPrimaryTemplate())
3253 OS << "<>";
3254 OS << "(";
3255 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
3256 if (I)
3257 OS << ", ";
3258 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
3259 }
3260
3261 if (Function->isVariadic()) {
3262 if (Function->getNumParams())
3263 OS << ", ";
3264 OS << "...";
3265 }
3266 OS << ")";
3267 return createCXString(OS.str());
3268 }
3269
3270 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
Dylan Noblesmith36d59272012-02-13 12:32:26 +00003271 SmallString<64> Str;
Douglas Gregor358559d2010-10-02 22:49:11 +00003272 llvm::raw_svector_ostream OS(Str);
Benjamin Kramera59d20b2012-02-07 11:57:57 +00003273 OS << *ClassTemplate;
Douglas Gregor358559d2010-10-02 22:49:11 +00003274 OS << "<";
3275 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
3276 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3277 if (I)
3278 OS << ", ";
3279
3280 NamedDecl *Param = Params->getParam(I);
3281 if (Param->getIdentifier()) {
3282 OS << Param->getIdentifier()->getName();
3283 continue;
3284 }
3285
3286 // There is no parameter name, which makes this tricky. Try to come up
3287 // with something useful that isn't too long.
3288 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3289 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
3290 else if (NonTypeTemplateParmDecl *NTTP
3291 = dyn_cast<NonTypeTemplateParmDecl>(Param))
3292 OS << NTTP->getType().getAsString(Policy);
3293 else
3294 OS << "template<...> class";
3295 }
3296
3297 OS << ">";
3298 return createCXString(OS.str());
3299 }
3300
3301 if (ClassTemplateSpecializationDecl *ClassSpec
3302 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
3303 // If the type was explicitly written, use that.
3304 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
3305 return createCXString(TSInfo->getType().getAsString(Policy));
3306
Dylan Noblesmith36d59272012-02-13 12:32:26 +00003307 SmallString<64> Str;
Douglas Gregor358559d2010-10-02 22:49:11 +00003308 llvm::raw_svector_ostream OS(Str);
Benjamin Kramera59d20b2012-02-07 11:57:57 +00003309 OS << *ClassSpec;
Douglas Gregor358559d2010-10-02 22:49:11 +00003310 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00003311 ClassSpec->getTemplateArgs().data(),
3312 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00003313 Policy);
3314 return createCXString(OS.str());
3315 }
3316
3317 return clang_getCursorSpelling(C);
3318}
3319
Ted Kremeneke68fff62010-02-17 00:41:32 +00003320CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00003321 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00003322 case CXCursor_FunctionDecl:
3323 return createCXString("FunctionDecl");
3324 case CXCursor_TypedefDecl:
3325 return createCXString("TypedefDecl");
3326 case CXCursor_EnumDecl:
3327 return createCXString("EnumDecl");
3328 case CXCursor_EnumConstantDecl:
3329 return createCXString("EnumConstantDecl");
3330 case CXCursor_StructDecl:
3331 return createCXString("StructDecl");
3332 case CXCursor_UnionDecl:
3333 return createCXString("UnionDecl");
3334 case CXCursor_ClassDecl:
3335 return createCXString("ClassDecl");
3336 case CXCursor_FieldDecl:
3337 return createCXString("FieldDecl");
3338 case CXCursor_VarDecl:
3339 return createCXString("VarDecl");
3340 case CXCursor_ParmDecl:
3341 return createCXString("ParmDecl");
3342 case CXCursor_ObjCInterfaceDecl:
3343 return createCXString("ObjCInterfaceDecl");
3344 case CXCursor_ObjCCategoryDecl:
3345 return createCXString("ObjCCategoryDecl");
3346 case CXCursor_ObjCProtocolDecl:
3347 return createCXString("ObjCProtocolDecl");
3348 case CXCursor_ObjCPropertyDecl:
3349 return createCXString("ObjCPropertyDecl");
3350 case CXCursor_ObjCIvarDecl:
3351 return createCXString("ObjCIvarDecl");
3352 case CXCursor_ObjCInstanceMethodDecl:
3353 return createCXString("ObjCInstanceMethodDecl");
3354 case CXCursor_ObjCClassMethodDecl:
3355 return createCXString("ObjCClassMethodDecl");
3356 case CXCursor_ObjCImplementationDecl:
3357 return createCXString("ObjCImplementationDecl");
3358 case CXCursor_ObjCCategoryImplDecl:
3359 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00003360 case CXCursor_CXXMethod:
3361 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003362 case CXCursor_UnexposedDecl:
3363 return createCXString("UnexposedDecl");
3364 case CXCursor_ObjCSuperClassRef:
3365 return createCXString("ObjCSuperClassRef");
3366 case CXCursor_ObjCProtocolRef:
3367 return createCXString("ObjCProtocolRef");
3368 case CXCursor_ObjCClassRef:
3369 return createCXString("ObjCClassRef");
3370 case CXCursor_TypeRef:
3371 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003372 case CXCursor_TemplateRef:
3373 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00003374 case CXCursor_NamespaceRef:
3375 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00003376 case CXCursor_MemberRef:
3377 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00003378 case CXCursor_LabelRef:
3379 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003380 case CXCursor_OverloadedDeclRef:
3381 return createCXString("OverloadedDeclRef");
Douglas Gregor011d8b92012-02-15 00:54:55 +00003382 case CXCursor_VariableRef:
3383 return createCXString("VariableRef");
Douglas Gregor42b29842011-10-05 19:00:14 +00003384 case CXCursor_IntegerLiteral:
3385 return createCXString("IntegerLiteral");
3386 case CXCursor_FloatingLiteral:
3387 return createCXString("FloatingLiteral");
3388 case CXCursor_ImaginaryLiteral:
3389 return createCXString("ImaginaryLiteral");
3390 case CXCursor_StringLiteral:
3391 return createCXString("StringLiteral");
3392 case CXCursor_CharacterLiteral:
3393 return createCXString("CharacterLiteral");
3394 case CXCursor_ParenExpr:
3395 return createCXString("ParenExpr");
3396 case CXCursor_UnaryOperator:
3397 return createCXString("UnaryOperator");
3398 case CXCursor_ArraySubscriptExpr:
3399 return createCXString("ArraySubscriptExpr");
3400 case CXCursor_BinaryOperator:
3401 return createCXString("BinaryOperator");
3402 case CXCursor_CompoundAssignOperator:
3403 return createCXString("CompoundAssignOperator");
3404 case CXCursor_ConditionalOperator:
3405 return createCXString("ConditionalOperator");
3406 case CXCursor_CStyleCastExpr:
3407 return createCXString("CStyleCastExpr");
3408 case CXCursor_CompoundLiteralExpr:
3409 return createCXString("CompoundLiteralExpr");
3410 case CXCursor_InitListExpr:
3411 return createCXString("InitListExpr");
3412 case CXCursor_AddrLabelExpr:
3413 return createCXString("AddrLabelExpr");
3414 case CXCursor_StmtExpr:
3415 return createCXString("StmtExpr");
3416 case CXCursor_GenericSelectionExpr:
3417 return createCXString("GenericSelectionExpr");
3418 case CXCursor_GNUNullExpr:
3419 return createCXString("GNUNullExpr");
3420 case CXCursor_CXXStaticCastExpr:
3421 return createCXString("CXXStaticCastExpr");
3422 case CXCursor_CXXDynamicCastExpr:
3423 return createCXString("CXXDynamicCastExpr");
3424 case CXCursor_CXXReinterpretCastExpr:
3425 return createCXString("CXXReinterpretCastExpr");
3426 case CXCursor_CXXConstCastExpr:
3427 return createCXString("CXXConstCastExpr");
3428 case CXCursor_CXXFunctionalCastExpr:
3429 return createCXString("CXXFunctionalCastExpr");
3430 case CXCursor_CXXTypeidExpr:
3431 return createCXString("CXXTypeidExpr");
3432 case CXCursor_CXXBoolLiteralExpr:
3433 return createCXString("CXXBoolLiteralExpr");
3434 case CXCursor_CXXNullPtrLiteralExpr:
3435 return createCXString("CXXNullPtrLiteralExpr");
3436 case CXCursor_CXXThisExpr:
3437 return createCXString("CXXThisExpr");
3438 case CXCursor_CXXThrowExpr:
3439 return createCXString("CXXThrowExpr");
3440 case CXCursor_CXXNewExpr:
3441 return createCXString("CXXNewExpr");
3442 case CXCursor_CXXDeleteExpr:
3443 return createCXString("CXXDeleteExpr");
3444 case CXCursor_UnaryExpr:
3445 return createCXString("UnaryExpr");
3446 case CXCursor_ObjCStringLiteral:
3447 return createCXString("ObjCStringLiteral");
Ted Kremenekb3f75422012-03-06 20:06:06 +00003448 case CXCursor_ObjCBoolLiteralExpr:
3449 return createCXString("ObjCBoolLiteralExpr");
Douglas Gregor42b29842011-10-05 19:00:14 +00003450 case CXCursor_ObjCEncodeExpr:
3451 return createCXString("ObjCEncodeExpr");
3452 case CXCursor_ObjCSelectorExpr:
3453 return createCXString("ObjCSelectorExpr");
3454 case CXCursor_ObjCProtocolExpr:
3455 return createCXString("ObjCProtocolExpr");
3456 case CXCursor_ObjCBridgedCastExpr:
3457 return createCXString("ObjCBridgedCastExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00003458 case CXCursor_BlockExpr:
3459 return createCXString("BlockExpr");
Douglas Gregor42b29842011-10-05 19:00:14 +00003460 case CXCursor_PackExpansionExpr:
3461 return createCXString("PackExpansionExpr");
3462 case CXCursor_SizeOfPackExpr:
3463 return createCXString("SizeOfPackExpr");
Douglas Gregor011d8b92012-02-15 00:54:55 +00003464 case CXCursor_LambdaExpr:
3465 return createCXString("LambdaExpr");
Douglas Gregor42b29842011-10-05 19:00:14 +00003466 case CXCursor_UnexposedExpr:
3467 return createCXString("UnexposedExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003468 case CXCursor_DeclRefExpr:
3469 return createCXString("DeclRefExpr");
3470 case CXCursor_MemberRefExpr:
3471 return createCXString("MemberRefExpr");
3472 case CXCursor_CallExpr:
3473 return createCXString("CallExpr");
3474 case CXCursor_ObjCMessageExpr:
3475 return createCXString("ObjCMessageExpr");
3476 case CXCursor_UnexposedStmt:
3477 return createCXString("UnexposedStmt");
Douglas Gregor42b29842011-10-05 19:00:14 +00003478 case CXCursor_DeclStmt:
3479 return createCXString("DeclStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00003480 case CXCursor_LabelStmt:
3481 return createCXString("LabelStmt");
Douglas Gregor42b29842011-10-05 19:00:14 +00003482 case CXCursor_CompoundStmt:
3483 return createCXString("CompoundStmt");
3484 case CXCursor_CaseStmt:
3485 return createCXString("CaseStmt");
3486 case CXCursor_DefaultStmt:
3487 return createCXString("DefaultStmt");
3488 case CXCursor_IfStmt:
3489 return createCXString("IfStmt");
3490 case CXCursor_SwitchStmt:
3491 return createCXString("SwitchStmt");
3492 case CXCursor_WhileStmt:
3493 return createCXString("WhileStmt");
3494 case CXCursor_DoStmt:
3495 return createCXString("DoStmt");
3496 case CXCursor_ForStmt:
3497 return createCXString("ForStmt");
3498 case CXCursor_GotoStmt:
3499 return createCXString("GotoStmt");
3500 case CXCursor_IndirectGotoStmt:
3501 return createCXString("IndirectGotoStmt");
3502 case CXCursor_ContinueStmt:
3503 return createCXString("ContinueStmt");
3504 case CXCursor_BreakStmt:
3505 return createCXString("BreakStmt");
3506 case CXCursor_ReturnStmt:
3507 return createCXString("ReturnStmt");
3508 case CXCursor_AsmStmt:
3509 return createCXString("AsmStmt");
3510 case CXCursor_ObjCAtTryStmt:
3511 return createCXString("ObjCAtTryStmt");
3512 case CXCursor_ObjCAtCatchStmt:
3513 return createCXString("ObjCAtCatchStmt");
3514 case CXCursor_ObjCAtFinallyStmt:
3515 return createCXString("ObjCAtFinallyStmt");
3516 case CXCursor_ObjCAtThrowStmt:
3517 return createCXString("ObjCAtThrowStmt");
3518 case CXCursor_ObjCAtSynchronizedStmt:
3519 return createCXString("ObjCAtSynchronizedStmt");
3520 case CXCursor_ObjCAutoreleasePoolStmt:
3521 return createCXString("ObjCAutoreleasePoolStmt");
3522 case CXCursor_ObjCForCollectionStmt:
3523 return createCXString("ObjCForCollectionStmt");
3524 case CXCursor_CXXCatchStmt:
3525 return createCXString("CXXCatchStmt");
3526 case CXCursor_CXXTryStmt:
3527 return createCXString("CXXTryStmt");
3528 case CXCursor_CXXForRangeStmt:
3529 return createCXString("CXXForRangeStmt");
3530 case CXCursor_SEHTryStmt:
3531 return createCXString("SEHTryStmt");
3532 case CXCursor_SEHExceptStmt:
3533 return createCXString("SEHExceptStmt");
3534 case CXCursor_SEHFinallyStmt:
3535 return createCXString("SEHFinallyStmt");
3536 case CXCursor_NullStmt:
3537 return createCXString("NullStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003538 case CXCursor_InvalidFile:
3539 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00003540 case CXCursor_InvalidCode:
3541 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003542 case CXCursor_NoDeclFound:
3543 return createCXString("NoDeclFound");
3544 case CXCursor_NotImplemented:
3545 return createCXString("NotImplemented");
3546 case CXCursor_TranslationUnit:
3547 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00003548 case CXCursor_UnexposedAttr:
3549 return createCXString("UnexposedAttr");
3550 case CXCursor_IBActionAttr:
3551 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003552 case CXCursor_IBOutletAttr:
3553 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003554 case CXCursor_IBOutletCollectionAttr:
3555 return createCXString("attribute(iboutletcollection)");
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00003556 case CXCursor_CXXFinalAttr:
3557 return createCXString("attribute(final)");
3558 case CXCursor_CXXOverrideAttr:
3559 return createCXString("attribute(override)");
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00003560 case CXCursor_AnnotateAttr:
3561 return createCXString("attribute(annotate)");
Argyrios Kyrtzidis84b79642011-12-06 22:05:01 +00003562 case CXCursor_AsmLabelAttr:
3563 return createCXString("asm label");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003564 case CXCursor_PreprocessingDirective:
3565 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003566 case CXCursor_MacroDefinition:
3567 return createCXString("macro definition");
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003568 case CXCursor_MacroExpansion:
3569 return createCXString("macro expansion");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003570 case CXCursor_InclusionDirective:
3571 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003572 case CXCursor_Namespace:
3573 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003574 case CXCursor_LinkageSpec:
3575 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003576 case CXCursor_CXXBaseSpecifier:
3577 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003578 case CXCursor_Constructor:
3579 return createCXString("CXXConstructor");
3580 case CXCursor_Destructor:
3581 return createCXString("CXXDestructor");
3582 case CXCursor_ConversionFunction:
3583 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003584 case CXCursor_TemplateTypeParameter:
3585 return createCXString("TemplateTypeParameter");
3586 case CXCursor_NonTypeTemplateParameter:
3587 return createCXString("NonTypeTemplateParameter");
3588 case CXCursor_TemplateTemplateParameter:
3589 return createCXString("TemplateTemplateParameter");
3590 case CXCursor_FunctionTemplate:
3591 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003592 case CXCursor_ClassTemplate:
3593 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003594 case CXCursor_ClassTemplatePartialSpecialization:
3595 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003596 case CXCursor_NamespaceAlias:
3597 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003598 case CXCursor_UsingDirective:
3599 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003600 case CXCursor_UsingDeclaration:
3601 return createCXString("UsingDeclaration");
Richard Smith162e1c12011-04-15 14:24:37 +00003602 case CXCursor_TypeAliasDecl:
Douglas Gregor352697a2011-06-03 23:08:58 +00003603 return createCXString("TypeAliasDecl");
3604 case CXCursor_ObjCSynthesizeDecl:
3605 return createCXString("ObjCSynthesizeDecl");
3606 case CXCursor_ObjCDynamicDecl:
3607 return createCXString("ObjCDynamicDecl");
Argyrios Kyrtzidis2dfdb942011-09-30 17:58:23 +00003608 case CXCursor_CXXAccessSpecifier:
3609 return createCXString("CXXAccessSpecifier");
Steve Naroff89922f82009-08-31 00:59:03 +00003610 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003611
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003612 llvm_unreachable("Unhandled CXCursorKind");
Steve Naroff600866c2009-08-27 19:51:58 +00003613}
Steve Naroff89922f82009-08-31 00:59:03 +00003614
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003615struct GetCursorData {
3616 SourceLocation TokenBeginLoc;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003617 bool PointsAtMacroArgExpansion;
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003618 CXCursor &BestCursor;
3619
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003620 GetCursorData(SourceManager &SM,
3621 SourceLocation tokenBegin, CXCursor &outputCursor)
3622 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
3623 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
3624 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003625};
3626
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003627static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3628 CXCursor parent,
3629 CXClientData client_data) {
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003630 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
3631 CXCursor *BestCursor = &Data->BestCursor;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003632
3633 // If we point inside a macro argument we should provide info of what the
3634 // token is so use the actual cursor, don't replace it with a macro expansion
3635 // cursor.
3636 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
3637 return CXChildVisit_Recurse;
Argyrios Kyrtzidis65ab9072011-09-26 19:05:37 +00003638
3639 if (clang_isDeclaration(cursor.kind)) {
3640 // Avoid having the implicit methods override the property decls.
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00003641 if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor)))
Argyrios Kyrtzidis65ab9072011-09-26 19:05:37 +00003642 if (MD->isImplicit())
3643 return CXChildVisit_Break;
3644 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003645
3646 if (clang_isExpression(cursor.kind) &&
3647 clang_isDeclaration(BestCursor->kind)) {
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00003648 if (Decl *D = getCursorDecl(*BestCursor)) {
3649 // Avoid having the cursor of an expression replace the declaration cursor
3650 // when the expression source range overlaps the declaration range.
3651 // This can happen for C++ constructor expressions whose range generally
3652 // include the variable declaration, e.g.:
3653 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
3654 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
3655 D->getLocation() == Data->TokenBeginLoc)
3656 return CXChildVisit_Break;
3657 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003658 }
3659
Douglas Gregor93798e22010-11-05 21:11:19 +00003660 // If our current best cursor is the construction of a temporary object,
3661 // don't replace that cursor with a type reference, because we want
3662 // clang_getCursor() to point at the constructor.
3663 if (clang_isExpression(BestCursor->kind) &&
3664 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003665 cursor.kind == CXCursor_TypeRef) {
3666 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
3667 // as having the actual point on the type reference.
3668 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
Douglas Gregor93798e22010-11-05 21:11:19 +00003669 return CXChildVisit_Recurse;
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003670 }
Douglas Gregor93798e22010-11-05 21:11:19 +00003671
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003672 *BestCursor = cursor;
3673 return CXChildVisit_Recurse;
3674}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003675
Douglas Gregorb9790342010-01-22 21:44:22 +00003676CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3677 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003678 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003679
Ted Kremeneka60ed472010-11-16 08:15:36 +00003680 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003681 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3682
Ted Kremeneka297de22010-01-25 22:34:44 +00003683 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003684 CXCursor Result = cxcursor::getCursor(TU, SLoc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003685
Douglas Gregor40749ee2010-11-03 00:35:38 +00003686 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregor40749ee2010-11-03 00:35:38 +00003687 if (Logging) {
3688 CXFile SearchFile;
3689 unsigned SearchLine, SearchColumn;
3690 CXFile ResultFile;
3691 unsigned ResultLine, ResultColumn;
Douglas Gregor66537982010-11-17 17:14:07 +00003692 CXString SearchFileName, ResultFileName, KindSpelling, USR;
3693 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
Douglas Gregor40749ee2010-11-03 00:35:38 +00003694 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3695
Chandler Carruth20174222011-08-31 16:53:37 +00003696 clang_getExpansionLocation(Loc, &SearchFile, &SearchLine, &SearchColumn, 0);
3697 clang_getExpansionLocation(ResultLoc, &ResultFile, &ResultLine,
3698 &ResultColumn, 0);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003699 SearchFileName = clang_getFileName(SearchFile);
3700 ResultFileName = clang_getFileName(ResultFile);
3701 KindSpelling = clang_getCursorKindSpelling(Result.kind);
Douglas Gregor66537982010-11-17 17:14:07 +00003702 USR = clang_getCursorUSR(Result);
3703 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n",
Douglas Gregor40749ee2010-11-03 00:35:38 +00003704 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3705 clang_getCString(KindSpelling),
Douglas Gregor66537982010-11-17 17:14:07 +00003706 clang_getCString(ResultFileName), ResultLine, ResultColumn,
3707 clang_getCString(USR), IsDef);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003708 clang_disposeString(SearchFileName);
3709 clang_disposeString(ResultFileName);
3710 clang_disposeString(KindSpelling);
Douglas Gregor66537982010-11-17 17:14:07 +00003711 clang_disposeString(USR);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003712
3713 CXCursor Definition = clang_getCursorDefinition(Result);
3714 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
3715 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
3716 CXString DefinitionKindSpelling
3717 = clang_getCursorKindSpelling(Definition.kind);
3718 CXFile DefinitionFile;
3719 unsigned DefinitionLine, DefinitionColumn;
Chandler Carruth20174222011-08-31 16:53:37 +00003720 clang_getExpansionLocation(DefinitionLoc, &DefinitionFile,
3721 &DefinitionLine, &DefinitionColumn, 0);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003722 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
3723 fprintf(stderr, " -> %s(%s:%d:%d)\n",
3724 clang_getCString(DefinitionKindSpelling),
3725 clang_getCString(DefinitionFileName),
3726 DefinitionLine, DefinitionColumn);
3727 clang_disposeString(DefinitionFileName);
3728 clang_disposeString(DefinitionKindSpelling);
3729 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003730 }
3731
Ted Kremeneke68fff62010-02-17 00:41:32 +00003732 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003733}
3734
Ted Kremenek73885552009-11-17 19:28:59 +00003735CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003736 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003737}
3738
3739unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003740 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003741}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003742
Douglas Gregor9ce55842010-11-20 00:09:34 +00003743unsigned clang_hashCursor(CXCursor C) {
3744 unsigned Index = 0;
3745 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
3746 Index = 1;
3747
3748 return llvm::DenseMapInfo<std::pair<unsigned, void*> >::getHashValue(
3749 std::make_pair(C.kind, C.data[Index]));
3750}
3751
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003752unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003753 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3754}
3755
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003756unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003757 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3758}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003759
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003760unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003761 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3762}
3763
Douglas Gregor97b98722010-01-19 23:20:36 +00003764unsigned clang_isExpression(enum CXCursorKind K) {
3765 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3766}
3767
3768unsigned clang_isStatement(enum CXCursorKind K) {
3769 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3770}
3771
Douglas Gregor8be80e12011-07-06 03:00:34 +00003772unsigned clang_isAttribute(enum CXCursorKind K) {
3773 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
3774}
3775
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003776unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3777 return K == CXCursor_TranslationUnit;
3778}
3779
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003780unsigned clang_isPreprocessing(enum CXCursorKind K) {
3781 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3782}
3783
Ted Kremenekad6eff62010-03-08 21:17:29 +00003784unsigned clang_isUnexposed(enum CXCursorKind K) {
3785 switch (K) {
3786 case CXCursor_UnexposedDecl:
3787 case CXCursor_UnexposedExpr:
3788 case CXCursor_UnexposedStmt:
3789 case CXCursor_UnexposedAttr:
3790 return true;
3791 default:
3792 return false;
3793 }
3794}
3795
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003796CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003797 return C.kind;
3798}
3799
Douglas Gregor98258af2010-01-18 22:46:11 +00003800CXSourceLocation clang_getCursorLocation(CXCursor C) {
3801 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003802 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003803 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003804 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3805 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003806 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003807 }
3808
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003809 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003810 std::pair<ObjCProtocolDecl *, SourceLocation> P
3811 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003812 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003813 }
3814
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003815 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003816 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3817 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003818 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003819 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003820
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003821 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003822 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003823 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003824 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003825
3826 case CXCursor_TemplateRef: {
3827 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3828 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3829 }
3830
Douglas Gregor69319002010-08-31 23:48:11 +00003831 case CXCursor_NamespaceRef: {
3832 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3833 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3834 }
3835
Douglas Gregora67e03f2010-09-09 21:42:20 +00003836 case CXCursor_MemberRef: {
3837 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3838 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3839 }
3840
Douglas Gregor011d8b92012-02-15 00:54:55 +00003841 case CXCursor_VariableRef: {
3842 std::pair<VarDecl *, SourceLocation> P = getCursorVariableRef(C);
3843 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3844 }
3845
Ted Kremenek3064ef92010-08-27 21:34:58 +00003846 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003847 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3848 if (!BaseSpec)
3849 return clang_getNullLocation();
3850
3851 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3852 return cxloc::translateSourceLocation(getCursorContext(C),
3853 TSInfo->getTypeLoc().getBeginLoc());
3854
3855 return cxloc::translateSourceLocation(getCursorContext(C),
Daniel Dunbar96a00142012-03-09 18:35:03 +00003856 BaseSpec->getLocStart());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003857 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003858
Douglas Gregor36897b02010-09-10 00:22:18 +00003859 case CXCursor_LabelRef: {
3860 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3861 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3862 }
3863
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003864 case CXCursor_OverloadedDeclRef:
3865 return cxloc::translateSourceLocation(getCursorContext(C),
3866 getCursorOverloadedDeclRef(C).second);
3867
Douglas Gregorf46034a2010-01-18 23:41:10 +00003868 default:
3869 // FIXME: Need a way to enumerate all non-reference cases.
3870 llvm_unreachable("Missed a reference kind");
3871 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003872 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003873
3874 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003875 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003876 getLocationFromExpr(getCursorExpr(C)));
3877
Douglas Gregor36897b02010-09-10 00:22:18 +00003878 if (clang_isStatement(C.kind))
3879 return cxloc::translateSourceLocation(getCursorContext(C),
3880 getCursorStmt(C)->getLocStart());
3881
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003882 if (C.kind == CXCursor_PreprocessingDirective) {
3883 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3884 return cxloc::translateSourceLocation(getCursorContext(C), L);
3885 }
Douglas Gregor48072312010-03-18 15:23:44 +00003886
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003887 if (C.kind == CXCursor_MacroExpansion) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003888 SourceLocation L
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003889 = cxcursor::getCursorMacroExpansion(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003890 return cxloc::translateSourceLocation(getCursorContext(C), L);
3891 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003892
3893 if (C.kind == CXCursor_MacroDefinition) {
3894 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3895 return cxloc::translateSourceLocation(getCursorContext(C), L);
3896 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003897
3898 if (C.kind == CXCursor_InclusionDirective) {
3899 SourceLocation L
3900 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3901 return cxloc::translateSourceLocation(getCursorContext(C), L);
3902 }
3903
Ted Kremenek9a700d22010-05-12 06:16:13 +00003904 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003905 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003906
Douglas Gregorf46034a2010-01-18 23:41:10 +00003907 Decl *D = getCursorDecl(C);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00003908 if (!D)
3909 return clang_getNullLocation();
3910
Douglas Gregorf46034a2010-01-18 23:41:10 +00003911 SourceLocation Loc = D->getLocation();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003912 // FIXME: Multiple variables declared in a single declaration
3913 // currently lack the information needed to correctly determine their
3914 // ranges when accounting for the type-specifier. We use context
3915 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3916 // and if so, whether it is the first decl.
3917 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3918 if (!cxcursor::isFirstInDeclGroup(C))
3919 Loc = VD->getLocation();
3920 }
3921
Argyrios Kyrtzidisccc6f362012-03-23 03:33:19 +00003922 // For ObjC methods, give the start location of the method name.
3923 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
3924 Loc = MD->getSelectorStartLoc();
3925
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003926 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003927}
Douglas Gregora7bde202010-01-19 00:34:46 +00003928
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003929} // end extern "C"
3930
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003931CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
3932 assert(TU);
3933
3934 // Guard against an invalid SourceLocation, or we may assert in one
3935 // of the following calls.
3936 if (SLoc.isInvalid())
3937 return clang_getNullCursor();
3938
3939 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
3940
3941 // Translate the given source location to make it point at the beginning of
3942 // the token under the cursor.
3943 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +00003944 CXXUnit->getASTContext().getLangOpts());
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003945
3946 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3947 if (SLoc.isValid()) {
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003948 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003949 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
3950 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00003951 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003952 SourceLocation(SLoc));
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00003953 CursorVis.visitFileRegion();
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003954 }
3955
3956 return Result;
3957}
3958
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003959static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003960 if (clang_isReference(C.kind)) {
3961 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003962 case CXCursor_ObjCSuperClassRef:
3963 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003964
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003965 case CXCursor_ObjCProtocolRef:
3966 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003967
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003968 case CXCursor_ObjCClassRef:
3969 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003970
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003971 case CXCursor_TypeRef:
3972 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003973
3974 case CXCursor_TemplateRef:
3975 return getCursorTemplateRef(C).second;
3976
Douglas Gregor69319002010-08-31 23:48:11 +00003977 case CXCursor_NamespaceRef:
3978 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003979
3980 case CXCursor_MemberRef:
3981 return getCursorMemberRef(C).second;
3982
Ted Kremenek3064ef92010-08-27 21:34:58 +00003983 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003984 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003985
Douglas Gregor36897b02010-09-10 00:22:18 +00003986 case CXCursor_LabelRef:
3987 return getCursorLabelRef(C).second;
3988
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003989 case CXCursor_OverloadedDeclRef:
3990 return getCursorOverloadedDeclRef(C).second;
3991
Douglas Gregor011d8b92012-02-15 00:54:55 +00003992 case CXCursor_VariableRef:
3993 return getCursorVariableRef(C).second;
3994
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003995 default:
3996 // FIXME: Need a way to enumerate all non-reference cases.
3997 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003998 }
3999 }
Douglas Gregor97b98722010-01-19 23:20:36 +00004000
4001 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004002 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00004003
4004 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004005 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004006
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00004007 if (clang_isAttribute(C.kind))
4008 return getCursorAttr(C)->getRange();
4009
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004010 if (C.kind == CXCursor_PreprocessingDirective)
4011 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00004012
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004013 if (C.kind == CXCursor_MacroExpansion) {
4014 ASTUnit *TU = getCursorASTUnit(C);
4015 SourceRange Range = cxcursor::getCursorMacroExpansion(C)->getSourceRange();
4016 return TU->mapRangeFromPreamble(Range);
4017 }
Douglas Gregor572feb22010-03-18 18:04:21 +00004018
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004019 if (C.kind == CXCursor_MacroDefinition) {
4020 ASTUnit *TU = getCursorASTUnit(C);
4021 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
4022 return TU->mapRangeFromPreamble(Range);
4023 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00004024
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004025 if (C.kind == CXCursor_InclusionDirective) {
4026 ASTUnit *TU = getCursorASTUnit(C);
4027 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
4028 return TU->mapRangeFromPreamble(Range);
4029 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00004030
Argyrios Kyrtzidis0822c5f2012-03-19 23:17:58 +00004031 if (C.kind == CXCursor_TranslationUnit) {
4032 ASTUnit *TU = getCursorASTUnit(C);
4033 FileID MainID = TU->getSourceManager().getMainFileID();
4034 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
4035 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
4036 return SourceRange(Start, End);
4037 }
4038
Ted Kremenek007a7c92010-11-01 23:26:51 +00004039 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
4040 Decl *D = cxcursor::getCursorDecl(C);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00004041 if (!D)
4042 return SourceRange();
4043
Ted Kremenek007a7c92010-11-01 23:26:51 +00004044 SourceRange R = D->getSourceRange();
4045 // FIXME: Multiple variables declared in a single declaration
4046 // currently lack the information needed to correctly determine their
4047 // ranges when accounting for the type-specifier. We use context
4048 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
4049 // and if so, whether it is the first decl.
4050 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4051 if (!cxcursor::isFirstInDeclGroup(C))
4052 R.setBegin(VD->getLocation());
4053 }
4054 return R;
4055 }
Douglas Gregor66537982010-11-17 17:14:07 +00004056 return SourceRange();
4057}
4058
4059/// \brief Retrieves the "raw" cursor extent, which is then extended to include
4060/// the decl-specifier-seq for declarations.
4061static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
4062 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
4063 Decl *D = cxcursor::getCursorDecl(C);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00004064 if (!D)
4065 return SourceRange();
4066
Douglas Gregor66537982010-11-17 17:14:07 +00004067 SourceRange R = D->getSourceRange();
Douglas Gregor66537982010-11-17 17:14:07 +00004068
Douglas Gregor2494dd02011-03-01 01:34:45 +00004069 // Adjust the start of the location for declarations preceded by
4070 // declaration specifiers.
4071 SourceLocation StartLoc;
4072 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
4073 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
Daniel Dunbar96a00142012-03-09 18:35:03 +00004074 StartLoc = TI->getTypeLoc().getLocStart();
Douglas Gregor2494dd02011-03-01 01:34:45 +00004075 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
4076 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
Daniel Dunbar96a00142012-03-09 18:35:03 +00004077 StartLoc = TI->getTypeLoc().getLocStart();
Douglas Gregor2494dd02011-03-01 01:34:45 +00004078 }
4079
4080 if (StartLoc.isValid() && R.getBegin().isValid() &&
4081 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
4082 R.setBegin(StartLoc);
4083
4084 // FIXME: Multiple variables declared in a single declaration
4085 // currently lack the information needed to correctly determine their
4086 // ranges when accounting for the type-specifier. We use context
4087 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
4088 // and if so, whether it is the first decl.
4089 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4090 if (!cxcursor::isFirstInDeclGroup(C))
4091 R.setBegin(VD->getLocation());
Douglas Gregor66537982010-11-17 17:14:07 +00004092 }
4093
4094 return R;
4095 }
4096
4097 return getRawCursorExtent(C);
4098}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004099
4100extern "C" {
4101
4102CXSourceRange clang_getCursorExtent(CXCursor C) {
4103 SourceRange R = getRawCursorExtent(C);
4104 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00004105 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004106
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004107 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00004108}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004109
4110CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00004111 if (clang_isInvalid(C.kind))
4112 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004113
Ted Kremeneka60ed472010-11-16 08:15:36 +00004114 CXTranslationUnit tu = getCursorTU(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004115 if (clang_isDeclaration(C.kind)) {
4116 Decl *D = getCursorDecl(C);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00004117 if (!D)
4118 return clang_getNullCursor();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004119 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004120 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Chris Lattner5f9e2722011-07-23 10:55:15 +00004121 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00004122 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
4123 return MakeCXCursor(Property, tu);
4124
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004125 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004126 }
4127
Douglas Gregor97b98722010-01-19 23:20:36 +00004128 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004129 Expr *E = getCursorExpr(C);
4130 Decl *D = getDeclFromExpr(E);
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00004131 if (D) {
4132 CXCursor declCursor = MakeCXCursor(D, tu);
4133 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
4134 declCursor);
4135 return declCursor;
4136 }
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004137
4138 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004139 return MakeCursorOverloadedDeclRef(Ovl, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004140
Douglas Gregor97b98722010-01-19 23:20:36 +00004141 return clang_getNullCursor();
4142 }
4143
Douglas Gregor36897b02010-09-10 00:22:18 +00004144 if (clang_isStatement(C.kind)) {
4145 Stmt *S = getCursorStmt(C);
4146 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Ted Kremenek37c2e962011-03-15 23:47:49 +00004147 if (LabelDecl *label = Goto->getLabel())
4148 if (LabelStmt *labelS = label->getStmt())
4149 return MakeCXCursor(labelS, getCursorDecl(C), tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00004150
4151 return clang_getNullCursor();
4152 }
4153
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004154 if (C.kind == CXCursor_MacroExpansion) {
Chandler Carruth9e5bb852011-07-14 08:20:46 +00004155 if (MacroDefinition *Def = getCursorMacroExpansion(C)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004156 return MakeMacroDefinitionCursor(Def, tu);
Douglas Gregorbf7efa22010-03-18 18:23:03 +00004157 }
4158
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004159 if (!clang_isReference(C.kind))
4160 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004161
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004162 switch (C.kind) {
4163 case CXCursor_ObjCSuperClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004164 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004165
4166 case CXCursor_ObjCProtocolRef: {
Argyrios Kyrtzidis98c16b82012-01-24 19:40:15 +00004167 ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
4168 if (ObjCProtocolDecl *Def = Prot->getDefinition())
4169 return MakeCXCursor(Def, tu);
4170
Argyrios Kyrtzidisc15707d2012-01-24 21:39:26 +00004171 return MakeCXCursor(Prot, tu);
Argyrios Kyrtzidis98c16b82012-01-24 19:40:15 +00004172 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004173
Douglas Gregor7723fec2011-12-15 20:29:51 +00004174 case CXCursor_ObjCClassRef: {
4175 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
4176 if (ObjCInterfaceDecl *Def = Class->getDefinition())
4177 return MakeCXCursor(Def, tu);
4178
Argyrios Kyrtzidisc15707d2012-01-24 21:39:26 +00004179 return MakeCXCursor(Class, tu);
Douglas Gregor7723fec2011-12-15 20:29:51 +00004180 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00004181
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004182 case CXCursor_TypeRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004183 return MakeCXCursor(getCursorTypeRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00004184
4185 case CXCursor_TemplateRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004186 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00004187
Douglas Gregor69319002010-08-31 23:48:11 +00004188 case CXCursor_NamespaceRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004189 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
Douglas Gregor69319002010-08-31 23:48:11 +00004190
Douglas Gregora67e03f2010-09-09 21:42:20 +00004191 case CXCursor_MemberRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004192 return MakeCXCursor(getCursorMemberRef(C).first, tu );
Douglas Gregora67e03f2010-09-09 21:42:20 +00004193
Ted Kremenek3064ef92010-08-27 21:34:58 +00004194 case CXCursor_CXXBaseSpecifier: {
4195 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
4196 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004197 tu ));
Ted Kremenek3064ef92010-08-27 21:34:58 +00004198 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004199
Douglas Gregor36897b02010-09-10 00:22:18 +00004200 case CXCursor_LabelRef:
4201 // FIXME: We end up faking the "parent" declaration here because we
4202 // don't want to make CXCursor larger.
4203 return MakeCXCursor(getCursorLabelRef(C).first,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004204 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
4205 .getTranslationUnitDecl(),
4206 tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00004207
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004208 case CXCursor_OverloadedDeclRef:
4209 return C;
Douglas Gregor011d8b92012-02-15 00:54:55 +00004210
4211 case CXCursor_VariableRef:
4212 return MakeCXCursor(getCursorVariableRef(C).first, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004213
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004214 default:
4215 // We would prefer to enumerate all non-reference cursor kinds here.
4216 llvm_unreachable("Unhandled reference cursor kind");
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004217 }
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004218}
4219
Douglas Gregorb6998662010-01-19 19:34:47 +00004220CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00004221 if (clang_isInvalid(C.kind))
4222 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004223
Ted Kremeneka60ed472010-11-16 08:15:36 +00004224 CXTranslationUnit TU = getCursorTU(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004225
Douglas Gregorb6998662010-01-19 19:34:47 +00004226 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00004227 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00004228 C = clang_getCursorReferenced(C);
4229 WasReference = true;
4230 }
4231
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004232 if (C.kind == CXCursor_MacroExpansion)
Douglas Gregorbf7efa22010-03-18 18:23:03 +00004233 return clang_getCursorReferenced(C);
4234
Douglas Gregorb6998662010-01-19 19:34:47 +00004235 if (!clang_isDeclaration(C.kind))
4236 return clang_getNullCursor();
4237
4238 Decl *D = getCursorDecl(C);
4239 if (!D)
4240 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004241
Douglas Gregorb6998662010-01-19 19:34:47 +00004242 switch (D->getKind()) {
4243 // Declaration kinds that don't really separate the notions of
4244 // declaration and definition.
4245 case Decl::Namespace:
4246 case Decl::Typedef:
Richard Smith162e1c12011-04-15 14:24:37 +00004247 case Decl::TypeAlias:
Richard Smith3e4c6c42011-05-05 21:57:07 +00004248 case Decl::TypeAliasTemplate:
Douglas Gregorb6998662010-01-19 19:34:47 +00004249 case Decl::TemplateTypeParm:
4250 case Decl::EnumConstant:
4251 case Decl::Field:
Benjamin Kramerd9811462010-11-21 14:11:41 +00004252 case Decl::IndirectField:
Douglas Gregorb6998662010-01-19 19:34:47 +00004253 case Decl::ObjCIvar:
4254 case Decl::ObjCAtDefsField:
4255 case Decl::ImplicitParam:
4256 case Decl::ParmVar:
4257 case Decl::NonTypeTemplateParm:
4258 case Decl::TemplateTemplateParm:
4259 case Decl::ObjCCategoryImpl:
4260 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00004261 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00004262 case Decl::LinkageSpec:
4263 case Decl::ObjCPropertyImpl:
4264 case Decl::FileScopeAsm:
4265 case Decl::StaticAssert:
4266 case Decl::Block:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00004267 case Decl::Label: // FIXME: Is this right??
Francois Pichetaf0f4d02011-08-14 03:52:19 +00004268 case Decl::ClassScopeFunctionSpecialization:
Douglas Gregor15de72c2011-12-02 23:23:56 +00004269 case Decl::Import:
Douglas Gregorb6998662010-01-19 19:34:47 +00004270 return C;
4271
4272 // Declaration kinds that don't make any sense here, but are
4273 // nonetheless harmless.
4274 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00004275 break;
4276
4277 // Declaration kinds for which the definition is not resolvable.
4278 case Decl::UnresolvedUsingTypename:
4279 case Decl::UnresolvedUsingValue:
4280 break;
4281
4282 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00004283 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004284 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004285
4286 case Decl::NamespaceAlias:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004287 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004288
4289 case Decl::Enum:
4290 case Decl::Record:
4291 case Decl::CXXRecord:
4292 case Decl::ClassTemplateSpecialization:
4293 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00004294 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004295 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004296 return clang_getNullCursor();
4297
4298 case Decl::Function:
4299 case Decl::CXXMethod:
4300 case Decl::CXXConstructor:
4301 case Decl::CXXDestructor:
4302 case Decl::CXXConversion: {
4303 const FunctionDecl *Def = 0;
4304 if (cast<FunctionDecl>(D)->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004305 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004306 return clang_getNullCursor();
4307 }
4308
4309 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00004310 // Ask the variable if it has a definition.
4311 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004312 return MakeCXCursor(Def, TU);
Sebastian Redl31310a22010-02-01 20:16:42 +00004313 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00004314 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004315
Douglas Gregorb6998662010-01-19 19:34:47 +00004316 case Decl::FunctionTemplate: {
4317 const FunctionDecl *Def = 0;
4318 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004319 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004320 return clang_getNullCursor();
4321 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004322
Douglas Gregorb6998662010-01-19 19:34:47 +00004323 case Decl::ClassTemplate: {
4324 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00004325 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00004326 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004327 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004328 return clang_getNullCursor();
4329 }
4330
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004331 case Decl::Using:
4332 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004333 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004334
4335 case Decl::UsingShadow:
4336 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004337 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004338 TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004339
4340 case Decl::ObjCMethod: {
4341 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
4342 if (Method->isThisDeclarationADefinition())
4343 return C;
4344
4345 // Dig out the method definition in the associated
4346 // @implementation, if we have it.
4347 // FIXME: The ASTs should make finding the definition easier.
4348 if (ObjCInterfaceDecl *Class
4349 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
4350 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
4351 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
4352 Method->isInstanceMethod()))
4353 if (Def->isThisDeclarationADefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004354 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004355
4356 return clang_getNullCursor();
4357 }
4358
4359 case Decl::ObjCCategory:
4360 if (ObjCCategoryImplDecl *Impl
4361 = cast<ObjCCategoryDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004362 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004363 return clang_getNullCursor();
4364
4365 case Decl::ObjCProtocol:
Douglas Gregor5e2a1ff2012-01-01 19:29:29 +00004366 if (ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
4367 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004368 return clang_getNullCursor();
4369
Douglas Gregor375bb142011-12-27 22:43:10 +00004370 case Decl::ObjCInterface: {
Douglas Gregorb6998662010-01-19 19:34:47 +00004371 // There are two notions of a "definition" for an Objective-C
4372 // class: the interface and its implementation. When we resolved a
4373 // reference to an Objective-C class, produce the @interface as
4374 // the definition; when we were provided with the interface,
4375 // produce the @implementation as the definition.
Douglas Gregor375bb142011-12-27 22:43:10 +00004376 ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
Douglas Gregorb6998662010-01-19 19:34:47 +00004377 if (WasReference) {
Douglas Gregor375bb142011-12-27 22:43:10 +00004378 if (ObjCInterfaceDecl *Def = IFace->getDefinition())
Douglas Gregor7723fec2011-12-15 20:29:51 +00004379 return MakeCXCursor(Def, TU);
Douglas Gregor375bb142011-12-27 22:43:10 +00004380 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004381 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004382 return clang_getNullCursor();
Douglas Gregor375bb142011-12-27 22:43:10 +00004383 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004384
Douglas Gregorb6998662010-01-19 19:34:47 +00004385 case Decl::ObjCProperty:
4386 // FIXME: We don't really know where to find the
4387 // ObjCPropertyImplDecls that implement this property.
4388 return clang_getNullCursor();
4389
4390 case Decl::ObjCCompatibleAlias:
4391 if (ObjCInterfaceDecl *Class
4392 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
Douglas Gregor7723fec2011-12-15 20:29:51 +00004393 if (ObjCInterfaceDecl *Def = Class->getDefinition())
4394 return MakeCXCursor(Def, TU);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004395
Douglas Gregorb6998662010-01-19 19:34:47 +00004396 return clang_getNullCursor();
4397
Douglas Gregorb6998662010-01-19 19:34:47 +00004398 case Decl::Friend:
4399 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004400 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004401 return clang_getNullCursor();
4402
4403 case Decl::FriendTemplate:
4404 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004405 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004406 return clang_getNullCursor();
4407 }
4408
4409 return clang_getNullCursor();
4410}
4411
4412unsigned clang_isCursorDefinition(CXCursor C) {
4413 if (!clang_isDeclaration(C.kind))
4414 return 0;
4415
4416 return clang_getCursorDefinition(C) == C;
4417}
4418
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004419CXCursor clang_getCanonicalCursor(CXCursor C) {
4420 if (!clang_isDeclaration(C.kind))
4421 return C;
4422
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004423 if (Decl *D = getCursorDecl(C)) {
Argyrios Kyrtzidisdebb00f2011-07-15 22:37:58 +00004424 if (ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
4425 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
4426 return MakeCXCursor(CatD, getCursorTU(C));
4427
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004428 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
4429 if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
4430 return MakeCXCursor(IFD, getCursorTU(C));
4431
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004432 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004433 }
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004434
4435 return C;
4436}
Argyrios Kyrtzidis34ebe1e2012-03-30 22:15:48 +00004437
4438int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) {
4439 return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first;
4440}
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004441
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004442unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004443 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004444 return 0;
4445
4446 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
4447 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
4448 return E->getNumDecls();
4449
4450 if (OverloadedTemplateStorage *S
4451 = Storage.dyn_cast<OverloadedTemplateStorage*>())
4452 return S->size();
4453
4454 Decl *D = Storage.get<Decl*>();
4455 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00004456 return Using->shadow_size();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004457
4458 return 0;
4459}
4460
4461CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004462 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004463 return clang_getNullCursor();
4464
4465 if (index >= clang_getNumOverloadedDecls(cursor))
4466 return clang_getNullCursor();
4467
Ted Kremeneka60ed472010-11-16 08:15:36 +00004468 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004469 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
4470 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004471 return MakeCXCursor(E->decls_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004472
4473 if (OverloadedTemplateStorage *S
4474 = Storage.dyn_cast<OverloadedTemplateStorage*>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004475 return MakeCXCursor(S->begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004476
4477 Decl *D = Storage.get<Decl*>();
4478 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
4479 // FIXME: This is, unfortunately, linear time.
4480 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
4481 std::advance(Pos, index);
Ted Kremeneka60ed472010-11-16 08:15:36 +00004482 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004483 }
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004484
4485 return clang_getNullCursor();
4486}
4487
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00004488void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00004489 const char **startBuf,
4490 const char **endBuf,
4491 unsigned *startLine,
4492 unsigned *startColumn,
4493 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00004494 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00004495 assert(getCursorDecl(C) && "CXCursor has null decl");
4496 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00004497 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
4498 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004499
Steve Naroff4ade6d62009-09-23 17:52:52 +00004500 SourceManager &SM = FD->getASTContext().getSourceManager();
4501 *startBuf = SM.getCharacterData(Body->getLBracLoc());
4502 *endBuf = SM.getCharacterData(Body->getRBracLoc());
4503 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
4504 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
4505 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
4506 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
4507}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004508
Douglas Gregor430d7a12011-07-25 17:48:11 +00004509
4510CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
4511 unsigned PieceIndex) {
4512 RefNamePieces Pieces;
4513
4514 switch (C.kind) {
4515 case CXCursor_MemberRefExpr:
4516 if (MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
4517 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
4518 E->getQualifierLoc().getSourceRange());
4519 break;
4520
4521 case CXCursor_DeclRefExpr:
4522 if (DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C)))
4523 Pieces = buildPieces(NameFlags, false, E->getNameInfo(),
4524 E->getQualifierLoc().getSourceRange(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00004525 E->getOptionalExplicitTemplateArgs());
Douglas Gregor430d7a12011-07-25 17:48:11 +00004526 break;
4527
4528 case CXCursor_CallExpr:
4529 if (CXXOperatorCallExpr *OCE =
4530 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
4531 Expr *Callee = OCE->getCallee();
4532 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
4533 Callee = ICE->getSubExpr();
4534
4535 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
4536 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
4537 DRE->getQualifierLoc().getSourceRange());
4538 }
4539 break;
4540
4541 default:
4542 break;
4543 }
4544
4545 if (Pieces.empty()) {
4546 if (PieceIndex == 0)
4547 return clang_getCursorExtent(C);
4548 } else if (PieceIndex < Pieces.size()) {
4549 SourceRange R = Pieces[PieceIndex];
4550 if (R.isValid())
4551 return cxloc::translateSourceRange(getCursorContext(C), R);
4552 }
4553
4554 return clang_getNullRange();
4555}
4556
Douglas Gregor0a812cf2010-02-18 23:07:20 +00004557void clang_enableStackTraces(void) {
4558 llvm::sys::PrintStackTraceOnErrorSignal();
4559}
4560
Daniel Dunbar995aaf92010-11-04 01:26:29 +00004561void clang_executeOnThread(void (*fn)(void*), void *user_data,
4562 unsigned stack_size) {
4563 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
4564}
4565
Ted Kremenekfb480492010-01-13 21:46:36 +00004566} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00004567
Ted Kremenekfb480492010-01-13 21:46:36 +00004568//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004569// Token-based Operations.
4570//===----------------------------------------------------------------------===//
4571
4572/* CXToken layout:
4573 * int_data[0]: a CXTokenKind
4574 * int_data[1]: starting token location
4575 * int_data[2]: token length
4576 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004577 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004578 * otherwise unused.
4579 */
4580extern "C" {
4581
4582CXTokenKind clang_getTokenKind(CXToken CXTok) {
4583 return static_cast<CXTokenKind>(CXTok.int_data[0]);
4584}
4585
4586CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
4587 switch (clang_getTokenKind(CXTok)) {
4588 case CXToken_Identifier:
4589 case CXToken_Keyword:
4590 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004591 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
4592 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004593
4594 case CXToken_Literal: {
4595 // We have stashed the starting pointer in the ptr_data field. Use it.
4596 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Chris Lattner5f9e2722011-07-23 10:55:15 +00004597 return createCXString(StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004598 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004599
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004600 case CXToken_Punctuation:
4601 case CXToken_Comment:
4602 break;
4603 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004604
4605 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004606 // deconstructing the source location.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004607 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004608 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004609 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004610
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004611 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
4612 std::pair<FileID, unsigned> LocInfo
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004613 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00004614 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004615 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004616 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
4617 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00004618 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004619
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004620 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004621}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004622
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004623CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004624 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004625 if (!CXXUnit)
4626 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004627
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004628 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
4629 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4630}
4631
4632CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004633 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor5352ac02010-01-28 00:27:43 +00004634 if (!CXXUnit)
4635 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004636
4637 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004638 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4639}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004640
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004641static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
4642 SmallVectorImpl<CXToken> &CXTokens) {
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004643 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4644 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004645 = SourceMgr.getDecomposedLoc(Range.getBegin());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004646 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004647 = SourceMgr.getDecomposedLoc(Range.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004648
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004649 // Cannot tokenize across files.
4650 if (BeginLocInfo.first != EndLocInfo.first)
4651 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004652
4653 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004654 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004655 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004656 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00004657 if (Invalid)
4658 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00004659
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004660 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
David Blaikie4e4d0842012-03-11 07:00:24 +00004661 CXXUnit->getASTContext().getLangOpts(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004662 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004663 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004664
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004665 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004666 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004667 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00004668 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004669 do {
4670 // Lex the next token
4671 Lex.LexFromRawLexer(Tok);
4672 if (Tok.is(tok::eof))
4673 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004674
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004675 // Initialize the CXToken.
4676 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004677
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004678 // - Common fields
4679 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
4680 CXTok.int_data[2] = Tok.getLength();
4681 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004682
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004683 // - Kind-specific fields
4684 if (Tok.isLiteral()) {
4685 CXTok.int_data[0] = CXToken_Literal;
4686 CXTok.ptr_data = (void *)Tok.getLiteralData();
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004687 } else if (Tok.is(tok::raw_identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00004688 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004689 IdentifierInfo *II
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004690 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004691
David Chisnall096428b2010-10-13 21:44:48 +00004692 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004693 CXTok.int_data[0] = CXToken_Keyword;
4694 }
4695 else {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004696 CXTok.int_data[0] = Tok.is(tok::identifier)
4697 ? CXToken_Identifier
4698 : CXToken_Keyword;
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004699 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004700 CXTok.ptr_data = II;
4701 } else if (Tok.is(tok::comment)) {
4702 CXTok.int_data[0] = CXToken_Comment;
4703 CXTok.ptr_data = 0;
4704 } else {
4705 CXTok.int_data[0] = CXToken_Punctuation;
4706 CXTok.ptr_data = 0;
4707 }
4708 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00004709 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004710 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004711}
4712
4713void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
4714 CXToken **Tokens, unsigned *NumTokens) {
4715 if (Tokens)
4716 *Tokens = 0;
4717 if (NumTokens)
4718 *NumTokens = 0;
4719
4720 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4721 if (!CXXUnit || !Tokens || !NumTokens)
4722 return;
4723
4724 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4725
4726 SourceRange R = cxloc::translateCXSourceRange(Range);
4727 if (R.isInvalid())
4728 return;
4729
4730 SmallVector<CXToken, 32> CXTokens;
4731 getTokens(CXXUnit, R, CXTokens);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004732
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004733 if (CXTokens.empty())
4734 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004735
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004736 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
4737 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
4738 *NumTokens = CXTokens.size();
4739}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004740
Ted Kremenek6db61092010-05-05 00:55:15 +00004741void clang_disposeTokens(CXTranslationUnit TU,
4742 CXToken *Tokens, unsigned NumTokens) {
4743 free(Tokens);
4744}
4745
4746} // end: extern "C"
4747
4748//===----------------------------------------------------------------------===//
4749// Token annotation APIs.
4750//===----------------------------------------------------------------------===//
4751
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004752typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004753static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4754 CXCursor parent,
4755 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00004756namespace {
4757class AnnotateTokensWorker {
4758 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004759 CXToken *Tokens;
4760 CXCursor *Cursors;
4761 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004762 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00004763 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004764 CursorVisitor AnnotateVis;
4765 SourceManager &SrcMgr;
Douglas Gregorf5251602011-03-08 17:10:18 +00004766 bool HasContextSensitiveKeywords;
4767
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004768 bool MoreTokens() const { return TokIdx < NumTokens; }
4769 unsigned NextToken() const { return TokIdx; }
4770 void AdvanceToken() { ++TokIdx; }
4771 SourceLocation GetTokenLoc(unsigned tokI) {
4772 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4773 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004774 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004775 return Tokens[tokI].int_data[3] != 0;
4776 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004777 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004778 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[3]);
4779 }
4780
4781 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004782 void annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
4783 SourceRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004784
Ted Kremenek6db61092010-05-05 00:55:15 +00004785public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00004786 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004787 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004788 CXTranslationUnit tu, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00004789 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00004790 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004791 AnnotateVis(tu,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00004792 AnnotateTokensVisitor, this,
4793 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00004794 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00004795 RegionOfInterest),
Douglas Gregorf5251602011-03-08 17:10:18 +00004796 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()),
4797 HasContextSensitiveKeywords(false) { }
Ted Kremenek11949cb2010-05-05 00:55:17 +00004798
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004799 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00004800 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004801 void AnnotateTokens();
Douglas Gregorf5251602011-03-08 17:10:18 +00004802
4803 /// \brief Determine whether the annotator saw any cursors that have
4804 /// context-sensitive keywords.
4805 bool hasContextSensitiveKeywords() const {
4806 return HasContextSensitiveKeywords;
4807 }
Ted Kremenek6db61092010-05-05 00:55:15 +00004808};
4809}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004810
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004811void AnnotateTokensWorker::AnnotateTokens() {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004812 // Walk the AST within the region of interest, annotating tokens
4813 // along the way.
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004814 AnnotateVis.visitFileRegion();
Ted Kremenek11949cb2010-05-05 00:55:17 +00004815
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004816 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4817 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004818 if (Pos != Annotated.end() &&
4819 (clang_isInvalid(Cursors[I].kind) ||
4820 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004821 Cursors[I] = Pos->second;
4822 }
4823
4824 // Finish up annotating any tokens left.
4825 if (!MoreTokens())
4826 return;
4827
4828 const CXCursor &C = clang_getNullCursor();
4829 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004830 if (I < PreprocessingTokIdx && clang_isPreprocessing(Cursors[I].kind))
4831 continue;
4832
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004833 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4834 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004835 }
4836}
4837
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004838/// \brief It annotates and advances tokens with a cursor until the comparison
4839//// between the cursor location and the source range is the same as
4840/// \arg compResult.
4841///
4842/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
4843/// Pass RangeOverlap to annotate tokens inside a range.
4844void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
4845 RangeComparisonResult compResult,
4846 SourceRange range) {
4847 while (MoreTokens()) {
4848 const unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004849 if (isFunctionMacroToken(I))
4850 return annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004851
4852 SourceLocation TokLoc = GetTokenLoc(I);
4853 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4854 Cursors[I] = updateC;
4855 AdvanceToken();
4856 continue;
4857 }
4858 break;
4859 }
4860}
4861
4862/// \brief Special annotation handling for macro argument tokens.
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004863void AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
4864 CXCursor updateC,
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004865 RangeComparisonResult compResult,
4866 SourceRange range) {
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004867 assert(MoreTokens());
4868 assert(isFunctionMacroToken(NextToken()) &&
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004869 "Should be called only for macro arg tokens");
4870
4871 // This works differently than annotateAndAdvanceTokens; because expanded
4872 // macro arguments can have arbitrary translation-unit source order, we do not
4873 // advance the token index one by one until a token fails the range test.
4874 // We only advance once past all of the macro arg tokens if all of them
4875 // pass the range test. If one of them fails we keep the token index pointing
4876 // at the start of the macro arg tokens so that the failing token will be
4877 // annotated by a subsequent annotation try.
4878
4879 bool atLeastOneCompFail = false;
4880
4881 unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004882 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
4883 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004884 if (TokLoc.isFileID())
4885 continue; // not macro arg token, it's parens or comma.
4886 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4887 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
4888 Cursors[I] = updateC;
4889 } else
4890 atLeastOneCompFail = true;
4891 }
4892
4893 if (!atLeastOneCompFail)
4894 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
4895}
4896
Ted Kremenek6db61092010-05-05 00:55:15 +00004897enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004898AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004899 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004900 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004901 if (cursorRange.isInvalid())
4902 return CXChildVisit_Recurse;
Douglas Gregorf5251602011-03-08 17:10:18 +00004903
4904 if (!HasContextSensitiveKeywords) {
4905 // Objective-C properties can have context-sensitive keywords.
4906 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
4907 if (ObjCPropertyDecl *Property
4908 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
4909 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
4910 }
4911 // Objective-C methods can have context-sensitive keywords.
4912 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
4913 cursor.kind == CXCursor_ObjCClassMethodDecl) {
4914 if (ObjCMethodDecl *Method
4915 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
4916 if (Method->getObjCDeclQualifier())
4917 HasContextSensitiveKeywords = true;
4918 else {
4919 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
4920 PEnd = Method->param_end();
4921 P != PEnd; ++P) {
4922 if ((*P)->getObjCDeclQualifier()) {
4923 HasContextSensitiveKeywords = true;
4924 break;
4925 }
4926 }
4927 }
4928 }
4929 }
4930 // C++ methods can have context-sensitive keywords.
4931 else if (cursor.kind == CXCursor_CXXMethod) {
4932 if (CXXMethodDecl *Method
4933 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
4934 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
4935 HasContextSensitiveKeywords = true;
4936 }
4937 }
4938 // C++ classes can have context-sensitive keywords.
4939 else if (cursor.kind == CXCursor_StructDecl ||
4940 cursor.kind == CXCursor_ClassDecl ||
4941 cursor.kind == CXCursor_ClassTemplate ||
4942 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
4943 if (Decl *D = getCursorDecl(cursor))
4944 if (D->hasAttr<FinalAttr>())
4945 HasContextSensitiveKeywords = true;
4946 }
4947 }
4948
Douglas Gregor4419b672010-10-21 06:10:04 +00004949 if (clang_isPreprocessing(cursor.kind)) {
Chandler Carruthcea731a2011-07-14 16:07:57 +00004950 // For macro expansions, just note where the beginning of the macro
4951 // expansion occurs.
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004952 if (cursor.kind == CXCursor_MacroExpansion) {
Douglas Gregor4419b672010-10-21 06:10:04 +00004953 Annotated[Loc.int_data] = cursor;
4954 return CXChildVisit_Recurse;
4955 }
4956
Douglas Gregor4419b672010-10-21 06:10:04 +00004957 // Items in the preprocessing record are kept separate from items in
4958 // declarations, so we keep a separate token index.
4959 unsigned SavedTokIdx = TokIdx;
4960 TokIdx = PreprocessingTokIdx;
4961
4962 // Skip tokens up until we catch up to the beginning of the preprocessing
4963 // entry.
4964 while (MoreTokens()) {
4965 const unsigned I = NextToken();
4966 SourceLocation TokLoc = GetTokenLoc(I);
4967 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4968 case RangeBefore:
4969 AdvanceToken();
4970 continue;
4971 case RangeAfter:
4972 case RangeOverlap:
4973 break;
4974 }
4975 break;
4976 }
4977
4978 // Look at all of the tokens within this range.
4979 while (MoreTokens()) {
4980 const unsigned I = NextToken();
4981 SourceLocation TokLoc = GetTokenLoc(I);
4982 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4983 case RangeBefore:
David Blaikieb219cfc2011-09-23 05:06:16 +00004984 llvm_unreachable("Infeasible");
Douglas Gregor4419b672010-10-21 06:10:04 +00004985 case RangeAfter:
4986 break;
4987 case RangeOverlap:
4988 Cursors[I] = cursor;
4989 AdvanceToken();
4990 continue;
4991 }
4992 break;
4993 }
4994
4995 // Save the preprocessing token index; restore the non-preprocessing
4996 // token index.
4997 PreprocessingTokIdx = TokIdx;
4998 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004999 return CXChildVisit_Recurse;
5000 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005001
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005002 if (cursorRange.isInvalid())
5003 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00005004
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005005 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
5006
Ted Kremeneka333c662010-05-12 05:29:33 +00005007 // Adjust the annotated range based specific declarations.
5008 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
5009 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00005010 Decl *D = cxcursor::getCursorDecl(cursor);
Douglas Gregor2494dd02011-03-01 01:34:45 +00005011
5012 SourceLocation StartLoc;
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00005013 if (const DeclaratorDecl *DD = dyn_cast_or_null<DeclaratorDecl>(D)) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00005014 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
Daniel Dunbar96a00142012-03-09 18:35:03 +00005015 StartLoc = TI->getTypeLoc().getLocStart();
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00005016 } else if (TypedefDecl *Typedef = dyn_cast_or_null<TypedefDecl>(D)) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00005017 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
Daniel Dunbar96a00142012-03-09 18:35:03 +00005018 StartLoc = TI->getTypeLoc().getLocStart();
Ted Kremeneka333c662010-05-12 05:29:33 +00005019 }
Douglas Gregor2494dd02011-03-01 01:34:45 +00005020
5021 if (StartLoc.isValid() && L.isValid() &&
5022 SrcMgr.isBeforeInTranslationUnit(StartLoc, L))
5023 cursorRange.setBegin(StartLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00005024 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00005025
Ted Kremenek3f404602010-08-14 01:14:06 +00005026 // If the location of the cursor occurs within a macro instantiation, record
5027 // the spelling location of the cursor in our annotation map. We can then
5028 // paper over the token labelings during a post-processing step to try and
5029 // get cursor mappings for tokens that are the *arguments* of a macro
5030 // instantiation.
5031 if (L.isMacroID()) {
5032 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
5033 // Only invalidate the old annotation if it isn't part of a preprocessing
5034 // directive. Here we assume that the default construction of CXCursor
5035 // results in CXCursor.kind being an initialized value (i.e., 0). If
5036 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00005037
Ted Kremenek3f404602010-08-14 01:14:06 +00005038 CXCursor &oldC = Annotated[rawEncoding];
5039 if (!clang_isPreprocessing(oldC.kind))
5040 oldC = cursor;
5041 }
5042
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005043 const enum CXCursorKind K = clang_getCursorKind(parent);
5044 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00005045 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
5046 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005047
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005048 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005049
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00005050 // Avoid having the cursor of an expression "overwrite" the annotation of the
5051 // variable declaration that it belongs to.
5052 // This can happen for C++ constructor expressions whose range generally
5053 // include the variable declaration, e.g.:
5054 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
5055 if (clang_isExpression(cursorK)) {
5056 Expr *E = getCursorExpr(cursor);
Argyrios Kyrtzidis8ccac3d2011-06-29 22:20:07 +00005057 if (Decl *D = getCursorParentDecl(cursor)) {
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00005058 const unsigned I = NextToken();
5059 if (E->getLocStart().isValid() && D->getLocation().isValid() &&
5060 E->getLocStart() == D->getLocation() &&
5061 E->getLocStart() == GetTokenLoc(I)) {
5062 Cursors[I] = updateC;
5063 AdvanceToken();
5064 }
5065 }
5066 }
5067
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005068 // Visit children to get their cursor information.
5069 const unsigned BeforeChildren = NextToken();
5070 VisitChildren(cursor);
5071 const unsigned AfterChildren = NextToken();
5072
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005073 // Scan the tokens that are at the end of the cursor, but are not captured
5074 // but the child cursors.
5075 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
Ted Kremenek6db61092010-05-05 00:55:15 +00005076
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005077 // Scan the tokens that are at the beginning of the cursor, but are not
5078 // capture by the child cursors.
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005079 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
5080 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
5081 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00005082
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005083 Cursors[I] = cursor;
5084 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005085
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005086 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005087}
5088
Ted Kremenek6db61092010-05-05 00:55:15 +00005089static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
5090 CXCursor parent,
5091 CXClientData client_data) {
5092 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
5093}
5094
Ted Kremenek6628a612011-03-18 22:51:30 +00005095namespace {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005096
5097/// \brief Uses the macro expansions in the preprocessing record to find
5098/// and mark tokens that are macro arguments. This info is used by the
5099/// AnnotateTokensWorker.
5100class MarkMacroArgTokensVisitor {
5101 SourceManager &SM;
5102 CXToken *Tokens;
5103 unsigned NumTokens;
5104 unsigned CurIdx;
5105
5106public:
5107 MarkMacroArgTokensVisitor(SourceManager &SM,
5108 CXToken *tokens, unsigned numTokens)
5109 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
5110
5111 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
5112 if (cursor.kind != CXCursor_MacroExpansion)
5113 return CXChildVisit_Continue;
5114
5115 SourceRange macroRange = getCursorMacroExpansion(cursor)->getSourceRange();
5116 if (macroRange.getBegin() == macroRange.getEnd())
5117 return CXChildVisit_Continue; // it's not a function macro.
5118
5119 for (; CurIdx < NumTokens; ++CurIdx) {
5120 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
5121 macroRange.getBegin()))
5122 break;
5123 }
5124
5125 if (CurIdx == NumTokens)
5126 return CXChildVisit_Break;
5127
5128 for (; CurIdx < NumTokens; ++CurIdx) {
5129 SourceLocation tokLoc = getTokenLoc(CurIdx);
5130 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
5131 break;
5132
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00005133 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005134 }
5135
5136 if (CurIdx == NumTokens)
5137 return CXChildVisit_Break;
5138
5139 return CXChildVisit_Continue;
5140 }
5141
5142private:
5143 SourceLocation getTokenLoc(unsigned tokI) {
5144 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
5145 }
5146
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00005147 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005148 // The third field is reserved and currently not used. Use it here
5149 // to mark macro arg expanded tokens with their expanded locations.
5150 Tokens[tokI].int_data[3] = loc.getRawEncoding();
5151 }
5152};
5153
5154} // end anonymous namespace
5155
5156static CXChildVisitResult
5157MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
5158 CXClientData client_data) {
5159 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
5160 parent);
5161}
5162
5163namespace {
Ted Kremenek6628a612011-03-18 22:51:30 +00005164 struct clang_annotateTokens_Data {
5165 CXTranslationUnit TU;
5166 ASTUnit *CXXUnit;
5167 CXToken *Tokens;
5168 unsigned NumTokens;
5169 CXCursor *Cursors;
5170 };
5171}
5172
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005173static void annotatePreprocessorTokens(CXTranslationUnit TU,
5174 SourceRange RegionOfInterest,
5175 AnnotateTokensData &Annotated) {
5176 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
5177
5178 SourceManager &SourceMgr = CXXUnit->getSourceManager();
5179 std::pair<FileID, unsigned> BeginLocInfo
5180 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
5181 std::pair<FileID, unsigned> EndLocInfo
5182 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
5183
5184 if (BeginLocInfo.first != EndLocInfo.first)
5185 return;
5186
5187 StringRef Buffer;
5188 bool Invalid = false;
5189 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
5190 if (Buffer.empty() || Invalid)
5191 return;
5192
5193 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
David Blaikie4e4d0842012-03-11 07:00:24 +00005194 CXXUnit->getASTContext().getLangOpts(),
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005195 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
5196 Buffer.end());
5197 Lex.SetCommentRetentionState(true);
5198
5199 // Lex tokens in raw mode until we hit the end of the range, to avoid
5200 // entering #includes or expanding macros.
5201 while (true) {
5202 Token Tok;
5203 Lex.LexFromRawLexer(Tok);
5204
5205 reprocess:
5206 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
5207 // We have found a preprocessing directive. Gobble it up so that we
5208 // don't see it while preprocessing these tokens later, but keep track
5209 // of all of the token locations inside this preprocessing directive so
5210 // that we can annotate them appropriately.
5211 //
5212 // FIXME: Some simple tests here could identify macro definitions and
5213 // #undefs, to provide specific cursor kinds for those.
5214 SmallVector<SourceLocation, 32> Locations;
5215 do {
5216 Locations.push_back(Tok.getLocation());
5217 Lex.LexFromRawLexer(Tok);
5218 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
5219
5220 using namespace cxcursor;
5221 CXCursor Cursor
5222 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
5223 Locations.back()),
5224 TU);
5225 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
5226 Annotated[Locations[I].getRawEncoding()] = Cursor;
5227 }
5228
5229 if (Tok.isAtStartOfLine())
5230 goto reprocess;
5231
5232 continue;
5233 }
5234
5235 if (Tok.is(tok::eof))
5236 break;
5237 }
5238}
5239
Ted Kremenekab979612010-11-11 08:05:23 +00005240// This gets run a separate thread to avoid stack blowout.
Ted Kremenek6628a612011-03-18 22:51:30 +00005241static void clang_annotateTokensImpl(void *UserData) {
5242 CXTranslationUnit TU = ((clang_annotateTokens_Data*)UserData)->TU;
5243 ASTUnit *CXXUnit = ((clang_annotateTokens_Data*)UserData)->CXXUnit;
5244 CXToken *Tokens = ((clang_annotateTokens_Data*)UserData)->Tokens;
5245 const unsigned NumTokens = ((clang_annotateTokens_Data*)UserData)->NumTokens;
5246 CXCursor *Cursors = ((clang_annotateTokens_Data*)UserData)->Cursors;
5247
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00005248 CIndexer *CXXIdx = (CIndexer*)TU->CIdx;
5249 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
Argyrios Kyrtzidis81b5ac32012-03-28 02:49:54 +00005250 setThreadBackgroundPriority();
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00005251
Ted Kremenek6628a612011-03-18 22:51:30 +00005252 // Determine the region of interest, which contains all of the tokens.
5253 SourceRange RegionOfInterest;
5254 RegionOfInterest.setBegin(
5255 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
5256 RegionOfInterest.setEnd(
5257 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
5258 Tokens[NumTokens-1])));
5259
5260 // A mapping from the source locations found when re-lexing or traversing the
5261 // region of interest to the corresponding cursors.
5262 AnnotateTokensData Annotated;
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005263
Ted Kremenek6628a612011-03-18 22:51:30 +00005264 // Relex the tokens within the source range to look for preprocessing
5265 // directives.
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005266 annotatePreprocessorTokens(TU, RegionOfInterest, Annotated);
Ted Kremenek6628a612011-03-18 22:51:30 +00005267
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005268 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
5269 // Search and mark tokens that are macro argument expansions.
5270 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
5271 Tokens, NumTokens);
5272 CursorVisitor MacroArgMarker(TU,
5273 MarkMacroArgTokensVisitorDelegate, &Visitor,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00005274 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00005275 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00005276 RegionOfInterest);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005277 MacroArgMarker.visitPreprocessedEntitiesInRegion();
5278 }
5279
Ted Kremenek6628a612011-03-18 22:51:30 +00005280 // Annotate all of the source locations in the region of interest that map to
5281 // a specific cursor.
5282 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
5283 TU, RegionOfInterest);
5284
5285 // FIXME: We use a ridiculous stack size here because the data-recursion
5286 // algorithm uses a large stack frame than the non-data recursive version,
5287 // and AnnotationTokensWorker currently transforms the data-recursion
5288 // algorithm back into a traditional recursion by explicitly calling
5289 // VisitChildren(). We will need to remove this explicit recursive call.
5290 W.AnnotateTokens();
5291
5292 // If we ran into any entities that involve context-sensitive keywords,
5293 // take another pass through the tokens to mark them as such.
5294 if (W.hasContextSensitiveKeywords()) {
5295 for (unsigned I = 0; I != NumTokens; ++I) {
5296 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
5297 continue;
5298
5299 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
5300 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5301 if (ObjCPropertyDecl *Property
5302 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
5303 if (Property->getPropertyAttributesAsWritten() != 0 &&
5304 llvm::StringSwitch<bool>(II->getName())
5305 .Case("readonly", true)
5306 .Case("assign", true)
John McCallf85e1932011-06-15 23:02:42 +00005307 .Case("unsafe_unretained", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00005308 .Case("readwrite", true)
5309 .Case("retain", true)
5310 .Case("copy", true)
5311 .Case("nonatomic", true)
5312 .Case("atomic", true)
5313 .Case("getter", true)
5314 .Case("setter", true)
John McCallf85e1932011-06-15 23:02:42 +00005315 .Case("strong", true)
5316 .Case("weak", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00005317 .Default(false))
5318 Tokens[I].int_data[0] = CXToken_Keyword;
5319 }
5320 continue;
5321 }
5322
5323 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
5324 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
5325 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5326 if (llvm::StringSwitch<bool>(II->getName())
5327 .Case("in", true)
5328 .Case("out", true)
5329 .Case("inout", true)
5330 .Case("oneway", true)
5331 .Case("bycopy", true)
5332 .Case("byref", true)
5333 .Default(false))
5334 Tokens[I].int_data[0] = CXToken_Keyword;
5335 continue;
5336 }
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00005337
5338 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
5339 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
5340 Tokens[I].int_data[0] = CXToken_Keyword;
Ted Kremenek6628a612011-03-18 22:51:30 +00005341 continue;
5342 }
5343 }
5344 }
Ted Kremenekab979612010-11-11 08:05:23 +00005345}
5346
Ted Kremenek6db61092010-05-05 00:55:15 +00005347extern "C" {
5348
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005349void clang_annotateTokens(CXTranslationUnit TU,
5350 CXToken *Tokens, unsigned NumTokens,
5351 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005352
5353 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005354 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005355
Douglas Gregor4419b672010-10-21 06:10:04 +00005356 // Any token we don't specifically annotate will have a NULL cursor.
5357 CXCursor C = clang_getNullCursor();
5358 for (unsigned I = 0; I != NumTokens; ++I)
5359 Cursors[I] = C;
5360
Ted Kremeneka60ed472010-11-16 08:15:36 +00005361 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor4419b672010-10-21 06:10:04 +00005362 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005363 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005364
Douglas Gregorbdf60622010-03-05 21:16:25 +00005365 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenek6628a612011-03-18 22:51:30 +00005366
5367 clang_annotateTokens_Data data = { TU, CXXUnit, Tokens, NumTokens, Cursors };
Ted Kremenekab979612010-11-11 08:05:23 +00005368 llvm::CrashRecoveryContext CRC;
Ted Kremenek6628a612011-03-18 22:51:30 +00005369 if (!RunSafely(CRC, clang_annotateTokensImpl, &data,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005370 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00005371 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
5372 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005373}
Ted Kremenek6628a612011-03-18 22:51:30 +00005374
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005375} // end: extern "C"
5376
5377//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00005378// Operations for querying linkage of a cursor.
5379//===----------------------------------------------------------------------===//
5380
5381extern "C" {
5382CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00005383 if (!clang_isDeclaration(cursor.kind))
5384 return CXLinkage_Invalid;
5385
Ted Kremenek16b42592010-03-03 06:36:57 +00005386 Decl *D = cxcursor::getCursorDecl(cursor);
5387 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
5388 switch (ND->getLinkage()) {
5389 case NoLinkage: return CXLinkage_NoLinkage;
5390 case InternalLinkage: return CXLinkage_Internal;
5391 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
5392 case ExternalLinkage: return CXLinkage_External;
5393 };
5394
5395 return CXLinkage_Invalid;
5396}
5397} // end: extern "C"
5398
5399//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005400// Operations for querying language of a cursor.
5401//===----------------------------------------------------------------------===//
5402
5403static CXLanguageKind getDeclLanguage(const Decl *D) {
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00005404 if (!D)
5405 return CXLanguage_C;
5406
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005407 switch (D->getKind()) {
5408 default:
5409 break;
5410 case Decl::ImplicitParam:
5411 case Decl::ObjCAtDefsField:
5412 case Decl::ObjCCategory:
5413 case Decl::ObjCCategoryImpl:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005414 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005415 case Decl::ObjCImplementation:
5416 case Decl::ObjCInterface:
5417 case Decl::ObjCIvar:
5418 case Decl::ObjCMethod:
5419 case Decl::ObjCProperty:
5420 case Decl::ObjCPropertyImpl:
5421 case Decl::ObjCProtocol:
5422 return CXLanguage_ObjC;
5423 case Decl::CXXConstructor:
5424 case Decl::CXXConversion:
5425 case Decl::CXXDestructor:
5426 case Decl::CXXMethod:
5427 case Decl::CXXRecord:
5428 case Decl::ClassTemplate:
5429 case Decl::ClassTemplatePartialSpecialization:
5430 case Decl::ClassTemplateSpecialization:
5431 case Decl::Friend:
5432 case Decl::FriendTemplate:
5433 case Decl::FunctionTemplate:
5434 case Decl::LinkageSpec:
5435 case Decl::Namespace:
5436 case Decl::NamespaceAlias:
5437 case Decl::NonTypeTemplateParm:
5438 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005439 case Decl::TemplateTemplateParm:
5440 case Decl::TemplateTypeParm:
5441 case Decl::UnresolvedUsingTypename:
5442 case Decl::UnresolvedUsingValue:
5443 case Decl::Using:
5444 case Decl::UsingDirective:
5445 case Decl::UsingShadow:
5446 return CXLanguage_CPlusPlus;
5447 }
5448
5449 return CXLanguage_C;
5450}
5451
5452extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00005453
5454enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
5455 if (clang_isDeclaration(cursor.kind))
5456 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005457 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Douglas Gregor58ddb602010-08-23 23:00:57 +00005458 return CXAvailability_Available;
5459
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005460 switch (D->getAvailability()) {
5461 case AR_Available:
5462 case AR_NotYetIntroduced:
5463 return CXAvailability_Available;
5464
5465 case AR_Deprecated:
Douglas Gregor58ddb602010-08-23 23:00:57 +00005466 return CXAvailability_Deprecated;
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005467
5468 case AR_Unavailable:
5469 return CXAvailability_NotAvailable;
5470 }
Douglas Gregor58ddb602010-08-23 23:00:57 +00005471 }
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005472
Douglas Gregor58ddb602010-08-23 23:00:57 +00005473 return CXAvailability_Available;
5474}
5475
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005476CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
5477 if (clang_isDeclaration(cursor.kind))
5478 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
5479
5480 return CXLanguage_Invalid;
5481}
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005482
5483 /// \brief If the given cursor is the "templated" declaration
5484 /// descibing a class or function template, return the class or
5485 /// function template.
5486static Decl *maybeGetTemplateCursor(Decl *D) {
5487 if (!D)
5488 return 0;
5489
5490 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
5491 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
5492 return FunTmpl;
5493
5494 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
5495 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
5496 return ClassTmpl;
5497
5498 return D;
5499}
5500
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005501CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
5502 if (clang_isDeclaration(cursor.kind)) {
5503 if (Decl *D = getCursorDecl(cursor)) {
5504 DeclContext *DC = D->getDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005505 if (!DC)
5506 return clang_getNullCursor();
5507
5508 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5509 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005510 }
5511 }
5512
5513 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
5514 if (Decl *D = getCursorDecl(cursor))
Ted Kremeneka60ed472010-11-16 08:15:36 +00005515 return MakeCXCursor(D, getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005516 }
5517
5518 return clang_getNullCursor();
5519}
5520
5521CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
5522 if (clang_isDeclaration(cursor.kind)) {
5523 if (Decl *D = getCursorDecl(cursor)) {
5524 DeclContext *DC = D->getLexicalDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005525 if (!DC)
5526 return clang_getNullCursor();
5527
5528 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5529 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005530 }
5531 }
5532
5533 // FIXME: Note that we can't easily compute the lexical context of a
5534 // statement or expression, so we return nothing.
5535 return clang_getNullCursor();
5536}
5537
Douglas Gregor9f592342010-10-01 20:25:15 +00005538void clang_getOverriddenCursors(CXCursor cursor,
5539 CXCursor **overridden,
5540 unsigned *num_overridden) {
5541 if (overridden)
5542 *overridden = 0;
5543 if (num_overridden)
5544 *num_overridden = 0;
5545 if (!overridden || !num_overridden)
5546 return;
Argyrios Kyrtzidis15f4c982012-04-10 21:01:03 +00005547 if (!clang_isDeclaration(cursor.kind))
5548 return;
Douglas Gregor9f592342010-10-01 20:25:15 +00005549
Argyrios Kyrtzidisb11be042011-10-06 07:00:46 +00005550 SmallVector<CXCursor, 8> Overridden;
5551 cxcursor::getOverriddenCursors(cursor, Overridden);
Douglas Gregor9f592342010-10-01 20:25:15 +00005552
Ted Kremenek24077122011-11-14 23:51:37 +00005553 // Don't allocate memory if we have no overriden cursors.
5554 if (Overridden.size() == 0)
5555 return;
5556
Argyrios Kyrtzidisb11be042011-10-06 07:00:46 +00005557 *num_overridden = Overridden.size();
5558 *overridden = new CXCursor [Overridden.size()];
5559 std::copy(Overridden.begin(), Overridden.end(), *overridden);
Douglas Gregor9f592342010-10-01 20:25:15 +00005560}
5561
5562void clang_disposeOverriddenCursors(CXCursor *overridden) {
5563 delete [] overridden;
5564}
5565
Douglas Gregorecdcb882010-10-20 22:00:55 +00005566CXFile clang_getIncludedFile(CXCursor cursor) {
5567 if (cursor.kind != CXCursor_InclusionDirective)
5568 return 0;
5569
5570 InclusionDirective *ID = getCursorInclusionDirective(cursor);
5571 return (void *)ID->getFile();
5572}
5573
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005574} // end: extern "C"
5575
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005576
5577//===----------------------------------------------------------------------===//
5578// C++ AST instrospection.
5579//===----------------------------------------------------------------------===//
5580
5581extern "C" {
5582unsigned clang_CXXMethod_isStatic(CXCursor C) {
5583 if (!clang_isDeclaration(C.kind))
5584 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00005585
5586 CXXMethodDecl *Method = 0;
5587 Decl *D = cxcursor::getCursorDecl(C);
5588 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5589 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5590 else
5591 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5592 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00005593}
Ted Kremenekb12903e2010-05-18 22:32:15 +00005594
Douglas Gregor211924b2011-05-12 15:17:24 +00005595unsigned clang_CXXMethod_isVirtual(CXCursor C) {
5596 if (!clang_isDeclaration(C.kind))
5597 return 0;
5598
5599 CXXMethodDecl *Method = 0;
5600 Decl *D = cxcursor::getCursorDecl(C);
5601 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5602 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5603 else
5604 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5605 return (Method && Method->isVirtual()) ? 1 : 0;
5606}
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005607} // end: extern "C"
5608
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005609//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00005610// Attribute introspection.
5611//===----------------------------------------------------------------------===//
5612
5613extern "C" {
5614CXType clang_getIBOutletCollectionType(CXCursor C) {
5615 if (C.kind != CXCursor_IBOutletCollectionAttr)
Ted Kremeneka60ed472010-11-16 08:15:36 +00005616 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005617
5618 IBOutletCollectionAttr *A =
5619 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
5620
Argyrios Kyrtzidis18aa2ff2011-09-13 18:49:52 +00005621 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005622}
5623} // end: extern "C"
5624
5625//===----------------------------------------------------------------------===//
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005626// Inspecting memory usage.
5627//===----------------------------------------------------------------------===//
5628
Ted Kremenekf7870022011-04-20 16:41:07 +00005629typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005630
Ted Kremenekf7870022011-04-20 16:41:07 +00005631static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
5632 enum CXTUResourceUsageKind k,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005633 unsigned long amount) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005634 CXTUResourceUsageEntry entry = { k, amount };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005635 entries.push_back(entry);
5636}
5637
5638extern "C" {
5639
Ted Kremenekf7870022011-04-20 16:41:07 +00005640const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005641 const char *str = "";
5642 switch (kind) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005643 case CXTUResourceUsage_AST:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005644 str = "ASTContext: expressions, declarations, and types";
5645 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005646 case CXTUResourceUsage_Identifiers:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005647 str = "ASTContext: identifiers";
5648 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005649 case CXTUResourceUsage_Selectors:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005650 str = "ASTContext: selectors";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005651 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005652 case CXTUResourceUsage_GlobalCompletionResults:
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005653 str = "Code completion: cached global results";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005654 break;
Ted Kremenek457aaf02011-04-28 04:10:31 +00005655 case CXTUResourceUsage_SourceManagerContentCache:
5656 str = "SourceManager: content cache allocator";
5657 break;
Ted Kremenekba29bd22011-04-28 04:53:38 +00005658 case CXTUResourceUsage_AST_SideTables:
5659 str = "ASTContext: side tables";
5660 break;
Ted Kremenekf61b8312011-04-28 20:36:42 +00005661 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
5662 str = "SourceManager: malloc'ed memory buffers";
5663 break;
5664 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
5665 str = "SourceManager: mmap'ed memory buffers";
5666 break;
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005667 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
5668 str = "ExternalASTSource: malloc'ed memory buffers";
5669 break;
5670 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
5671 str = "ExternalASTSource: mmap'ed memory buffers";
5672 break;
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005673 case CXTUResourceUsage_Preprocessor:
5674 str = "Preprocessor: malloc'ed memory";
5675 break;
5676 case CXTUResourceUsage_PreprocessingRecord:
5677 str = "Preprocessor: PreprocessingRecord";
5678 break;
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005679 case CXTUResourceUsage_SourceManager_DataStructures:
5680 str = "SourceManager: data structures and tables";
5681 break;
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005682 case CXTUResourceUsage_Preprocessor_HeaderSearch:
5683 str = "Preprocessor: header search tables";
5684 break;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005685 }
5686 return str;
5687}
5688
Ted Kremenekf7870022011-04-20 16:41:07 +00005689CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005690 if (!TU) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005691 CXTUResourceUsage usage = { (void*) 0, 0, 0 };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005692 return usage;
5693 }
5694
5695 ASTUnit *astUnit = static_cast<ASTUnit*>(TU->TUData);
Dylan Noblesmith1e4c01b2012-02-13 12:32:21 +00005696 OwningPtr<MemUsageEntries> entries(new MemUsageEntries());
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005697 ASTContext &astContext = astUnit->getASTContext();
5698
5699 // How much memory is used by AST nodes and types?
Ted Kremenekf7870022011-04-20 16:41:07 +00005700 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005701 (unsigned long) astContext.getASTAllocatedMemory());
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005702
5703 // How much memory is used by identifiers?
Ted Kremenekf7870022011-04-20 16:41:07 +00005704 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005705 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
5706
5707 // How much memory is used for selectors?
Ted Kremenekf7870022011-04-20 16:41:07 +00005708 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005709 (unsigned long) astContext.Selectors.getTotalMemory());
5710
Ted Kremenekba29bd22011-04-28 04:53:38 +00005711 // How much memory is used by ASTContext's side tables?
5712 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
5713 (unsigned long) astContext.getSideTableAllocatedMemory());
5714
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005715 // How much memory is used for caching global code completion results?
5716 unsigned long completionBytes = 0;
5717 if (GlobalCodeCompletionAllocator *completionAllocator =
5718 astUnit->getCachedCompletionAllocator().getPtr()) {
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005719 completionBytes = completionAllocator->getTotalMemory();
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005720 }
Ted Kremenek457aaf02011-04-28 04:10:31 +00005721 createCXTUResourceUsageEntry(*entries,
5722 CXTUResourceUsage_GlobalCompletionResults,
5723 completionBytes);
5724
5725 // How much memory is being used by SourceManager's content cache?
5726 createCXTUResourceUsageEntry(*entries,
5727 CXTUResourceUsage_SourceManagerContentCache,
5728 (unsigned long) astContext.getSourceManager().getContentCacheSize());
Ted Kremenekf61b8312011-04-28 20:36:42 +00005729
5730 // How much memory is being used by the MemoryBuffer's in SourceManager?
5731 const SourceManager::MemoryBufferSizes &srcBufs =
5732 astUnit->getSourceManager().getMemoryBufferSizes();
5733
5734 createCXTUResourceUsageEntry(*entries,
5735 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
5736 (unsigned long) srcBufs.malloc_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005737 createCXTUResourceUsageEntry(*entries,
Ted Kremenekf61b8312011-04-28 20:36:42 +00005738 CXTUResourceUsage_SourceManager_Membuffer_MMap,
5739 (unsigned long) srcBufs.mmap_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005740 createCXTUResourceUsageEntry(*entries,
5741 CXTUResourceUsage_SourceManager_DataStructures,
5742 (unsigned long) astContext.getSourceManager()
5743 .getDataStructureSizes());
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005744
5745 // How much memory is being used by the ExternalASTSource?
5746 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
5747 const ExternalASTSource::MemoryBufferSizes &sizes =
5748 esrc->getMemoryBufferSizes();
5749
5750 createCXTUResourceUsageEntry(*entries,
5751 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
5752 (unsigned long) sizes.malloc_bytes);
5753 createCXTUResourceUsageEntry(*entries,
5754 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
5755 (unsigned long) sizes.mmap_bytes);
5756 }
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005757
5758 // How much memory is being used by the Preprocessor?
5759 Preprocessor &pp = astUnit->getPreprocessor();
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005760 createCXTUResourceUsageEntry(*entries,
5761 CXTUResourceUsage_Preprocessor,
Argyrios Kyrtzidisc5c5e922011-06-29 22:20:04 +00005762 pp.getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005763
5764 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
5765 createCXTUResourceUsageEntry(*entries,
5766 CXTUResourceUsage_PreprocessingRecord,
5767 pRec->getTotalMemory());
5768 }
5769
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005770 createCXTUResourceUsageEntry(*entries,
5771 CXTUResourceUsage_Preprocessor_HeaderSearch,
5772 pp.getHeaderSearchInfo().getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005773
Ted Kremenekf7870022011-04-20 16:41:07 +00005774 CXTUResourceUsage usage = { (void*) entries.get(),
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005775 (unsigned) entries->size(),
5776 entries->size() ? &(*entries)[0] : 0 };
5777 entries.take();
5778 return usage;
5779}
5780
Ted Kremenekf7870022011-04-20 16:41:07 +00005781void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005782 if (usage.data)
5783 delete (MemUsageEntries*) usage.data;
5784}
5785
5786} // end extern "C"
5787
Douglas Gregor6df78732011-05-05 20:27:22 +00005788void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
5789 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
5790 for (unsigned I = 0; I != Usage.numEntries; ++I)
5791 fprintf(stderr, " %s: %lu\n",
5792 clang_getTUResourceUsageName(Usage.entries[I].kind),
5793 Usage.entries[I].amount);
5794
5795 clang_disposeCXTUResourceUsage(Usage);
5796}
5797
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005798//===----------------------------------------------------------------------===//
Ted Kremenek04bb7162010-01-22 22:44:15 +00005799// Misc. utility functions.
5800//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00005801
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00005802/// Default to using an 8 MB stack size on "safety" threads.
5803static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005804
5805namespace clang {
5806
5807bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005808 void (*Fn)(void*), void *UserData,
5809 unsigned Size) {
5810 if (!Size)
5811 Size = GetSafetyThreadStackSize();
5812 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005813 return CRC.RunSafelyOnThread(Fn, UserData, Size);
5814 return CRC.RunSafely(Fn, UserData);
5815}
5816
5817unsigned GetSafetyThreadStackSize() {
5818 return SafetyStackThreadSize;
5819}
5820
5821void SetSafetyThreadStackSize(unsigned Value) {
5822 SafetyStackThreadSize = Value;
5823}
5824
Argyrios Kyrtzidis8e7c48a2012-03-28 02:49:50 +00005825}
5826
Argyrios Kyrtzidis81b5ac32012-03-28 02:49:54 +00005827void clang::setThreadBackgroundPriority() {
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00005828 // FIXME: Move to llvm/Support and make it cross-platform.
5829#ifdef __APPLE__
5830 setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG);
5831#endif
5832}
5833
Ted Kremenek04bb7162010-01-22 22:44:15 +00005834extern "C" {
5835
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00005836CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00005837 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00005838}
5839
5840} // end: extern "C"
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005841