blob: 67c56a26746636ab7945d7c27064ecbfe17b3ad7 [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
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002487struct ParseTranslationUnitInfo {
2488 CXIndex CIdx;
2489 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002490 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002491 int num_command_line_args;
2492 struct CXUnsavedFile *unsaved_files;
2493 unsigned num_unsaved_files;
2494 unsigned options;
2495 CXTranslationUnit result;
2496};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002497static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002498 ParseTranslationUnitInfo *PTUI =
2499 static_cast<ParseTranslationUnitInfo*>(UserData);
2500 CXIndex CIdx = PTUI->CIdx;
2501 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002502 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002503 int num_command_line_args = PTUI->num_command_line_args;
2504 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2505 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2506 unsigned options = PTUI->options;
2507 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002508
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002509 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002510 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002511
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002512 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2513
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002514 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
Argyrios Kyrtzidis81b5ac32012-03-28 02:49:54 +00002515 setThreadBackgroundPriority();
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002516
Douglas Gregor44c181a2010-07-23 00:33:23 +00002517 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregor467dc882011-08-25 22:30:56 +00002518 // FIXME: Add a flag for modules.
2519 TranslationUnitKind TUKind
2520 = (options & CXTranslationUnit_Incomplete)? TU_Prefix : TU_Complete;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002521 bool CacheCodeCompetionResults
2522 = options & CXTranslationUnit_CacheCompletionResults;
2523
Douglas Gregor5352ac02010-01-28 00:27:43 +00002524 // Configure the diagnostics.
2525 DiagnosticOptions DiagOpts;
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00002526 IntrusiveRefCntPtr<DiagnosticsEngine>
Ted Kremenek25a11e12011-03-22 01:15:24 +00002527 Diags(CompilerInstance::createDiagnostics(DiagOpts, num_command_line_args,
2528 command_line_args));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002529
Ted Kremenek25a11e12011-03-22 01:15:24 +00002530 // Recover resources if we crash before exiting this function.
David Blaikied6471f72011-09-25 23:23:43 +00002531 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
2532 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00002533 DiagCleanup(Diags.getPtr());
2534
Dylan Noblesmith1e4c01b2012-02-13 12:32:21 +00002535 OwningPtr<std::vector<ASTUnit::RemappedFile> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00002536 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2537
2538 // Recover resources if we crash before exiting this function.
2539 llvm::CrashRecoveryContextCleanupRegistrar<
2540 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2541
Douglas Gregor4db64a42010-01-23 00:14:00 +00002542 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002543 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002544 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002545 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002546 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2547 Buffer));
Douglas Gregor4db64a42010-01-23 00:14:00 +00002548 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002549
Dylan Noblesmith1e4c01b2012-02-13 12:32:21 +00002550 OwningPtr<std::vector<const char *> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00002551 Args(new std::vector<const char*>());
2552
2553 // Recover resources if we crash before exiting this method.
2554 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
2555 ArgsCleanup(Args.get());
2556
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002557 // Since the Clang C library is primarily used by batch tools dealing with
2558 // (often very broken) source code, where spell-checking can have a
2559 // significant negative impact on performance (particularly when
2560 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002561 // Only do this if we haven't found a spell-checking-related argument.
2562 bool FoundSpellCheckingArgument = false;
2563 for (int I = 0; I != num_command_line_args; ++I) {
2564 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2565 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2566 FoundSpellCheckingArgument = true;
2567 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002568 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002569 }
2570 if (!FoundSpellCheckingArgument)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002571 Args->push_back("-fno-spell-checking");
Douglas Gregorb10daed2010-10-11 16:52:23 +00002572
Ted Kremenek25a11e12011-03-22 01:15:24 +00002573 Args->insert(Args->end(), command_line_args,
2574 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002575
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002576 // The 'source_filename' argument is optional. If the caller does not
2577 // specify it then it is assumed that the source file is specified
2578 // in the actual argument list.
2579 // Put the source file after command_line_args otherwise if '-x' flag is
2580 // present it will be unused.
2581 if (source_filename)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002582 Args->push_back(source_filename);
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002583
Douglas Gregor44c181a2010-07-23 00:33:23 +00002584 // Do we need the detailed preprocessing record?
2585 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Ted Kremenek25a11e12011-03-22 01:15:24 +00002586 Args->push_back("-Xclang");
2587 Args->push_back("-detailed-preprocessing-record");
Douglas Gregor44c181a2010-07-23 00:33:23 +00002588 }
2589
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002590 unsigned NumErrors = Diags->getClient()->getNumErrors();
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00002591 OwningPtr<ASTUnit> ErrUnit;
Dylan Noblesmith1e4c01b2012-02-13 12:32:21 +00002592 OwningPtr<ASTUnit> Unit(
Ted Kremenek4ee99262011-03-22 20:16:19 +00002593 ASTUnit::LoadFromCommandLine(Args->size() ? &(*Args)[0] : 0
2594 /* vector::data() not portable */,
2595 Args->size() ? (&(*Args)[0] + Args->size()) :0,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002596 Diags,
2597 CXXIdx->getClangResourcesPath(),
2598 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002599 /*CaptureDiagnostics=*/true,
Ted Kremenek4ee99262011-03-22 20:16:19 +00002600 RemappedFiles->size() ? &(*RemappedFiles)[0]:0,
Ted Kremenek25a11e12011-03-22 01:15:24 +00002601 RemappedFiles->size(),
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00002602 /*RemappedFilesKeepOriginalName=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002603 PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00002604 TUKind,
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00002605 CacheCodeCompetionResults,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00002606 /*AllowPCHWithCompilerErrors=*/true,
2607 &ErrUnit));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002608
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002609 if (NumErrors != Diags->getClient()->getNumErrors()) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002610 // Make sure to check that 'Unit' is non-NULL.
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00002611 if (CXXIdx->getDisplayDiagnostics())
2612 printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
Douglas Gregora88084b2010-02-18 18:08:43 +00002613 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002614
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002615 PTUI->result = MakeCXTranslationUnit(CXXIdx, Unit.take());
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002616}
2617CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2618 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002619 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002620 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002621 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002622 unsigned num_unsaved_files,
2623 unsigned options) {
2624 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002625 num_command_line_args, unsaved_files,
2626 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002627 llvm::CrashRecoveryContext CRC;
2628
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002629 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002630 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2631 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2632 fprintf(stderr, " 'command_line_args' : [");
2633 for (int i = 0; i != num_command_line_args; ++i) {
2634 if (i)
2635 fprintf(stderr, ", ");
2636 fprintf(stderr, "'%s'", command_line_args[i]);
2637 }
2638 fprintf(stderr, "],\n");
2639 fprintf(stderr, " 'unsaved_files' : [");
2640 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2641 if (i)
2642 fprintf(stderr, ", ");
2643 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2644 unsaved_files[i].Length);
2645 }
2646 fprintf(stderr, "],\n");
2647 fprintf(stderr, " 'options' : %d,\n", options);
2648 fprintf(stderr, "}\n");
2649
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002650 return 0;
Douglas Gregor6df78732011-05-05 20:27:22 +00002651 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
2652 PrintLibclangResourceUsage(PTUI.result);
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002653 }
Douglas Gregor6df78732011-05-05 20:27:22 +00002654
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002655 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002656}
2657
Douglas Gregor19998442010-08-13 15:35:05 +00002658unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2659 return CXSaveTranslationUnit_None;
2660}
Argyrios Kyrtzidis142bcb52012-03-28 02:17:59 +00002661
2662namespace {
2663
2664struct SaveTranslationUnitInfo {
2665 CXTranslationUnit TU;
2666 const char *FileName;
2667 unsigned options;
2668 CXSaveError result;
2669};
2670
2671}
2672
2673static void clang_saveTranslationUnit_Impl(void *UserData) {
2674 SaveTranslationUnitInfo *STUI =
2675 static_cast<SaveTranslationUnitInfo*>(UserData);
2676
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002677 CIndexer *CXXIdx = (CIndexer*)STUI->TU->CIdx;
2678 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
Argyrios Kyrtzidis81b5ac32012-03-28 02:49:54 +00002679 setThreadBackgroundPriority();
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002680
Argyrios Kyrtzidis142bcb52012-03-28 02:17:59 +00002681 STUI->result = static_cast<ASTUnit *>(STUI->TU->TUData)->Save(STUI->FileName);
2682}
2683
Douglas Gregor19998442010-08-13 15:35:05 +00002684int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2685 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002686 if (!TU)
Douglas Gregor39c411f2011-07-06 16:43:36 +00002687 return CXSaveError_InvalidTU;
Argyrios Kyrtzidis142bcb52012-03-28 02:17:59 +00002688
2689 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
2690 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2691
2692 SaveTranslationUnitInfo STUI = { TU, FileName, options, CXSaveError_None };
2693
2694 if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred() ||
2695 getenv("LIBCLANG_NOTHREADS")) {
2696 clang_saveTranslationUnit_Impl(&STUI);
2697
2698 if (getenv("LIBCLANG_RESOURCE_USAGE"))
2699 PrintLibclangResourceUsage(TU);
2700
2701 return STUI.result;
2702 }
2703
2704 // We have an AST that has invalid nodes due to compiler errors.
2705 // Use a crash recovery thread for protection.
2706
2707 llvm::CrashRecoveryContext CRC;
2708
2709 if (!RunSafely(CRC, clang_saveTranslationUnit_Impl, &STUI)) {
2710 fprintf(stderr, "libclang: crash detected during AST saving: {\n");
2711 fprintf(stderr, " 'filename' : '%s'\n", FileName);
2712 fprintf(stderr, " 'options' : %d,\n", options);
2713 fprintf(stderr, "}\n");
2714
2715 return CXSaveError_Unknown;
2716
2717 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
Douglas Gregor6df78732011-05-05 20:27:22 +00002718 PrintLibclangResourceUsage(TU);
Argyrios Kyrtzidis142bcb52012-03-28 02:17:59 +00002719 }
2720
2721 return STUI.result;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002722}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002723
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002724void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002725 if (CTUnit) {
2726 // If the translation unit has been marked as unsafe to free, just discard
2727 // it.
Ted Kremeneka60ed472010-11-16 08:15:36 +00002728 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002729 return;
2730
Ted Kremeneka60ed472010-11-16 08:15:36 +00002731 delete static_cast<ASTUnit *>(CTUnit->TUData);
2732 disposeCXStringPool(CTUnit->StringPool);
Ted Kremenek15322172011-11-10 08:43:12 +00002733 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002734 delete CTUnit;
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002735 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002736}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002737
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002738unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2739 return CXReparse_None;
2740}
2741
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002742struct ReparseTranslationUnitInfo {
2743 CXTranslationUnit TU;
2744 unsigned num_unsaved_files;
2745 struct CXUnsavedFile *unsaved_files;
2746 unsigned options;
2747 int result;
2748};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002749
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002750static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002751 ReparseTranslationUnitInfo *RTUI =
2752 static_cast<ReparseTranslationUnitInfo*>(UserData);
2753 CXTranslationUnit TU = RTUI->TU;
Ted Kremenek15322172011-11-10 08:43:12 +00002754
2755 // Reset the associated diagnostics.
2756 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
2757 TU->Diagnostics = 0;
2758
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002759 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2760 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2761 unsigned options = RTUI->options;
2762 (void) options;
2763 RTUI->result = 1;
2764
Douglas Gregorabc563f2010-07-19 21:46:24 +00002765 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002766 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002767
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002768 CIndexer *CXXIdx = (CIndexer*)TU->CIdx;
2769 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
Argyrios Kyrtzidis81b5ac32012-03-28 02:49:54 +00002770 setThreadBackgroundPriority();
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002771
Ted Kremeneka60ed472010-11-16 08:15:36 +00002772 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor593b0c12010-09-23 18:47:53 +00002773 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002774
Dylan Noblesmith1e4c01b2012-02-13 12:32:21 +00002775 OwningPtr<std::vector<ASTUnit::RemappedFile> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00002776 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2777
2778 // Recover resources if we crash before exiting this function.
2779 llvm::CrashRecoveryContextCleanupRegistrar<
2780 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2781
Douglas Gregorabc563f2010-07-19 21:46:24 +00002782 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002783 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002784 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002785 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002786 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2787 Buffer));
Douglas Gregorabc563f2010-07-19 21:46:24 +00002788 }
2789
Ted Kremenek4ee99262011-03-22 20:16:19 +00002790 if (!CXXUnit->Reparse(RemappedFiles->size() ? &(*RemappedFiles)[0] : 0,
2791 RemappedFiles->size()))
Douglas Gregor593b0c12010-09-23 18:47:53 +00002792 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002793}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002794
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002795int clang_reparseTranslationUnit(CXTranslationUnit TU,
2796 unsigned num_unsaved_files,
2797 struct CXUnsavedFile *unsaved_files,
2798 unsigned options) {
2799 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2800 options, 0 };
Argyrios Kyrtzidis8c4b47e2011-10-28 22:54:33 +00002801
Argyrios Kyrtzidise7de9b42011-10-29 19:32:39 +00002802 if (getenv("LIBCLANG_NOTHREADS")) {
Argyrios Kyrtzidis8c4b47e2011-10-28 22:54:33 +00002803 clang_reparseTranslationUnit_Impl(&RTUI);
2804 return RTUI.result;
2805 }
2806
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002807 llvm::CrashRecoveryContext CRC;
2808
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002809 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002810 fprintf(stderr, "libclang: crash detected during reparsing\n");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002811 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002812 return 1;
Douglas Gregor6df78732011-05-05 20:27:22 +00002813 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
2814 PrintLibclangResourceUsage(TU);
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002815
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002816 return RTUI.result;
2817}
2818
Douglas Gregordf95a132010-08-09 20:45:32 +00002819
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002820CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002821 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002822 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002823
Ted Kremeneka60ed472010-11-16 08:15:36 +00002824 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002825 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002826}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002827
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002828CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002829 CXCursor Result = { CXCursor_TranslationUnit, 0, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002830 return Result;
2831}
2832
Ted Kremenekfb480492010-01-13 21:46:36 +00002833} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002834
Ted Kremenekfb480492010-01-13 21:46:36 +00002835//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002836// CXFile Operations.
2837//===----------------------------------------------------------------------===//
2838
2839extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002840CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002841 if (!SFile)
Ted Kremeneka60ed472010-11-16 08:15:36 +00002842 return createCXString((const char*)NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002843
Steve Naroff88145032009-10-27 14:35:18 +00002844 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002845 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002846}
2847
2848time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002849 if (!SFile)
2850 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002851
Steve Naroff88145032009-10-27 14:35:18 +00002852 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2853 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002854}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002855
Douglas Gregorb9790342010-01-22 21:44:22 +00002856CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2857 if (!tu)
2858 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002859
Ted Kremeneka60ed472010-11-16 08:15:36 +00002860 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002861
Douglas Gregorb9790342010-01-22 21:44:22 +00002862 FileManager &FMgr = CXXUnit->getFileManager();
Chris Lattner39b49bc2010-11-23 08:35:12 +00002863 return const_cast<FileEntry *>(FMgr.getFile(file_name));
Douglas Gregorb9790342010-01-22 21:44:22 +00002864}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002865
Douglas Gregordd3e5542011-05-04 00:14:37 +00002866unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit tu, CXFile file) {
2867 if (!tu || !file)
2868 return 0;
2869
2870 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
2871 FileEntry *FEnt = static_cast<FileEntry *>(file);
2872 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
2873 .isFileMultipleIncludeGuarded(FEnt);
2874}
2875
Ted Kremenekfb480492010-01-13 21:46:36 +00002876} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002877
Ted Kremenekfb480492010-01-13 21:46:36 +00002878//===----------------------------------------------------------------------===//
2879// CXCursor Operations.
2880//===----------------------------------------------------------------------===//
2881
Ted Kremenekfb480492010-01-13 21:46:36 +00002882static Decl *getDeclFromExpr(Stmt *E) {
Argyrios Kyrtzidisc2954612011-09-12 22:17:26 +00002883 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Douglas Gregordb1314e2010-10-01 21:11:22 +00002884 return getDeclFromExpr(CE->getSubExpr());
2885
Ted Kremenekfb480492010-01-13 21:46:36 +00002886 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2887 return RefExpr->getDecl();
2888 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2889 return ME->getMemberDecl();
2890 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2891 return RE->getDecl();
Argyrios Kyrtzidisb085d892012-03-30 00:19:18 +00002892 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
2893 if (PRE->isExplicitProperty())
2894 return PRE->getExplicitProperty();
2895 // It could be messaging both getter and setter as in:
2896 // ++myobj.myprop;
2897 // in which case prefer to associate the setter since it is less obvious
2898 // from inspecting the source that the setter is going to get called.
2899 if (PRE->isMessagingSetter())
2900 return PRE->getImplicitPropertySetter();
2901 return PRE->getImplicitPropertyGetter();
2902 }
John McCall4b9c2d22011-11-06 09:01:30 +00002903 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
2904 return getDeclFromExpr(POE->getSyntacticForm());
2905 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
2906 if (Expr *Src = OVE->getSourceExpr())
2907 return getDeclFromExpr(Src);
Douglas Gregordb1314e2010-10-01 21:11:22 +00002908
Ted Kremenekfb480492010-01-13 21:46:36 +00002909 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2910 return getDeclFromExpr(CE->getCallee());
Chris Lattner5f9e2722011-07-23 10:55:15 +00002911 if (CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Douglas Gregor93798e22010-11-05 21:11:19 +00002912 if (!CE->isElidable())
2913 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002914 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2915 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002916
Douglas Gregordb1314e2010-10-01 21:11:22 +00002917 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2918 return PE->getProtocol();
Douglas Gregorc7793c72011-01-15 01:15:58 +00002919 if (SubstNonTypeTemplateParmPackExpr *NTTP
2920 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
2921 return NTTP->getParameterPack();
Douglas Gregor94d96292011-01-19 20:34:17 +00002922 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2923 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
2924 isa<ParmVarDecl>(SizeOfPack->getPack()))
2925 return SizeOfPack->getPack();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002926
Ted Kremenekfb480492010-01-13 21:46:36 +00002927 return 0;
2928}
2929
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002930static SourceLocation getLocationFromExpr(Expr *E) {
Argyrios Kyrtzidisc2954612011-09-12 22:17:26 +00002931 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
2932 return getLocationFromExpr(CE->getSubExpr());
2933
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002934 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2935 return /*FIXME:*/Msg->getLeftLoc();
2936 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2937 return DRE->getLocation();
2938 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2939 return Member->getMemberLoc();
2940 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2941 return Ivar->getLocation();
Douglas Gregor94d96292011-01-19 20:34:17 +00002942 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2943 return SizeOfPack->getPackLoc();
Argyrios Kyrtzidisd0469522012-03-30 00:19:13 +00002944 if (ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
2945 return PropRef->getLocation();
Douglas Gregor94d96292011-01-19 20:34:17 +00002946
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002947 return E->getLocStart();
2948}
2949
Ted Kremenekfb480492010-01-13 21:46:36 +00002950extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002951
2952unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002953 CXCursorVisitor visitor,
2954 CXClientData client_data) {
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00002955 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
2956 /*VisitPreprocessorLast=*/false);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002957 return CursorVis.VisitChildren(parent);
2958}
2959
David Chisnall3387c652010-11-03 14:12:26 +00002960#ifndef __has_feature
2961#define __has_feature(x) 0
2962#endif
2963#if __has_feature(blocks)
2964typedef enum CXChildVisitResult
2965 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2966
2967static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2968 CXClientData client_data) {
2969 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2970 return block(cursor, parent);
2971}
2972#else
2973// If we are compiled with a compiler that doesn't have native blocks support,
2974// define and call the block manually, so the
2975typedef struct _CXChildVisitResult
2976{
2977 void *isa;
2978 int flags;
2979 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002980 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2981 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00002982} *CXCursorVisitorBlock;
2983
2984static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2985 CXClientData client_data) {
2986 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2987 return block->invoke(block, cursor, parent);
2988}
2989#endif
2990
2991
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002992unsigned clang_visitChildrenWithBlock(CXCursor parent,
2993 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00002994 return clang_visitChildren(parent, visitWithBlock, block);
2995}
2996
Douglas Gregor78205d42010-01-20 21:45:58 +00002997static CXString getDeclSpelling(Decl *D) {
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00002998 if (!D)
2999 return createCXString("");
3000
3001 NamedDecl *ND = dyn_cast<NamedDecl>(D);
Douglas Gregore3c60a72010-11-17 00:13:31 +00003002 if (!ND) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003003 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00003004 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3005 return createCXString(Property->getIdentifier()->getName());
3006
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003007 return createCXString("");
Douglas Gregore3c60a72010-11-17 00:13:31 +00003008 }
3009
Douglas Gregor78205d42010-01-20 21:45:58 +00003010 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003011 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003012
Douglas Gregor78205d42010-01-20 21:45:58 +00003013 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
3014 // No, this isn't the same as the code below. getIdentifier() is non-virtual
3015 // and returns different names. NamedDecl returns the class name and
3016 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003017 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003018
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003019 if (isa<UsingDirectiveDecl>(D))
3020 return createCXString("");
3021
Dylan Noblesmith36d59272012-02-13 12:32:26 +00003022 SmallString<1024> S;
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00003023 llvm::raw_svector_ostream os(S);
3024 ND->printName(os);
3025
3026 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00003027}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003028
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003029CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003030 if (clang_isTranslationUnit(C.kind))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003031 return clang_getTranslationUnitSpelling(
3032 static_cast<CXTranslationUnit>(C.data[2]));
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003033
Steve Narofff334b4e2009-09-02 18:26:48 +00003034 if (clang_isReference(C.kind)) {
3035 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00003036 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00003037 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003038 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003039 }
3040 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00003041 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003042 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003043 }
3044 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00003045 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00003046 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003047 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003048 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00003049 case CXCursor_CXXBaseSpecifier: {
3050 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
3051 return createCXString(B->getType().getAsString());
3052 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003053 case CXCursor_TypeRef: {
3054 TypeDecl *Type = getCursorTypeRef(C).first;
3055 assert(Type && "Missing type decl");
3056
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003057 return createCXString(getCursorContext(C).getTypeDeclType(Type).
3058 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003059 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003060 case CXCursor_TemplateRef: {
3061 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00003062 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003063
3064 return createCXString(Template->getNameAsString());
3065 }
Douglas Gregor69319002010-08-31 23:48:11 +00003066
3067 case CXCursor_NamespaceRef: {
3068 NamedDecl *NS = getCursorNamespaceRef(C).first;
3069 assert(NS && "Missing namespace decl");
3070
3071 return createCXString(NS->getNameAsString());
3072 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003073
Douglas Gregora67e03f2010-09-09 21:42:20 +00003074 case CXCursor_MemberRef: {
3075 FieldDecl *Field = getCursorMemberRef(C).first;
3076 assert(Field && "Missing member decl");
3077
3078 return createCXString(Field->getNameAsString());
3079 }
3080
Douglas Gregor36897b02010-09-10 00:22:18 +00003081 case CXCursor_LabelRef: {
3082 LabelStmt *Label = getCursorLabelRef(C).first;
3083 assert(Label && "Missing label");
3084
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003085 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00003086 }
3087
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003088 case CXCursor_OverloadedDeclRef: {
3089 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3090 if (Decl *D = Storage.dyn_cast<Decl *>()) {
3091 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
3092 return createCXString(ND->getNameAsString());
3093 return createCXString("");
3094 }
3095 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3096 return createCXString(E->getName().getAsString());
3097 OverloadedTemplateStorage *Ovl
3098 = Storage.get<OverloadedTemplateStorage*>();
3099 if (Ovl->size() == 0)
3100 return createCXString("");
3101 return createCXString((*Ovl->begin())->getNameAsString());
3102 }
3103
Douglas Gregor011d8b92012-02-15 00:54:55 +00003104 case CXCursor_VariableRef: {
3105 VarDecl *Var = getCursorVariableRef(C).first;
3106 assert(Var && "Missing variable decl");
3107
3108 return createCXString(Var->getNameAsString());
3109 }
3110
Daniel Dunbaracca7252009-11-30 20:42:49 +00003111 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003112 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00003113 }
3114 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003115
3116 if (clang_isExpression(C.kind)) {
3117 Decl *D = getDeclFromExpr(getCursorExpr(C));
3118 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00003119 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003120 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00003121 }
3122
Douglas Gregor36897b02010-09-10 00:22:18 +00003123 if (clang_isStatement(C.kind)) {
3124 Stmt *S = getCursorStmt(C);
3125 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003126 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00003127
3128 return createCXString("");
3129 }
3130
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003131 if (C.kind == CXCursor_MacroExpansion)
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003132 return createCXString(getCursorMacroExpansion(C)->getName()
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003133 ->getNameStart());
3134
Douglas Gregor572feb22010-03-18 18:04:21 +00003135 if (C.kind == CXCursor_MacroDefinition)
3136 return createCXString(getCursorMacroDefinition(C)->getName()
3137 ->getNameStart());
3138
Douglas Gregorecdcb882010-10-20 22:00:55 +00003139 if (C.kind == CXCursor_InclusionDirective)
3140 return createCXString(getCursorInclusionDirective(C)->getFileName());
3141
Douglas Gregor60cbfac2010-01-25 16:56:17 +00003142 if (clang_isDeclaration(C.kind))
3143 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00003144
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00003145 if (C.kind == CXCursor_AnnotateAttr) {
3146 AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
3147 return createCXString(AA->getAnnotation());
3148 }
3149
Argyrios Kyrtzidis84b79642011-12-06 22:05:01 +00003150 if (C.kind == CXCursor_AsmLabelAttr) {
3151 AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
3152 return createCXString(AA->getLabel());
3153 }
3154
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003155 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00003156}
3157
Argyrios Kyrtzidisba1da142012-03-30 20:58:35 +00003158CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C,
3159 unsigned pieceIndex,
3160 unsigned options) {
3161 if (clang_Cursor_isNull(C))
3162 return clang_getNullRange();
3163
3164 ASTContext &Ctx = getCursorContext(C);
3165
3166 if (clang_isStatement(C.kind)) {
3167 Stmt *S = getCursorStmt(C);
3168 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
3169 if (pieceIndex > 0)
3170 return clang_getNullRange();
3171 return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
3172 }
3173
3174 return clang_getNullRange();
3175 }
3176
3177 if (C.kind == CXCursor_ObjCMessageExpr) {
3178 if (ObjCMessageExpr *
3179 ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
3180 if (pieceIndex >= ME->getNumSelectorLocs())
3181 return clang_getNullRange();
3182 return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
3183 }
3184 }
3185
3186 if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
3187 C.kind == CXCursor_ObjCClassMethodDecl) {
3188 if (ObjCMethodDecl *
3189 MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
3190 if (pieceIndex >= MD->getNumSelectorLocs())
3191 return clang_getNullRange();
3192 return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
3193 }
3194 }
3195
3196 // FIXME: A CXCursor_InclusionDirective should give the location of the
3197 // filename, but we don't keep track of this.
3198
3199 // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
3200 // but we don't keep track of this.
3201
3202 // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
3203 // but we don't keep track of this.
3204
3205 // Default handling, give the location of the cursor.
3206
3207 if (pieceIndex > 0)
3208 return clang_getNullRange();
3209
3210 CXSourceLocation CXLoc = clang_getCursorLocation(C);
3211 SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
3212 return cxloc::translateSourceRange(Ctx, Loc);
3213}
3214
Douglas Gregor358559d2010-10-02 22:49:11 +00003215CXString clang_getCursorDisplayName(CXCursor C) {
3216 if (!clang_isDeclaration(C.kind))
3217 return clang_getCursorSpelling(C);
3218
3219 Decl *D = getCursorDecl(C);
3220 if (!D)
3221 return createCXString("");
3222
Douglas Gregor30c42402011-09-27 22:38:19 +00003223 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
Douglas Gregor358559d2010-10-02 22:49:11 +00003224 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
3225 D = FunTmpl->getTemplatedDecl();
3226
3227 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Dylan Noblesmith36d59272012-02-13 12:32:26 +00003228 SmallString<64> Str;
Douglas Gregor358559d2010-10-02 22:49:11 +00003229 llvm::raw_svector_ostream OS(Str);
Benjamin Kramera59d20b2012-02-07 11:57:57 +00003230 OS << *Function;
Douglas Gregor358559d2010-10-02 22:49:11 +00003231 if (Function->getPrimaryTemplate())
3232 OS << "<>";
3233 OS << "(";
3234 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
3235 if (I)
3236 OS << ", ";
3237 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
3238 }
3239
3240 if (Function->isVariadic()) {
3241 if (Function->getNumParams())
3242 OS << ", ";
3243 OS << "...";
3244 }
3245 OS << ")";
3246 return createCXString(OS.str());
3247 }
3248
3249 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
Dylan Noblesmith36d59272012-02-13 12:32:26 +00003250 SmallString<64> Str;
Douglas Gregor358559d2010-10-02 22:49:11 +00003251 llvm::raw_svector_ostream OS(Str);
Benjamin Kramera59d20b2012-02-07 11:57:57 +00003252 OS << *ClassTemplate;
Douglas Gregor358559d2010-10-02 22:49:11 +00003253 OS << "<";
3254 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
3255 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3256 if (I)
3257 OS << ", ";
3258
3259 NamedDecl *Param = Params->getParam(I);
3260 if (Param->getIdentifier()) {
3261 OS << Param->getIdentifier()->getName();
3262 continue;
3263 }
3264
3265 // There is no parameter name, which makes this tricky. Try to come up
3266 // with something useful that isn't too long.
3267 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3268 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
3269 else if (NonTypeTemplateParmDecl *NTTP
3270 = dyn_cast<NonTypeTemplateParmDecl>(Param))
3271 OS << NTTP->getType().getAsString(Policy);
3272 else
3273 OS << "template<...> class";
3274 }
3275
3276 OS << ">";
3277 return createCXString(OS.str());
3278 }
3279
3280 if (ClassTemplateSpecializationDecl *ClassSpec
3281 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
3282 // If the type was explicitly written, use that.
3283 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
3284 return createCXString(TSInfo->getType().getAsString(Policy));
3285
Dylan Noblesmith36d59272012-02-13 12:32:26 +00003286 SmallString<64> Str;
Douglas Gregor358559d2010-10-02 22:49:11 +00003287 llvm::raw_svector_ostream OS(Str);
Benjamin Kramera59d20b2012-02-07 11:57:57 +00003288 OS << *ClassSpec;
Douglas Gregor358559d2010-10-02 22:49:11 +00003289 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00003290 ClassSpec->getTemplateArgs().data(),
3291 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00003292 Policy);
3293 return createCXString(OS.str());
3294 }
3295
3296 return clang_getCursorSpelling(C);
3297}
3298
Ted Kremeneke68fff62010-02-17 00:41:32 +00003299CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00003300 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00003301 case CXCursor_FunctionDecl:
3302 return createCXString("FunctionDecl");
3303 case CXCursor_TypedefDecl:
3304 return createCXString("TypedefDecl");
3305 case CXCursor_EnumDecl:
3306 return createCXString("EnumDecl");
3307 case CXCursor_EnumConstantDecl:
3308 return createCXString("EnumConstantDecl");
3309 case CXCursor_StructDecl:
3310 return createCXString("StructDecl");
3311 case CXCursor_UnionDecl:
3312 return createCXString("UnionDecl");
3313 case CXCursor_ClassDecl:
3314 return createCXString("ClassDecl");
3315 case CXCursor_FieldDecl:
3316 return createCXString("FieldDecl");
3317 case CXCursor_VarDecl:
3318 return createCXString("VarDecl");
3319 case CXCursor_ParmDecl:
3320 return createCXString("ParmDecl");
3321 case CXCursor_ObjCInterfaceDecl:
3322 return createCXString("ObjCInterfaceDecl");
3323 case CXCursor_ObjCCategoryDecl:
3324 return createCXString("ObjCCategoryDecl");
3325 case CXCursor_ObjCProtocolDecl:
3326 return createCXString("ObjCProtocolDecl");
3327 case CXCursor_ObjCPropertyDecl:
3328 return createCXString("ObjCPropertyDecl");
3329 case CXCursor_ObjCIvarDecl:
3330 return createCXString("ObjCIvarDecl");
3331 case CXCursor_ObjCInstanceMethodDecl:
3332 return createCXString("ObjCInstanceMethodDecl");
3333 case CXCursor_ObjCClassMethodDecl:
3334 return createCXString("ObjCClassMethodDecl");
3335 case CXCursor_ObjCImplementationDecl:
3336 return createCXString("ObjCImplementationDecl");
3337 case CXCursor_ObjCCategoryImplDecl:
3338 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00003339 case CXCursor_CXXMethod:
3340 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003341 case CXCursor_UnexposedDecl:
3342 return createCXString("UnexposedDecl");
3343 case CXCursor_ObjCSuperClassRef:
3344 return createCXString("ObjCSuperClassRef");
3345 case CXCursor_ObjCProtocolRef:
3346 return createCXString("ObjCProtocolRef");
3347 case CXCursor_ObjCClassRef:
3348 return createCXString("ObjCClassRef");
3349 case CXCursor_TypeRef:
3350 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003351 case CXCursor_TemplateRef:
3352 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00003353 case CXCursor_NamespaceRef:
3354 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00003355 case CXCursor_MemberRef:
3356 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00003357 case CXCursor_LabelRef:
3358 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003359 case CXCursor_OverloadedDeclRef:
3360 return createCXString("OverloadedDeclRef");
Douglas Gregor011d8b92012-02-15 00:54:55 +00003361 case CXCursor_VariableRef:
3362 return createCXString("VariableRef");
Douglas Gregor42b29842011-10-05 19:00:14 +00003363 case CXCursor_IntegerLiteral:
3364 return createCXString("IntegerLiteral");
3365 case CXCursor_FloatingLiteral:
3366 return createCXString("FloatingLiteral");
3367 case CXCursor_ImaginaryLiteral:
3368 return createCXString("ImaginaryLiteral");
3369 case CXCursor_StringLiteral:
3370 return createCXString("StringLiteral");
3371 case CXCursor_CharacterLiteral:
3372 return createCXString("CharacterLiteral");
3373 case CXCursor_ParenExpr:
3374 return createCXString("ParenExpr");
3375 case CXCursor_UnaryOperator:
3376 return createCXString("UnaryOperator");
3377 case CXCursor_ArraySubscriptExpr:
3378 return createCXString("ArraySubscriptExpr");
3379 case CXCursor_BinaryOperator:
3380 return createCXString("BinaryOperator");
3381 case CXCursor_CompoundAssignOperator:
3382 return createCXString("CompoundAssignOperator");
3383 case CXCursor_ConditionalOperator:
3384 return createCXString("ConditionalOperator");
3385 case CXCursor_CStyleCastExpr:
3386 return createCXString("CStyleCastExpr");
3387 case CXCursor_CompoundLiteralExpr:
3388 return createCXString("CompoundLiteralExpr");
3389 case CXCursor_InitListExpr:
3390 return createCXString("InitListExpr");
3391 case CXCursor_AddrLabelExpr:
3392 return createCXString("AddrLabelExpr");
3393 case CXCursor_StmtExpr:
3394 return createCXString("StmtExpr");
3395 case CXCursor_GenericSelectionExpr:
3396 return createCXString("GenericSelectionExpr");
3397 case CXCursor_GNUNullExpr:
3398 return createCXString("GNUNullExpr");
3399 case CXCursor_CXXStaticCastExpr:
3400 return createCXString("CXXStaticCastExpr");
3401 case CXCursor_CXXDynamicCastExpr:
3402 return createCXString("CXXDynamicCastExpr");
3403 case CXCursor_CXXReinterpretCastExpr:
3404 return createCXString("CXXReinterpretCastExpr");
3405 case CXCursor_CXXConstCastExpr:
3406 return createCXString("CXXConstCastExpr");
3407 case CXCursor_CXXFunctionalCastExpr:
3408 return createCXString("CXXFunctionalCastExpr");
3409 case CXCursor_CXXTypeidExpr:
3410 return createCXString("CXXTypeidExpr");
3411 case CXCursor_CXXBoolLiteralExpr:
3412 return createCXString("CXXBoolLiteralExpr");
3413 case CXCursor_CXXNullPtrLiteralExpr:
3414 return createCXString("CXXNullPtrLiteralExpr");
3415 case CXCursor_CXXThisExpr:
3416 return createCXString("CXXThisExpr");
3417 case CXCursor_CXXThrowExpr:
3418 return createCXString("CXXThrowExpr");
3419 case CXCursor_CXXNewExpr:
3420 return createCXString("CXXNewExpr");
3421 case CXCursor_CXXDeleteExpr:
3422 return createCXString("CXXDeleteExpr");
3423 case CXCursor_UnaryExpr:
3424 return createCXString("UnaryExpr");
3425 case CXCursor_ObjCStringLiteral:
3426 return createCXString("ObjCStringLiteral");
Ted Kremenekb3f75422012-03-06 20:06:06 +00003427 case CXCursor_ObjCBoolLiteralExpr:
3428 return createCXString("ObjCBoolLiteralExpr");
Douglas Gregor42b29842011-10-05 19:00:14 +00003429 case CXCursor_ObjCEncodeExpr:
3430 return createCXString("ObjCEncodeExpr");
3431 case CXCursor_ObjCSelectorExpr:
3432 return createCXString("ObjCSelectorExpr");
3433 case CXCursor_ObjCProtocolExpr:
3434 return createCXString("ObjCProtocolExpr");
3435 case CXCursor_ObjCBridgedCastExpr:
3436 return createCXString("ObjCBridgedCastExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00003437 case CXCursor_BlockExpr:
3438 return createCXString("BlockExpr");
Douglas Gregor42b29842011-10-05 19:00:14 +00003439 case CXCursor_PackExpansionExpr:
3440 return createCXString("PackExpansionExpr");
3441 case CXCursor_SizeOfPackExpr:
3442 return createCXString("SizeOfPackExpr");
Douglas Gregor011d8b92012-02-15 00:54:55 +00003443 case CXCursor_LambdaExpr:
3444 return createCXString("LambdaExpr");
Douglas Gregor42b29842011-10-05 19:00:14 +00003445 case CXCursor_UnexposedExpr:
3446 return createCXString("UnexposedExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003447 case CXCursor_DeclRefExpr:
3448 return createCXString("DeclRefExpr");
3449 case CXCursor_MemberRefExpr:
3450 return createCXString("MemberRefExpr");
3451 case CXCursor_CallExpr:
3452 return createCXString("CallExpr");
3453 case CXCursor_ObjCMessageExpr:
3454 return createCXString("ObjCMessageExpr");
3455 case CXCursor_UnexposedStmt:
3456 return createCXString("UnexposedStmt");
Douglas Gregor42b29842011-10-05 19:00:14 +00003457 case CXCursor_DeclStmt:
3458 return createCXString("DeclStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00003459 case CXCursor_LabelStmt:
3460 return createCXString("LabelStmt");
Douglas Gregor42b29842011-10-05 19:00:14 +00003461 case CXCursor_CompoundStmt:
3462 return createCXString("CompoundStmt");
3463 case CXCursor_CaseStmt:
3464 return createCXString("CaseStmt");
3465 case CXCursor_DefaultStmt:
3466 return createCXString("DefaultStmt");
3467 case CXCursor_IfStmt:
3468 return createCXString("IfStmt");
3469 case CXCursor_SwitchStmt:
3470 return createCXString("SwitchStmt");
3471 case CXCursor_WhileStmt:
3472 return createCXString("WhileStmt");
3473 case CXCursor_DoStmt:
3474 return createCXString("DoStmt");
3475 case CXCursor_ForStmt:
3476 return createCXString("ForStmt");
3477 case CXCursor_GotoStmt:
3478 return createCXString("GotoStmt");
3479 case CXCursor_IndirectGotoStmt:
3480 return createCXString("IndirectGotoStmt");
3481 case CXCursor_ContinueStmt:
3482 return createCXString("ContinueStmt");
3483 case CXCursor_BreakStmt:
3484 return createCXString("BreakStmt");
3485 case CXCursor_ReturnStmt:
3486 return createCXString("ReturnStmt");
3487 case CXCursor_AsmStmt:
3488 return createCXString("AsmStmt");
3489 case CXCursor_ObjCAtTryStmt:
3490 return createCXString("ObjCAtTryStmt");
3491 case CXCursor_ObjCAtCatchStmt:
3492 return createCXString("ObjCAtCatchStmt");
3493 case CXCursor_ObjCAtFinallyStmt:
3494 return createCXString("ObjCAtFinallyStmt");
3495 case CXCursor_ObjCAtThrowStmt:
3496 return createCXString("ObjCAtThrowStmt");
3497 case CXCursor_ObjCAtSynchronizedStmt:
3498 return createCXString("ObjCAtSynchronizedStmt");
3499 case CXCursor_ObjCAutoreleasePoolStmt:
3500 return createCXString("ObjCAutoreleasePoolStmt");
3501 case CXCursor_ObjCForCollectionStmt:
3502 return createCXString("ObjCForCollectionStmt");
3503 case CXCursor_CXXCatchStmt:
3504 return createCXString("CXXCatchStmt");
3505 case CXCursor_CXXTryStmt:
3506 return createCXString("CXXTryStmt");
3507 case CXCursor_CXXForRangeStmt:
3508 return createCXString("CXXForRangeStmt");
3509 case CXCursor_SEHTryStmt:
3510 return createCXString("SEHTryStmt");
3511 case CXCursor_SEHExceptStmt:
3512 return createCXString("SEHExceptStmt");
3513 case CXCursor_SEHFinallyStmt:
3514 return createCXString("SEHFinallyStmt");
3515 case CXCursor_NullStmt:
3516 return createCXString("NullStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003517 case CXCursor_InvalidFile:
3518 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00003519 case CXCursor_InvalidCode:
3520 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003521 case CXCursor_NoDeclFound:
3522 return createCXString("NoDeclFound");
3523 case CXCursor_NotImplemented:
3524 return createCXString("NotImplemented");
3525 case CXCursor_TranslationUnit:
3526 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00003527 case CXCursor_UnexposedAttr:
3528 return createCXString("UnexposedAttr");
3529 case CXCursor_IBActionAttr:
3530 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003531 case CXCursor_IBOutletAttr:
3532 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003533 case CXCursor_IBOutletCollectionAttr:
3534 return createCXString("attribute(iboutletcollection)");
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00003535 case CXCursor_CXXFinalAttr:
3536 return createCXString("attribute(final)");
3537 case CXCursor_CXXOverrideAttr:
3538 return createCXString("attribute(override)");
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00003539 case CXCursor_AnnotateAttr:
3540 return createCXString("attribute(annotate)");
Argyrios Kyrtzidis84b79642011-12-06 22:05:01 +00003541 case CXCursor_AsmLabelAttr:
3542 return createCXString("asm label");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003543 case CXCursor_PreprocessingDirective:
3544 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003545 case CXCursor_MacroDefinition:
3546 return createCXString("macro definition");
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003547 case CXCursor_MacroExpansion:
3548 return createCXString("macro expansion");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003549 case CXCursor_InclusionDirective:
3550 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003551 case CXCursor_Namespace:
3552 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003553 case CXCursor_LinkageSpec:
3554 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003555 case CXCursor_CXXBaseSpecifier:
3556 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003557 case CXCursor_Constructor:
3558 return createCXString("CXXConstructor");
3559 case CXCursor_Destructor:
3560 return createCXString("CXXDestructor");
3561 case CXCursor_ConversionFunction:
3562 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003563 case CXCursor_TemplateTypeParameter:
3564 return createCXString("TemplateTypeParameter");
3565 case CXCursor_NonTypeTemplateParameter:
3566 return createCXString("NonTypeTemplateParameter");
3567 case CXCursor_TemplateTemplateParameter:
3568 return createCXString("TemplateTemplateParameter");
3569 case CXCursor_FunctionTemplate:
3570 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003571 case CXCursor_ClassTemplate:
3572 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003573 case CXCursor_ClassTemplatePartialSpecialization:
3574 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003575 case CXCursor_NamespaceAlias:
3576 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003577 case CXCursor_UsingDirective:
3578 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003579 case CXCursor_UsingDeclaration:
3580 return createCXString("UsingDeclaration");
Richard Smith162e1c12011-04-15 14:24:37 +00003581 case CXCursor_TypeAliasDecl:
Douglas Gregor352697a2011-06-03 23:08:58 +00003582 return createCXString("TypeAliasDecl");
3583 case CXCursor_ObjCSynthesizeDecl:
3584 return createCXString("ObjCSynthesizeDecl");
3585 case CXCursor_ObjCDynamicDecl:
3586 return createCXString("ObjCDynamicDecl");
Argyrios Kyrtzidis2dfdb942011-09-30 17:58:23 +00003587 case CXCursor_CXXAccessSpecifier:
3588 return createCXString("CXXAccessSpecifier");
Steve Naroff89922f82009-08-31 00:59:03 +00003589 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003590
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003591 llvm_unreachable("Unhandled CXCursorKind");
Steve Naroff600866c2009-08-27 19:51:58 +00003592}
Steve Naroff89922f82009-08-31 00:59:03 +00003593
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003594struct GetCursorData {
3595 SourceLocation TokenBeginLoc;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003596 bool PointsAtMacroArgExpansion;
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003597 CXCursor &BestCursor;
3598
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003599 GetCursorData(SourceManager &SM,
3600 SourceLocation tokenBegin, CXCursor &outputCursor)
3601 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
3602 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
3603 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003604};
3605
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003606static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3607 CXCursor parent,
3608 CXClientData client_data) {
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003609 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
3610 CXCursor *BestCursor = &Data->BestCursor;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003611
3612 // If we point inside a macro argument we should provide info of what the
3613 // token is so use the actual cursor, don't replace it with a macro expansion
3614 // cursor.
3615 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
3616 return CXChildVisit_Recurse;
Argyrios Kyrtzidis65ab9072011-09-26 19:05:37 +00003617
3618 if (clang_isDeclaration(cursor.kind)) {
3619 // Avoid having the implicit methods override the property decls.
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00003620 if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor)))
Argyrios Kyrtzidis65ab9072011-09-26 19:05:37 +00003621 if (MD->isImplicit())
3622 return CXChildVisit_Break;
3623 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003624
3625 if (clang_isExpression(cursor.kind) &&
3626 clang_isDeclaration(BestCursor->kind)) {
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00003627 if (Decl *D = getCursorDecl(*BestCursor)) {
3628 // Avoid having the cursor of an expression replace the declaration cursor
3629 // when the expression source range overlaps the declaration range.
3630 // This can happen for C++ constructor expressions whose range generally
3631 // include the variable declaration, e.g.:
3632 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
3633 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
3634 D->getLocation() == Data->TokenBeginLoc)
3635 return CXChildVisit_Break;
3636 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003637 }
3638
Douglas Gregor93798e22010-11-05 21:11:19 +00003639 // If our current best cursor is the construction of a temporary object,
3640 // don't replace that cursor with a type reference, because we want
3641 // clang_getCursor() to point at the constructor.
3642 if (clang_isExpression(BestCursor->kind) &&
3643 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003644 cursor.kind == CXCursor_TypeRef) {
3645 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
3646 // as having the actual point on the type reference.
3647 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
Douglas Gregor93798e22010-11-05 21:11:19 +00003648 return CXChildVisit_Recurse;
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003649 }
Douglas Gregor93798e22010-11-05 21:11:19 +00003650
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003651 *BestCursor = cursor;
3652 return CXChildVisit_Recurse;
3653}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003654
Douglas Gregorb9790342010-01-22 21:44:22 +00003655CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3656 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003657 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003658
Ted Kremeneka60ed472010-11-16 08:15:36 +00003659 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003660 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3661
Ted Kremeneka297de22010-01-25 22:34:44 +00003662 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003663 CXCursor Result = cxcursor::getCursor(TU, SLoc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003664
Douglas Gregor40749ee2010-11-03 00:35:38 +00003665 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregor40749ee2010-11-03 00:35:38 +00003666 if (Logging) {
3667 CXFile SearchFile;
3668 unsigned SearchLine, SearchColumn;
3669 CXFile ResultFile;
3670 unsigned ResultLine, ResultColumn;
Douglas Gregor66537982010-11-17 17:14:07 +00003671 CXString SearchFileName, ResultFileName, KindSpelling, USR;
3672 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
Douglas Gregor40749ee2010-11-03 00:35:38 +00003673 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3674
Chandler Carruth20174222011-08-31 16:53:37 +00003675 clang_getExpansionLocation(Loc, &SearchFile, &SearchLine, &SearchColumn, 0);
3676 clang_getExpansionLocation(ResultLoc, &ResultFile, &ResultLine,
3677 &ResultColumn, 0);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003678 SearchFileName = clang_getFileName(SearchFile);
3679 ResultFileName = clang_getFileName(ResultFile);
3680 KindSpelling = clang_getCursorKindSpelling(Result.kind);
Douglas Gregor66537982010-11-17 17:14:07 +00003681 USR = clang_getCursorUSR(Result);
3682 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n",
Douglas Gregor40749ee2010-11-03 00:35:38 +00003683 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3684 clang_getCString(KindSpelling),
Douglas Gregor66537982010-11-17 17:14:07 +00003685 clang_getCString(ResultFileName), ResultLine, ResultColumn,
3686 clang_getCString(USR), IsDef);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003687 clang_disposeString(SearchFileName);
3688 clang_disposeString(ResultFileName);
3689 clang_disposeString(KindSpelling);
Douglas Gregor66537982010-11-17 17:14:07 +00003690 clang_disposeString(USR);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003691
3692 CXCursor Definition = clang_getCursorDefinition(Result);
3693 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
3694 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
3695 CXString DefinitionKindSpelling
3696 = clang_getCursorKindSpelling(Definition.kind);
3697 CXFile DefinitionFile;
3698 unsigned DefinitionLine, DefinitionColumn;
Chandler Carruth20174222011-08-31 16:53:37 +00003699 clang_getExpansionLocation(DefinitionLoc, &DefinitionFile,
3700 &DefinitionLine, &DefinitionColumn, 0);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003701 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
3702 fprintf(stderr, " -> %s(%s:%d:%d)\n",
3703 clang_getCString(DefinitionKindSpelling),
3704 clang_getCString(DefinitionFileName),
3705 DefinitionLine, DefinitionColumn);
3706 clang_disposeString(DefinitionFileName);
3707 clang_disposeString(DefinitionKindSpelling);
3708 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003709 }
3710
Ted Kremeneke68fff62010-02-17 00:41:32 +00003711 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003712}
3713
Ted Kremenek73885552009-11-17 19:28:59 +00003714CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003715 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003716}
3717
3718unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003719 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003720}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003721
Douglas Gregor9ce55842010-11-20 00:09:34 +00003722unsigned clang_hashCursor(CXCursor C) {
3723 unsigned Index = 0;
3724 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
3725 Index = 1;
3726
3727 return llvm::DenseMapInfo<std::pair<unsigned, void*> >::getHashValue(
3728 std::make_pair(C.kind, C.data[Index]));
3729}
3730
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003731unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003732 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3733}
3734
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003735unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003736 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3737}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003738
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003739unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003740 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3741}
3742
Douglas Gregor97b98722010-01-19 23:20:36 +00003743unsigned clang_isExpression(enum CXCursorKind K) {
3744 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3745}
3746
3747unsigned clang_isStatement(enum CXCursorKind K) {
3748 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3749}
3750
Douglas Gregor8be80e12011-07-06 03:00:34 +00003751unsigned clang_isAttribute(enum CXCursorKind K) {
3752 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
3753}
3754
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003755unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3756 return K == CXCursor_TranslationUnit;
3757}
3758
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003759unsigned clang_isPreprocessing(enum CXCursorKind K) {
3760 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3761}
3762
Ted Kremenekad6eff62010-03-08 21:17:29 +00003763unsigned clang_isUnexposed(enum CXCursorKind K) {
3764 switch (K) {
3765 case CXCursor_UnexposedDecl:
3766 case CXCursor_UnexposedExpr:
3767 case CXCursor_UnexposedStmt:
3768 case CXCursor_UnexposedAttr:
3769 return true;
3770 default:
3771 return false;
3772 }
3773}
3774
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003775CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003776 return C.kind;
3777}
3778
Douglas Gregor98258af2010-01-18 22:46:11 +00003779CXSourceLocation clang_getCursorLocation(CXCursor C) {
3780 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003781 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003782 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003783 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3784 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003785 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003786 }
3787
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003788 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003789 std::pair<ObjCProtocolDecl *, SourceLocation> P
3790 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003791 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003792 }
3793
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003794 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003795 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3796 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003797 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003798 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003799
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003800 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003801 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003802 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003803 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003804
3805 case CXCursor_TemplateRef: {
3806 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3807 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3808 }
3809
Douglas Gregor69319002010-08-31 23:48:11 +00003810 case CXCursor_NamespaceRef: {
3811 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3812 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3813 }
3814
Douglas Gregora67e03f2010-09-09 21:42:20 +00003815 case CXCursor_MemberRef: {
3816 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3817 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3818 }
3819
Douglas Gregor011d8b92012-02-15 00:54:55 +00003820 case CXCursor_VariableRef: {
3821 std::pair<VarDecl *, SourceLocation> P = getCursorVariableRef(C);
3822 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3823 }
3824
Ted Kremenek3064ef92010-08-27 21:34:58 +00003825 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003826 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3827 if (!BaseSpec)
3828 return clang_getNullLocation();
3829
3830 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3831 return cxloc::translateSourceLocation(getCursorContext(C),
3832 TSInfo->getTypeLoc().getBeginLoc());
3833
3834 return cxloc::translateSourceLocation(getCursorContext(C),
Daniel Dunbar96a00142012-03-09 18:35:03 +00003835 BaseSpec->getLocStart());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003836 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003837
Douglas Gregor36897b02010-09-10 00:22:18 +00003838 case CXCursor_LabelRef: {
3839 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3840 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3841 }
3842
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003843 case CXCursor_OverloadedDeclRef:
3844 return cxloc::translateSourceLocation(getCursorContext(C),
3845 getCursorOverloadedDeclRef(C).second);
3846
Douglas Gregorf46034a2010-01-18 23:41:10 +00003847 default:
3848 // FIXME: Need a way to enumerate all non-reference cases.
3849 llvm_unreachable("Missed a reference kind");
3850 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003851 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003852
3853 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003854 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003855 getLocationFromExpr(getCursorExpr(C)));
3856
Douglas Gregor36897b02010-09-10 00:22:18 +00003857 if (clang_isStatement(C.kind))
3858 return cxloc::translateSourceLocation(getCursorContext(C),
3859 getCursorStmt(C)->getLocStart());
3860
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003861 if (C.kind == CXCursor_PreprocessingDirective) {
3862 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3863 return cxloc::translateSourceLocation(getCursorContext(C), L);
3864 }
Douglas Gregor48072312010-03-18 15:23:44 +00003865
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003866 if (C.kind == CXCursor_MacroExpansion) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003867 SourceLocation L
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003868 = cxcursor::getCursorMacroExpansion(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003869 return cxloc::translateSourceLocation(getCursorContext(C), L);
3870 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003871
3872 if (C.kind == CXCursor_MacroDefinition) {
3873 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3874 return cxloc::translateSourceLocation(getCursorContext(C), L);
3875 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003876
3877 if (C.kind == CXCursor_InclusionDirective) {
3878 SourceLocation L
3879 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3880 return cxloc::translateSourceLocation(getCursorContext(C), L);
3881 }
3882
Ted Kremenek9a700d22010-05-12 06:16:13 +00003883 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003884 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003885
Douglas Gregorf46034a2010-01-18 23:41:10 +00003886 Decl *D = getCursorDecl(C);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00003887 if (!D)
3888 return clang_getNullLocation();
3889
Douglas Gregorf46034a2010-01-18 23:41:10 +00003890 SourceLocation Loc = D->getLocation();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003891 // FIXME: Multiple variables declared in a single declaration
3892 // currently lack the information needed to correctly determine their
3893 // ranges when accounting for the type-specifier. We use context
3894 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3895 // and if so, whether it is the first decl.
3896 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3897 if (!cxcursor::isFirstInDeclGroup(C))
3898 Loc = VD->getLocation();
3899 }
3900
Argyrios Kyrtzidisccc6f362012-03-23 03:33:19 +00003901 // For ObjC methods, give the start location of the method name.
3902 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
3903 Loc = MD->getSelectorStartLoc();
3904
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003905 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003906}
Douglas Gregora7bde202010-01-19 00:34:46 +00003907
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003908} // end extern "C"
3909
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003910CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
3911 assert(TU);
3912
3913 // Guard against an invalid SourceLocation, or we may assert in one
3914 // of the following calls.
3915 if (SLoc.isInvalid())
3916 return clang_getNullCursor();
3917
3918 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
3919
3920 // Translate the given source location to make it point at the beginning of
3921 // the token under the cursor.
3922 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +00003923 CXXUnit->getASTContext().getLangOpts());
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003924
3925 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3926 if (SLoc.isValid()) {
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003927 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003928 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
3929 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00003930 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003931 SourceLocation(SLoc));
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00003932 CursorVis.visitFileRegion();
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003933 }
3934
3935 return Result;
3936}
3937
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003938static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003939 if (clang_isReference(C.kind)) {
3940 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003941 case CXCursor_ObjCSuperClassRef:
3942 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003943
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003944 case CXCursor_ObjCProtocolRef:
3945 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003946
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003947 case CXCursor_ObjCClassRef:
3948 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003949
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003950 case CXCursor_TypeRef:
3951 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003952
3953 case CXCursor_TemplateRef:
3954 return getCursorTemplateRef(C).second;
3955
Douglas Gregor69319002010-08-31 23:48:11 +00003956 case CXCursor_NamespaceRef:
3957 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003958
3959 case CXCursor_MemberRef:
3960 return getCursorMemberRef(C).second;
3961
Ted Kremenek3064ef92010-08-27 21:34:58 +00003962 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003963 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003964
Douglas Gregor36897b02010-09-10 00:22:18 +00003965 case CXCursor_LabelRef:
3966 return getCursorLabelRef(C).second;
3967
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003968 case CXCursor_OverloadedDeclRef:
3969 return getCursorOverloadedDeclRef(C).second;
3970
Douglas Gregor011d8b92012-02-15 00:54:55 +00003971 case CXCursor_VariableRef:
3972 return getCursorVariableRef(C).second;
3973
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003974 default:
3975 // FIXME: Need a way to enumerate all non-reference cases.
3976 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003977 }
3978 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003979
3980 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003981 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003982
3983 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003984 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003985
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00003986 if (clang_isAttribute(C.kind))
3987 return getCursorAttr(C)->getRange();
3988
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003989 if (C.kind == CXCursor_PreprocessingDirective)
3990 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003991
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00003992 if (C.kind == CXCursor_MacroExpansion) {
3993 ASTUnit *TU = getCursorASTUnit(C);
3994 SourceRange Range = cxcursor::getCursorMacroExpansion(C)->getSourceRange();
3995 return TU->mapRangeFromPreamble(Range);
3996 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003997
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00003998 if (C.kind == CXCursor_MacroDefinition) {
3999 ASTUnit *TU = getCursorASTUnit(C);
4000 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
4001 return TU->mapRangeFromPreamble(Range);
4002 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00004003
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004004 if (C.kind == CXCursor_InclusionDirective) {
4005 ASTUnit *TU = getCursorASTUnit(C);
4006 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
4007 return TU->mapRangeFromPreamble(Range);
4008 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00004009
Argyrios Kyrtzidis0822c5f2012-03-19 23:17:58 +00004010 if (C.kind == CXCursor_TranslationUnit) {
4011 ASTUnit *TU = getCursorASTUnit(C);
4012 FileID MainID = TU->getSourceManager().getMainFileID();
4013 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
4014 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
4015 return SourceRange(Start, End);
4016 }
4017
Ted Kremenek007a7c92010-11-01 23:26:51 +00004018 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
4019 Decl *D = cxcursor::getCursorDecl(C);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00004020 if (!D)
4021 return SourceRange();
4022
Ted Kremenek007a7c92010-11-01 23:26:51 +00004023 SourceRange R = D->getSourceRange();
4024 // FIXME: Multiple variables declared in a single declaration
4025 // currently lack the information needed to correctly determine their
4026 // ranges when accounting for the type-specifier. We use context
4027 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
4028 // and if so, whether it is the first decl.
4029 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4030 if (!cxcursor::isFirstInDeclGroup(C))
4031 R.setBegin(VD->getLocation());
4032 }
4033 return R;
4034 }
Douglas Gregor66537982010-11-17 17:14:07 +00004035 return SourceRange();
4036}
4037
4038/// \brief Retrieves the "raw" cursor extent, which is then extended to include
4039/// the decl-specifier-seq for declarations.
4040static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
4041 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
4042 Decl *D = cxcursor::getCursorDecl(C);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00004043 if (!D)
4044 return SourceRange();
4045
Douglas Gregor66537982010-11-17 17:14:07 +00004046 SourceRange R = D->getSourceRange();
Douglas Gregor66537982010-11-17 17:14:07 +00004047
Douglas Gregor2494dd02011-03-01 01:34:45 +00004048 // Adjust the start of the location for declarations preceded by
4049 // declaration specifiers.
4050 SourceLocation StartLoc;
4051 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
4052 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
Daniel Dunbar96a00142012-03-09 18:35:03 +00004053 StartLoc = TI->getTypeLoc().getLocStart();
Douglas Gregor2494dd02011-03-01 01:34:45 +00004054 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
4055 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
Daniel Dunbar96a00142012-03-09 18:35:03 +00004056 StartLoc = TI->getTypeLoc().getLocStart();
Douglas Gregor2494dd02011-03-01 01:34:45 +00004057 }
4058
4059 if (StartLoc.isValid() && R.getBegin().isValid() &&
4060 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
4061 R.setBegin(StartLoc);
4062
4063 // FIXME: Multiple variables declared in a single declaration
4064 // currently lack the information needed to correctly determine their
4065 // ranges when accounting for the type-specifier. We use context
4066 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
4067 // and if so, whether it is the first decl.
4068 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4069 if (!cxcursor::isFirstInDeclGroup(C))
4070 R.setBegin(VD->getLocation());
Douglas Gregor66537982010-11-17 17:14:07 +00004071 }
4072
4073 return R;
4074 }
4075
4076 return getRawCursorExtent(C);
4077}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004078
4079extern "C" {
4080
4081CXSourceRange clang_getCursorExtent(CXCursor C) {
4082 SourceRange R = getRawCursorExtent(C);
4083 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00004084 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004085
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004086 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00004087}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004088
4089CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00004090 if (clang_isInvalid(C.kind))
4091 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004092
Ted Kremeneka60ed472010-11-16 08:15:36 +00004093 CXTranslationUnit tu = getCursorTU(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004094 if (clang_isDeclaration(C.kind)) {
4095 Decl *D = getCursorDecl(C);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00004096 if (!D)
4097 return clang_getNullCursor();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004098 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004099 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Chris Lattner5f9e2722011-07-23 10:55:15 +00004100 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00004101 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
4102 return MakeCXCursor(Property, tu);
4103
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004104 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004105 }
4106
Douglas Gregor97b98722010-01-19 23:20:36 +00004107 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004108 Expr *E = getCursorExpr(C);
4109 Decl *D = getDeclFromExpr(E);
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00004110 if (D) {
4111 CXCursor declCursor = MakeCXCursor(D, tu);
4112 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
4113 declCursor);
4114 return declCursor;
4115 }
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004116
4117 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004118 return MakeCursorOverloadedDeclRef(Ovl, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004119
Douglas Gregor97b98722010-01-19 23:20:36 +00004120 return clang_getNullCursor();
4121 }
4122
Douglas Gregor36897b02010-09-10 00:22:18 +00004123 if (clang_isStatement(C.kind)) {
4124 Stmt *S = getCursorStmt(C);
4125 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Ted Kremenek37c2e962011-03-15 23:47:49 +00004126 if (LabelDecl *label = Goto->getLabel())
4127 if (LabelStmt *labelS = label->getStmt())
4128 return MakeCXCursor(labelS, getCursorDecl(C), tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00004129
4130 return clang_getNullCursor();
4131 }
4132
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004133 if (C.kind == CXCursor_MacroExpansion) {
Chandler Carruth9e5bb852011-07-14 08:20:46 +00004134 if (MacroDefinition *Def = getCursorMacroExpansion(C)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004135 return MakeMacroDefinitionCursor(Def, tu);
Douglas Gregorbf7efa22010-03-18 18:23:03 +00004136 }
4137
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004138 if (!clang_isReference(C.kind))
4139 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004140
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004141 switch (C.kind) {
4142 case CXCursor_ObjCSuperClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004143 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004144
4145 case CXCursor_ObjCProtocolRef: {
Argyrios Kyrtzidis98c16b82012-01-24 19:40:15 +00004146 ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
4147 if (ObjCProtocolDecl *Def = Prot->getDefinition())
4148 return MakeCXCursor(Def, tu);
4149
Argyrios Kyrtzidisc15707d2012-01-24 21:39:26 +00004150 return MakeCXCursor(Prot, tu);
Argyrios Kyrtzidis98c16b82012-01-24 19:40:15 +00004151 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004152
Douglas Gregor7723fec2011-12-15 20:29:51 +00004153 case CXCursor_ObjCClassRef: {
4154 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
4155 if (ObjCInterfaceDecl *Def = Class->getDefinition())
4156 return MakeCXCursor(Def, tu);
4157
Argyrios Kyrtzidisc15707d2012-01-24 21:39:26 +00004158 return MakeCXCursor(Class, tu);
Douglas Gregor7723fec2011-12-15 20:29:51 +00004159 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00004160
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004161 case CXCursor_TypeRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004162 return MakeCXCursor(getCursorTypeRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00004163
4164 case CXCursor_TemplateRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004165 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00004166
Douglas Gregor69319002010-08-31 23:48:11 +00004167 case CXCursor_NamespaceRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004168 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
Douglas Gregor69319002010-08-31 23:48:11 +00004169
Douglas Gregora67e03f2010-09-09 21:42:20 +00004170 case CXCursor_MemberRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004171 return MakeCXCursor(getCursorMemberRef(C).first, tu );
Douglas Gregora67e03f2010-09-09 21:42:20 +00004172
Ted Kremenek3064ef92010-08-27 21:34:58 +00004173 case CXCursor_CXXBaseSpecifier: {
4174 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
4175 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004176 tu ));
Ted Kremenek3064ef92010-08-27 21:34:58 +00004177 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004178
Douglas Gregor36897b02010-09-10 00:22:18 +00004179 case CXCursor_LabelRef:
4180 // FIXME: We end up faking the "parent" declaration here because we
4181 // don't want to make CXCursor larger.
4182 return MakeCXCursor(getCursorLabelRef(C).first,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004183 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
4184 .getTranslationUnitDecl(),
4185 tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00004186
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004187 case CXCursor_OverloadedDeclRef:
4188 return C;
Douglas Gregor011d8b92012-02-15 00:54:55 +00004189
4190 case CXCursor_VariableRef:
4191 return MakeCXCursor(getCursorVariableRef(C).first, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004192
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004193 default:
4194 // We would prefer to enumerate all non-reference cursor kinds here.
4195 llvm_unreachable("Unhandled reference cursor kind");
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004196 }
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004197}
4198
Douglas Gregorb6998662010-01-19 19:34:47 +00004199CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00004200 if (clang_isInvalid(C.kind))
4201 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004202
Ted Kremeneka60ed472010-11-16 08:15:36 +00004203 CXTranslationUnit TU = getCursorTU(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004204
Douglas Gregorb6998662010-01-19 19:34:47 +00004205 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00004206 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00004207 C = clang_getCursorReferenced(C);
4208 WasReference = true;
4209 }
4210
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004211 if (C.kind == CXCursor_MacroExpansion)
Douglas Gregorbf7efa22010-03-18 18:23:03 +00004212 return clang_getCursorReferenced(C);
4213
Douglas Gregorb6998662010-01-19 19:34:47 +00004214 if (!clang_isDeclaration(C.kind))
4215 return clang_getNullCursor();
4216
4217 Decl *D = getCursorDecl(C);
4218 if (!D)
4219 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004220
Douglas Gregorb6998662010-01-19 19:34:47 +00004221 switch (D->getKind()) {
4222 // Declaration kinds that don't really separate the notions of
4223 // declaration and definition.
4224 case Decl::Namespace:
4225 case Decl::Typedef:
Richard Smith162e1c12011-04-15 14:24:37 +00004226 case Decl::TypeAlias:
Richard Smith3e4c6c42011-05-05 21:57:07 +00004227 case Decl::TypeAliasTemplate:
Douglas Gregorb6998662010-01-19 19:34:47 +00004228 case Decl::TemplateTypeParm:
4229 case Decl::EnumConstant:
4230 case Decl::Field:
Benjamin Kramerd9811462010-11-21 14:11:41 +00004231 case Decl::IndirectField:
Douglas Gregorb6998662010-01-19 19:34:47 +00004232 case Decl::ObjCIvar:
4233 case Decl::ObjCAtDefsField:
4234 case Decl::ImplicitParam:
4235 case Decl::ParmVar:
4236 case Decl::NonTypeTemplateParm:
4237 case Decl::TemplateTemplateParm:
4238 case Decl::ObjCCategoryImpl:
4239 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00004240 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00004241 case Decl::LinkageSpec:
4242 case Decl::ObjCPropertyImpl:
4243 case Decl::FileScopeAsm:
4244 case Decl::StaticAssert:
4245 case Decl::Block:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00004246 case Decl::Label: // FIXME: Is this right??
Francois Pichetaf0f4d02011-08-14 03:52:19 +00004247 case Decl::ClassScopeFunctionSpecialization:
Douglas Gregor15de72c2011-12-02 23:23:56 +00004248 case Decl::Import:
Douglas Gregorb6998662010-01-19 19:34:47 +00004249 return C;
4250
4251 // Declaration kinds that don't make any sense here, but are
4252 // nonetheless harmless.
4253 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00004254 break;
4255
4256 // Declaration kinds for which the definition is not resolvable.
4257 case Decl::UnresolvedUsingTypename:
4258 case Decl::UnresolvedUsingValue:
4259 break;
4260
4261 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00004262 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004263 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004264
4265 case Decl::NamespaceAlias:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004266 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004267
4268 case Decl::Enum:
4269 case Decl::Record:
4270 case Decl::CXXRecord:
4271 case Decl::ClassTemplateSpecialization:
4272 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00004273 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004274 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004275 return clang_getNullCursor();
4276
4277 case Decl::Function:
4278 case Decl::CXXMethod:
4279 case Decl::CXXConstructor:
4280 case Decl::CXXDestructor:
4281 case Decl::CXXConversion: {
4282 const FunctionDecl *Def = 0;
4283 if (cast<FunctionDecl>(D)->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004284 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004285 return clang_getNullCursor();
4286 }
4287
4288 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00004289 // Ask the variable if it has a definition.
4290 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004291 return MakeCXCursor(Def, TU);
Sebastian Redl31310a22010-02-01 20:16:42 +00004292 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00004293 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004294
Douglas Gregorb6998662010-01-19 19:34:47 +00004295 case Decl::FunctionTemplate: {
4296 const FunctionDecl *Def = 0;
4297 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004298 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004299 return clang_getNullCursor();
4300 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004301
Douglas Gregorb6998662010-01-19 19:34:47 +00004302 case Decl::ClassTemplate: {
4303 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00004304 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00004305 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004306 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004307 return clang_getNullCursor();
4308 }
4309
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004310 case Decl::Using:
4311 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004312 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004313
4314 case Decl::UsingShadow:
4315 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004316 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004317 TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004318
4319 case Decl::ObjCMethod: {
4320 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
4321 if (Method->isThisDeclarationADefinition())
4322 return C;
4323
4324 // Dig out the method definition in the associated
4325 // @implementation, if we have it.
4326 // FIXME: The ASTs should make finding the definition easier.
4327 if (ObjCInterfaceDecl *Class
4328 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
4329 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
4330 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
4331 Method->isInstanceMethod()))
4332 if (Def->isThisDeclarationADefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004333 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004334
4335 return clang_getNullCursor();
4336 }
4337
4338 case Decl::ObjCCategory:
4339 if (ObjCCategoryImplDecl *Impl
4340 = cast<ObjCCategoryDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004341 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004342 return clang_getNullCursor();
4343
4344 case Decl::ObjCProtocol:
Douglas Gregor5e2a1ff2012-01-01 19:29:29 +00004345 if (ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
4346 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004347 return clang_getNullCursor();
4348
Douglas Gregor375bb142011-12-27 22:43:10 +00004349 case Decl::ObjCInterface: {
Douglas Gregorb6998662010-01-19 19:34:47 +00004350 // There are two notions of a "definition" for an Objective-C
4351 // class: the interface and its implementation. When we resolved a
4352 // reference to an Objective-C class, produce the @interface as
4353 // the definition; when we were provided with the interface,
4354 // produce the @implementation as the definition.
Douglas Gregor375bb142011-12-27 22:43:10 +00004355 ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
Douglas Gregorb6998662010-01-19 19:34:47 +00004356 if (WasReference) {
Douglas Gregor375bb142011-12-27 22:43:10 +00004357 if (ObjCInterfaceDecl *Def = IFace->getDefinition())
Douglas Gregor7723fec2011-12-15 20:29:51 +00004358 return MakeCXCursor(Def, TU);
Douglas Gregor375bb142011-12-27 22:43:10 +00004359 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004360 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004361 return clang_getNullCursor();
Douglas Gregor375bb142011-12-27 22:43:10 +00004362 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004363
Douglas Gregorb6998662010-01-19 19:34:47 +00004364 case Decl::ObjCProperty:
4365 // FIXME: We don't really know where to find the
4366 // ObjCPropertyImplDecls that implement this property.
4367 return clang_getNullCursor();
4368
4369 case Decl::ObjCCompatibleAlias:
4370 if (ObjCInterfaceDecl *Class
4371 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
Douglas Gregor7723fec2011-12-15 20:29:51 +00004372 if (ObjCInterfaceDecl *Def = Class->getDefinition())
4373 return MakeCXCursor(Def, TU);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004374
Douglas Gregorb6998662010-01-19 19:34:47 +00004375 return clang_getNullCursor();
4376
Douglas Gregorb6998662010-01-19 19:34:47 +00004377 case Decl::Friend:
4378 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004379 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004380 return clang_getNullCursor();
4381
4382 case Decl::FriendTemplate:
4383 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004384 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004385 return clang_getNullCursor();
4386 }
4387
4388 return clang_getNullCursor();
4389}
4390
4391unsigned clang_isCursorDefinition(CXCursor C) {
4392 if (!clang_isDeclaration(C.kind))
4393 return 0;
4394
4395 return clang_getCursorDefinition(C) == C;
4396}
4397
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004398CXCursor clang_getCanonicalCursor(CXCursor C) {
4399 if (!clang_isDeclaration(C.kind))
4400 return C;
4401
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004402 if (Decl *D = getCursorDecl(C)) {
Argyrios Kyrtzidisdebb00f2011-07-15 22:37:58 +00004403 if (ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
4404 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
4405 return MakeCXCursor(CatD, getCursorTU(C));
4406
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004407 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
4408 if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
4409 return MakeCXCursor(IFD, getCursorTU(C));
4410
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004411 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004412 }
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004413
4414 return C;
4415}
Argyrios Kyrtzidis34ebe1e2012-03-30 22:15:48 +00004416
4417int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) {
4418 return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first;
4419}
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004420
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004421unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004422 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004423 return 0;
4424
4425 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
4426 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
4427 return E->getNumDecls();
4428
4429 if (OverloadedTemplateStorage *S
4430 = Storage.dyn_cast<OverloadedTemplateStorage*>())
4431 return S->size();
4432
4433 Decl *D = Storage.get<Decl*>();
4434 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00004435 return Using->shadow_size();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004436
4437 return 0;
4438}
4439
4440CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004441 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004442 return clang_getNullCursor();
4443
4444 if (index >= clang_getNumOverloadedDecls(cursor))
4445 return clang_getNullCursor();
4446
Ted Kremeneka60ed472010-11-16 08:15:36 +00004447 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004448 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
4449 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004450 return MakeCXCursor(E->decls_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004451
4452 if (OverloadedTemplateStorage *S
4453 = Storage.dyn_cast<OverloadedTemplateStorage*>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004454 return MakeCXCursor(S->begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004455
4456 Decl *D = Storage.get<Decl*>();
4457 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
4458 // FIXME: This is, unfortunately, linear time.
4459 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
4460 std::advance(Pos, index);
Ted Kremeneka60ed472010-11-16 08:15:36 +00004461 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004462 }
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004463
4464 return clang_getNullCursor();
4465}
4466
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00004467void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00004468 const char **startBuf,
4469 const char **endBuf,
4470 unsigned *startLine,
4471 unsigned *startColumn,
4472 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00004473 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00004474 assert(getCursorDecl(C) && "CXCursor has null decl");
4475 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00004476 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
4477 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004478
Steve Naroff4ade6d62009-09-23 17:52:52 +00004479 SourceManager &SM = FD->getASTContext().getSourceManager();
4480 *startBuf = SM.getCharacterData(Body->getLBracLoc());
4481 *endBuf = SM.getCharacterData(Body->getRBracLoc());
4482 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
4483 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
4484 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
4485 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
4486}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004487
Douglas Gregor430d7a12011-07-25 17:48:11 +00004488
4489CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
4490 unsigned PieceIndex) {
4491 RefNamePieces Pieces;
4492
4493 switch (C.kind) {
4494 case CXCursor_MemberRefExpr:
4495 if (MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
4496 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
4497 E->getQualifierLoc().getSourceRange());
4498 break;
4499
4500 case CXCursor_DeclRefExpr:
4501 if (DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C)))
4502 Pieces = buildPieces(NameFlags, false, E->getNameInfo(),
4503 E->getQualifierLoc().getSourceRange(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00004504 E->getOptionalExplicitTemplateArgs());
Douglas Gregor430d7a12011-07-25 17:48:11 +00004505 break;
4506
4507 case CXCursor_CallExpr:
4508 if (CXXOperatorCallExpr *OCE =
4509 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
4510 Expr *Callee = OCE->getCallee();
4511 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
4512 Callee = ICE->getSubExpr();
4513
4514 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
4515 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
4516 DRE->getQualifierLoc().getSourceRange());
4517 }
4518 break;
4519
4520 default:
4521 break;
4522 }
4523
4524 if (Pieces.empty()) {
4525 if (PieceIndex == 0)
4526 return clang_getCursorExtent(C);
4527 } else if (PieceIndex < Pieces.size()) {
4528 SourceRange R = Pieces[PieceIndex];
4529 if (R.isValid())
4530 return cxloc::translateSourceRange(getCursorContext(C), R);
4531 }
4532
4533 return clang_getNullRange();
4534}
4535
Douglas Gregor0a812cf2010-02-18 23:07:20 +00004536void clang_enableStackTraces(void) {
4537 llvm::sys::PrintStackTraceOnErrorSignal();
4538}
4539
Daniel Dunbar995aaf92010-11-04 01:26:29 +00004540void clang_executeOnThread(void (*fn)(void*), void *user_data,
4541 unsigned stack_size) {
4542 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
4543}
4544
Ted Kremenekfb480492010-01-13 21:46:36 +00004545} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00004546
Ted Kremenekfb480492010-01-13 21:46:36 +00004547//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004548// Token-based Operations.
4549//===----------------------------------------------------------------------===//
4550
4551/* CXToken layout:
4552 * int_data[0]: a CXTokenKind
4553 * int_data[1]: starting token location
4554 * int_data[2]: token length
4555 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004556 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004557 * otherwise unused.
4558 */
4559extern "C" {
4560
4561CXTokenKind clang_getTokenKind(CXToken CXTok) {
4562 return static_cast<CXTokenKind>(CXTok.int_data[0]);
4563}
4564
4565CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
4566 switch (clang_getTokenKind(CXTok)) {
4567 case CXToken_Identifier:
4568 case CXToken_Keyword:
4569 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004570 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
4571 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004572
4573 case CXToken_Literal: {
4574 // We have stashed the starting pointer in the ptr_data field. Use it.
4575 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Chris Lattner5f9e2722011-07-23 10:55:15 +00004576 return createCXString(StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004577 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004578
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004579 case CXToken_Punctuation:
4580 case CXToken_Comment:
4581 break;
4582 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004583
4584 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004585 // deconstructing the source location.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004586 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004587 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004588 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004589
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004590 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
4591 std::pair<FileID, unsigned> LocInfo
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004592 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00004593 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004594 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004595 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
4596 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00004597 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004598
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004599 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004600}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004601
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004602CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004603 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004604 if (!CXXUnit)
4605 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004606
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004607 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
4608 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4609}
4610
4611CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004612 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor5352ac02010-01-28 00:27:43 +00004613 if (!CXXUnit)
4614 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004615
4616 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004617 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4618}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004619
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004620static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
4621 SmallVectorImpl<CXToken> &CXTokens) {
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004622 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4623 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004624 = SourceMgr.getDecomposedLoc(Range.getBegin());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004625 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004626 = SourceMgr.getDecomposedLoc(Range.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004627
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004628 // Cannot tokenize across files.
4629 if (BeginLocInfo.first != EndLocInfo.first)
4630 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004631
4632 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004633 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004634 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004635 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00004636 if (Invalid)
4637 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00004638
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004639 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
David Blaikie4e4d0842012-03-11 07:00:24 +00004640 CXXUnit->getASTContext().getLangOpts(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004641 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004642 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004643
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004644 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004645 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004646 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00004647 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004648 do {
4649 // Lex the next token
4650 Lex.LexFromRawLexer(Tok);
4651 if (Tok.is(tok::eof))
4652 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004653
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004654 // Initialize the CXToken.
4655 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004656
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004657 // - Common fields
4658 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
4659 CXTok.int_data[2] = Tok.getLength();
4660 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004661
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004662 // - Kind-specific fields
4663 if (Tok.isLiteral()) {
4664 CXTok.int_data[0] = CXToken_Literal;
4665 CXTok.ptr_data = (void *)Tok.getLiteralData();
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004666 } else if (Tok.is(tok::raw_identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00004667 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004668 IdentifierInfo *II
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004669 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004670
David Chisnall096428b2010-10-13 21:44:48 +00004671 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004672 CXTok.int_data[0] = CXToken_Keyword;
4673 }
4674 else {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004675 CXTok.int_data[0] = Tok.is(tok::identifier)
4676 ? CXToken_Identifier
4677 : CXToken_Keyword;
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004678 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004679 CXTok.ptr_data = II;
4680 } else if (Tok.is(tok::comment)) {
4681 CXTok.int_data[0] = CXToken_Comment;
4682 CXTok.ptr_data = 0;
4683 } else {
4684 CXTok.int_data[0] = CXToken_Punctuation;
4685 CXTok.ptr_data = 0;
4686 }
4687 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00004688 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004689 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004690}
4691
4692void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
4693 CXToken **Tokens, unsigned *NumTokens) {
4694 if (Tokens)
4695 *Tokens = 0;
4696 if (NumTokens)
4697 *NumTokens = 0;
4698
4699 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4700 if (!CXXUnit || !Tokens || !NumTokens)
4701 return;
4702
4703 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4704
4705 SourceRange R = cxloc::translateCXSourceRange(Range);
4706 if (R.isInvalid())
4707 return;
4708
4709 SmallVector<CXToken, 32> CXTokens;
4710 getTokens(CXXUnit, R, CXTokens);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004711
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004712 if (CXTokens.empty())
4713 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004714
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004715 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
4716 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
4717 *NumTokens = CXTokens.size();
4718}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004719
Ted Kremenek6db61092010-05-05 00:55:15 +00004720void clang_disposeTokens(CXTranslationUnit TU,
4721 CXToken *Tokens, unsigned NumTokens) {
4722 free(Tokens);
4723}
4724
4725} // end: extern "C"
4726
4727//===----------------------------------------------------------------------===//
4728// Token annotation APIs.
4729//===----------------------------------------------------------------------===//
4730
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004731typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004732static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4733 CXCursor parent,
4734 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00004735namespace {
4736class AnnotateTokensWorker {
4737 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004738 CXToken *Tokens;
4739 CXCursor *Cursors;
4740 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004741 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00004742 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004743 CursorVisitor AnnotateVis;
4744 SourceManager &SrcMgr;
Douglas Gregorf5251602011-03-08 17:10:18 +00004745 bool HasContextSensitiveKeywords;
4746
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004747 bool MoreTokens() const { return TokIdx < NumTokens; }
4748 unsigned NextToken() const { return TokIdx; }
4749 void AdvanceToken() { ++TokIdx; }
4750 SourceLocation GetTokenLoc(unsigned tokI) {
4751 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4752 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004753 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004754 return Tokens[tokI].int_data[3] != 0;
4755 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004756 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004757 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[3]);
4758 }
4759
4760 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004761 void annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
4762 SourceRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004763
Ted Kremenek6db61092010-05-05 00:55:15 +00004764public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00004765 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004766 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004767 CXTranslationUnit tu, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00004768 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00004769 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004770 AnnotateVis(tu,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00004771 AnnotateTokensVisitor, this,
4772 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00004773 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00004774 RegionOfInterest),
Douglas Gregorf5251602011-03-08 17:10:18 +00004775 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()),
4776 HasContextSensitiveKeywords(false) { }
Ted Kremenek11949cb2010-05-05 00:55:17 +00004777
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004778 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00004779 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004780 void AnnotateTokens();
Douglas Gregorf5251602011-03-08 17:10:18 +00004781
4782 /// \brief Determine whether the annotator saw any cursors that have
4783 /// context-sensitive keywords.
4784 bool hasContextSensitiveKeywords() const {
4785 return HasContextSensitiveKeywords;
4786 }
Ted Kremenek6db61092010-05-05 00:55:15 +00004787};
4788}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004789
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004790void AnnotateTokensWorker::AnnotateTokens() {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004791 // Walk the AST within the region of interest, annotating tokens
4792 // along the way.
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004793 AnnotateVis.visitFileRegion();
Ted Kremenek11949cb2010-05-05 00:55:17 +00004794
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004795 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4796 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004797 if (Pos != Annotated.end() &&
4798 (clang_isInvalid(Cursors[I].kind) ||
4799 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004800 Cursors[I] = Pos->second;
4801 }
4802
4803 // Finish up annotating any tokens left.
4804 if (!MoreTokens())
4805 return;
4806
4807 const CXCursor &C = clang_getNullCursor();
4808 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004809 if (I < PreprocessingTokIdx && clang_isPreprocessing(Cursors[I].kind))
4810 continue;
4811
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004812 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4813 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004814 }
4815}
4816
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004817/// \brief It annotates and advances tokens with a cursor until the comparison
4818//// between the cursor location and the source range is the same as
4819/// \arg compResult.
4820///
4821/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
4822/// Pass RangeOverlap to annotate tokens inside a range.
4823void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
4824 RangeComparisonResult compResult,
4825 SourceRange range) {
4826 while (MoreTokens()) {
4827 const unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004828 if (isFunctionMacroToken(I))
4829 return annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004830
4831 SourceLocation TokLoc = GetTokenLoc(I);
4832 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4833 Cursors[I] = updateC;
4834 AdvanceToken();
4835 continue;
4836 }
4837 break;
4838 }
4839}
4840
4841/// \brief Special annotation handling for macro argument tokens.
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004842void AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
4843 CXCursor updateC,
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004844 RangeComparisonResult compResult,
4845 SourceRange range) {
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004846 assert(MoreTokens());
4847 assert(isFunctionMacroToken(NextToken()) &&
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004848 "Should be called only for macro arg tokens");
4849
4850 // This works differently than annotateAndAdvanceTokens; because expanded
4851 // macro arguments can have arbitrary translation-unit source order, we do not
4852 // advance the token index one by one until a token fails the range test.
4853 // We only advance once past all of the macro arg tokens if all of them
4854 // pass the range test. If one of them fails we keep the token index pointing
4855 // at the start of the macro arg tokens so that the failing token will be
4856 // annotated by a subsequent annotation try.
4857
4858 bool atLeastOneCompFail = false;
4859
4860 unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004861 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
4862 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004863 if (TokLoc.isFileID())
4864 continue; // not macro arg token, it's parens or comma.
4865 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4866 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
4867 Cursors[I] = updateC;
4868 } else
4869 atLeastOneCompFail = true;
4870 }
4871
4872 if (!atLeastOneCompFail)
4873 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
4874}
4875
Ted Kremenek6db61092010-05-05 00:55:15 +00004876enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004877AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004878 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004879 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004880 if (cursorRange.isInvalid())
4881 return CXChildVisit_Recurse;
Douglas Gregorf5251602011-03-08 17:10:18 +00004882
4883 if (!HasContextSensitiveKeywords) {
4884 // Objective-C properties can have context-sensitive keywords.
4885 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
4886 if (ObjCPropertyDecl *Property
4887 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
4888 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
4889 }
4890 // Objective-C methods can have context-sensitive keywords.
4891 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
4892 cursor.kind == CXCursor_ObjCClassMethodDecl) {
4893 if (ObjCMethodDecl *Method
4894 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
4895 if (Method->getObjCDeclQualifier())
4896 HasContextSensitiveKeywords = true;
4897 else {
4898 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
4899 PEnd = Method->param_end();
4900 P != PEnd; ++P) {
4901 if ((*P)->getObjCDeclQualifier()) {
4902 HasContextSensitiveKeywords = true;
4903 break;
4904 }
4905 }
4906 }
4907 }
4908 }
4909 // C++ methods can have context-sensitive keywords.
4910 else if (cursor.kind == CXCursor_CXXMethod) {
4911 if (CXXMethodDecl *Method
4912 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
4913 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
4914 HasContextSensitiveKeywords = true;
4915 }
4916 }
4917 // C++ classes can have context-sensitive keywords.
4918 else if (cursor.kind == CXCursor_StructDecl ||
4919 cursor.kind == CXCursor_ClassDecl ||
4920 cursor.kind == CXCursor_ClassTemplate ||
4921 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
4922 if (Decl *D = getCursorDecl(cursor))
4923 if (D->hasAttr<FinalAttr>())
4924 HasContextSensitiveKeywords = true;
4925 }
4926 }
4927
Douglas Gregor4419b672010-10-21 06:10:04 +00004928 if (clang_isPreprocessing(cursor.kind)) {
Chandler Carruthcea731a2011-07-14 16:07:57 +00004929 // For macro expansions, just note where the beginning of the macro
4930 // expansion occurs.
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004931 if (cursor.kind == CXCursor_MacroExpansion) {
Douglas Gregor4419b672010-10-21 06:10:04 +00004932 Annotated[Loc.int_data] = cursor;
4933 return CXChildVisit_Recurse;
4934 }
4935
Douglas Gregor4419b672010-10-21 06:10:04 +00004936 // Items in the preprocessing record are kept separate from items in
4937 // declarations, so we keep a separate token index.
4938 unsigned SavedTokIdx = TokIdx;
4939 TokIdx = PreprocessingTokIdx;
4940
4941 // Skip tokens up until we catch up to the beginning of the preprocessing
4942 // entry.
4943 while (MoreTokens()) {
4944 const unsigned I = NextToken();
4945 SourceLocation TokLoc = GetTokenLoc(I);
4946 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4947 case RangeBefore:
4948 AdvanceToken();
4949 continue;
4950 case RangeAfter:
4951 case RangeOverlap:
4952 break;
4953 }
4954 break;
4955 }
4956
4957 // Look at all of the tokens within this range.
4958 while (MoreTokens()) {
4959 const unsigned I = NextToken();
4960 SourceLocation TokLoc = GetTokenLoc(I);
4961 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4962 case RangeBefore:
David Blaikieb219cfc2011-09-23 05:06:16 +00004963 llvm_unreachable("Infeasible");
Douglas Gregor4419b672010-10-21 06:10:04 +00004964 case RangeAfter:
4965 break;
4966 case RangeOverlap:
4967 Cursors[I] = cursor;
4968 AdvanceToken();
4969 continue;
4970 }
4971 break;
4972 }
4973
4974 // Save the preprocessing token index; restore the non-preprocessing
4975 // token index.
4976 PreprocessingTokIdx = TokIdx;
4977 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004978 return CXChildVisit_Recurse;
4979 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004980
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004981 if (cursorRange.isInvalid())
4982 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004983
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004984 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4985
Ted Kremeneka333c662010-05-12 05:29:33 +00004986 // Adjust the annotated range based specific declarations.
4987 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4988 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004989 Decl *D = cxcursor::getCursorDecl(cursor);
Douglas Gregor2494dd02011-03-01 01:34:45 +00004990
4991 SourceLocation StartLoc;
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00004992 if (const DeclaratorDecl *DD = dyn_cast_or_null<DeclaratorDecl>(D)) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00004993 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
Daniel Dunbar96a00142012-03-09 18:35:03 +00004994 StartLoc = TI->getTypeLoc().getLocStart();
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00004995 } else if (TypedefDecl *Typedef = dyn_cast_or_null<TypedefDecl>(D)) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00004996 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
Daniel Dunbar96a00142012-03-09 18:35:03 +00004997 StartLoc = TI->getTypeLoc().getLocStart();
Ted Kremeneka333c662010-05-12 05:29:33 +00004998 }
Douglas Gregor2494dd02011-03-01 01:34:45 +00004999
5000 if (StartLoc.isValid() && L.isValid() &&
5001 SrcMgr.isBeforeInTranslationUnit(StartLoc, L))
5002 cursorRange.setBegin(StartLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00005003 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00005004
Ted Kremenek3f404602010-08-14 01:14:06 +00005005 // If the location of the cursor occurs within a macro instantiation, record
5006 // the spelling location of the cursor in our annotation map. We can then
5007 // paper over the token labelings during a post-processing step to try and
5008 // get cursor mappings for tokens that are the *arguments* of a macro
5009 // instantiation.
5010 if (L.isMacroID()) {
5011 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
5012 // Only invalidate the old annotation if it isn't part of a preprocessing
5013 // directive. Here we assume that the default construction of CXCursor
5014 // results in CXCursor.kind being an initialized value (i.e., 0). If
5015 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00005016
Ted Kremenek3f404602010-08-14 01:14:06 +00005017 CXCursor &oldC = Annotated[rawEncoding];
5018 if (!clang_isPreprocessing(oldC.kind))
5019 oldC = cursor;
5020 }
5021
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005022 const enum CXCursorKind K = clang_getCursorKind(parent);
5023 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00005024 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
5025 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005026
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005027 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005028
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00005029 // Avoid having the cursor of an expression "overwrite" the annotation of the
5030 // variable declaration that it belongs to.
5031 // This can happen for C++ constructor expressions whose range generally
5032 // include the variable declaration, e.g.:
5033 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
5034 if (clang_isExpression(cursorK)) {
5035 Expr *E = getCursorExpr(cursor);
Argyrios Kyrtzidis8ccac3d2011-06-29 22:20:07 +00005036 if (Decl *D = getCursorParentDecl(cursor)) {
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00005037 const unsigned I = NextToken();
5038 if (E->getLocStart().isValid() && D->getLocation().isValid() &&
5039 E->getLocStart() == D->getLocation() &&
5040 E->getLocStart() == GetTokenLoc(I)) {
5041 Cursors[I] = updateC;
5042 AdvanceToken();
5043 }
5044 }
5045 }
5046
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005047 // Visit children to get their cursor information.
5048 const unsigned BeforeChildren = NextToken();
5049 VisitChildren(cursor);
5050 const unsigned AfterChildren = NextToken();
5051
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005052 // Scan the tokens that are at the end of the cursor, but are not captured
5053 // but the child cursors.
5054 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
Ted Kremenek6db61092010-05-05 00:55:15 +00005055
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005056 // Scan the tokens that are at the beginning of the cursor, but are not
5057 // capture by the child cursors.
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005058 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
5059 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
5060 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00005061
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005062 Cursors[I] = cursor;
5063 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005064
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005065 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005066}
5067
Ted Kremenek6db61092010-05-05 00:55:15 +00005068static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
5069 CXCursor parent,
5070 CXClientData client_data) {
5071 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
5072}
5073
Ted Kremenek6628a612011-03-18 22:51:30 +00005074namespace {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005075
5076/// \brief Uses the macro expansions in the preprocessing record to find
5077/// and mark tokens that are macro arguments. This info is used by the
5078/// AnnotateTokensWorker.
5079class MarkMacroArgTokensVisitor {
5080 SourceManager &SM;
5081 CXToken *Tokens;
5082 unsigned NumTokens;
5083 unsigned CurIdx;
5084
5085public:
5086 MarkMacroArgTokensVisitor(SourceManager &SM,
5087 CXToken *tokens, unsigned numTokens)
5088 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
5089
5090 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
5091 if (cursor.kind != CXCursor_MacroExpansion)
5092 return CXChildVisit_Continue;
5093
5094 SourceRange macroRange = getCursorMacroExpansion(cursor)->getSourceRange();
5095 if (macroRange.getBegin() == macroRange.getEnd())
5096 return CXChildVisit_Continue; // it's not a function macro.
5097
5098 for (; CurIdx < NumTokens; ++CurIdx) {
5099 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
5100 macroRange.getBegin()))
5101 break;
5102 }
5103
5104 if (CurIdx == NumTokens)
5105 return CXChildVisit_Break;
5106
5107 for (; CurIdx < NumTokens; ++CurIdx) {
5108 SourceLocation tokLoc = getTokenLoc(CurIdx);
5109 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
5110 break;
5111
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00005112 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005113 }
5114
5115 if (CurIdx == NumTokens)
5116 return CXChildVisit_Break;
5117
5118 return CXChildVisit_Continue;
5119 }
5120
5121private:
5122 SourceLocation getTokenLoc(unsigned tokI) {
5123 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
5124 }
5125
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00005126 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005127 // The third field is reserved and currently not used. Use it here
5128 // to mark macro arg expanded tokens with their expanded locations.
5129 Tokens[tokI].int_data[3] = loc.getRawEncoding();
5130 }
5131};
5132
5133} // end anonymous namespace
5134
5135static CXChildVisitResult
5136MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
5137 CXClientData client_data) {
5138 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
5139 parent);
5140}
5141
5142namespace {
Ted Kremenek6628a612011-03-18 22:51:30 +00005143 struct clang_annotateTokens_Data {
5144 CXTranslationUnit TU;
5145 ASTUnit *CXXUnit;
5146 CXToken *Tokens;
5147 unsigned NumTokens;
5148 CXCursor *Cursors;
5149 };
5150}
5151
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005152static void annotatePreprocessorTokens(CXTranslationUnit TU,
5153 SourceRange RegionOfInterest,
5154 AnnotateTokensData &Annotated) {
5155 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
5156
5157 SourceManager &SourceMgr = CXXUnit->getSourceManager();
5158 std::pair<FileID, unsigned> BeginLocInfo
5159 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
5160 std::pair<FileID, unsigned> EndLocInfo
5161 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
5162
5163 if (BeginLocInfo.first != EndLocInfo.first)
5164 return;
5165
5166 StringRef Buffer;
5167 bool Invalid = false;
5168 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
5169 if (Buffer.empty() || Invalid)
5170 return;
5171
5172 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
David Blaikie4e4d0842012-03-11 07:00:24 +00005173 CXXUnit->getASTContext().getLangOpts(),
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005174 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
5175 Buffer.end());
5176 Lex.SetCommentRetentionState(true);
5177
5178 // Lex tokens in raw mode until we hit the end of the range, to avoid
5179 // entering #includes or expanding macros.
5180 while (true) {
5181 Token Tok;
5182 Lex.LexFromRawLexer(Tok);
5183
5184 reprocess:
5185 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
5186 // We have found a preprocessing directive. Gobble it up so that we
5187 // don't see it while preprocessing these tokens later, but keep track
5188 // of all of the token locations inside this preprocessing directive so
5189 // that we can annotate them appropriately.
5190 //
5191 // FIXME: Some simple tests here could identify macro definitions and
5192 // #undefs, to provide specific cursor kinds for those.
5193 SmallVector<SourceLocation, 32> Locations;
5194 do {
5195 Locations.push_back(Tok.getLocation());
5196 Lex.LexFromRawLexer(Tok);
5197 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
5198
5199 using namespace cxcursor;
5200 CXCursor Cursor
5201 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
5202 Locations.back()),
5203 TU);
5204 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
5205 Annotated[Locations[I].getRawEncoding()] = Cursor;
5206 }
5207
5208 if (Tok.isAtStartOfLine())
5209 goto reprocess;
5210
5211 continue;
5212 }
5213
5214 if (Tok.is(tok::eof))
5215 break;
5216 }
5217}
5218
Ted Kremenekab979612010-11-11 08:05:23 +00005219// This gets run a separate thread to avoid stack blowout.
Ted Kremenek6628a612011-03-18 22:51:30 +00005220static void clang_annotateTokensImpl(void *UserData) {
5221 CXTranslationUnit TU = ((clang_annotateTokens_Data*)UserData)->TU;
5222 ASTUnit *CXXUnit = ((clang_annotateTokens_Data*)UserData)->CXXUnit;
5223 CXToken *Tokens = ((clang_annotateTokens_Data*)UserData)->Tokens;
5224 const unsigned NumTokens = ((clang_annotateTokens_Data*)UserData)->NumTokens;
5225 CXCursor *Cursors = ((clang_annotateTokens_Data*)UserData)->Cursors;
5226
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00005227 CIndexer *CXXIdx = (CIndexer*)TU->CIdx;
5228 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
Argyrios Kyrtzidis81b5ac32012-03-28 02:49:54 +00005229 setThreadBackgroundPriority();
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00005230
Ted Kremenek6628a612011-03-18 22:51:30 +00005231 // Determine the region of interest, which contains all of the tokens.
5232 SourceRange RegionOfInterest;
5233 RegionOfInterest.setBegin(
5234 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
5235 RegionOfInterest.setEnd(
5236 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
5237 Tokens[NumTokens-1])));
5238
5239 // A mapping from the source locations found when re-lexing or traversing the
5240 // region of interest to the corresponding cursors.
5241 AnnotateTokensData Annotated;
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005242
Ted Kremenek6628a612011-03-18 22:51:30 +00005243 // Relex the tokens within the source range to look for preprocessing
5244 // directives.
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005245 annotatePreprocessorTokens(TU, RegionOfInterest, Annotated);
Ted Kremenek6628a612011-03-18 22:51:30 +00005246
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005247 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
5248 // Search and mark tokens that are macro argument expansions.
5249 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
5250 Tokens, NumTokens);
5251 CursorVisitor MacroArgMarker(TU,
5252 MarkMacroArgTokensVisitorDelegate, &Visitor,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00005253 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00005254 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00005255 RegionOfInterest);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005256 MacroArgMarker.visitPreprocessedEntitiesInRegion();
5257 }
5258
Ted Kremenek6628a612011-03-18 22:51:30 +00005259 // Annotate all of the source locations in the region of interest that map to
5260 // a specific cursor.
5261 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
5262 TU, RegionOfInterest);
5263
5264 // FIXME: We use a ridiculous stack size here because the data-recursion
5265 // algorithm uses a large stack frame than the non-data recursive version,
5266 // and AnnotationTokensWorker currently transforms the data-recursion
5267 // algorithm back into a traditional recursion by explicitly calling
5268 // VisitChildren(). We will need to remove this explicit recursive call.
5269 W.AnnotateTokens();
5270
5271 // If we ran into any entities that involve context-sensitive keywords,
5272 // take another pass through the tokens to mark them as such.
5273 if (W.hasContextSensitiveKeywords()) {
5274 for (unsigned I = 0; I != NumTokens; ++I) {
5275 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
5276 continue;
5277
5278 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
5279 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5280 if (ObjCPropertyDecl *Property
5281 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
5282 if (Property->getPropertyAttributesAsWritten() != 0 &&
5283 llvm::StringSwitch<bool>(II->getName())
5284 .Case("readonly", true)
5285 .Case("assign", true)
John McCallf85e1932011-06-15 23:02:42 +00005286 .Case("unsafe_unretained", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00005287 .Case("readwrite", true)
5288 .Case("retain", true)
5289 .Case("copy", true)
5290 .Case("nonatomic", true)
5291 .Case("atomic", true)
5292 .Case("getter", true)
5293 .Case("setter", true)
John McCallf85e1932011-06-15 23:02:42 +00005294 .Case("strong", true)
5295 .Case("weak", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00005296 .Default(false))
5297 Tokens[I].int_data[0] = CXToken_Keyword;
5298 }
5299 continue;
5300 }
5301
5302 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
5303 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
5304 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5305 if (llvm::StringSwitch<bool>(II->getName())
5306 .Case("in", true)
5307 .Case("out", true)
5308 .Case("inout", true)
5309 .Case("oneway", true)
5310 .Case("bycopy", true)
5311 .Case("byref", true)
5312 .Default(false))
5313 Tokens[I].int_data[0] = CXToken_Keyword;
5314 continue;
5315 }
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00005316
5317 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
5318 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
5319 Tokens[I].int_data[0] = CXToken_Keyword;
Ted Kremenek6628a612011-03-18 22:51:30 +00005320 continue;
5321 }
5322 }
5323 }
Ted Kremenekab979612010-11-11 08:05:23 +00005324}
5325
Ted Kremenek6db61092010-05-05 00:55:15 +00005326extern "C" {
5327
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005328void clang_annotateTokens(CXTranslationUnit TU,
5329 CXToken *Tokens, unsigned NumTokens,
5330 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005331
5332 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005333 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005334
Douglas Gregor4419b672010-10-21 06:10:04 +00005335 // Any token we don't specifically annotate will have a NULL cursor.
5336 CXCursor C = clang_getNullCursor();
5337 for (unsigned I = 0; I != NumTokens; ++I)
5338 Cursors[I] = C;
5339
Ted Kremeneka60ed472010-11-16 08:15:36 +00005340 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor4419b672010-10-21 06:10:04 +00005341 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005342 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005343
Douglas Gregorbdf60622010-03-05 21:16:25 +00005344 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenek6628a612011-03-18 22:51:30 +00005345
5346 clang_annotateTokens_Data data = { TU, CXXUnit, Tokens, NumTokens, Cursors };
Ted Kremenekab979612010-11-11 08:05:23 +00005347 llvm::CrashRecoveryContext CRC;
Ted Kremenek6628a612011-03-18 22:51:30 +00005348 if (!RunSafely(CRC, clang_annotateTokensImpl, &data,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005349 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00005350 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
5351 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005352}
Ted Kremenek6628a612011-03-18 22:51:30 +00005353
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005354} // end: extern "C"
5355
5356//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00005357// Operations for querying linkage of a cursor.
5358//===----------------------------------------------------------------------===//
5359
5360extern "C" {
5361CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00005362 if (!clang_isDeclaration(cursor.kind))
5363 return CXLinkage_Invalid;
5364
Ted Kremenek16b42592010-03-03 06:36:57 +00005365 Decl *D = cxcursor::getCursorDecl(cursor);
5366 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
5367 switch (ND->getLinkage()) {
5368 case NoLinkage: return CXLinkage_NoLinkage;
5369 case InternalLinkage: return CXLinkage_Internal;
5370 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
5371 case ExternalLinkage: return CXLinkage_External;
5372 };
5373
5374 return CXLinkage_Invalid;
5375}
5376} // end: extern "C"
5377
5378//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005379// Operations for querying language of a cursor.
5380//===----------------------------------------------------------------------===//
5381
5382static CXLanguageKind getDeclLanguage(const Decl *D) {
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00005383 if (!D)
5384 return CXLanguage_C;
5385
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005386 switch (D->getKind()) {
5387 default:
5388 break;
5389 case Decl::ImplicitParam:
5390 case Decl::ObjCAtDefsField:
5391 case Decl::ObjCCategory:
5392 case Decl::ObjCCategoryImpl:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005393 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005394 case Decl::ObjCImplementation:
5395 case Decl::ObjCInterface:
5396 case Decl::ObjCIvar:
5397 case Decl::ObjCMethod:
5398 case Decl::ObjCProperty:
5399 case Decl::ObjCPropertyImpl:
5400 case Decl::ObjCProtocol:
5401 return CXLanguage_ObjC;
5402 case Decl::CXXConstructor:
5403 case Decl::CXXConversion:
5404 case Decl::CXXDestructor:
5405 case Decl::CXXMethod:
5406 case Decl::CXXRecord:
5407 case Decl::ClassTemplate:
5408 case Decl::ClassTemplatePartialSpecialization:
5409 case Decl::ClassTemplateSpecialization:
5410 case Decl::Friend:
5411 case Decl::FriendTemplate:
5412 case Decl::FunctionTemplate:
5413 case Decl::LinkageSpec:
5414 case Decl::Namespace:
5415 case Decl::NamespaceAlias:
5416 case Decl::NonTypeTemplateParm:
5417 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005418 case Decl::TemplateTemplateParm:
5419 case Decl::TemplateTypeParm:
5420 case Decl::UnresolvedUsingTypename:
5421 case Decl::UnresolvedUsingValue:
5422 case Decl::Using:
5423 case Decl::UsingDirective:
5424 case Decl::UsingShadow:
5425 return CXLanguage_CPlusPlus;
5426 }
5427
5428 return CXLanguage_C;
5429}
5430
5431extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00005432
5433enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
5434 if (clang_isDeclaration(cursor.kind))
5435 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005436 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Douglas Gregor58ddb602010-08-23 23:00:57 +00005437 return CXAvailability_Available;
5438
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005439 switch (D->getAvailability()) {
5440 case AR_Available:
5441 case AR_NotYetIntroduced:
5442 return CXAvailability_Available;
5443
5444 case AR_Deprecated:
Douglas Gregor58ddb602010-08-23 23:00:57 +00005445 return CXAvailability_Deprecated;
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005446
5447 case AR_Unavailable:
5448 return CXAvailability_NotAvailable;
5449 }
Douglas Gregor58ddb602010-08-23 23:00:57 +00005450 }
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005451
Douglas Gregor58ddb602010-08-23 23:00:57 +00005452 return CXAvailability_Available;
5453}
5454
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005455CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
5456 if (clang_isDeclaration(cursor.kind))
5457 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
5458
5459 return CXLanguage_Invalid;
5460}
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005461
5462 /// \brief If the given cursor is the "templated" declaration
5463 /// descibing a class or function template, return the class or
5464 /// function template.
5465static Decl *maybeGetTemplateCursor(Decl *D) {
5466 if (!D)
5467 return 0;
5468
5469 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
5470 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
5471 return FunTmpl;
5472
5473 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
5474 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
5475 return ClassTmpl;
5476
5477 return D;
5478}
5479
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005480CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
5481 if (clang_isDeclaration(cursor.kind)) {
5482 if (Decl *D = getCursorDecl(cursor)) {
5483 DeclContext *DC = D->getDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005484 if (!DC)
5485 return clang_getNullCursor();
5486
5487 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5488 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005489 }
5490 }
5491
5492 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
5493 if (Decl *D = getCursorDecl(cursor))
Ted Kremeneka60ed472010-11-16 08:15:36 +00005494 return MakeCXCursor(D, getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005495 }
5496
5497 return clang_getNullCursor();
5498}
5499
5500CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
5501 if (clang_isDeclaration(cursor.kind)) {
5502 if (Decl *D = getCursorDecl(cursor)) {
5503 DeclContext *DC = D->getLexicalDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005504 if (!DC)
5505 return clang_getNullCursor();
5506
5507 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5508 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005509 }
5510 }
5511
5512 // FIXME: Note that we can't easily compute the lexical context of a
5513 // statement or expression, so we return nothing.
5514 return clang_getNullCursor();
5515}
5516
Douglas Gregor9f592342010-10-01 20:25:15 +00005517void clang_getOverriddenCursors(CXCursor cursor,
5518 CXCursor **overridden,
5519 unsigned *num_overridden) {
5520 if (overridden)
5521 *overridden = 0;
5522 if (num_overridden)
5523 *num_overridden = 0;
5524 if (!overridden || !num_overridden)
5525 return;
Argyrios Kyrtzidis15f4c982012-04-10 21:01:03 +00005526 if (!clang_isDeclaration(cursor.kind))
5527 return;
Douglas Gregor9f592342010-10-01 20:25:15 +00005528
Argyrios Kyrtzidisb11be042011-10-06 07:00:46 +00005529 SmallVector<CXCursor, 8> Overridden;
5530 cxcursor::getOverriddenCursors(cursor, Overridden);
Douglas Gregor9f592342010-10-01 20:25:15 +00005531
Ted Kremenek24077122011-11-14 23:51:37 +00005532 // Don't allocate memory if we have no overriden cursors.
5533 if (Overridden.size() == 0)
5534 return;
5535
Argyrios Kyrtzidisb11be042011-10-06 07:00:46 +00005536 *num_overridden = Overridden.size();
5537 *overridden = new CXCursor [Overridden.size()];
5538 std::copy(Overridden.begin(), Overridden.end(), *overridden);
Douglas Gregor9f592342010-10-01 20:25:15 +00005539}
5540
5541void clang_disposeOverriddenCursors(CXCursor *overridden) {
5542 delete [] overridden;
5543}
5544
Douglas Gregorecdcb882010-10-20 22:00:55 +00005545CXFile clang_getIncludedFile(CXCursor cursor) {
5546 if (cursor.kind != CXCursor_InclusionDirective)
5547 return 0;
5548
5549 InclusionDirective *ID = getCursorInclusionDirective(cursor);
5550 return (void *)ID->getFile();
5551}
5552
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005553} // end: extern "C"
5554
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005555
5556//===----------------------------------------------------------------------===//
5557// C++ AST instrospection.
5558//===----------------------------------------------------------------------===//
5559
5560extern "C" {
5561unsigned clang_CXXMethod_isStatic(CXCursor C) {
5562 if (!clang_isDeclaration(C.kind))
5563 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00005564
5565 CXXMethodDecl *Method = 0;
5566 Decl *D = cxcursor::getCursorDecl(C);
5567 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5568 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5569 else
5570 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5571 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00005572}
Ted Kremenekb12903e2010-05-18 22:32:15 +00005573
Douglas Gregor211924b2011-05-12 15:17:24 +00005574unsigned clang_CXXMethod_isVirtual(CXCursor C) {
5575 if (!clang_isDeclaration(C.kind))
5576 return 0;
5577
5578 CXXMethodDecl *Method = 0;
5579 Decl *D = cxcursor::getCursorDecl(C);
5580 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5581 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5582 else
5583 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5584 return (Method && Method->isVirtual()) ? 1 : 0;
5585}
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005586} // end: extern "C"
5587
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005588//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00005589// Attribute introspection.
5590//===----------------------------------------------------------------------===//
5591
5592extern "C" {
5593CXType clang_getIBOutletCollectionType(CXCursor C) {
5594 if (C.kind != CXCursor_IBOutletCollectionAttr)
Ted Kremeneka60ed472010-11-16 08:15:36 +00005595 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005596
5597 IBOutletCollectionAttr *A =
5598 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
5599
Argyrios Kyrtzidis18aa2ff2011-09-13 18:49:52 +00005600 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005601}
5602} // end: extern "C"
5603
5604//===----------------------------------------------------------------------===//
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005605// Inspecting memory usage.
5606//===----------------------------------------------------------------------===//
5607
Ted Kremenekf7870022011-04-20 16:41:07 +00005608typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005609
Ted Kremenekf7870022011-04-20 16:41:07 +00005610static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
5611 enum CXTUResourceUsageKind k,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005612 unsigned long amount) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005613 CXTUResourceUsageEntry entry = { k, amount };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005614 entries.push_back(entry);
5615}
5616
5617extern "C" {
5618
Ted Kremenekf7870022011-04-20 16:41:07 +00005619const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005620 const char *str = "";
5621 switch (kind) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005622 case CXTUResourceUsage_AST:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005623 str = "ASTContext: expressions, declarations, and types";
5624 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005625 case CXTUResourceUsage_Identifiers:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005626 str = "ASTContext: identifiers";
5627 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005628 case CXTUResourceUsage_Selectors:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005629 str = "ASTContext: selectors";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005630 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005631 case CXTUResourceUsage_GlobalCompletionResults:
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005632 str = "Code completion: cached global results";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005633 break;
Ted Kremenek457aaf02011-04-28 04:10:31 +00005634 case CXTUResourceUsage_SourceManagerContentCache:
5635 str = "SourceManager: content cache allocator";
5636 break;
Ted Kremenekba29bd22011-04-28 04:53:38 +00005637 case CXTUResourceUsage_AST_SideTables:
5638 str = "ASTContext: side tables";
5639 break;
Ted Kremenekf61b8312011-04-28 20:36:42 +00005640 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
5641 str = "SourceManager: malloc'ed memory buffers";
5642 break;
5643 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
5644 str = "SourceManager: mmap'ed memory buffers";
5645 break;
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005646 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
5647 str = "ExternalASTSource: malloc'ed memory buffers";
5648 break;
5649 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
5650 str = "ExternalASTSource: mmap'ed memory buffers";
5651 break;
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005652 case CXTUResourceUsage_Preprocessor:
5653 str = "Preprocessor: malloc'ed memory";
5654 break;
5655 case CXTUResourceUsage_PreprocessingRecord:
5656 str = "Preprocessor: PreprocessingRecord";
5657 break;
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005658 case CXTUResourceUsage_SourceManager_DataStructures:
5659 str = "SourceManager: data structures and tables";
5660 break;
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005661 case CXTUResourceUsage_Preprocessor_HeaderSearch:
5662 str = "Preprocessor: header search tables";
5663 break;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005664 }
5665 return str;
5666}
5667
Ted Kremenekf7870022011-04-20 16:41:07 +00005668CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005669 if (!TU) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005670 CXTUResourceUsage usage = { (void*) 0, 0, 0 };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005671 return usage;
5672 }
5673
5674 ASTUnit *astUnit = static_cast<ASTUnit*>(TU->TUData);
Dylan Noblesmith1e4c01b2012-02-13 12:32:21 +00005675 OwningPtr<MemUsageEntries> entries(new MemUsageEntries());
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005676 ASTContext &astContext = astUnit->getASTContext();
5677
5678 // How much memory is used by AST nodes and types?
Ted Kremenekf7870022011-04-20 16:41:07 +00005679 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005680 (unsigned long) astContext.getASTAllocatedMemory());
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005681
5682 // How much memory is used by identifiers?
Ted Kremenekf7870022011-04-20 16:41:07 +00005683 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005684 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
5685
5686 // How much memory is used for selectors?
Ted Kremenekf7870022011-04-20 16:41:07 +00005687 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005688 (unsigned long) astContext.Selectors.getTotalMemory());
5689
Ted Kremenekba29bd22011-04-28 04:53:38 +00005690 // How much memory is used by ASTContext's side tables?
5691 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
5692 (unsigned long) astContext.getSideTableAllocatedMemory());
5693
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005694 // How much memory is used for caching global code completion results?
5695 unsigned long completionBytes = 0;
5696 if (GlobalCodeCompletionAllocator *completionAllocator =
5697 astUnit->getCachedCompletionAllocator().getPtr()) {
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005698 completionBytes = completionAllocator->getTotalMemory();
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005699 }
Ted Kremenek457aaf02011-04-28 04:10:31 +00005700 createCXTUResourceUsageEntry(*entries,
5701 CXTUResourceUsage_GlobalCompletionResults,
5702 completionBytes);
5703
5704 // How much memory is being used by SourceManager's content cache?
5705 createCXTUResourceUsageEntry(*entries,
5706 CXTUResourceUsage_SourceManagerContentCache,
5707 (unsigned long) astContext.getSourceManager().getContentCacheSize());
Ted Kremenekf61b8312011-04-28 20:36:42 +00005708
5709 // How much memory is being used by the MemoryBuffer's in SourceManager?
5710 const SourceManager::MemoryBufferSizes &srcBufs =
5711 astUnit->getSourceManager().getMemoryBufferSizes();
5712
5713 createCXTUResourceUsageEntry(*entries,
5714 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
5715 (unsigned long) srcBufs.malloc_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005716 createCXTUResourceUsageEntry(*entries,
Ted Kremenekf61b8312011-04-28 20:36:42 +00005717 CXTUResourceUsage_SourceManager_Membuffer_MMap,
5718 (unsigned long) srcBufs.mmap_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005719 createCXTUResourceUsageEntry(*entries,
5720 CXTUResourceUsage_SourceManager_DataStructures,
5721 (unsigned long) astContext.getSourceManager()
5722 .getDataStructureSizes());
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005723
5724 // How much memory is being used by the ExternalASTSource?
5725 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
5726 const ExternalASTSource::MemoryBufferSizes &sizes =
5727 esrc->getMemoryBufferSizes();
5728
5729 createCXTUResourceUsageEntry(*entries,
5730 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
5731 (unsigned long) sizes.malloc_bytes);
5732 createCXTUResourceUsageEntry(*entries,
5733 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
5734 (unsigned long) sizes.mmap_bytes);
5735 }
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005736
5737 // How much memory is being used by the Preprocessor?
5738 Preprocessor &pp = astUnit->getPreprocessor();
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005739 createCXTUResourceUsageEntry(*entries,
5740 CXTUResourceUsage_Preprocessor,
Argyrios Kyrtzidisc5c5e922011-06-29 22:20:04 +00005741 pp.getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005742
5743 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
5744 createCXTUResourceUsageEntry(*entries,
5745 CXTUResourceUsage_PreprocessingRecord,
5746 pRec->getTotalMemory());
5747 }
5748
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005749 createCXTUResourceUsageEntry(*entries,
5750 CXTUResourceUsage_Preprocessor_HeaderSearch,
5751 pp.getHeaderSearchInfo().getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005752
Ted Kremenekf7870022011-04-20 16:41:07 +00005753 CXTUResourceUsage usage = { (void*) entries.get(),
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005754 (unsigned) entries->size(),
5755 entries->size() ? &(*entries)[0] : 0 };
5756 entries.take();
5757 return usage;
5758}
5759
Ted Kremenekf7870022011-04-20 16:41:07 +00005760void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005761 if (usage.data)
5762 delete (MemUsageEntries*) usage.data;
5763}
5764
5765} // end extern "C"
5766
Douglas Gregor6df78732011-05-05 20:27:22 +00005767void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
5768 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
5769 for (unsigned I = 0; I != Usage.numEntries; ++I)
5770 fprintf(stderr, " %s: %lu\n",
5771 clang_getTUResourceUsageName(Usage.entries[I].kind),
5772 Usage.entries[I].amount);
5773
5774 clang_disposeCXTUResourceUsage(Usage);
5775}
5776
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005777//===----------------------------------------------------------------------===//
Ted Kremenek04bb7162010-01-22 22:44:15 +00005778// Misc. utility functions.
5779//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00005780
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00005781/// Default to using an 8 MB stack size on "safety" threads.
5782static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005783
5784namespace clang {
5785
5786bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005787 void (*Fn)(void*), void *UserData,
5788 unsigned Size) {
5789 if (!Size)
5790 Size = GetSafetyThreadStackSize();
5791 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005792 return CRC.RunSafelyOnThread(Fn, UserData, Size);
5793 return CRC.RunSafely(Fn, UserData);
5794}
5795
5796unsigned GetSafetyThreadStackSize() {
5797 return SafetyStackThreadSize;
5798}
5799
5800void SetSafetyThreadStackSize(unsigned Value) {
5801 SafetyStackThreadSize = Value;
5802}
5803
Argyrios Kyrtzidis8e7c48a2012-03-28 02:49:50 +00005804}
5805
Argyrios Kyrtzidis81b5ac32012-03-28 02:49:54 +00005806void clang::setThreadBackgroundPriority() {
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00005807 // FIXME: Move to llvm/Support and make it cross-platform.
5808#ifdef __APPLE__
5809 setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG);
5810#endif
5811}
5812
Argyrios Kyrtzidis97934282012-04-11 03:52:18 +00005813void cxindex::printDiagsToStderr(ASTUnit *Unit) {
5814 if (!Unit)
5815 return;
5816
5817 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
5818 DEnd = Unit->stored_diag_end();
5819 D != DEnd; ++D) {
5820 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOpts());
5821 CXString Msg = clang_formatDiagnostic(&Diag,
5822 clang_defaultDiagnosticDisplayOptions());
5823 fprintf(stderr, "%s\n", clang_getCString(Msg));
5824 clang_disposeString(Msg);
5825 }
5826#ifdef LLVM_ON_WIN32
5827 // On Windows, force a flush, since there may be multiple copies of
5828 // stderr and stdout in the file system, all with different buffers
5829 // but writing to the same device.
5830 fflush(stderr);
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