blob: 605cc8bdee2647dec0e4ad9c9dd7ff7249038555 [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();
Argyrios Kyrtzidiseba8cd52012-04-11 18:15:01 +0000115 if (EndLoc.isValid() && EndLoc.isMacroID() && !SM.isMacroArgExpansion(EndLoc))
Chandler Carruthedc3dcc2011-07-25 16:56:02 +0000116 EndLoc = SM.getExpansionRange(EndLoc).second;
Argyrios Kyrtzidiseba8cd52012-04-11 18:15:01 +0000117 if (R.isTokenRange() && !EndLoc.isInvalid()) {
118 unsigned Length = Lexer::MeasureTokenLength(SM.getSpellingLoc(EndLoc),
119 SM, LangOpts);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000120 EndLoc = EndLoc.getLocWithOffset(Length);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000121 }
122
123 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
124 R.getBegin().getRawEncoding(),
125 EndLoc.getRawEncoding() };
126 return Result;
127}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000128
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000129//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000130// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000131//===----------------------------------------------------------------------===//
132
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000133static SourceRange getRawCursorExtent(CXCursor C);
Douglas Gregor66537982010-11-17 17:14:07 +0000134static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
135
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000136
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000137RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000138 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000139}
140
Douglas Gregorb1373d02010-01-20 20:59:29 +0000141/// \brief Visit the given cursor and, if requested by the visitor,
142/// its children.
143///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000144/// \param Cursor the cursor to visit.
145///
146/// \param CheckRegionOfInterest if true, then the caller already checked that
147/// this cursor is within the region of interest.
148///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000149/// \returns true if the visitation should be aborted, false if it
150/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000151bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000152 if (clang_isInvalid(Cursor.kind))
153 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000154
Douglas Gregorb1373d02010-01-20 20:59:29 +0000155 if (clang_isDeclaration(Cursor.kind)) {
156 Decl *D = getCursorDecl(Cursor);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +0000157 if (!D) {
158 assert(0 && "Invalid declaration cursor");
159 return true; // abort.
160 }
161
Argyrios Kyrtzidis65ab9072011-09-26 19:05:37 +0000162 // Ignore implicit declarations, unless it's an objc method because
163 // currently we should report implicit methods for properties when indexing.
164 if (D->isImplicit() && !isa<ObjCMethodDecl>(D))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000165 return false;
166 }
167
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000168 // If we have a range of interest, and this cursor doesn't intersect with it,
169 // we're done.
170 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000171 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000172 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000173 return false;
174 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000175
Douglas Gregorb1373d02010-01-20 20:59:29 +0000176 switch (Visitor(Cursor, Parent, ClientData)) {
177 case CXChildVisit_Break:
178 return true;
179
180 case CXChildVisit_Continue:
181 return false;
182
183 case CXChildVisit_Recurse:
184 return VisitChildren(Cursor);
185 }
186
David Blaikie7530c032012-01-17 06:56:22 +0000187 llvm_unreachable("Invalid CXChildVisitResult!");
Douglas Gregorb1373d02010-01-20 20:59:29 +0000188}
189
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000190static bool visitPreprocessedEntitiesInRange(SourceRange R,
191 PreprocessingRecord &PPRec,
192 CursorVisitor &Visitor) {
193 SourceManager &SM = Visitor.getASTUnit()->getSourceManager();
194 FileID FID;
195
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +0000196 if (!Visitor.shouldVisitIncludedEntities()) {
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000197 // If the begin/end of the range lie in the same FileID, do the optimization
198 // where we skip preprocessed entities that do not come from the same FileID.
Argyrios Kyrtzidisacca4112011-12-21 16:56:38 +0000199 FID = SM.getFileID(SM.getFileLoc(R.getBegin()));
200 if (FID != SM.getFileID(SM.getFileLoc(R.getEnd())))
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000201 FID = FileID();
202 }
203
204 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
205 Entities = PPRec.getPreprocessedEntitiesInRange(R);
206 return Visitor.visitPreprocessedEntities(Entities.first, Entities.second,
207 PPRec, FID);
208}
209
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000210void CursorVisitor::visitFileRegion() {
211 if (RegionOfInterest.isInvalid())
212 return;
213
214 ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData);
215 SourceManager &SM = Unit->getSourceManager();
216
217 std::pair<FileID, unsigned>
218 Begin = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getBegin())),
219 End = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getEnd()));
220
221 if (End.first != Begin.first) {
222 // If the end does not reside in the same file, try to recover by
223 // picking the end of the file of begin location.
224 End.first = Begin.first;
225 End.second = SM.getFileIDSize(Begin.first);
226 }
227
228 assert(Begin.first == End.first);
229 if (Begin.second > End.second)
230 return;
231
232 FileID File = Begin.first;
233 unsigned Offset = Begin.second;
234 unsigned Length = End.second - Begin.second;
235
Argyrios Kyrtzidisb49e7282011-11-29 03:14:11 +0000236 if (!VisitDeclsOnly && !VisitPreprocessorLast)
237 if (visitPreprocessedEntitiesInRegion())
238 return; // visitation break.
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000239
240 visitDeclsFromFileRegion(File, Offset, Length);
241
Argyrios Kyrtzidisb49e7282011-11-29 03:14:11 +0000242 if (!VisitDeclsOnly && VisitPreprocessorLast)
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000243 visitPreprocessedEntitiesInRegion();
244}
245
Argyrios Kyrtzidise2079cf2011-11-16 08:58:54 +0000246static bool isInLexicalContext(Decl *D, DeclContext *DC) {
247 if (!DC)
248 return false;
249
250 for (DeclContext *DeclDC = D->getLexicalDeclContext();
251 DeclDC; DeclDC = DeclDC->getLexicalParent()) {
252 if (DeclDC == DC)
253 return true;
254 }
255 return false;
256}
257
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000258void CursorVisitor::visitDeclsFromFileRegion(FileID File,
259 unsigned Offset, unsigned Length) {
260 ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData);
261 SourceManager &SM = Unit->getSourceManager();
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000262 SourceRange Range = RegionOfInterest;
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000263
264 SmallVector<Decl *, 16> Decls;
265 Unit->findFileRegionDecls(File, Offset, Length, Decls);
266
267 // If we didn't find any file level decls for the file, try looking at the
268 // file that it was included from.
Argyrios Kyrtzidisc14a03d2011-11-23 20:27:36 +0000269 while (Decls.empty() || Decls.front()->isTopLevelDeclInObjCContainer()) {
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000270 bool Invalid = false;
271 const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid);
272 if (Invalid)
273 return;
274
275 SourceLocation Outer;
276 if (SLEntry.isFile())
277 Outer = SLEntry.getFile().getIncludeLoc();
278 else
279 Outer = SLEntry.getExpansion().getExpansionLocStart();
280 if (Outer.isInvalid())
281 return;
282
283 llvm::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer);
284 Length = 0;
285 Unit->findFileRegionDecls(File, Offset, Length, Decls);
286 }
287
288 assert(!Decls.empty());
289
290 bool VisitedAtLeastOnce = false;
Argyrios Kyrtzidise2079cf2011-11-16 08:58:54 +0000291 DeclContext *CurDC = 0;
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000292 SmallVector<Decl *, 16>::iterator DIt = Decls.begin();
293 for (SmallVector<Decl *, 16>::iterator DE = Decls.end(); DIt != DE; ++DIt) {
294 Decl *D = *DIt;
Argyrios Kyrtzidised8bef42011-11-28 22:38:07 +0000295 if (D->getSourceRange().isInvalid())
296 continue;
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000297
Argyrios Kyrtzidise2079cf2011-11-16 08:58:54 +0000298 if (isInLexicalContext(D, CurDC))
299 continue;
300
301 CurDC = dyn_cast<DeclContext>(D);
302
Argyrios Kyrtzidise2079cf2011-11-16 08:58:54 +0000303 if (TagDecl *TD = dyn_cast<TagDecl>(D))
304 if (!TD->isFreeStanding())
305 continue;
306
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000307 RangeComparisonResult CompRes = RangeCompare(SM, D->getSourceRange(),Range);
308 if (CompRes == RangeBefore)
309 continue;
310 if (CompRes == RangeAfter)
311 break;
312
313 assert(CompRes == RangeOverlap);
314 VisitedAtLeastOnce = true;
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +0000315
316 if (isa<ObjCContainerDecl>(D)) {
317 FileDI_current = &DIt;
318 FileDE_current = DE;
319 } else {
320 FileDI_current = 0;
321 }
322
Argyrios Kyrtzidisba986172011-11-03 19:02:28 +0000323 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000324 break;
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000325 }
326
327 if (VisitedAtLeastOnce)
328 return;
329
330 // No Decls overlapped with the range. Move up the lexical context until there
331 // is a context that contains the range or we reach the translation unit
332 // level.
333 DeclContext *DC = DIt == Decls.begin() ? (*DIt)->getLexicalDeclContext()
334 : (*(DIt-1))->getLexicalDeclContext();
335
336 while (DC && !DC->isTranslationUnit()) {
337 Decl *D = cast<Decl>(DC);
338 SourceRange CurDeclRange = D->getSourceRange();
339 if (CurDeclRange.isInvalid())
340 break;
341
342 if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) {
Argyrios Kyrtzidisba986172011-11-03 19:02:28 +0000343 Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true);
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000344 break;
345 }
346
347 DC = D->getLexicalDeclContext();
348 }
349}
350
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000351bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
Argyrios Kyrtzidisb49e7282011-11-29 03:14:11 +0000352 if (!AU->getPreprocessor().getPreprocessingRecord())
353 return false;
354
Douglas Gregor788f5a12010-03-20 00:41:21 +0000355 PreprocessingRecord &PPRec
Ted Kremeneka60ed472010-11-16 08:15:36 +0000356 = *AU->getPreprocessor().getPreprocessingRecord();
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000357 SourceManager &SM = AU->getSourceManager();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000358
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000359 if (RegionOfInterest.isValid()) {
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +0000360 SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000361 SourceLocation B = MappedRange.getBegin();
362 SourceLocation E = MappedRange.getEnd();
363
364 if (AU->isInPreambleFileID(B)) {
365 if (SM.isLoadedSourceLocation(E))
366 return visitPreprocessedEntitiesInRange(SourceRange(B, E),
367 PPRec, *this);
368
369 // Beginning of range lies in the preamble but it also extends beyond
370 // it into the main file. Split the range into 2 parts, one covering
371 // the preamble and another covering the main file. This allows subsequent
372 // calls to visitPreprocessedEntitiesInRange to accept a source range that
373 // lies in the same FileID, allowing it to skip preprocessed entities that
374 // do not come from the same FileID.
375 bool breaked =
376 visitPreprocessedEntitiesInRange(
377 SourceRange(B, AU->getEndOfPreambleFileID()),
378 PPRec, *this);
379 if (breaked) return true;
380 return visitPreprocessedEntitiesInRange(
381 SourceRange(AU->getStartOfMainFileID(), E),
382 PPRec, *this);
383 }
384
385 return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this);
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000386 }
387
Douglas Gregor788f5a12010-03-20 00:41:21 +0000388 bool OnlyLocalDecls
Douglas Gregor32038bb2010-12-21 19:07:48 +0000389 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
390
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000391 if (OnlyLocalDecls)
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000392 return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(),
393 PPRec);
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000394
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000395 return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec);
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000396}
397
398template<typename InputIterator>
399bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000400 InputIterator Last,
401 PreprocessingRecord &PPRec,
402 FileID FID) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000403 for (; First != Last; ++First) {
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000404 if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID))
405 continue;
406
407 PreprocessedEntity *PPE = *First;
408 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000409 if (Visit(MakeMacroExpansionCursor(ME, TU)))
410 return true;
411
412 continue;
413 }
414
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000415 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(PPE)) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000416 if (Visit(MakeMacroDefinitionCursor(MD, TU)))
417 return true;
418
419 continue;
420 }
421
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000422 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000423 if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
424 return true;
425
426 continue;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000427 }
428 }
429
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000430 return false;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000431}
432
Douglas Gregorb1373d02010-01-20 20:59:29 +0000433/// \brief Visit the children of the given cursor.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000434///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000435/// \returns true if the visitation should be aborted, false if it
436/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000437bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregorc314aa42011-03-02 19:17:03 +0000438 if (clang_isReference(Cursor.kind) &&
439 Cursor.kind != CXCursor_CXXBaseSpecifier) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000440 // By definition, references have no children.
441 return false;
442 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000443
444 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000445 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000446 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000447
Douglas Gregorb1373d02010-01-20 20:59:29 +0000448 if (clang_isDeclaration(Cursor.kind)) {
449 Decl *D = getCursorDecl(Cursor);
Douglas Gregor06d9b1a2011-04-14 21:41:34 +0000450 if (!D)
451 return false;
452
Ted Kremenek539311e2010-02-18 18:47:01 +0000453 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000454 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000455
Douglas Gregor06d9b1a2011-04-14 21:41:34 +0000456 if (clang_isStatement(Cursor.kind)) {
457 if (Stmt *S = getCursorStmt(Cursor))
458 return Visit(S);
459
460 return false;
461 }
462
463 if (clang_isExpression(Cursor.kind)) {
464 if (Expr *E = getCursorExpr(Cursor))
465 return Visit(E);
466
467 return false;
468 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000469
Douglas Gregorb1373d02010-01-20 20:59:29 +0000470 if (clang_isTranslationUnit(Cursor.kind)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000471 CXTranslationUnit tu = getCursorTU(Cursor);
472 ASTUnit *CXXUnit = static_cast<ASTUnit*>(tu->TUData);
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000473
474 int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
475 for (unsigned I = 0; I != 2; ++I) {
476 if (VisitOrder[I]) {
477 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
478 RegionOfInterest.isInvalid()) {
479 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
480 TLEnd = CXXUnit->top_level_end();
481 TL != TLEnd; ++TL) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000482 if (Visit(MakeCXCursor(*TL, tu, RegionOfInterest), true))
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000483 return true;
484 }
485 } else if (VisitDeclContext(
486 CXXUnit->getASTContext().getTranslationUnitDecl()))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000487 return true;
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000488 continue;
Douglas Gregor7b691f332010-01-20 21:13:59 +0000489 }
Bob Wilson3178cb62010-03-19 03:57:57 +0000490
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000491 // Walk the preprocessing record.
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000492 if (CXXUnit->getPreprocessor().getPreprocessingRecord())
493 visitPreprocessedEntitiesInRegion();
Douglas Gregor0396f462010-03-19 05:22:59 +0000494 }
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000495
Douglas Gregor7b691f332010-01-20 21:13:59 +0000496 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000497 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000498
Douglas Gregorc314aa42011-03-02 19:17:03 +0000499 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
500 if (CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
501 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
502 return Visit(BaseTSInfo->getTypeLoc());
503 }
504 }
505 }
Argyrios Kyrtzidis221d5a52011-09-13 18:49:56 +0000506
507 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
508 IBOutletCollectionAttr *A =
509 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
510 if (const ObjCInterfaceType *InterT = A->getInterface()->getAs<ObjCInterfaceType>())
511 return Visit(cxcursor::MakeCursorObjCClassRef(InterT->getInterface(),
512 A->getInterfaceLoc(), TU));
513 }
514
Douglas Gregorb1373d02010-01-20 20:59:29 +0000515 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000516 return false;
517}
518
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000519bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
Douglas Gregor13c8ccb2011-04-22 23:49:24 +0000520 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
521 if (Visit(TSInfo->getTypeLoc()))
522 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000523
Ted Kremenek664cffd2010-07-22 11:30:19 +0000524 if (Stmt *Body = B->getBody())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000525 return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest));
Ted Kremenek664cffd2010-07-22 11:30:19 +0000526
527 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000528}
529
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000530llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
531 if (RegionOfInterest.isValid()) {
Douglas Gregor66537982010-11-17 17:14:07 +0000532 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000533 if (Range.isInvalid())
534 return llvm::Optional<bool>();
Douglas Gregor66537982010-11-17 17:14:07 +0000535
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000536 switch (CompareRegionOfInterest(Range)) {
537 case RangeBefore:
538 // This declaration comes before the region of interest; skip it.
539 return llvm::Optional<bool>();
540
541 case RangeAfter:
542 // This declaration comes after the region of interest; we're done.
543 return false;
544
545 case RangeOverlap:
546 // This declaration overlaps the region of interest; visit it.
547 break;
548 }
549 }
550 return true;
551}
552
553bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
554 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
555
556 // FIXME: Eventually remove. This part of a hack to support proper
557 // iteration over all Decls contained lexically within an ObjC container.
558 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
559 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
560
561 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000562 Decl *D = *I;
563 if (D->getLexicalDeclContext() != DC)
564 continue;
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000565 CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
Argyrios Kyrtzidis1836db02012-02-04 01:04:58 +0000566
567 // FIXME: ObjCClassRef/ObjCProtocolRef for forward class/protocol
568 // declarations is a mismatch with the compiler semantics.
569 if (Cursor.kind == CXCursor_ObjCInterfaceDecl) {
570 ObjCInterfaceDecl *ID = cast<ObjCInterfaceDecl>(D);
571 if (!ID->isThisDeclarationADefinition())
572 Cursor = MakeCursorObjCClassRef(ID, ID->getLocation(), TU);
573
574 } else if (Cursor.kind == CXCursor_ObjCProtocolDecl) {
575 ObjCProtocolDecl *PD = cast<ObjCProtocolDecl>(D);
576 if (!PD->isThisDeclarationADefinition())
577 Cursor = MakeCursorObjCProtocolRef(PD, PD->getLocation(), TU);
578 }
579
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000580 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
581 if (!V.hasValue())
582 continue;
583 if (!V.getValue())
584 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000585 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000586 return true;
587 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000588 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000589}
590
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000591bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
592 llvm_unreachable("Translation units are visited directly by Visit()");
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000593}
594
Richard Smith162e1c12011-04-15 14:24:37 +0000595bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
596 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
597 return Visit(TSInfo->getTypeLoc());
598
599 return false;
600}
601
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000602bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
603 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
604 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000605
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000606 return false;
607}
608
609bool CursorVisitor::VisitTagDecl(TagDecl *D) {
610 return VisitDeclContext(D);
611}
612
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000613bool CursorVisitor::VisitClassTemplateSpecializationDecl(
614 ClassTemplateSpecializationDecl *D) {
615 bool ShouldVisitBody = false;
616 switch (D->getSpecializationKind()) {
617 case TSK_Undeclared:
618 case TSK_ImplicitInstantiation:
619 // Nothing to visit
620 return false;
621
622 case TSK_ExplicitInstantiationDeclaration:
623 case TSK_ExplicitInstantiationDefinition:
624 break;
625
626 case TSK_ExplicitSpecialization:
627 ShouldVisitBody = true;
628 break;
629 }
630
631 // Visit the template arguments used in the specialization.
632 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
633 TypeLoc TL = SpecType->getTypeLoc();
634 if (TemplateSpecializationTypeLoc *TSTLoc
635 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
636 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
637 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
638 return true;
639 }
640 }
641
642 if (ShouldVisitBody && VisitCXXRecordDecl(D))
643 return true;
644
645 return false;
646}
647
Douglas Gregor74dbe642010-08-31 19:31:58 +0000648bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
649 ClassTemplatePartialSpecializationDecl *D) {
650 // FIXME: Visit the "outer" template parameter lists on the TagDecl
651 // before visiting these template parameters.
652 if (VisitTemplateParameters(D->getTemplateParameters()))
653 return true;
654
655 // Visit the partial specialization arguments.
656 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
657 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
658 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
659 return true;
660
661 return VisitCXXRecordDecl(D);
662}
663
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000664bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000665 // Visit the default argument.
666 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
667 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
668 if (Visit(DefArg->getTypeLoc()))
669 return true;
670
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000671 return false;
672}
673
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000674bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
675 if (Expr *Init = D->getInitExpr())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000676 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000677 return false;
678}
679
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000680bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
681 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
682 if (Visit(TSInfo->getTypeLoc()))
683 return true;
684
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000685 // Visit the nested-name-specifier, if present.
686 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
687 if (VisitNestedNameSpecifierLoc(QualifierLoc))
688 return true;
689
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000690 return false;
691}
692
Douglas Gregora67e03f2010-09-09 21:42:20 +0000693/// \brief Compare two base or member initializers based on their source order.
Sean Huntcbb67482011-01-08 20:30:50 +0000694static int CompareCXXCtorInitializers(const void* Xp, const void *Yp) {
695 CXXCtorInitializer const * const *X
696 = static_cast<CXXCtorInitializer const * const *>(Xp);
697 CXXCtorInitializer const * const *Y
698 = static_cast<CXXCtorInitializer const * const *>(Yp);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000699
700 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
701 return -1;
702 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
703 return 1;
704 else
705 return 0;
706}
707
Douglas Gregorb1373d02010-01-20 20:59:29 +0000708bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000709 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
710 // Visit the function declaration's syntactic components in the order
711 // written. This requires a bit of work.
Abramo Bagnara723df242010-12-14 22:11:44 +0000712 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
Douglas Gregor01829d32010-08-31 14:41:23 +0000713 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
714
715 // If we have a function declared directly (without the use of a typedef),
716 // visit just the return type. Otherwise, just visit the function's type
717 // now.
718 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
719 (!FTL && Visit(TL)))
720 return true;
721
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000722 // Visit the nested-name-specifier, if present.
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000723 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
724 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000725 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000726
727 // Visit the declaration name.
728 if (VisitDeclarationNameInfo(ND->getNameInfo()))
729 return true;
730
731 // FIXME: Visit explicitly-specified template arguments!
732
733 // Visit the function parameters, if we have a function type.
734 if (FTL && VisitFunctionTypeLoc(*FTL, true))
735 return true;
736
737 // FIXME: Attributes?
738 }
739
Sean Hunt10620eb2011-05-06 20:44:56 +0000740 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
Douglas Gregora67e03f2010-09-09 21:42:20 +0000741 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
742 // Find the initializers that were written in the source.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000743 SmallVector<CXXCtorInitializer *, 4> WrittenInits;
Douglas Gregora67e03f2010-09-09 21:42:20 +0000744 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
745 IEnd = Constructor->init_end();
746 I != IEnd; ++I) {
747 if (!(*I)->isWritten())
748 continue;
749
750 WrittenInits.push_back(*I);
751 }
752
753 // Sort the initializers in source order
754 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
Sean Huntcbb67482011-01-08 20:30:50 +0000755 &CompareCXXCtorInitializers);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000756
757 // Visit the initializers in source order
758 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
Sean Huntcbb67482011-01-08 20:30:50 +0000759 CXXCtorInitializer *Init = WrittenInits[I];
Francois Pichet00eb3f92010-12-04 09:14:42 +0000760 if (Init->isAnyMemberInitializer()) {
761 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
Douglas Gregora67e03f2010-09-09 21:42:20 +0000762 Init->getMemberLocation(), TU)))
763 return true;
Douglas Gregor76852c22011-11-01 01:16:03 +0000764 } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) {
765 if (Visit(TInfo->getTypeLoc()))
Douglas Gregora67e03f2010-09-09 21:42:20 +0000766 return true;
767 }
768
769 // Visit the initializer value.
770 if (Expr *Initializer = Init->getInit())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000771 if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
Douglas Gregora67e03f2010-09-09 21:42:20 +0000772 return true;
773 }
774 }
775
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000776 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
Douglas Gregora67e03f2010-09-09 21:42:20 +0000777 return true;
778 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000779
Douglas Gregorb1373d02010-01-20 20:59:29 +0000780 return false;
781}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000782
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000783bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
784 if (VisitDeclaratorDecl(D))
785 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000786
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000787 if (Expr *BitWidth = D->getBitWidth())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000788 return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000789
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000790 return false;
791}
792
793bool CursorVisitor::VisitVarDecl(VarDecl *D) {
794 if (VisitDeclaratorDecl(D))
795 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000796
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000797 if (Expr *Init = D->getInit())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000798 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000799
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000800 return false;
801}
802
Douglas Gregor84b51d72010-09-01 20:16:53 +0000803bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
804 if (VisitDeclaratorDecl(D))
805 return true;
806
807 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
808 if (Expr *DefArg = D->getDefaultArgument())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000809 return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
Douglas Gregor84b51d72010-09-01 20:16:53 +0000810
811 return false;
812}
813
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000814bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
815 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
816 // before visiting these template parameters.
817 if (VisitTemplateParameters(D->getTemplateParameters()))
818 return true;
819
820 return VisitFunctionDecl(D->getTemplatedDecl());
821}
822
Douglas Gregor39d6f072010-08-31 19:02:00 +0000823bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
824 // FIXME: Visit the "outer" template parameter lists on the TagDecl
825 // before visiting these template parameters.
826 if (VisitTemplateParameters(D->getTemplateParameters()))
827 return true;
828
829 return VisitCXXRecordDecl(D->getTemplatedDecl());
830}
831
Douglas Gregor84b51d72010-09-01 20:16:53 +0000832bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
833 if (VisitTemplateParameters(D->getTemplateParameters()))
834 return true;
835
836 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
837 VisitTemplateArgumentLoc(D->getDefaultArgument()))
838 return true;
839
840 return false;
841}
842
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000843bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000844 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
845 if (Visit(TSInfo->getTypeLoc()))
846 return true;
847
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000848 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000849 PEnd = ND->param_end();
850 P != PEnd; ++P) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000851 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000852 return true;
853 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000854
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000855 if (ND->isThisDeclarationADefinition() &&
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000856 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000857 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000858
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000859 return false;
860}
861
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +0000862template <typename DeclIt>
863static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current,
864 SourceManager &SM, SourceLocation EndLoc,
865 SmallVectorImpl<Decl *> &Decls) {
866 DeclIt next = *DI_current;
867 while (++next != DE_current) {
868 Decl *D_next = *next;
869 if (!D_next)
870 break;
871 SourceLocation L = D_next->getLocStart();
872 if (!L.isValid())
873 break;
874 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
875 *DI_current = next;
876 Decls.push_back(D_next);
877 continue;
878 }
879 break;
880 }
881}
882
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000883namespace {
884 struct ContainerDeclsSort {
885 SourceManager &SM;
886 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
887 bool operator()(Decl *A, Decl *B) {
888 SourceLocation L_A = A->getLocStart();
889 SourceLocation L_B = B->getLocStart();
890 assert(L_A.isValid() && L_B.isValid());
891 return SM.isBeforeInTranslationUnit(L_A, L_B);
892 }
893 };
894}
895
Douglas Gregora59e3902010-01-21 23:27:09 +0000896bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000897 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
898 // an @implementation can lexically contain Decls that are not properly
899 // nested in the AST. When we identify such cases, we need to retrofit
900 // this nesting here.
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +0000901 if (!DI_current && !FileDI_current)
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000902 return VisitDeclContext(D);
903
904 // Scan the Decls that immediately come after the container
905 // in the current DeclContext. If any fall within the
906 // container's lexical region, stash them into a vector
907 // for later processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000908 SmallVector<Decl *, 24> DeclsInContainer;
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000909 SourceLocation EndLoc = D->getSourceRange().getEnd();
Ted Kremeneka60ed472010-11-16 08:15:36 +0000910 SourceManager &SM = AU->getSourceManager();
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000911 if (EndLoc.isValid()) {
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +0000912 if (DI_current) {
913 addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc,
914 DeclsInContainer);
915 } else {
916 addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc,
917 DeclsInContainer);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000918 }
919 }
920
921 // The common case.
922 if (DeclsInContainer.empty())
923 return VisitDeclContext(D);
924
925 // Get all the Decls in the DeclContext, and sort them with the
926 // additional ones we've collected. Then visit them.
927 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
928 I!=E; ++I) {
929 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000930 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
931 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000932 continue;
933 DeclsInContainer.push_back(subDecl);
934 }
935
936 // Now sort the Decls so that they appear in lexical order.
937 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
938 ContainerDeclsSort(SM));
939
940 // Now visit the decls.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000941 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000942 E = DeclsInContainer.end(); I != E; ++I) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000943 CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000944 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
945 if (!V.hasValue())
946 continue;
947 if (!V.getValue())
948 return false;
949 if (Visit(Cursor, true))
950 return true;
951 }
952 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000953}
954
Douglas Gregorb1373d02010-01-20 20:59:29 +0000955bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000956 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
957 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000958 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000959
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000960 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
961 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
962 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000963 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000964 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000965
Douglas Gregora59e3902010-01-21 23:27:09 +0000966 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000967}
968
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000969bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000970 if (!PID->isThisDeclarationADefinition())
971 return Visit(MakeCursorObjCProtocolRef(PID, PID->getLocation(), TU));
972
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000973 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
974 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
975 E = PID->protocol_end(); I != E; ++I, ++PL)
976 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
977 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000978
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000979 return VisitObjCContainerDecl(PID);
980}
981
Ted Kremenek23173d72010-05-18 21:09:07 +0000982bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000983 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000984 return true;
985
Ted Kremenek23173d72010-05-18 21:09:07 +0000986 // FIXME: This implements a workaround with @property declarations also being
987 // installed in the DeclContext for the @interface. Eventually this code
988 // should be removed.
989 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
990 if (!CDecl || !CDecl->IsClassExtension())
991 return false;
992
993 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
994 if (!ID)
995 return false;
996
997 IdentifierInfo *PropertyId = PD->getIdentifier();
998 ObjCPropertyDecl *prevDecl =
999 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
1000
1001 if (!prevDecl)
1002 return false;
1003
1004 // Visit synthesized methods since they will be skipped when visiting
1005 // the @interface.
1006 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +00001007 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001008 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
Ted Kremenek23173d72010-05-18 21:09:07 +00001009 return true;
1010
1011 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +00001012 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001013 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
Ted Kremenek23173d72010-05-18 21:09:07 +00001014 return true;
1015
1016 return false;
1017}
1018
Douglas Gregorb1373d02010-01-20 20:59:29 +00001019bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Douglas Gregor375bb142011-12-27 22:43:10 +00001020 if (!D->isThisDeclarationADefinition()) {
1021 // Forward declaration is treated like a reference.
1022 return Visit(MakeCursorObjCClassRef(D, D->getLocation(), TU));
1023 }
1024
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001025 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +00001026 if (D->getSuperClass() &&
1027 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001028 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001029 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001030 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001031
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001032 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1033 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1034 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001035 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001036 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001037
Douglas Gregora59e3902010-01-21 23:27:09 +00001038 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001039}
1040
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001041bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1042 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001043}
1044
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001045bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +00001046 // 'ID' could be null when dealing with invalid code.
1047 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1048 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1049 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001050
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001051 return VisitObjCImplDecl(D);
1052}
1053
1054bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1055#if 0
1056 // Issue callbacks for super class.
1057 // FIXME: No source location information!
1058 if (D->getSuperClass() &&
1059 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001060 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001061 TU)))
1062 return true;
1063#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001064
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001065 return VisitObjCImplDecl(D);
1066}
1067
Douglas Gregora4ffd852010-11-17 01:03:52 +00001068bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1069 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1070 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1071
1072 return false;
1073}
1074
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001075bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1076 return VisitDeclContext(D);
1077}
1078
Douglas Gregor69319002010-08-31 23:48:11 +00001079bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001080 // Visit nested-name-specifier.
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00001081 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1082 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001083 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001084
1085 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1086 D->getTargetNameLoc(), TU));
1087}
1088
Douglas Gregor7e242562010-09-01 19:52:22 +00001089bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001090 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001091 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1092 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001093 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001094 }
Douglas Gregor7e242562010-09-01 19:52:22 +00001095
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001096 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1097 return true;
1098
Douglas Gregor7e242562010-09-01 19:52:22 +00001099 return VisitDeclarationNameInfo(D->getNameInfo());
1100}
1101
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001102bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001103 // Visit nested-name-specifier.
Douglas Gregordb992412011-02-25 16:33:46 +00001104 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1105 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001106 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001107
1108 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1109 D->getIdentLocation(), TU));
1110}
1111
Douglas Gregor7e242562010-09-01 19:52:22 +00001112bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001113 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001114 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1115 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001116 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001117 }
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001118
Douglas Gregor7e242562010-09-01 19:52:22 +00001119 return VisitDeclarationNameInfo(D->getNameInfo());
1120}
1121
1122bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1123 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001124 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001125 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1126 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001127 return true;
1128
Douglas Gregor7e242562010-09-01 19:52:22 +00001129 return false;
1130}
1131
Douglas Gregor01829d32010-08-31 14:41:23 +00001132bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1133 switch (Name.getName().getNameKind()) {
1134 case clang::DeclarationName::Identifier:
1135 case clang::DeclarationName::CXXLiteralOperatorName:
1136 case clang::DeclarationName::CXXOperatorName:
1137 case clang::DeclarationName::CXXUsingDirective:
1138 return false;
1139
1140 case clang::DeclarationName::CXXConstructorName:
1141 case clang::DeclarationName::CXXDestructorName:
1142 case clang::DeclarationName::CXXConversionFunctionName:
1143 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1144 return Visit(TSInfo->getTypeLoc());
1145 return false;
1146
1147 case clang::DeclarationName::ObjCZeroArgSelector:
1148 case clang::DeclarationName::ObjCOneArgSelector:
1149 case clang::DeclarationName::ObjCMultiArgSelector:
1150 // FIXME: Per-identifier location info?
1151 return false;
1152 }
David Blaikie7530c032012-01-17 06:56:22 +00001153
1154 llvm_unreachable("Invalid DeclarationName::Kind!");
Douglas Gregor01829d32010-08-31 14:41:23 +00001155}
1156
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001157bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1158 SourceRange Range) {
1159 // FIXME: This whole routine is a hack to work around the lack of proper
1160 // source information in nested-name-specifiers (PR5791). Since we do have
1161 // a beginning source location, we can visit the first component of the
1162 // nested-name-specifier, if it's a single-token component.
1163 if (!NNS)
1164 return false;
1165
1166 // Get the first component in the nested-name-specifier.
1167 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1168 NNS = Prefix;
1169
1170 switch (NNS->getKind()) {
1171 case NestedNameSpecifier::Namespace:
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001172 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1173 TU));
1174
Douglas Gregor14aba762011-02-24 02:36:08 +00001175 case NestedNameSpecifier::NamespaceAlias:
1176 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1177 Range.getBegin(), TU));
1178
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001179 case NestedNameSpecifier::TypeSpec: {
1180 // If the type has a form where we know that the beginning of the source
1181 // range matches up with a reference cursor. Visit the appropriate reference
1182 // cursor.
John McCallf4c73712011-01-19 06:33:43 +00001183 const Type *T = NNS->getAsType();
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001184 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1185 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1186 if (const TagType *Tag = dyn_cast<TagType>(T))
1187 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1188 if (const TemplateSpecializationType *TST
1189 = dyn_cast<TemplateSpecializationType>(T))
1190 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1191 break;
1192 }
1193
1194 case NestedNameSpecifier::TypeSpecWithTemplate:
1195 case NestedNameSpecifier::Global:
1196 case NestedNameSpecifier::Identifier:
1197 break;
1198 }
1199
1200 return false;
1201}
1202
Douglas Gregordc355712011-02-25 00:36:19 +00001203bool
1204CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001205 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
Douglas Gregordc355712011-02-25 00:36:19 +00001206 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1207 Qualifiers.push_back(Qualifier);
1208
1209 while (!Qualifiers.empty()) {
1210 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1211 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1212 switch (NNS->getKind()) {
1213 case NestedNameSpecifier::Namespace:
1214 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001215 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001216 TU)))
1217 return true;
1218
1219 break;
1220
1221 case NestedNameSpecifier::NamespaceAlias:
1222 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001223 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001224 TU)))
1225 return true;
1226
1227 break;
1228
1229 case NestedNameSpecifier::TypeSpec:
1230 case NestedNameSpecifier::TypeSpecWithTemplate:
1231 if (Visit(Q.getTypeLoc()))
1232 return true;
1233
1234 break;
1235
1236 case NestedNameSpecifier::Global:
1237 case NestedNameSpecifier::Identifier:
1238 break;
1239 }
1240 }
1241
1242 return false;
1243}
1244
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001245bool CursorVisitor::VisitTemplateParameters(
1246 const TemplateParameterList *Params) {
1247 if (!Params)
1248 return false;
1249
1250 for (TemplateParameterList::const_iterator P = Params->begin(),
1251 PEnd = Params->end();
1252 P != PEnd; ++P) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001253 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001254 return true;
1255 }
1256
1257 return false;
1258}
1259
Douglas Gregor0b36e612010-08-31 20:37:03 +00001260bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1261 switch (Name.getKind()) {
1262 case TemplateName::Template:
1263 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1264
1265 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001266 // Visit the overloaded template set.
1267 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1268 return true;
1269
Douglas Gregor0b36e612010-08-31 20:37:03 +00001270 return false;
1271
1272 case TemplateName::DependentTemplate:
1273 // FIXME: Visit nested-name-specifier.
1274 return false;
1275
1276 case TemplateName::QualifiedTemplate:
1277 // FIXME: Visit nested-name-specifier.
1278 return Visit(MakeCursorTemplateRef(
1279 Name.getAsQualifiedTemplateName()->getDecl(),
1280 Loc, TU));
John McCall14606042011-06-30 08:33:18 +00001281
1282 case TemplateName::SubstTemplateTemplateParm:
1283 return Visit(MakeCursorTemplateRef(
1284 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1285 Loc, TU));
Douglas Gregor1aee05d2011-01-15 06:45:20 +00001286
1287 case TemplateName::SubstTemplateTemplateParmPack:
1288 return Visit(MakeCursorTemplateRef(
1289 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1290 Loc, TU));
Douglas Gregor0b36e612010-08-31 20:37:03 +00001291 }
David Blaikie7530c032012-01-17 06:56:22 +00001292
1293 llvm_unreachable("Invalid TemplateName::Kind!");
Douglas Gregor0b36e612010-08-31 20:37:03 +00001294}
1295
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001296bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1297 switch (TAL.getArgument().getKind()) {
1298 case TemplateArgument::Null:
1299 case TemplateArgument::Integral:
Douglas Gregor87dd6972010-12-20 16:52:59 +00001300 case TemplateArgument::Pack:
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001301 return false;
1302
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001303 case TemplateArgument::Type:
1304 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1305 return Visit(TSInfo->getTypeLoc());
1306 return false;
1307
1308 case TemplateArgument::Declaration:
1309 if (Expr *E = TAL.getSourceDeclExpression())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001310 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001311 return false;
1312
1313 case TemplateArgument::Expression:
1314 if (Expr *E = TAL.getSourceExpression())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001315 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001316 return false;
1317
1318 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001319 case TemplateArgument::TemplateExpansion:
Douglas Gregorb6744ef2011-03-02 17:09:35 +00001320 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1321 return true;
1322
Douglas Gregora7fc9012011-01-05 18:58:31 +00001323 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
Douglas Gregor0b36e612010-08-31 20:37:03 +00001324 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001325 }
David Blaikie7530c032012-01-17 06:56:22 +00001326
1327 llvm_unreachable("Invalid TemplateArgument::Kind!");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001328}
1329
Ted Kremeneka0536d82010-05-07 01:04:29 +00001330bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1331 return VisitDeclContext(D);
1332}
1333
Douglas Gregor01829d32010-08-31 14:41:23 +00001334bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1335 return Visit(TL.getUnqualifiedLoc());
1336}
1337
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001338bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00001339 ASTContext &Context = AU->getASTContext();
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001340
1341 // Some builtin types (such as Objective-C's "id", "sel", and
1342 // "Class") have associated declarations. Create cursors for those.
1343 QualType VisitType;
John McCalle0a22d02011-10-18 21:02:43 +00001344 switch (TL.getTypePtr()->getKind()) {
John McCall2dde35b2011-10-18 22:28:37 +00001345
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001346 case BuiltinType::Void:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001347 case BuiltinType::NullPtr:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001348 case BuiltinType::Dependent:
John McCall2dde35b2011-10-18 22:28:37 +00001349#define BUILTIN_TYPE(Id, SingletonId)
1350#define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1351#define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1352#define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
1353#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
1354#include "clang/AST/BuiltinTypes.def"
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001355 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001356
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001357 case BuiltinType::ObjCId:
1358 VisitType = Context.getObjCIdType();
1359 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001360
1361 case BuiltinType::ObjCClass:
1362 VisitType = Context.getObjCClassType();
1363 break;
1364
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001365 case BuiltinType::ObjCSel:
1366 VisitType = Context.getObjCSelType();
1367 break;
1368 }
1369
1370 if (!VisitType.isNull()) {
1371 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001372 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001373 TU));
1374 }
1375
1376 return false;
1377}
1378
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001379bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
Richard Smith162e1c12011-04-15 14:24:37 +00001380 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001381}
1382
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001383bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1384 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1385}
1386
1387bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
Argyrios Kyrtzidis6f155de2011-08-25 22:24:47 +00001388 if (TL.isDefinition())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001389 return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
Argyrios Kyrtzidis6f155de2011-08-25 22:24:47 +00001390
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001391 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1392}
1393
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001394bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Chandler Carruth960d13d2011-05-01 09:53:37 +00001395 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001396}
1397
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001398bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1399 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1400 return true;
1401
John McCallc12c5bb2010-05-15 11:32:37 +00001402 return false;
1403}
1404
1405bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1406 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1407 return true;
1408
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001409 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1410 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1411 TU)))
1412 return true;
1413 }
1414
1415 return false;
1416}
1417
1418bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001419 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001420}
1421
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001422bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1423 return Visit(TL.getInnerLoc());
1424}
1425
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001426bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1427 return Visit(TL.getPointeeLoc());
1428}
1429
1430bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1431 return Visit(TL.getPointeeLoc());
1432}
1433
1434bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1435 return Visit(TL.getPointeeLoc());
1436}
1437
1438bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001439 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001440}
1441
1442bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001443 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001444}
1445
Argyrios Kyrtzidis3422fbc2011-08-15 18:44:43 +00001446bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1447 return Visit(TL.getModifiedLoc());
1448}
1449
Douglas Gregor01829d32010-08-31 14:41:23 +00001450bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1451 bool SkipResultType) {
1452 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001453 return true;
1454
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001455 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001456 if (Decl *D = TL.getArg(I))
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001457 if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001458 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001459
1460 return false;
1461}
1462
1463bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1464 if (Visit(TL.getElementLoc()))
1465 return true;
1466
1467 if (Expr *Size = TL.getSizeExpr())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001468 return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001469
1470 return false;
1471}
1472
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001473bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1474 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001475 // Visit the template name.
1476 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1477 TL.getTemplateNameLoc()))
1478 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001479
1480 // Visit the template arguments.
1481 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1482 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1483 return true;
1484
1485 return false;
1486}
1487
Douglas Gregor2332c112010-01-21 20:48:56 +00001488bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1489 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1490}
1491
1492bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1493 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1494 return Visit(TSInfo->getTypeLoc());
1495
1496 return false;
1497}
1498
Sean Huntca63c202011-05-24 22:41:36 +00001499bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1500 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1501 return Visit(TSInfo->getTypeLoc());
1502
1503 return false;
1504}
1505
Douglas Gregor2494dd02011-03-01 01:34:45 +00001506bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
1507 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1508 return true;
1509
1510 return false;
1511}
1512
Douglas Gregor94fdffa2011-03-01 20:11:18 +00001513bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1514 DependentTemplateSpecializationTypeLoc TL) {
1515 // Visit the nested-name-specifier, if there is one.
1516 if (TL.getQualifierLoc() &&
1517 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1518 return true;
1519
1520 // Visit the template arguments.
1521 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1522 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1523 return true;
1524
1525 return false;
1526}
1527
Douglas Gregor9e876872011-03-01 18:12:44 +00001528bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1529 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1530 return true;
1531
1532 return Visit(TL.getNamedTypeLoc());
1533}
1534
Douglas Gregor7536dd52010-12-20 02:24:11 +00001535bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1536 return Visit(TL.getPatternLoc());
1537}
1538
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +00001539bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1540 if (Expr *E = TL.getUnderlyingExpr())
1541 return Visit(MakeCXCursor(E, StmtParent, TU));
1542
1543 return false;
1544}
1545
1546bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1547 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1548}
1549
Eli Friedmanb001de72011-10-06 23:00:33 +00001550bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1551 return Visit(TL.getValueLoc());
1552}
1553
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +00001554#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1555bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1556 return Visit##PARENT##Loc(TL); \
1557}
1558
1559DEFAULT_TYPELOC_IMPL(Complex, Type)
1560DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1561DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1562DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1563DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
1564DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1565DEFAULT_TYPELOC_IMPL(Vector, Type)
1566DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1567DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1568DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1569DEFAULT_TYPELOC_IMPL(Record, TagType)
1570DEFAULT_TYPELOC_IMPL(Enum, TagType)
1571DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1572DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1573DEFAULT_TYPELOC_IMPL(Auto, Type)
1574
Ted Kremenek3064ef92010-08-27 21:34:58 +00001575bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001576 // Visit the nested-name-specifier, if present.
1577 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1578 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1579 return true;
1580
John McCall5e1cdac2011-10-07 06:10:15 +00001581 if (D->isCompleteDefinition()) {
Ted Kremenek3064ef92010-08-27 21:34:58 +00001582 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1583 E = D->bases_end(); I != E; ++I) {
1584 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1585 return true;
1586 }
1587 }
1588
1589 return VisitTagDecl(D);
1590}
1591
Ted Kremenek09dfa372010-02-18 05:46:33 +00001592bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001593 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1594 i != e; ++i)
1595 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001596 return true;
1597
1598 return false;
1599}
1600
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001601//===----------------------------------------------------------------------===//
1602// Data-recursive visitor methods.
1603//===----------------------------------------------------------------------===//
1604
Ted Kremenek28a71942010-11-13 00:36:47 +00001605namespace {
Ted Kremenek035dc412010-11-13 00:36:50 +00001606#define DEF_JOB(NAME, DATA, KIND)\
1607class NAME : public VisitorJob {\
1608public:\
1609 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1610 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Ted Kremenekf64d8032010-11-18 00:02:32 +00001611 DATA *get() const { return static_cast<DATA*>(data[0]); }\
Ted Kremenek035dc412010-11-13 00:36:50 +00001612};
1613
1614DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1615DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001616DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001617DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001618DEF_JOB(ExplicitTemplateArgsVisit, ASTTemplateArgumentListInfo,
Ted Kremenek60608ec2010-11-17 00:50:47 +00001619 ExplicitTemplateArgsVisitKind)
Douglas Gregor94d96292011-01-19 20:34:17 +00001620DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
Douglas Gregor011d8b92012-02-15 00:54:55 +00001621DEF_JOB(LambdaExprParts, LambdaExpr, LambdaExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001622#undef DEF_JOB
1623
1624class DeclVisit : public VisitorJob {
1625public:
1626 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1627 VisitorJob(parent, VisitorJob::DeclVisitKind,
1628 d, isFirst ? (void*) 1 : (void*) 0) {}
1629 static bool classof(const VisitorJob *VJ) {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001630 return VJ->getKind() == DeclVisitKind;
Ted Kremenek035dc412010-11-13 00:36:50 +00001631 }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001632 Decl *get() const { return static_cast<Decl*>(data[0]); }
1633 bool isFirst() const { return data[1] ? true : false; }
Ted Kremenek035dc412010-11-13 00:36:50 +00001634};
Ted Kremenek035dc412010-11-13 00:36:50 +00001635class TypeLocVisit : public VisitorJob {
1636public:
1637 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1638 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1639 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1640
1641 static bool classof(const VisitorJob *VJ) {
1642 return VJ->getKind() == TypeLocVisitKind;
1643 }
1644
Ted Kremenek82f3c502010-11-15 22:23:26 +00001645 TypeLoc get() const {
Ted Kremenekf64d8032010-11-18 00:02:32 +00001646 QualType T = QualType::getFromOpaquePtr(data[0]);
1647 return TypeLoc(T, data[1]);
Ted Kremenek035dc412010-11-13 00:36:50 +00001648 }
1649};
1650
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001651class LabelRefVisit : public VisitorJob {
1652public:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001653 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1654 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001655 labelLoc.getPtrEncoding()) {}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001656
1657 static bool classof(const VisitorJob *VJ) {
1658 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1659 }
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001660 LabelDecl *get() const { return static_cast<LabelDecl*>(data[0]); }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001661 SourceLocation getLoc() const {
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001662 return SourceLocation::getFromPtrEncoding(data[1]); }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001663};
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001664
1665class NestedNameSpecifierLocVisit : public VisitorJob {
1666public:
1667 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1668 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1669 Qualifier.getNestedNameSpecifier(),
1670 Qualifier.getOpaqueData()) { }
1671
1672 static bool classof(const VisitorJob *VJ) {
1673 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1674 }
1675
1676 NestedNameSpecifierLoc get() const {
1677 return NestedNameSpecifierLoc(static_cast<NestedNameSpecifier*>(data[0]),
1678 data[1]);
1679 }
1680};
1681
Ted Kremenekf64d8032010-11-18 00:02:32 +00001682class DeclarationNameInfoVisit : public VisitorJob {
1683public:
1684 DeclarationNameInfoVisit(Stmt *S, CXCursor parent)
1685 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
1686 static bool classof(const VisitorJob *VJ) {
1687 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1688 }
1689 DeclarationNameInfo get() const {
1690 Stmt *S = static_cast<Stmt*>(data[0]);
1691 switch (S->getStmtClass()) {
1692 default:
1693 llvm_unreachable("Unhandled Stmt");
Douglas Gregorba0513d2011-10-25 01:33:02 +00001694 case clang::Stmt::MSDependentExistsStmtClass:
1695 return cast<MSDependentExistsStmt>(S)->getNameInfo();
Ted Kremenekf64d8032010-11-18 00:02:32 +00001696 case Stmt::CXXDependentScopeMemberExprClass:
1697 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1698 case Stmt::DependentScopeDeclRefExprClass:
1699 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
1700 }
1701 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001702};
Ted Kremenekcdba6592010-11-18 00:42:18 +00001703class MemberRefVisit : public VisitorJob {
1704public:
1705 MemberRefVisit(FieldDecl *D, SourceLocation L, CXCursor parent)
1706 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001707 L.getPtrEncoding()) {}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001708 static bool classof(const VisitorJob *VJ) {
1709 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1710 }
1711 FieldDecl *get() const {
1712 return static_cast<FieldDecl*>(data[0]);
1713 }
1714 SourceLocation getLoc() const {
1715 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1716 }
1717};
Ted Kremenek28a71942010-11-13 00:36:47 +00001718class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1719 VisitorWorkList &WL;
1720 CXCursor Parent;
1721public:
1722 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1723 : WL(wl), Parent(parent) {}
1724
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001725 void VisitAddrLabelExpr(AddrLabelExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001726 void VisitBlockExpr(BlockExpr *B);
Ted Kremenek28a71942010-11-13 00:36:47 +00001727 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek083c7e22010-11-13 05:38:03 +00001728 void VisitCompoundStmt(CompoundStmt *S);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001729 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
Douglas Gregorba0513d2011-10-25 01:33:02 +00001730 void VisitMSDependentExistsStmt(MSDependentExistsStmt *S);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001731 void VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001732 void VisitCXXNewExpr(CXXNewExpr *E);
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001733 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001734 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001735 void VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001736 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001737 void VisitCXXTypeidExpr(CXXTypeidExpr *E);
Ted Kremenek55b933a2010-11-17 00:50:36 +00001738 void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001739 void VisitCXXUuidofExpr(CXXUuidofExpr *E);
Argyrios Kyrtzidisdcbb2fb2011-12-03 03:49:44 +00001740 void VisitCXXCatchStmt(CXXCatchStmt *S);
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001741 void VisitDeclRefExpr(DeclRefExpr *D);
Ted Kremenek035dc412010-11-13 00:36:50 +00001742 void VisitDeclStmt(DeclStmt *S);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001743 void VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001744 void VisitDesignatedInitExpr(DesignatedInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001745 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1746 void VisitForStmt(ForStmt *FS);
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001747 void VisitGotoStmt(GotoStmt *GS);
Ted Kremenek28a71942010-11-13 00:36:47 +00001748 void VisitIfStmt(IfStmt *If);
1749 void VisitInitListExpr(InitListExpr *IE);
1750 void VisitMemberExpr(MemberExpr *M);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001751 void VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001752 void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001753 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1754 void VisitOverloadExpr(OverloadExpr *E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001755 void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001756 void VisitStmt(Stmt *S);
1757 void VisitSwitchStmt(SwitchStmt *S);
1758 void VisitWhileStmt(WhileStmt *W);
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001759 void VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Francois Pichet6ad6f282010-12-07 00:08:36 +00001760 void VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E);
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00001761 void VisitTypeTraitExpr(TypeTraitExpr *E);
John Wiegley21ff2e52011-04-28 00:16:57 +00001762 void VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E);
John Wiegley55262202011-04-25 06:54:41 +00001763 void VisitExpressionTraitExpr(ExpressionTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001764 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001765 void VisitVAArgExpr(VAArgExpr *E);
Douglas Gregor94d96292011-01-19 20:34:17 +00001766 void VisitSizeOfPackExpr(SizeOfPackExpr *E);
John McCall4b9c2d22011-11-06 09:01:30 +00001767 void VisitPseudoObjectExpr(PseudoObjectExpr *E);
1768 void VisitOpaqueValueExpr(OpaqueValueExpr *E);
Douglas Gregor011d8b92012-02-15 00:54:55 +00001769 void VisitLambdaExpr(LambdaExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00001770
Ted Kremenek28a71942010-11-13 00:36:47 +00001771private:
Ted Kremenekf64d8032010-11-18 00:02:32 +00001772 void AddDeclarationNameInfo(Stmt *S);
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001773 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001774 void AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001775 void AddMemberRef(FieldDecl *D, SourceLocation L);
Ted Kremenek28a71942010-11-13 00:36:47 +00001776 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001777 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001778 void AddTypeLoc(TypeSourceInfo *TI);
1779 void EnqueueChildren(Stmt *S);
1780};
1781} // end anonyous namespace
1782
Ted Kremenekf64d8032010-11-18 00:02:32 +00001783void EnqueueVisitor::AddDeclarationNameInfo(Stmt *S) {
1784 // 'S' should always be non-null, since it comes from the
1785 // statement we are visiting.
1786 WL.push_back(DeclarationNameInfoVisit(S, Parent));
1787}
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001788
1789void
1790EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1791 if (Qualifier)
1792 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
1793}
1794
Ted Kremenek28a71942010-11-13 00:36:47 +00001795void EnqueueVisitor::AddStmt(Stmt *S) {
1796 if (S)
1797 WL.push_back(StmtVisit(S, Parent));
1798}
Ted Kremenek035dc412010-11-13 00:36:50 +00001799void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001800 if (D)
Ted Kremenek035dc412010-11-13 00:36:50 +00001801 WL.push_back(DeclVisit(D, Parent, isFirst));
Ted Kremenek28a71942010-11-13 00:36:47 +00001802}
Ted Kremenek60608ec2010-11-17 00:50:47 +00001803void EnqueueVisitor::
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001804 AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001805 if (A)
1806 WL.push_back(ExplicitTemplateArgsVisit(
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001807 const_cast<ASTTemplateArgumentListInfo*>(A), Parent));
Ted Kremenek60608ec2010-11-17 00:50:47 +00001808}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001809void EnqueueVisitor::AddMemberRef(FieldDecl *D, SourceLocation L) {
1810 if (D)
1811 WL.push_back(MemberRefVisit(D, L, Parent));
1812}
Ted Kremenek28a71942010-11-13 00:36:47 +00001813void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1814 if (TI)
1815 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1816 }
1817void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001818 unsigned size = WL.size();
John McCall7502c1d2011-02-13 04:07:26 +00001819 for (Stmt::child_range Child = S->children(); Child; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001820 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001821 }
1822 if (size == WL.size())
1823 return;
1824 // Now reverse the entries we just added. This will match the DFS
1825 // ordering performed by the worklist.
1826 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1827 std::reverse(I, E);
1828}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001829void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1830 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
1831}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001832void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1833 AddDecl(B->getBlockDecl());
1834}
Ted Kremenek28a71942010-11-13 00:36:47 +00001835void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1836 EnqueueChildren(E);
1837 AddTypeLoc(E->getTypeSourceInfo());
1838}
Ted Kremenek083c7e22010-11-13 05:38:03 +00001839void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1840 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1841 E = S->body_rend(); I != E; ++I) {
1842 AddStmt(*I);
1843 }
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001844}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001845void EnqueueVisitor::
Douglas Gregorba0513d2011-10-25 01:33:02 +00001846VisitMSDependentExistsStmt(MSDependentExistsStmt *S) {
1847 AddStmt(S->getSubStmt());
1848 AddDeclarationNameInfo(S);
1849 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
1850 AddNestedNameSpecifierLoc(QualifierLoc);
1851}
1852
1853void EnqueueVisitor::
Ted Kremenekf64d8032010-11-18 00:02:32 +00001854VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
1855 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1856 AddDeclarationNameInfo(E);
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001857 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1858 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001859 if (!E->isImplicitAccess())
1860 AddStmt(E->getBase());
1861}
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001862void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001863 // Enqueue the initializer , if any.
1864 AddStmt(E->getInitializer());
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001865 // Enqueue the array size, if any.
1866 AddStmt(E->getArraySize());
1867 // Enqueue the allocated type.
1868 AddTypeLoc(E->getAllocatedTypeSourceInfo());
1869 // Enqueue the placement arguments.
1870 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1871 AddStmt(E->getPlacementArg(I-1));
1872}
Ted Kremenek28a71942010-11-13 00:36:47 +00001873void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
Ted Kremenek8b8d8c92010-11-13 05:55:56 +00001874 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1875 AddStmt(CE->getArg(I-1));
Ted Kremenek28a71942010-11-13 00:36:47 +00001876 AddStmt(CE->getCallee());
1877 AddStmt(CE->getArg(0));
1878}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001879void EnqueueVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1880 // Visit the name of the type being destroyed.
1881 AddTypeLoc(E->getDestroyedTypeInfo());
1882 // Visit the scope type that looks disturbingly like the nested-name-specifier
1883 // but isn't.
1884 AddTypeLoc(E->getScopeTypeInfo());
1885 // Visit the nested-name-specifier.
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001886 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1887 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001888 // Visit base expression.
1889 AddStmt(E->getBase());
1890}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001891void EnqueueVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1892 AddTypeLoc(E->getTypeSourceInfo());
1893}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001894void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1895 EnqueueChildren(E);
1896 AddTypeLoc(E->getTypeSourceInfo());
1897}
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001898void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1899 EnqueueChildren(E);
1900 if (E->isTypeOperand())
1901 AddTypeLoc(E->getTypeOperandSourceInfo());
1902}
Ted Kremenek55b933a2010-11-17 00:50:36 +00001903
1904void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
1905 *E) {
1906 EnqueueChildren(E);
1907 AddTypeLoc(E->getTypeSourceInfo());
1908}
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001909void EnqueueVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1910 EnqueueChildren(E);
1911 if (E->isTypeOperand())
1912 AddTypeLoc(E->getTypeOperandSourceInfo());
1913}
Argyrios Kyrtzidisdcbb2fb2011-12-03 03:49:44 +00001914
1915void EnqueueVisitor::VisitCXXCatchStmt(CXXCatchStmt *S) {
1916 EnqueueChildren(S);
1917 AddDecl(S->getExceptionDecl());
1918}
1919
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001920void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001921 if (DR->hasExplicitTemplateArgs()) {
1922 AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
1923 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001924 WL.push_back(DeclRefExprParts(DR, Parent));
1925}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001926void EnqueueVisitor::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
1927 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1928 AddDeclarationNameInfo(E);
Douglas Gregor00cf3cc2011-02-25 20:49:16 +00001929 AddNestedNameSpecifierLoc(E->getQualifierLoc());
Ted Kremenekf64d8032010-11-18 00:02:32 +00001930}
Ted Kremenek035dc412010-11-13 00:36:50 +00001931void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1932 unsigned size = WL.size();
1933 bool isFirst = true;
1934 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1935 D != DEnd; ++D) {
1936 AddDecl(*D, isFirst);
1937 isFirst = false;
1938 }
1939 if (size == WL.size())
1940 return;
1941 // Now reverse the entries we just added. This will match the DFS
1942 // ordering performed by the worklist.
1943 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1944 std::reverse(I, E);
1945}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001946void EnqueueVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1947 AddStmt(E->getInit());
1948 typedef DesignatedInitExpr::Designator Designator;
1949 for (DesignatedInitExpr::reverse_designators_iterator
1950 D = E->designators_rbegin(), DEnd = E->designators_rend();
1951 D != DEnd; ++D) {
1952 if (D->isFieldDesignator()) {
1953 if (FieldDecl *Field = D->getField())
1954 AddMemberRef(Field, D->getFieldLoc());
1955 continue;
1956 }
1957 if (D->isArrayDesignator()) {
1958 AddStmt(E->getArrayIndex(*D));
1959 continue;
1960 }
1961 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1962 AddStmt(E->getArrayRangeEnd(*D));
1963 AddStmt(E->getArrayRangeStart(*D));
1964 }
1965}
Ted Kremenek28a71942010-11-13 00:36:47 +00001966void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1967 EnqueueChildren(E);
1968 AddTypeLoc(E->getTypeInfoAsWritten());
1969}
1970void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1971 AddStmt(FS->getBody());
1972 AddStmt(FS->getInc());
1973 AddStmt(FS->getCond());
1974 AddDecl(FS->getConditionVariable());
1975 AddStmt(FS->getInit());
1976}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001977void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) {
1978 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
1979}
Ted Kremenek28a71942010-11-13 00:36:47 +00001980void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
1981 AddStmt(If->getElse());
1982 AddStmt(If->getThen());
1983 AddStmt(If->getCond());
1984 AddDecl(If->getConditionVariable());
1985}
1986void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
1987 // We care about the syntactic form of the initializer list, only.
1988 if (InitListExpr *Syntactic = IE->getSyntacticForm())
1989 IE = Syntactic;
1990 EnqueueChildren(IE);
1991}
1992void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
Douglas Gregor89629a72010-11-17 17:15:08 +00001993 WL.push_back(MemberExprParts(M, Parent));
1994
1995 // If the base of the member access expression is an implicit 'this', don't
1996 // visit it.
1997 // FIXME: If we ever want to show these implicit accesses, this will be
1998 // unfortunate. However, clang_getCursor() relies on this behavior.
Douglas Gregor75e85042011-03-02 21:06:53 +00001999 if (!M->isImplicitAccess())
2000 AddStmt(M->getBase());
Ted Kremenek28a71942010-11-13 00:36:47 +00002001}
Ted Kremenek73d15c42010-11-13 01:09:29 +00002002void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
2003 AddTypeLoc(E->getEncodedTypeSourceInfo());
2004}
Ted Kremenek28a71942010-11-13 00:36:47 +00002005void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
2006 EnqueueChildren(M);
2007 AddTypeLoc(M->getClassReceiverTypeInfo());
2008}
Ted Kremenekcdba6592010-11-18 00:42:18 +00002009void EnqueueVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
2010 // Visit the components of the offsetof expression.
2011 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
2012 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
2013 const OffsetOfNode &Node = E->getComponent(I-1);
2014 switch (Node.getKind()) {
2015 case OffsetOfNode::Array:
2016 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2017 break;
2018 case OffsetOfNode::Field:
Abramo Bagnara06dec892011-03-12 09:45:03 +00002019 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
Ted Kremenekcdba6592010-11-18 00:42:18 +00002020 break;
2021 case OffsetOfNode::Identifier:
2022 case OffsetOfNode::Base:
2023 continue;
2024 }
2025 }
2026 // Visit the type into which we're computing the offset.
2027 AddTypeLoc(E->getTypeSourceInfo());
2028}
Ted Kremenek28a71942010-11-13 00:36:47 +00002029void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00002030 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
Ted Kremenek60458782010-11-12 21:34:16 +00002031 WL.push_back(OverloadExprParts(E, Parent));
2032}
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002033void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
2034 UnaryExprOrTypeTraitExpr *E) {
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00002035 EnqueueChildren(E);
2036 if (E->isArgumentType())
2037 AddTypeLoc(E->getArgumentTypeInfo());
2038}
Ted Kremenek28a71942010-11-13 00:36:47 +00002039void EnqueueVisitor::VisitStmt(Stmt *S) {
2040 EnqueueChildren(S);
2041}
2042void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
2043 AddStmt(S->getBody());
2044 AddStmt(S->getCond());
2045 AddDecl(S->getConditionVariable());
2046}
Ted Kremenekfafa75a2010-11-17 00:50:39 +00002047
Ted Kremenek28a71942010-11-13 00:36:47 +00002048void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
2049 AddStmt(W->getBody());
2050 AddStmt(W->getCond());
2051 AddDecl(W->getConditionVariable());
2052}
John Wiegley21ff2e52011-04-28 00:16:57 +00002053
Ted Kremenek2939b6f2010-11-17 00:50:50 +00002054void EnqueueVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
2055 AddTypeLoc(E->getQueriedTypeSourceInfo());
2056}
Francois Pichet6ad6f282010-12-07 00:08:36 +00002057
2058void EnqueueVisitor::VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
Francois Pichet6ad6f282010-12-07 00:08:36 +00002059 AddTypeLoc(E->getRhsTypeSourceInfo());
Francois Pichet0a03a3f2010-12-08 09:11:05 +00002060 AddTypeLoc(E->getLhsTypeSourceInfo());
Francois Pichet6ad6f282010-12-07 00:08:36 +00002061}
2062
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00002063void EnqueueVisitor::VisitTypeTraitExpr(TypeTraitExpr *E) {
2064 for (unsigned I = E->getNumArgs(); I > 0; --I)
2065 AddTypeLoc(E->getArg(I-1));
2066}
2067
John Wiegley21ff2e52011-04-28 00:16:57 +00002068void EnqueueVisitor::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
2069 AddTypeLoc(E->getQueriedTypeSourceInfo());
2070}
2071
John Wiegley55262202011-04-25 06:54:41 +00002072void EnqueueVisitor::VisitExpressionTraitExpr(ExpressionTraitExpr *E) {
2073 EnqueueChildren(E);
2074}
2075
Ted Kremenek28a71942010-11-13 00:36:47 +00002076void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
2077 VisitOverloadExpr(U);
2078 if (!U->isImplicitAccess())
2079 AddStmt(U->getBase());
2080}
Ted Kremenek9d3bf792010-11-17 00:50:43 +00002081void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) {
2082 AddStmt(E->getSubExpr());
2083 AddTypeLoc(E->getWrittenTypeInfo());
2084}
Douglas Gregor94d96292011-01-19 20:34:17 +00002085void EnqueueVisitor::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
2086 WL.push_back(SizeOfPackExprParts(E, Parent));
2087}
John McCall4b9c2d22011-11-06 09:01:30 +00002088void EnqueueVisitor::VisitOpaqueValueExpr(OpaqueValueExpr *E) {
2089 // If the opaque value has a source expression, just transparently
2090 // visit that. This is useful for (e.g.) pseudo-object expressions.
2091 if (Expr *SourceExpr = E->getSourceExpr())
2092 return Visit(SourceExpr);
John McCall4b9c2d22011-11-06 09:01:30 +00002093}
Douglas Gregor011d8b92012-02-15 00:54:55 +00002094void EnqueueVisitor::VisitLambdaExpr(LambdaExpr *E) {
2095 AddStmt(E->getBody());
2096 WL.push_back(LambdaExprParts(E, Parent));
2097}
John McCall4b9c2d22011-11-06 09:01:30 +00002098void EnqueueVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *E) {
2099 // Treat the expression like its syntactic form.
2100 Visit(E->getSyntacticForm());
2101}
Ted Kremenek60458782010-11-12 21:34:16 +00002102
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002103void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002104 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002105}
2106
2107bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2108 if (RegionOfInterest.isValid()) {
2109 SourceRange Range = getRawCursorExtent(C);
2110 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2111 return false;
2112 }
2113 return true;
2114}
2115
2116bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2117 while (!WL.empty()) {
2118 // Dequeue the worklist item.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002119 VisitorJob LI = WL.back();
2120 WL.pop_back();
2121
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002122 // Set the Parent field, then back to its old value once we're done.
2123 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2124
2125 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00002126 case VisitorJob::DeclVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002127 Decl *D = cast<DeclVisit>(&LI)->get();
Ted Kremenekf1107452010-11-12 18:26:56 +00002128 if (!D)
2129 continue;
2130
2131 // For now, perform default visitation for Decls.
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002132 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2133 cast<DeclVisit>(&LI)->isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00002134 return true;
2135
2136 continue;
2137 }
Ted Kremenek60608ec2010-11-17 00:50:47 +00002138 case VisitorJob::ExplicitTemplateArgsVisitKind: {
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00002139 const ASTTemplateArgumentListInfo *ArgList =
Ted Kremenek60608ec2010-11-17 00:50:47 +00002140 cast<ExplicitTemplateArgsVisit>(&LI)->get();
2141 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2142 *ArgEnd = Arg + ArgList->NumTemplateArgs;
2143 Arg != ArgEnd; ++Arg) {
2144 if (VisitTemplateArgumentLoc(*Arg))
2145 return true;
2146 }
2147 continue;
2148 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002149 case VisitorJob::TypeLocVisitKind: {
2150 // Perform default visitation for TypeLocs.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002151 if (Visit(cast<TypeLocVisit>(&LI)->get()))
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002152 return true;
2153 continue;
2154 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002155 case VisitorJob::LabelRefVisitKind: {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002156 LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Ted Kremeneke7455012011-02-23 04:54:51 +00002157 if (LabelStmt *stmt = LS->getStmt()) {
2158 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2159 TU))) {
2160 return true;
2161 }
2162 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002163 continue;
2164 }
Ted Kremenek47695c82011-08-18 22:25:21 +00002165
Douglas Gregorf3db29f2011-02-25 18:19:59 +00002166 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2167 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2168 if (VisitNestedNameSpecifierLoc(V->get()))
2169 return true;
2170 continue;
2171 }
2172
Ted Kremenekf64d8032010-11-18 00:02:32 +00002173 case VisitorJob::DeclarationNameInfoVisitKind: {
2174 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2175 ->get()))
2176 return true;
2177 continue;
2178 }
Ted Kremenekcdba6592010-11-18 00:42:18 +00002179 case VisitorJob::MemberRefVisitKind: {
2180 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2181 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2182 return true;
2183 continue;
2184 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002185 case VisitorJob::StmtVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002186 Stmt *S = cast<StmtVisit>(&LI)->get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00002187 if (!S)
2188 continue;
2189
Ted Kremenekf1107452010-11-12 18:26:56 +00002190 // Update the current cursor.
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002191 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
Ted Kremenekcdba6592010-11-18 00:42:18 +00002192 if (!IsInRegionOfInterest(Cursor))
2193 continue;
2194 switch (Visitor(Cursor, Parent, ClientData)) {
2195 case CXChildVisit_Break: return true;
2196 case CXChildVisit_Continue: break;
2197 case CXChildVisit_Recurse:
2198 EnqueueWorkList(WL, S);
Ted Kremenek82f3c502010-11-15 22:23:26 +00002199 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002200 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00002201 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002202 }
2203 case VisitorJob::MemberExprPartsKind: {
2204 // Handle the other pieces in the MemberExpr besides the base.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002205 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002206
2207 // Visit the nested-name-specifier
Douglas Gregor40d96a62011-02-28 21:54:11 +00002208 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
2209 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002210 return true;
2211
2212 // Visit the declaration name.
2213 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2214 return true;
2215
2216 // Visit the explicitly-specified template arguments, if any.
2217 if (M->hasExplicitTemplateArgs()) {
2218 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2219 *ArgEnd = Arg + M->getNumTemplateArgs();
2220 Arg != ArgEnd; ++Arg) {
2221 if (VisitTemplateArgumentLoc(*Arg))
2222 return true;
2223 }
2224 }
2225 continue;
2226 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002227 case VisitorJob::DeclRefExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002228 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002229 // Visit nested-name-specifier, if present.
Douglas Gregor40d96a62011-02-28 21:54:11 +00002230 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
2231 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002232 return true;
2233 // Visit declaration name.
2234 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2235 return true;
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002236 continue;
2237 }
Ted Kremenek60458782010-11-12 21:34:16 +00002238 case VisitorJob::OverloadExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002239 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Ted Kremenek60458782010-11-12 21:34:16 +00002240 // Visit the nested-name-specifier.
Douglas Gregor4c9be892011-02-28 20:01:57 +00002241 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
2242 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenek60458782010-11-12 21:34:16 +00002243 return true;
2244 // Visit the declaration name.
2245 if (VisitDeclarationNameInfo(O->getNameInfo()))
2246 return true;
2247 // Visit the overloaded declaration reference.
2248 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2249 return true;
Ted Kremenek60458782010-11-12 21:34:16 +00002250 continue;
2251 }
Douglas Gregor94d96292011-01-19 20:34:17 +00002252 case VisitorJob::SizeOfPackExprPartsKind: {
2253 SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
2254 NamedDecl *Pack = E->getPack();
2255 if (isa<TemplateTypeParmDecl>(Pack)) {
2256 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
2257 E->getPackLoc(), TU)))
2258 return true;
2259
2260 continue;
2261 }
2262
2263 if (isa<TemplateTemplateParmDecl>(Pack)) {
2264 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
2265 E->getPackLoc(), TU)))
2266 return true;
2267
2268 continue;
2269 }
2270
2271 // Non-type template parameter packs and function parameter packs are
2272 // treated like DeclRefExpr cursors.
2273 continue;
2274 }
Douglas Gregor011d8b92012-02-15 00:54:55 +00002275
2276 case VisitorJob::LambdaExprPartsKind: {
2277 // Visit captures.
2278 LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
2279 for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
2280 CEnd = E->explicit_capture_end();
2281 C != CEnd; ++C) {
2282 if (C->capturesThis())
2283 continue;
2284
2285 if (Visit(MakeCursorVariableRef(C->getCapturedVar(),
2286 C->getLocation(),
2287 TU)))
2288 return true;
2289 }
2290
2291 // Visit parameters and return type, if present.
2292 if (E->hasExplicitParameters() || E->hasExplicitResultType()) {
2293 TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
2294 if (E->hasExplicitParameters() && E->hasExplicitResultType()) {
2295 // Visit the whole type.
2296 if (Visit(TL))
2297 return true;
2298 } else if (isa<FunctionProtoTypeLoc>(TL)) {
2299 FunctionProtoTypeLoc Proto = cast<FunctionProtoTypeLoc>(TL);
2300 if (E->hasExplicitParameters()) {
2301 // Visit parameters.
2302 for (unsigned I = 0, N = Proto.getNumArgs(); I != N; ++I)
2303 if (Visit(MakeCXCursor(Proto.getArg(I), TU)))
2304 return true;
2305 } else {
2306 // Visit result type.
2307 if (Visit(Proto.getResultLoc()))
2308 return true;
2309 }
2310 }
2311 }
2312 break;
2313 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002314 }
2315 }
2316 return false;
2317}
2318
Ted Kremenekcdba6592010-11-18 00:42:18 +00002319bool CursorVisitor::Visit(Stmt *S) {
Ted Kremenekd1ded662010-11-15 23:31:32 +00002320 VisitorWorkList *WL = 0;
2321 if (!WorkListFreeList.empty()) {
2322 WL = WorkListFreeList.back();
2323 WL->clear();
2324 WorkListFreeList.pop_back();
2325 }
2326 else {
2327 WL = new VisitorWorkList();
2328 WorkListCache.push_back(WL);
2329 }
2330 EnqueueWorkList(*WL, S);
2331 bool result = RunVisitorWorkList(*WL);
2332 WorkListFreeList.push_back(WL);
2333 return result;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002334}
2335
Francois Pichet48a8d142011-07-25 22:00:44 +00002336namespace {
2337typedef llvm::SmallVector<SourceRange, 4> RefNamePieces;
2338RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
2339 const DeclarationNameInfo &NI,
2340 const SourceRange &QLoc,
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00002341 const ASTTemplateArgumentListInfo *TemplateArgs = 0){
Francois Pichet48a8d142011-07-25 22:00:44 +00002342 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
2343 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
2344 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
2345
2346 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
2347
2348 RefNamePieces Pieces;
2349
2350 if (WantQualifier && QLoc.isValid())
2351 Pieces.push_back(QLoc);
2352
2353 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
2354 Pieces.push_back(NI.getLoc());
2355
2356 if (WantTemplateArgs && TemplateArgs)
2357 Pieces.push_back(SourceRange(TemplateArgs->LAngleLoc,
2358 TemplateArgs->RAngleLoc));
2359
2360 if (Kind == DeclarationName::CXXOperatorName) {
2361 Pieces.push_back(SourceLocation::getFromRawEncoding(
2362 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
2363 Pieces.push_back(SourceLocation::getFromRawEncoding(
2364 NI.getInfo().CXXOperatorName.EndOpNameLoc));
2365 }
2366
2367 if (WantSinglePiece) {
2368 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
2369 Pieces.clear();
2370 Pieces.push_back(R);
2371 }
2372
2373 return Pieces;
2374}
2375}
2376
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002377//===----------------------------------------------------------------------===//
2378// Misc. API hooks.
2379//===----------------------------------------------------------------------===//
2380
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002381static llvm::sys::Mutex EnableMultithreadingMutex;
2382static bool EnabledMultithreading;
2383
Argyrios Kyrtzidisfa39f5b2011-12-15 04:52:41 +00002384static void fatal_error_handler(void *user_data, const std::string& reason) {
Argyrios Kyrtzidisfa39f5b2011-12-15 04:52:41 +00002385 // Write the result out to stderr avoiding errs() because raw_ostreams can
2386 // call report_fatal_error.
Argyrios Kyrtzidisdb7a8002011-12-15 06:51:30 +00002387 fprintf(stderr, "LIBCLANG FATAL ERROR: %s\n", reason.c_str());
Argyrios Kyrtzidisfa39f5b2011-12-15 04:52:41 +00002388 ::abort();
2389}
2390
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002391extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002392CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2393 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002394 // Disable pretty stack trace functionality, which will otherwise be a very
2395 // poor citizen of the world and set up all sorts of signal handlers.
2396 llvm::DisablePrettyStackTrace = true;
2397
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002398 // We use crash recovery to make some of our APIs more reliable, implicitly
2399 // enable it.
2400 llvm::CrashRecoveryContext::Enable();
2401
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002402 // Enable support for multithreading in LLVM.
2403 {
2404 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2405 if (!EnabledMultithreading) {
Argyrios Kyrtzidisfa39f5b2011-12-15 04:52:41 +00002406 llvm::install_fatal_error_handler(fatal_error_handler, 0);
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002407 llvm::llvm_start_multithreaded();
2408 EnabledMultithreading = true;
2409 }
2410 }
2411
Douglas Gregora030b7c2010-01-22 20:35:53 +00002412 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002413 if (excludeDeclarationsFromPCH)
2414 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002415 if (displayDiagnostics)
2416 CIdxr->setDisplayDiagnostics();
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002417
2418 if (getenv("LIBCLANG_BGPRIO_INDEX"))
2419 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
2420 CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
2421 if (getenv("LIBCLANG_BGPRIO_EDIT"))
2422 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
2423 CXGlobalOpt_ThreadBackgroundPriorityForEditing);
2424
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002425 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002426}
2427
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002428void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002429 if (CIdx)
2430 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002431}
2432
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002433void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
2434 if (CIdx)
2435 static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
2436}
2437
2438unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
2439 if (CIdx)
2440 return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
2441 return 0;
2442}
2443
Ted Kremenekd2427dd2011-03-18 23:05:39 +00002444void clang_toggleCrashRecovery(unsigned isEnabled) {
2445 if (isEnabled)
2446 llvm::CrashRecoveryContext::Enable();
2447 else
2448 llvm::CrashRecoveryContext::Disable();
2449}
2450
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002451CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002452 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002453 if (!CIdx)
2454 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002455
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002456 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002457 FileSystemOptions FileSystemOpts;
2458 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002459
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00002460 IntrusiveRefCntPtr<DiagnosticsEngine> Diags;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002461 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002462 CXXIdx->getOnlyLocalDecls(),
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00002463 0, 0,
2464 /*CaptureDiagnostics=*/true,
2465 /*AllowPCHWithCompilerErrors=*/true);
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002466 return MakeCXTranslationUnit(CXXIdx, TU);
Steve Naroff600866c2009-08-27 19:51:58 +00002467}
2468
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002469unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002470 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregorb5af8432011-08-25 22:54:01 +00002471 CXTranslationUnit_CacheCompletionResults;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002472}
2473
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002474CXTranslationUnit
2475clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2476 const char *source_filename,
2477 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002478 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002479 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002480 struct CXUnsavedFile *unsaved_files) {
Argyrios Kyrtzidise1d43302012-02-25 02:41:16 +00002481 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
Douglas Gregor5a430212010-07-21 18:52:53 +00002482 return clang_parseTranslationUnit(CIdx, source_filename,
2483 command_line_args, num_command_line_args,
2484 unsaved_files, num_unsaved_files,
Douglas Gregordca8ee82011-05-06 16:33:08 +00002485 Options);
Douglas Gregor5a430212010-07-21 18:52:53 +00002486}
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00002487
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002488struct ParseTranslationUnitInfo {
2489 CXIndex CIdx;
2490 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002491 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002492 int num_command_line_args;
2493 struct CXUnsavedFile *unsaved_files;
2494 unsigned num_unsaved_files;
2495 unsigned options;
2496 CXTranslationUnit result;
2497};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002498static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002499 ParseTranslationUnitInfo *PTUI =
2500 static_cast<ParseTranslationUnitInfo*>(UserData);
2501 CXIndex CIdx = PTUI->CIdx;
2502 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002503 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002504 int num_command_line_args = PTUI->num_command_line_args;
2505 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2506 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2507 unsigned options = PTUI->options;
2508 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002509
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002510 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002511 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002512
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002513 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2514
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002515 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
Argyrios Kyrtzidis81b5ac32012-03-28 02:49:54 +00002516 setThreadBackgroundPriority();
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002517
Douglas Gregor44c181a2010-07-23 00:33:23 +00002518 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregor467dc882011-08-25 22:30:56 +00002519 // FIXME: Add a flag for modules.
2520 TranslationUnitKind TUKind
2521 = (options & CXTranslationUnit_Incomplete)? TU_Prefix : TU_Complete;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002522 bool CacheCodeCompetionResults
2523 = options & CXTranslationUnit_CacheCompletionResults;
Erik Verbruggen6a91d382012-04-12 10:11:59 +00002524 bool SkipFunctionBodies = options & CXTranslationUnit_SkipFunctionBodies;
2525
Douglas Gregor5352ac02010-01-28 00:27:43 +00002526 // Configure the diagnostics.
2527 DiagnosticOptions DiagOpts;
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00002528 IntrusiveRefCntPtr<DiagnosticsEngine>
Ted Kremenek25a11e12011-03-22 01:15:24 +00002529 Diags(CompilerInstance::createDiagnostics(DiagOpts, num_command_line_args,
2530 command_line_args));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002531
Ted Kremenek25a11e12011-03-22 01:15:24 +00002532 // Recover resources if we crash before exiting this function.
David Blaikied6471f72011-09-25 23:23:43 +00002533 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
2534 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00002535 DiagCleanup(Diags.getPtr());
2536
Dylan Noblesmith1e4c01b2012-02-13 12:32:21 +00002537 OwningPtr<std::vector<ASTUnit::RemappedFile> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00002538 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2539
2540 // Recover resources if we crash before exiting this function.
2541 llvm::CrashRecoveryContextCleanupRegistrar<
2542 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2543
Douglas Gregor4db64a42010-01-23 00:14:00 +00002544 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002545 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002546 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002547 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002548 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2549 Buffer));
Douglas Gregor4db64a42010-01-23 00:14:00 +00002550 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002551
Dylan Noblesmith1e4c01b2012-02-13 12:32:21 +00002552 OwningPtr<std::vector<const char *> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00002553 Args(new std::vector<const char*>());
2554
2555 // Recover resources if we crash before exiting this method.
2556 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
2557 ArgsCleanup(Args.get());
2558
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002559 // Since the Clang C library is primarily used by batch tools dealing with
2560 // (often very broken) source code, where spell-checking can have a
2561 // significant negative impact on performance (particularly when
2562 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002563 // Only do this if we haven't found a spell-checking-related argument.
2564 bool FoundSpellCheckingArgument = false;
2565 for (int I = 0; I != num_command_line_args; ++I) {
2566 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2567 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2568 FoundSpellCheckingArgument = true;
2569 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002570 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002571 }
2572 if (!FoundSpellCheckingArgument)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002573 Args->push_back("-fno-spell-checking");
Douglas Gregorb10daed2010-10-11 16:52:23 +00002574
Ted Kremenek25a11e12011-03-22 01:15:24 +00002575 Args->insert(Args->end(), command_line_args,
2576 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002577
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002578 // The 'source_filename' argument is optional. If the caller does not
2579 // specify it then it is assumed that the source file is specified
2580 // in the actual argument list.
2581 // Put the source file after command_line_args otherwise if '-x' flag is
2582 // present it will be unused.
2583 if (source_filename)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002584 Args->push_back(source_filename);
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002585
Douglas Gregor44c181a2010-07-23 00:33:23 +00002586 // Do we need the detailed preprocessing record?
2587 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Ted Kremenek25a11e12011-03-22 01:15:24 +00002588 Args->push_back("-Xclang");
2589 Args->push_back("-detailed-preprocessing-record");
Douglas Gregor44c181a2010-07-23 00:33:23 +00002590 }
2591
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002592 unsigned NumErrors = Diags->getClient()->getNumErrors();
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00002593 OwningPtr<ASTUnit> ErrUnit;
Dylan Noblesmith1e4c01b2012-02-13 12:32:21 +00002594 OwningPtr<ASTUnit> Unit(
Ted Kremenek4ee99262011-03-22 20:16:19 +00002595 ASTUnit::LoadFromCommandLine(Args->size() ? &(*Args)[0] : 0
2596 /* vector::data() not portable */,
2597 Args->size() ? (&(*Args)[0] + Args->size()) :0,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002598 Diags,
2599 CXXIdx->getClangResourcesPath(),
2600 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002601 /*CaptureDiagnostics=*/true,
Ted Kremenek4ee99262011-03-22 20:16:19 +00002602 RemappedFiles->size() ? &(*RemappedFiles)[0]:0,
Ted Kremenek25a11e12011-03-22 01:15:24 +00002603 RemappedFiles->size(),
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00002604 /*RemappedFilesKeepOriginalName=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002605 PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00002606 TUKind,
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00002607 CacheCodeCompetionResults,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00002608 /*AllowPCHWithCompilerErrors=*/true,
Erik Verbruggen6a91d382012-04-12 10:11:59 +00002609 SkipFunctionBodies,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00002610 &ErrUnit));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002611
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002612 if (NumErrors != Diags->getClient()->getNumErrors()) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002613 // Make sure to check that 'Unit' is non-NULL.
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00002614 if (CXXIdx->getDisplayDiagnostics())
2615 printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
Douglas Gregora88084b2010-02-18 18:08:43 +00002616 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002617
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002618 PTUI->result = MakeCXTranslationUnit(CXXIdx, Unit.take());
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002619}
2620CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2621 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002622 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002623 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002624 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002625 unsigned num_unsaved_files,
2626 unsigned options) {
2627 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002628 num_command_line_args, unsaved_files,
2629 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002630 llvm::CrashRecoveryContext CRC;
2631
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002632 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002633 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2634 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2635 fprintf(stderr, " 'command_line_args' : [");
2636 for (int i = 0; i != num_command_line_args; ++i) {
2637 if (i)
2638 fprintf(stderr, ", ");
2639 fprintf(stderr, "'%s'", command_line_args[i]);
2640 }
2641 fprintf(stderr, "],\n");
2642 fprintf(stderr, " 'unsaved_files' : [");
2643 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2644 if (i)
2645 fprintf(stderr, ", ");
2646 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2647 unsaved_files[i].Length);
2648 }
2649 fprintf(stderr, "],\n");
2650 fprintf(stderr, " 'options' : %d,\n", options);
2651 fprintf(stderr, "}\n");
2652
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002653 return 0;
Douglas Gregor6df78732011-05-05 20:27:22 +00002654 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
2655 PrintLibclangResourceUsage(PTUI.result);
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002656 }
Douglas Gregor6df78732011-05-05 20:27:22 +00002657
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002658 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002659}
2660
Douglas Gregor19998442010-08-13 15:35:05 +00002661unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2662 return CXSaveTranslationUnit_None;
2663}
Argyrios Kyrtzidis142bcb52012-03-28 02:17:59 +00002664
2665namespace {
2666
2667struct SaveTranslationUnitInfo {
2668 CXTranslationUnit TU;
2669 const char *FileName;
2670 unsigned options;
2671 CXSaveError result;
2672};
2673
2674}
2675
2676static void clang_saveTranslationUnit_Impl(void *UserData) {
2677 SaveTranslationUnitInfo *STUI =
2678 static_cast<SaveTranslationUnitInfo*>(UserData);
2679
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002680 CIndexer *CXXIdx = (CIndexer*)STUI->TU->CIdx;
2681 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
Argyrios Kyrtzidis81b5ac32012-03-28 02:49:54 +00002682 setThreadBackgroundPriority();
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002683
Argyrios Kyrtzidis142bcb52012-03-28 02:17:59 +00002684 STUI->result = static_cast<ASTUnit *>(STUI->TU->TUData)->Save(STUI->FileName);
2685}
2686
Douglas Gregor19998442010-08-13 15:35:05 +00002687int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2688 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002689 if (!TU)
Douglas Gregor39c411f2011-07-06 16:43:36 +00002690 return CXSaveError_InvalidTU;
Argyrios Kyrtzidis142bcb52012-03-28 02:17:59 +00002691
2692 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
2693 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2694
2695 SaveTranslationUnitInfo STUI = { TU, FileName, options, CXSaveError_None };
2696
2697 if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred() ||
2698 getenv("LIBCLANG_NOTHREADS")) {
2699 clang_saveTranslationUnit_Impl(&STUI);
2700
2701 if (getenv("LIBCLANG_RESOURCE_USAGE"))
2702 PrintLibclangResourceUsage(TU);
2703
2704 return STUI.result;
2705 }
2706
2707 // We have an AST that has invalid nodes due to compiler errors.
2708 // Use a crash recovery thread for protection.
2709
2710 llvm::CrashRecoveryContext CRC;
2711
2712 if (!RunSafely(CRC, clang_saveTranslationUnit_Impl, &STUI)) {
2713 fprintf(stderr, "libclang: crash detected during AST saving: {\n");
2714 fprintf(stderr, " 'filename' : '%s'\n", FileName);
2715 fprintf(stderr, " 'options' : %d,\n", options);
2716 fprintf(stderr, "}\n");
2717
2718 return CXSaveError_Unknown;
2719
2720 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
Douglas Gregor6df78732011-05-05 20:27:22 +00002721 PrintLibclangResourceUsage(TU);
Argyrios Kyrtzidis142bcb52012-03-28 02:17:59 +00002722 }
2723
2724 return STUI.result;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002725}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002726
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002727void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002728 if (CTUnit) {
2729 // If the translation unit has been marked as unsafe to free, just discard
2730 // it.
Ted Kremeneka60ed472010-11-16 08:15:36 +00002731 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002732 return;
2733
Ted Kremeneka60ed472010-11-16 08:15:36 +00002734 delete static_cast<ASTUnit *>(CTUnit->TUData);
2735 disposeCXStringPool(CTUnit->StringPool);
Ted Kremenek15322172011-11-10 08:43:12 +00002736 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002737 delete CTUnit;
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002738 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002739}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002740
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002741unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2742 return CXReparse_None;
2743}
2744
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002745struct ReparseTranslationUnitInfo {
2746 CXTranslationUnit TU;
2747 unsigned num_unsaved_files;
2748 struct CXUnsavedFile *unsaved_files;
2749 unsigned options;
2750 int result;
2751};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002752
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002753static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002754 ReparseTranslationUnitInfo *RTUI =
2755 static_cast<ReparseTranslationUnitInfo*>(UserData);
2756 CXTranslationUnit TU = RTUI->TU;
Ted Kremenek15322172011-11-10 08:43:12 +00002757
2758 // Reset the associated diagnostics.
2759 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
2760 TU->Diagnostics = 0;
2761
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002762 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2763 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2764 unsigned options = RTUI->options;
2765 (void) options;
2766 RTUI->result = 1;
2767
Douglas Gregorabc563f2010-07-19 21:46:24 +00002768 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002769 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002770
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002771 CIndexer *CXXIdx = (CIndexer*)TU->CIdx;
2772 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
Argyrios Kyrtzidis81b5ac32012-03-28 02:49:54 +00002773 setThreadBackgroundPriority();
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002774
Ted Kremeneka60ed472010-11-16 08:15:36 +00002775 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor593b0c12010-09-23 18:47:53 +00002776 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002777
Dylan Noblesmith1e4c01b2012-02-13 12:32:21 +00002778 OwningPtr<std::vector<ASTUnit::RemappedFile> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00002779 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2780
2781 // Recover resources if we crash before exiting this function.
2782 llvm::CrashRecoveryContextCleanupRegistrar<
2783 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2784
Douglas Gregorabc563f2010-07-19 21:46:24 +00002785 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002786 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002787 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002788 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002789 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2790 Buffer));
Douglas Gregorabc563f2010-07-19 21:46:24 +00002791 }
2792
Ted Kremenek4ee99262011-03-22 20:16:19 +00002793 if (!CXXUnit->Reparse(RemappedFiles->size() ? &(*RemappedFiles)[0] : 0,
2794 RemappedFiles->size()))
Douglas Gregor593b0c12010-09-23 18:47:53 +00002795 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002796}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002797
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002798int clang_reparseTranslationUnit(CXTranslationUnit TU,
2799 unsigned num_unsaved_files,
2800 struct CXUnsavedFile *unsaved_files,
2801 unsigned options) {
2802 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2803 options, 0 };
Argyrios Kyrtzidis8c4b47e2011-10-28 22:54:33 +00002804
Argyrios Kyrtzidise7de9b42011-10-29 19:32:39 +00002805 if (getenv("LIBCLANG_NOTHREADS")) {
Argyrios Kyrtzidis8c4b47e2011-10-28 22:54:33 +00002806 clang_reparseTranslationUnit_Impl(&RTUI);
2807 return RTUI.result;
2808 }
2809
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002810 llvm::CrashRecoveryContext CRC;
2811
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002812 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002813 fprintf(stderr, "libclang: crash detected during reparsing\n");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002814 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002815 return 1;
Douglas Gregor6df78732011-05-05 20:27:22 +00002816 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
2817 PrintLibclangResourceUsage(TU);
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002818
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002819 return RTUI.result;
2820}
2821
Douglas Gregordf95a132010-08-09 20:45:32 +00002822
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002823CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002824 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002825 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002826
Ted Kremeneka60ed472010-11-16 08:15:36 +00002827 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002828 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002829}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002830
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002831CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002832 CXCursor Result = { CXCursor_TranslationUnit, 0, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002833 return Result;
2834}
2835
Ted Kremenekfb480492010-01-13 21:46:36 +00002836} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002837
Ted Kremenekfb480492010-01-13 21:46:36 +00002838//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002839// CXFile Operations.
2840//===----------------------------------------------------------------------===//
2841
2842extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002843CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002844 if (!SFile)
Ted Kremeneka60ed472010-11-16 08:15:36 +00002845 return createCXString((const char*)NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002846
Steve Naroff88145032009-10-27 14:35:18 +00002847 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002848 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002849}
2850
2851time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002852 if (!SFile)
2853 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002854
Steve Naroff88145032009-10-27 14:35:18 +00002855 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2856 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002857}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002858
Douglas Gregorb9790342010-01-22 21:44:22 +00002859CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2860 if (!tu)
2861 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002862
Ted Kremeneka60ed472010-11-16 08:15:36 +00002863 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002864
Douglas Gregorb9790342010-01-22 21:44:22 +00002865 FileManager &FMgr = CXXUnit->getFileManager();
Chris Lattner39b49bc2010-11-23 08:35:12 +00002866 return const_cast<FileEntry *>(FMgr.getFile(file_name));
Douglas Gregorb9790342010-01-22 21:44:22 +00002867}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002868
Douglas Gregordd3e5542011-05-04 00:14:37 +00002869unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit tu, CXFile file) {
2870 if (!tu || !file)
2871 return 0;
2872
2873 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
2874 FileEntry *FEnt = static_cast<FileEntry *>(file);
2875 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
2876 .isFileMultipleIncludeGuarded(FEnt);
2877}
2878
Ted Kremenekfb480492010-01-13 21:46:36 +00002879} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002880
Ted Kremenekfb480492010-01-13 21:46:36 +00002881//===----------------------------------------------------------------------===//
2882// CXCursor Operations.
2883//===----------------------------------------------------------------------===//
2884
Ted Kremenekfb480492010-01-13 21:46:36 +00002885static Decl *getDeclFromExpr(Stmt *E) {
Argyrios Kyrtzidisc2954612011-09-12 22:17:26 +00002886 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Douglas Gregordb1314e2010-10-01 21:11:22 +00002887 return getDeclFromExpr(CE->getSubExpr());
2888
Ted Kremenekfb480492010-01-13 21:46:36 +00002889 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2890 return RefExpr->getDecl();
2891 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2892 return ME->getMemberDecl();
2893 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2894 return RE->getDecl();
Argyrios Kyrtzidisb085d892012-03-30 00:19:18 +00002895 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
2896 if (PRE->isExplicitProperty())
2897 return PRE->getExplicitProperty();
2898 // It could be messaging both getter and setter as in:
2899 // ++myobj.myprop;
2900 // in which case prefer to associate the setter since it is less obvious
2901 // from inspecting the source that the setter is going to get called.
2902 if (PRE->isMessagingSetter())
2903 return PRE->getImplicitPropertySetter();
2904 return PRE->getImplicitPropertyGetter();
2905 }
John McCall4b9c2d22011-11-06 09:01:30 +00002906 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
2907 return getDeclFromExpr(POE->getSyntacticForm());
2908 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
2909 if (Expr *Src = OVE->getSourceExpr())
2910 return getDeclFromExpr(Src);
Douglas Gregordb1314e2010-10-01 21:11:22 +00002911
Ted Kremenekfb480492010-01-13 21:46:36 +00002912 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2913 return getDeclFromExpr(CE->getCallee());
Chris Lattner5f9e2722011-07-23 10:55:15 +00002914 if (CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Douglas Gregor93798e22010-11-05 21:11:19 +00002915 if (!CE->isElidable())
2916 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002917 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2918 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002919
Douglas Gregordb1314e2010-10-01 21:11:22 +00002920 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2921 return PE->getProtocol();
Douglas Gregorc7793c72011-01-15 01:15:58 +00002922 if (SubstNonTypeTemplateParmPackExpr *NTTP
2923 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
2924 return NTTP->getParameterPack();
Douglas Gregor94d96292011-01-19 20:34:17 +00002925 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2926 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
2927 isa<ParmVarDecl>(SizeOfPack->getPack()))
2928 return SizeOfPack->getPack();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002929
Ted Kremenekfb480492010-01-13 21:46:36 +00002930 return 0;
2931}
2932
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002933static SourceLocation getLocationFromExpr(Expr *E) {
Argyrios Kyrtzidisc2954612011-09-12 22:17:26 +00002934 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
2935 return getLocationFromExpr(CE->getSubExpr());
2936
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002937 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2938 return /*FIXME:*/Msg->getLeftLoc();
2939 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2940 return DRE->getLocation();
2941 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2942 return Member->getMemberLoc();
2943 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2944 return Ivar->getLocation();
Douglas Gregor94d96292011-01-19 20:34:17 +00002945 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2946 return SizeOfPack->getPackLoc();
Argyrios Kyrtzidisd0469522012-03-30 00:19:13 +00002947 if (ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
2948 return PropRef->getLocation();
Douglas Gregor94d96292011-01-19 20:34:17 +00002949
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002950 return E->getLocStart();
2951}
2952
Ted Kremenekfb480492010-01-13 21:46:36 +00002953extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002954
2955unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002956 CXCursorVisitor visitor,
2957 CXClientData client_data) {
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00002958 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
2959 /*VisitPreprocessorLast=*/false);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002960 return CursorVis.VisitChildren(parent);
2961}
2962
David Chisnall3387c652010-11-03 14:12:26 +00002963#ifndef __has_feature
2964#define __has_feature(x) 0
2965#endif
2966#if __has_feature(blocks)
2967typedef enum CXChildVisitResult
2968 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2969
2970static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2971 CXClientData client_data) {
2972 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2973 return block(cursor, parent);
2974}
2975#else
2976// If we are compiled with a compiler that doesn't have native blocks support,
2977// define and call the block manually, so the
2978typedef struct _CXChildVisitResult
2979{
2980 void *isa;
2981 int flags;
2982 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002983 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2984 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00002985} *CXCursorVisitorBlock;
2986
2987static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2988 CXClientData client_data) {
2989 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2990 return block->invoke(block, cursor, parent);
2991}
2992#endif
2993
2994
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002995unsigned clang_visitChildrenWithBlock(CXCursor parent,
2996 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00002997 return clang_visitChildren(parent, visitWithBlock, block);
2998}
2999
Douglas Gregor78205d42010-01-20 21:45:58 +00003000static CXString getDeclSpelling(Decl *D) {
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00003001 if (!D)
3002 return createCXString("");
3003
3004 NamedDecl *ND = dyn_cast<NamedDecl>(D);
Douglas Gregore3c60a72010-11-17 00:13:31 +00003005 if (!ND) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003006 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00003007 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3008 return createCXString(Property->getIdentifier()->getName());
3009
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003010 return createCXString("");
Douglas Gregore3c60a72010-11-17 00:13:31 +00003011 }
3012
Douglas Gregor78205d42010-01-20 21:45:58 +00003013 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003014 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003015
Douglas Gregor78205d42010-01-20 21:45:58 +00003016 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
3017 // No, this isn't the same as the code below. getIdentifier() is non-virtual
3018 // and returns different names. NamedDecl returns the class name and
3019 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003020 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003021
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003022 if (isa<UsingDirectiveDecl>(D))
3023 return createCXString("");
3024
Dylan Noblesmith36d59272012-02-13 12:32:26 +00003025 SmallString<1024> S;
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00003026 llvm::raw_svector_ostream os(S);
3027 ND->printName(os);
3028
3029 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00003030}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003031
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003032CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003033 if (clang_isTranslationUnit(C.kind))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003034 return clang_getTranslationUnitSpelling(
3035 static_cast<CXTranslationUnit>(C.data[2]));
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003036
Steve Narofff334b4e2009-09-02 18:26:48 +00003037 if (clang_isReference(C.kind)) {
3038 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00003039 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00003040 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003041 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003042 }
3043 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00003044 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003045 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003046 }
3047 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00003048 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00003049 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003050 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003051 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00003052 case CXCursor_CXXBaseSpecifier: {
3053 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
3054 return createCXString(B->getType().getAsString());
3055 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003056 case CXCursor_TypeRef: {
3057 TypeDecl *Type = getCursorTypeRef(C).first;
3058 assert(Type && "Missing type decl");
3059
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003060 return createCXString(getCursorContext(C).getTypeDeclType(Type).
3061 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003062 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003063 case CXCursor_TemplateRef: {
3064 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00003065 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003066
3067 return createCXString(Template->getNameAsString());
3068 }
Douglas Gregor69319002010-08-31 23:48:11 +00003069
3070 case CXCursor_NamespaceRef: {
3071 NamedDecl *NS = getCursorNamespaceRef(C).first;
3072 assert(NS && "Missing namespace decl");
3073
3074 return createCXString(NS->getNameAsString());
3075 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003076
Douglas Gregora67e03f2010-09-09 21:42:20 +00003077 case CXCursor_MemberRef: {
3078 FieldDecl *Field = getCursorMemberRef(C).first;
3079 assert(Field && "Missing member decl");
3080
3081 return createCXString(Field->getNameAsString());
3082 }
3083
Douglas Gregor36897b02010-09-10 00:22:18 +00003084 case CXCursor_LabelRef: {
3085 LabelStmt *Label = getCursorLabelRef(C).first;
3086 assert(Label && "Missing label");
3087
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003088 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00003089 }
3090
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003091 case CXCursor_OverloadedDeclRef: {
3092 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3093 if (Decl *D = Storage.dyn_cast<Decl *>()) {
3094 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
3095 return createCXString(ND->getNameAsString());
3096 return createCXString("");
3097 }
3098 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3099 return createCXString(E->getName().getAsString());
3100 OverloadedTemplateStorage *Ovl
3101 = Storage.get<OverloadedTemplateStorage*>();
3102 if (Ovl->size() == 0)
3103 return createCXString("");
3104 return createCXString((*Ovl->begin())->getNameAsString());
3105 }
3106
Douglas Gregor011d8b92012-02-15 00:54:55 +00003107 case CXCursor_VariableRef: {
3108 VarDecl *Var = getCursorVariableRef(C).first;
3109 assert(Var && "Missing variable decl");
3110
3111 return createCXString(Var->getNameAsString());
3112 }
3113
Daniel Dunbaracca7252009-11-30 20:42:49 +00003114 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003115 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00003116 }
3117 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003118
3119 if (clang_isExpression(C.kind)) {
3120 Decl *D = getDeclFromExpr(getCursorExpr(C));
3121 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00003122 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003123 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00003124 }
3125
Douglas Gregor36897b02010-09-10 00:22:18 +00003126 if (clang_isStatement(C.kind)) {
3127 Stmt *S = getCursorStmt(C);
3128 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003129 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00003130
3131 return createCXString("");
3132 }
3133
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003134 if (C.kind == CXCursor_MacroExpansion)
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003135 return createCXString(getCursorMacroExpansion(C)->getName()
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003136 ->getNameStart());
3137
Douglas Gregor572feb22010-03-18 18:04:21 +00003138 if (C.kind == CXCursor_MacroDefinition)
3139 return createCXString(getCursorMacroDefinition(C)->getName()
3140 ->getNameStart());
3141
Douglas Gregorecdcb882010-10-20 22:00:55 +00003142 if (C.kind == CXCursor_InclusionDirective)
3143 return createCXString(getCursorInclusionDirective(C)->getFileName());
3144
Douglas Gregor60cbfac2010-01-25 16:56:17 +00003145 if (clang_isDeclaration(C.kind))
3146 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00003147
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00003148 if (C.kind == CXCursor_AnnotateAttr) {
3149 AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
3150 return createCXString(AA->getAnnotation());
3151 }
3152
Argyrios Kyrtzidis84b79642011-12-06 22:05:01 +00003153 if (C.kind == CXCursor_AsmLabelAttr) {
3154 AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
3155 return createCXString(AA->getLabel());
3156 }
3157
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003158 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00003159}
3160
Argyrios Kyrtzidisba1da142012-03-30 20:58:35 +00003161CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C,
3162 unsigned pieceIndex,
3163 unsigned options) {
3164 if (clang_Cursor_isNull(C))
3165 return clang_getNullRange();
3166
3167 ASTContext &Ctx = getCursorContext(C);
3168
3169 if (clang_isStatement(C.kind)) {
3170 Stmt *S = getCursorStmt(C);
3171 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
3172 if (pieceIndex > 0)
3173 return clang_getNullRange();
3174 return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
3175 }
3176
3177 return clang_getNullRange();
3178 }
3179
3180 if (C.kind == CXCursor_ObjCMessageExpr) {
3181 if (ObjCMessageExpr *
3182 ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
3183 if (pieceIndex >= ME->getNumSelectorLocs())
3184 return clang_getNullRange();
3185 return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
3186 }
3187 }
3188
3189 if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
3190 C.kind == CXCursor_ObjCClassMethodDecl) {
3191 if (ObjCMethodDecl *
3192 MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
3193 if (pieceIndex >= MD->getNumSelectorLocs())
3194 return clang_getNullRange();
3195 return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
3196 }
3197 }
3198
Argyrios Kyrtzidis9482a182012-04-16 20:01:28 +00003199 if (C.kind == CXCursor_ObjCCategoryDecl ||
3200 C.kind == CXCursor_ObjCCategoryImplDecl) {
3201 if (pieceIndex > 0)
3202 return clang_getNullRange();
3203 if (ObjCCategoryDecl *
3204 CD = dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
3205 return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
3206 if (ObjCCategoryImplDecl *
3207 CID = dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
3208 return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
3209 }
3210
Argyrios Kyrtzidisba1da142012-03-30 20:58:35 +00003211 // FIXME: A CXCursor_InclusionDirective should give the location of the
3212 // filename, but we don't keep track of this.
3213
3214 // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
3215 // but we don't keep track of this.
3216
3217 // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
3218 // but we don't keep track of this.
3219
3220 // Default handling, give the location of the cursor.
3221
3222 if (pieceIndex > 0)
3223 return clang_getNullRange();
3224
3225 CXSourceLocation CXLoc = clang_getCursorLocation(C);
3226 SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
3227 return cxloc::translateSourceRange(Ctx, Loc);
3228}
3229
Douglas Gregor358559d2010-10-02 22:49:11 +00003230CXString clang_getCursorDisplayName(CXCursor C) {
3231 if (!clang_isDeclaration(C.kind))
3232 return clang_getCursorSpelling(C);
3233
3234 Decl *D = getCursorDecl(C);
3235 if (!D)
3236 return createCXString("");
3237
Douglas Gregor30c42402011-09-27 22:38:19 +00003238 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
Douglas Gregor358559d2010-10-02 22:49:11 +00003239 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
3240 D = FunTmpl->getTemplatedDecl();
3241
3242 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Dylan Noblesmith36d59272012-02-13 12:32:26 +00003243 SmallString<64> Str;
Douglas Gregor358559d2010-10-02 22:49:11 +00003244 llvm::raw_svector_ostream OS(Str);
Benjamin Kramera59d20b2012-02-07 11:57:57 +00003245 OS << *Function;
Douglas Gregor358559d2010-10-02 22:49:11 +00003246 if (Function->getPrimaryTemplate())
3247 OS << "<>";
3248 OS << "(";
3249 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
3250 if (I)
3251 OS << ", ";
3252 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
3253 }
3254
3255 if (Function->isVariadic()) {
3256 if (Function->getNumParams())
3257 OS << ", ";
3258 OS << "...";
3259 }
3260 OS << ")";
3261 return createCXString(OS.str());
3262 }
3263
3264 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
Dylan Noblesmith36d59272012-02-13 12:32:26 +00003265 SmallString<64> Str;
Douglas Gregor358559d2010-10-02 22:49:11 +00003266 llvm::raw_svector_ostream OS(Str);
Benjamin Kramera59d20b2012-02-07 11:57:57 +00003267 OS << *ClassTemplate;
Douglas Gregor358559d2010-10-02 22:49:11 +00003268 OS << "<";
3269 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
3270 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3271 if (I)
3272 OS << ", ";
3273
3274 NamedDecl *Param = Params->getParam(I);
3275 if (Param->getIdentifier()) {
3276 OS << Param->getIdentifier()->getName();
3277 continue;
3278 }
3279
3280 // There is no parameter name, which makes this tricky. Try to come up
3281 // with something useful that isn't too long.
3282 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3283 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
3284 else if (NonTypeTemplateParmDecl *NTTP
3285 = dyn_cast<NonTypeTemplateParmDecl>(Param))
3286 OS << NTTP->getType().getAsString(Policy);
3287 else
3288 OS << "template<...> class";
3289 }
3290
3291 OS << ">";
3292 return createCXString(OS.str());
3293 }
3294
3295 if (ClassTemplateSpecializationDecl *ClassSpec
3296 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
3297 // If the type was explicitly written, use that.
3298 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
3299 return createCXString(TSInfo->getType().getAsString(Policy));
3300
Dylan Noblesmith36d59272012-02-13 12:32:26 +00003301 SmallString<64> Str;
Douglas Gregor358559d2010-10-02 22:49:11 +00003302 llvm::raw_svector_ostream OS(Str);
Benjamin Kramera59d20b2012-02-07 11:57:57 +00003303 OS << *ClassSpec;
Douglas Gregor358559d2010-10-02 22:49:11 +00003304 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00003305 ClassSpec->getTemplateArgs().data(),
3306 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00003307 Policy);
3308 return createCXString(OS.str());
3309 }
3310
3311 return clang_getCursorSpelling(C);
3312}
3313
Ted Kremeneke68fff62010-02-17 00:41:32 +00003314CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00003315 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00003316 case CXCursor_FunctionDecl:
3317 return createCXString("FunctionDecl");
3318 case CXCursor_TypedefDecl:
3319 return createCXString("TypedefDecl");
3320 case CXCursor_EnumDecl:
3321 return createCXString("EnumDecl");
3322 case CXCursor_EnumConstantDecl:
3323 return createCXString("EnumConstantDecl");
3324 case CXCursor_StructDecl:
3325 return createCXString("StructDecl");
3326 case CXCursor_UnionDecl:
3327 return createCXString("UnionDecl");
3328 case CXCursor_ClassDecl:
3329 return createCXString("ClassDecl");
3330 case CXCursor_FieldDecl:
3331 return createCXString("FieldDecl");
3332 case CXCursor_VarDecl:
3333 return createCXString("VarDecl");
3334 case CXCursor_ParmDecl:
3335 return createCXString("ParmDecl");
3336 case CXCursor_ObjCInterfaceDecl:
3337 return createCXString("ObjCInterfaceDecl");
3338 case CXCursor_ObjCCategoryDecl:
3339 return createCXString("ObjCCategoryDecl");
3340 case CXCursor_ObjCProtocolDecl:
3341 return createCXString("ObjCProtocolDecl");
3342 case CXCursor_ObjCPropertyDecl:
3343 return createCXString("ObjCPropertyDecl");
3344 case CXCursor_ObjCIvarDecl:
3345 return createCXString("ObjCIvarDecl");
3346 case CXCursor_ObjCInstanceMethodDecl:
3347 return createCXString("ObjCInstanceMethodDecl");
3348 case CXCursor_ObjCClassMethodDecl:
3349 return createCXString("ObjCClassMethodDecl");
3350 case CXCursor_ObjCImplementationDecl:
3351 return createCXString("ObjCImplementationDecl");
3352 case CXCursor_ObjCCategoryImplDecl:
3353 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00003354 case CXCursor_CXXMethod:
3355 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003356 case CXCursor_UnexposedDecl:
3357 return createCXString("UnexposedDecl");
3358 case CXCursor_ObjCSuperClassRef:
3359 return createCXString("ObjCSuperClassRef");
3360 case CXCursor_ObjCProtocolRef:
3361 return createCXString("ObjCProtocolRef");
3362 case CXCursor_ObjCClassRef:
3363 return createCXString("ObjCClassRef");
3364 case CXCursor_TypeRef:
3365 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003366 case CXCursor_TemplateRef:
3367 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00003368 case CXCursor_NamespaceRef:
3369 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00003370 case CXCursor_MemberRef:
3371 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00003372 case CXCursor_LabelRef:
3373 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003374 case CXCursor_OverloadedDeclRef:
3375 return createCXString("OverloadedDeclRef");
Douglas Gregor011d8b92012-02-15 00:54:55 +00003376 case CXCursor_VariableRef:
3377 return createCXString("VariableRef");
Douglas Gregor42b29842011-10-05 19:00:14 +00003378 case CXCursor_IntegerLiteral:
3379 return createCXString("IntegerLiteral");
3380 case CXCursor_FloatingLiteral:
3381 return createCXString("FloatingLiteral");
3382 case CXCursor_ImaginaryLiteral:
3383 return createCXString("ImaginaryLiteral");
3384 case CXCursor_StringLiteral:
3385 return createCXString("StringLiteral");
3386 case CXCursor_CharacterLiteral:
3387 return createCXString("CharacterLiteral");
3388 case CXCursor_ParenExpr:
3389 return createCXString("ParenExpr");
3390 case CXCursor_UnaryOperator:
3391 return createCXString("UnaryOperator");
3392 case CXCursor_ArraySubscriptExpr:
3393 return createCXString("ArraySubscriptExpr");
3394 case CXCursor_BinaryOperator:
3395 return createCXString("BinaryOperator");
3396 case CXCursor_CompoundAssignOperator:
3397 return createCXString("CompoundAssignOperator");
3398 case CXCursor_ConditionalOperator:
3399 return createCXString("ConditionalOperator");
3400 case CXCursor_CStyleCastExpr:
3401 return createCXString("CStyleCastExpr");
3402 case CXCursor_CompoundLiteralExpr:
3403 return createCXString("CompoundLiteralExpr");
3404 case CXCursor_InitListExpr:
3405 return createCXString("InitListExpr");
3406 case CXCursor_AddrLabelExpr:
3407 return createCXString("AddrLabelExpr");
3408 case CXCursor_StmtExpr:
3409 return createCXString("StmtExpr");
3410 case CXCursor_GenericSelectionExpr:
3411 return createCXString("GenericSelectionExpr");
3412 case CXCursor_GNUNullExpr:
3413 return createCXString("GNUNullExpr");
3414 case CXCursor_CXXStaticCastExpr:
3415 return createCXString("CXXStaticCastExpr");
3416 case CXCursor_CXXDynamicCastExpr:
3417 return createCXString("CXXDynamicCastExpr");
3418 case CXCursor_CXXReinterpretCastExpr:
3419 return createCXString("CXXReinterpretCastExpr");
3420 case CXCursor_CXXConstCastExpr:
3421 return createCXString("CXXConstCastExpr");
3422 case CXCursor_CXXFunctionalCastExpr:
3423 return createCXString("CXXFunctionalCastExpr");
3424 case CXCursor_CXXTypeidExpr:
3425 return createCXString("CXXTypeidExpr");
3426 case CXCursor_CXXBoolLiteralExpr:
3427 return createCXString("CXXBoolLiteralExpr");
3428 case CXCursor_CXXNullPtrLiteralExpr:
3429 return createCXString("CXXNullPtrLiteralExpr");
3430 case CXCursor_CXXThisExpr:
3431 return createCXString("CXXThisExpr");
3432 case CXCursor_CXXThrowExpr:
3433 return createCXString("CXXThrowExpr");
3434 case CXCursor_CXXNewExpr:
3435 return createCXString("CXXNewExpr");
3436 case CXCursor_CXXDeleteExpr:
3437 return createCXString("CXXDeleteExpr");
3438 case CXCursor_UnaryExpr:
3439 return createCXString("UnaryExpr");
3440 case CXCursor_ObjCStringLiteral:
3441 return createCXString("ObjCStringLiteral");
Ted Kremenekb3f75422012-03-06 20:06:06 +00003442 case CXCursor_ObjCBoolLiteralExpr:
3443 return createCXString("ObjCBoolLiteralExpr");
Douglas Gregor42b29842011-10-05 19:00:14 +00003444 case CXCursor_ObjCEncodeExpr:
3445 return createCXString("ObjCEncodeExpr");
3446 case CXCursor_ObjCSelectorExpr:
3447 return createCXString("ObjCSelectorExpr");
3448 case CXCursor_ObjCProtocolExpr:
3449 return createCXString("ObjCProtocolExpr");
3450 case CXCursor_ObjCBridgedCastExpr:
3451 return createCXString("ObjCBridgedCastExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00003452 case CXCursor_BlockExpr:
3453 return createCXString("BlockExpr");
Douglas Gregor42b29842011-10-05 19:00:14 +00003454 case CXCursor_PackExpansionExpr:
3455 return createCXString("PackExpansionExpr");
3456 case CXCursor_SizeOfPackExpr:
3457 return createCXString("SizeOfPackExpr");
Douglas Gregor011d8b92012-02-15 00:54:55 +00003458 case CXCursor_LambdaExpr:
3459 return createCXString("LambdaExpr");
Douglas Gregor42b29842011-10-05 19:00:14 +00003460 case CXCursor_UnexposedExpr:
3461 return createCXString("UnexposedExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003462 case CXCursor_DeclRefExpr:
3463 return createCXString("DeclRefExpr");
3464 case CXCursor_MemberRefExpr:
3465 return createCXString("MemberRefExpr");
3466 case CXCursor_CallExpr:
3467 return createCXString("CallExpr");
3468 case CXCursor_ObjCMessageExpr:
3469 return createCXString("ObjCMessageExpr");
3470 case CXCursor_UnexposedStmt:
3471 return createCXString("UnexposedStmt");
Douglas Gregor42b29842011-10-05 19:00:14 +00003472 case CXCursor_DeclStmt:
3473 return createCXString("DeclStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00003474 case CXCursor_LabelStmt:
3475 return createCXString("LabelStmt");
Douglas Gregor42b29842011-10-05 19:00:14 +00003476 case CXCursor_CompoundStmt:
3477 return createCXString("CompoundStmt");
3478 case CXCursor_CaseStmt:
3479 return createCXString("CaseStmt");
3480 case CXCursor_DefaultStmt:
3481 return createCXString("DefaultStmt");
3482 case CXCursor_IfStmt:
3483 return createCXString("IfStmt");
3484 case CXCursor_SwitchStmt:
3485 return createCXString("SwitchStmt");
3486 case CXCursor_WhileStmt:
3487 return createCXString("WhileStmt");
3488 case CXCursor_DoStmt:
3489 return createCXString("DoStmt");
3490 case CXCursor_ForStmt:
3491 return createCXString("ForStmt");
3492 case CXCursor_GotoStmt:
3493 return createCXString("GotoStmt");
3494 case CXCursor_IndirectGotoStmt:
3495 return createCXString("IndirectGotoStmt");
3496 case CXCursor_ContinueStmt:
3497 return createCXString("ContinueStmt");
3498 case CXCursor_BreakStmt:
3499 return createCXString("BreakStmt");
3500 case CXCursor_ReturnStmt:
3501 return createCXString("ReturnStmt");
3502 case CXCursor_AsmStmt:
3503 return createCXString("AsmStmt");
3504 case CXCursor_ObjCAtTryStmt:
3505 return createCXString("ObjCAtTryStmt");
3506 case CXCursor_ObjCAtCatchStmt:
3507 return createCXString("ObjCAtCatchStmt");
3508 case CXCursor_ObjCAtFinallyStmt:
3509 return createCXString("ObjCAtFinallyStmt");
3510 case CXCursor_ObjCAtThrowStmt:
3511 return createCXString("ObjCAtThrowStmt");
3512 case CXCursor_ObjCAtSynchronizedStmt:
3513 return createCXString("ObjCAtSynchronizedStmt");
3514 case CXCursor_ObjCAutoreleasePoolStmt:
3515 return createCXString("ObjCAutoreleasePoolStmt");
3516 case CXCursor_ObjCForCollectionStmt:
3517 return createCXString("ObjCForCollectionStmt");
3518 case CXCursor_CXXCatchStmt:
3519 return createCXString("CXXCatchStmt");
3520 case CXCursor_CXXTryStmt:
3521 return createCXString("CXXTryStmt");
3522 case CXCursor_CXXForRangeStmt:
3523 return createCXString("CXXForRangeStmt");
3524 case CXCursor_SEHTryStmt:
3525 return createCXString("SEHTryStmt");
3526 case CXCursor_SEHExceptStmt:
3527 return createCXString("SEHExceptStmt");
3528 case CXCursor_SEHFinallyStmt:
3529 return createCXString("SEHFinallyStmt");
3530 case CXCursor_NullStmt:
3531 return createCXString("NullStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003532 case CXCursor_InvalidFile:
3533 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00003534 case CXCursor_InvalidCode:
3535 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003536 case CXCursor_NoDeclFound:
3537 return createCXString("NoDeclFound");
3538 case CXCursor_NotImplemented:
3539 return createCXString("NotImplemented");
3540 case CXCursor_TranslationUnit:
3541 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00003542 case CXCursor_UnexposedAttr:
3543 return createCXString("UnexposedAttr");
3544 case CXCursor_IBActionAttr:
3545 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003546 case CXCursor_IBOutletAttr:
3547 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003548 case CXCursor_IBOutletCollectionAttr:
3549 return createCXString("attribute(iboutletcollection)");
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00003550 case CXCursor_CXXFinalAttr:
3551 return createCXString("attribute(final)");
3552 case CXCursor_CXXOverrideAttr:
3553 return createCXString("attribute(override)");
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00003554 case CXCursor_AnnotateAttr:
3555 return createCXString("attribute(annotate)");
Argyrios Kyrtzidis84b79642011-12-06 22:05:01 +00003556 case CXCursor_AsmLabelAttr:
3557 return createCXString("asm label");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003558 case CXCursor_PreprocessingDirective:
3559 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003560 case CXCursor_MacroDefinition:
3561 return createCXString("macro definition");
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003562 case CXCursor_MacroExpansion:
3563 return createCXString("macro expansion");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003564 case CXCursor_InclusionDirective:
3565 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003566 case CXCursor_Namespace:
3567 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003568 case CXCursor_LinkageSpec:
3569 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003570 case CXCursor_CXXBaseSpecifier:
3571 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003572 case CXCursor_Constructor:
3573 return createCXString("CXXConstructor");
3574 case CXCursor_Destructor:
3575 return createCXString("CXXDestructor");
3576 case CXCursor_ConversionFunction:
3577 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003578 case CXCursor_TemplateTypeParameter:
3579 return createCXString("TemplateTypeParameter");
3580 case CXCursor_NonTypeTemplateParameter:
3581 return createCXString("NonTypeTemplateParameter");
3582 case CXCursor_TemplateTemplateParameter:
3583 return createCXString("TemplateTemplateParameter");
3584 case CXCursor_FunctionTemplate:
3585 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003586 case CXCursor_ClassTemplate:
3587 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003588 case CXCursor_ClassTemplatePartialSpecialization:
3589 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003590 case CXCursor_NamespaceAlias:
3591 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003592 case CXCursor_UsingDirective:
3593 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003594 case CXCursor_UsingDeclaration:
3595 return createCXString("UsingDeclaration");
Richard Smith162e1c12011-04-15 14:24:37 +00003596 case CXCursor_TypeAliasDecl:
Douglas Gregor352697a2011-06-03 23:08:58 +00003597 return createCXString("TypeAliasDecl");
3598 case CXCursor_ObjCSynthesizeDecl:
3599 return createCXString("ObjCSynthesizeDecl");
3600 case CXCursor_ObjCDynamicDecl:
3601 return createCXString("ObjCDynamicDecl");
Argyrios Kyrtzidis2dfdb942011-09-30 17:58:23 +00003602 case CXCursor_CXXAccessSpecifier:
3603 return createCXString("CXXAccessSpecifier");
Steve Naroff89922f82009-08-31 00:59:03 +00003604 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003605
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003606 llvm_unreachable("Unhandled CXCursorKind");
Steve Naroff600866c2009-08-27 19:51:58 +00003607}
Steve Naroff89922f82009-08-31 00:59:03 +00003608
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003609struct GetCursorData {
3610 SourceLocation TokenBeginLoc;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003611 bool PointsAtMacroArgExpansion;
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003612 CXCursor &BestCursor;
3613
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003614 GetCursorData(SourceManager &SM,
3615 SourceLocation tokenBegin, CXCursor &outputCursor)
3616 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
3617 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
3618 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003619};
3620
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003621static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3622 CXCursor parent,
3623 CXClientData client_data) {
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003624 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
3625 CXCursor *BestCursor = &Data->BestCursor;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003626
3627 // If we point inside a macro argument we should provide info of what the
3628 // token is so use the actual cursor, don't replace it with a macro expansion
3629 // cursor.
3630 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
3631 return CXChildVisit_Recurse;
Argyrios Kyrtzidis65ab9072011-09-26 19:05:37 +00003632
3633 if (clang_isDeclaration(cursor.kind)) {
3634 // Avoid having the implicit methods override the property decls.
Argyrios Kyrtzidisa9d45a32012-04-16 22:42:01 +00003635 if (ObjCMethodDecl *MD
3636 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
Argyrios Kyrtzidis65ab9072011-09-26 19:05:37 +00003637 if (MD->isImplicit())
3638 return CXChildVisit_Break;
Argyrios Kyrtzidisa9d45a32012-04-16 22:42:01 +00003639
3640 } else if (ObjCInterfaceDecl *ID
3641 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) {
3642 // Check that when we have multiple @class references in the same line,
3643 // that later ones do not override the previous ones.
3644 // If we have:
3645 // @class Foo, Bar;
3646 // source ranges for both start at '@', so 'Bar' will end up overriding
3647 // 'Foo' even though the cursor location was at 'Foo'.
3648 if (BestCursor->kind == CXCursor_ObjCInterfaceDecl ||
3649 BestCursor->kind == CXCursor_ObjCClassRef)
3650 if (ObjCInterfaceDecl *PrevID
3651 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(*BestCursor))){
3652 if (PrevID != ID &&
3653 !PrevID->isThisDeclarationADefinition() &&
3654 !ID->isThisDeclarationADefinition())
3655 return CXChildVisit_Break;
3656 }
3657 }
Argyrios Kyrtzidis65ab9072011-09-26 19:05:37 +00003658 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003659
3660 if (clang_isExpression(cursor.kind) &&
3661 clang_isDeclaration(BestCursor->kind)) {
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00003662 if (Decl *D = getCursorDecl(*BestCursor)) {
3663 // Avoid having the cursor of an expression replace the declaration cursor
3664 // when the expression source range overlaps the declaration range.
3665 // This can happen for C++ constructor expressions whose range generally
3666 // include the variable declaration, e.g.:
3667 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
3668 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
3669 D->getLocation() == Data->TokenBeginLoc)
3670 return CXChildVisit_Break;
3671 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003672 }
3673
Douglas Gregor93798e22010-11-05 21:11:19 +00003674 // If our current best cursor is the construction of a temporary object,
3675 // don't replace that cursor with a type reference, because we want
3676 // clang_getCursor() to point at the constructor.
3677 if (clang_isExpression(BestCursor->kind) &&
3678 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003679 cursor.kind == CXCursor_TypeRef) {
3680 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
3681 // as having the actual point on the type reference.
3682 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
Douglas Gregor93798e22010-11-05 21:11:19 +00003683 return CXChildVisit_Recurse;
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003684 }
Douglas Gregor93798e22010-11-05 21:11:19 +00003685
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003686 *BestCursor = cursor;
3687 return CXChildVisit_Recurse;
3688}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003689
Douglas Gregorb9790342010-01-22 21:44:22 +00003690CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3691 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003692 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003693
Ted Kremeneka60ed472010-11-16 08:15:36 +00003694 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003695 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3696
Ted Kremeneka297de22010-01-25 22:34:44 +00003697 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003698 CXCursor Result = cxcursor::getCursor(TU, SLoc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003699
Douglas Gregor40749ee2010-11-03 00:35:38 +00003700 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregor40749ee2010-11-03 00:35:38 +00003701 if (Logging) {
3702 CXFile SearchFile;
3703 unsigned SearchLine, SearchColumn;
3704 CXFile ResultFile;
3705 unsigned ResultLine, ResultColumn;
Douglas Gregor66537982010-11-17 17:14:07 +00003706 CXString SearchFileName, ResultFileName, KindSpelling, USR;
3707 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
Douglas Gregor40749ee2010-11-03 00:35:38 +00003708 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3709
Chandler Carruth20174222011-08-31 16:53:37 +00003710 clang_getExpansionLocation(Loc, &SearchFile, &SearchLine, &SearchColumn, 0);
3711 clang_getExpansionLocation(ResultLoc, &ResultFile, &ResultLine,
3712 &ResultColumn, 0);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003713 SearchFileName = clang_getFileName(SearchFile);
3714 ResultFileName = clang_getFileName(ResultFile);
3715 KindSpelling = clang_getCursorKindSpelling(Result.kind);
Douglas Gregor66537982010-11-17 17:14:07 +00003716 USR = clang_getCursorUSR(Result);
3717 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n",
Douglas Gregor40749ee2010-11-03 00:35:38 +00003718 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3719 clang_getCString(KindSpelling),
Douglas Gregor66537982010-11-17 17:14:07 +00003720 clang_getCString(ResultFileName), ResultLine, ResultColumn,
3721 clang_getCString(USR), IsDef);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003722 clang_disposeString(SearchFileName);
3723 clang_disposeString(ResultFileName);
3724 clang_disposeString(KindSpelling);
Douglas Gregor66537982010-11-17 17:14:07 +00003725 clang_disposeString(USR);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003726
3727 CXCursor Definition = clang_getCursorDefinition(Result);
3728 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
3729 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
3730 CXString DefinitionKindSpelling
3731 = clang_getCursorKindSpelling(Definition.kind);
3732 CXFile DefinitionFile;
3733 unsigned DefinitionLine, DefinitionColumn;
Chandler Carruth20174222011-08-31 16:53:37 +00003734 clang_getExpansionLocation(DefinitionLoc, &DefinitionFile,
3735 &DefinitionLine, &DefinitionColumn, 0);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003736 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
3737 fprintf(stderr, " -> %s(%s:%d:%d)\n",
3738 clang_getCString(DefinitionKindSpelling),
3739 clang_getCString(DefinitionFileName),
3740 DefinitionLine, DefinitionColumn);
3741 clang_disposeString(DefinitionFileName);
3742 clang_disposeString(DefinitionKindSpelling);
3743 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003744 }
3745
Ted Kremeneke68fff62010-02-17 00:41:32 +00003746 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003747}
3748
Ted Kremenek73885552009-11-17 19:28:59 +00003749CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003750 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003751}
3752
3753unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003754 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003755}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003756
Douglas Gregor9ce55842010-11-20 00:09:34 +00003757unsigned clang_hashCursor(CXCursor C) {
3758 unsigned Index = 0;
3759 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
3760 Index = 1;
3761
3762 return llvm::DenseMapInfo<std::pair<unsigned, void*> >::getHashValue(
3763 std::make_pair(C.kind, C.data[Index]));
3764}
3765
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003766unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003767 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3768}
3769
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003770unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003771 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3772}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003773
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003774unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003775 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3776}
3777
Douglas Gregor97b98722010-01-19 23:20:36 +00003778unsigned clang_isExpression(enum CXCursorKind K) {
3779 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3780}
3781
3782unsigned clang_isStatement(enum CXCursorKind K) {
3783 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3784}
3785
Douglas Gregor8be80e12011-07-06 03:00:34 +00003786unsigned clang_isAttribute(enum CXCursorKind K) {
3787 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
3788}
3789
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003790unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3791 return K == CXCursor_TranslationUnit;
3792}
3793
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003794unsigned clang_isPreprocessing(enum CXCursorKind K) {
3795 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3796}
3797
Ted Kremenekad6eff62010-03-08 21:17:29 +00003798unsigned clang_isUnexposed(enum CXCursorKind K) {
3799 switch (K) {
3800 case CXCursor_UnexposedDecl:
3801 case CXCursor_UnexposedExpr:
3802 case CXCursor_UnexposedStmt:
3803 case CXCursor_UnexposedAttr:
3804 return true;
3805 default:
3806 return false;
3807 }
3808}
3809
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003810CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003811 return C.kind;
3812}
3813
Douglas Gregor98258af2010-01-18 22:46:11 +00003814CXSourceLocation clang_getCursorLocation(CXCursor C) {
3815 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003816 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003817 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003818 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3819 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003820 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003821 }
3822
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003823 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003824 std::pair<ObjCProtocolDecl *, SourceLocation> P
3825 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003826 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003827 }
3828
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003829 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003830 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3831 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003832 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003833 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003834
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003835 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003836 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003837 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003838 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003839
3840 case CXCursor_TemplateRef: {
3841 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3842 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3843 }
3844
Douglas Gregor69319002010-08-31 23:48:11 +00003845 case CXCursor_NamespaceRef: {
3846 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3847 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3848 }
3849
Douglas Gregora67e03f2010-09-09 21:42:20 +00003850 case CXCursor_MemberRef: {
3851 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3852 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3853 }
3854
Douglas Gregor011d8b92012-02-15 00:54:55 +00003855 case CXCursor_VariableRef: {
3856 std::pair<VarDecl *, SourceLocation> P = getCursorVariableRef(C);
3857 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3858 }
3859
Ted Kremenek3064ef92010-08-27 21:34:58 +00003860 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003861 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3862 if (!BaseSpec)
3863 return clang_getNullLocation();
3864
3865 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3866 return cxloc::translateSourceLocation(getCursorContext(C),
3867 TSInfo->getTypeLoc().getBeginLoc());
3868
3869 return cxloc::translateSourceLocation(getCursorContext(C),
Daniel Dunbar96a00142012-03-09 18:35:03 +00003870 BaseSpec->getLocStart());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003871 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003872
Douglas Gregor36897b02010-09-10 00:22:18 +00003873 case CXCursor_LabelRef: {
3874 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3875 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3876 }
3877
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003878 case CXCursor_OverloadedDeclRef:
3879 return cxloc::translateSourceLocation(getCursorContext(C),
3880 getCursorOverloadedDeclRef(C).second);
3881
Douglas Gregorf46034a2010-01-18 23:41:10 +00003882 default:
3883 // FIXME: Need a way to enumerate all non-reference cases.
3884 llvm_unreachable("Missed a reference kind");
3885 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003886 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003887
3888 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003889 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003890 getLocationFromExpr(getCursorExpr(C)));
3891
Douglas Gregor36897b02010-09-10 00:22:18 +00003892 if (clang_isStatement(C.kind))
3893 return cxloc::translateSourceLocation(getCursorContext(C),
3894 getCursorStmt(C)->getLocStart());
3895
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003896 if (C.kind == CXCursor_PreprocessingDirective) {
3897 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3898 return cxloc::translateSourceLocation(getCursorContext(C), L);
3899 }
Douglas Gregor48072312010-03-18 15:23:44 +00003900
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003901 if (C.kind == CXCursor_MacroExpansion) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003902 SourceLocation L
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003903 = cxcursor::getCursorMacroExpansion(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003904 return cxloc::translateSourceLocation(getCursorContext(C), L);
3905 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003906
3907 if (C.kind == CXCursor_MacroDefinition) {
3908 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3909 return cxloc::translateSourceLocation(getCursorContext(C), L);
3910 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003911
3912 if (C.kind == CXCursor_InclusionDirective) {
3913 SourceLocation L
3914 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3915 return cxloc::translateSourceLocation(getCursorContext(C), L);
3916 }
3917
Ted Kremenek9a700d22010-05-12 06:16:13 +00003918 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003919 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003920
Douglas Gregorf46034a2010-01-18 23:41:10 +00003921 Decl *D = getCursorDecl(C);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00003922 if (!D)
3923 return clang_getNullLocation();
3924
Douglas Gregorf46034a2010-01-18 23:41:10 +00003925 SourceLocation Loc = D->getLocation();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003926 // FIXME: Multiple variables declared in a single declaration
3927 // currently lack the information needed to correctly determine their
3928 // ranges when accounting for the type-specifier. We use context
3929 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3930 // and if so, whether it is the first decl.
3931 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3932 if (!cxcursor::isFirstInDeclGroup(C))
3933 Loc = VD->getLocation();
3934 }
3935
Argyrios Kyrtzidisccc6f362012-03-23 03:33:19 +00003936 // For ObjC methods, give the start location of the method name.
3937 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
3938 Loc = MD->getSelectorStartLoc();
3939
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003940 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003941}
Douglas Gregora7bde202010-01-19 00:34:46 +00003942
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003943} // end extern "C"
3944
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003945CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
3946 assert(TU);
3947
3948 // Guard against an invalid SourceLocation, or we may assert in one
3949 // of the following calls.
3950 if (SLoc.isInvalid())
3951 return clang_getNullCursor();
3952
3953 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
3954
3955 // Translate the given source location to make it point at the beginning of
3956 // the token under the cursor.
3957 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +00003958 CXXUnit->getASTContext().getLangOpts());
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003959
3960 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3961 if (SLoc.isValid()) {
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003962 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003963 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
3964 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00003965 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003966 SourceLocation(SLoc));
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00003967 CursorVis.visitFileRegion();
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003968 }
3969
3970 return Result;
3971}
3972
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003973static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003974 if (clang_isReference(C.kind)) {
3975 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003976 case CXCursor_ObjCSuperClassRef:
3977 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003978
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003979 case CXCursor_ObjCProtocolRef:
3980 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003981
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003982 case CXCursor_ObjCClassRef:
3983 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003984
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003985 case CXCursor_TypeRef:
3986 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003987
3988 case CXCursor_TemplateRef:
3989 return getCursorTemplateRef(C).second;
3990
Douglas Gregor69319002010-08-31 23:48:11 +00003991 case CXCursor_NamespaceRef:
3992 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003993
3994 case CXCursor_MemberRef:
3995 return getCursorMemberRef(C).second;
3996
Ted Kremenek3064ef92010-08-27 21:34:58 +00003997 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003998 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003999
Douglas Gregor36897b02010-09-10 00:22:18 +00004000 case CXCursor_LabelRef:
4001 return getCursorLabelRef(C).second;
4002
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004003 case CXCursor_OverloadedDeclRef:
4004 return getCursorOverloadedDeclRef(C).second;
4005
Douglas Gregor011d8b92012-02-15 00:54:55 +00004006 case CXCursor_VariableRef:
4007 return getCursorVariableRef(C).second;
4008
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004009 default:
4010 // FIXME: Need a way to enumerate all non-reference cases.
4011 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00004012 }
4013 }
Douglas Gregor97b98722010-01-19 23:20:36 +00004014
4015 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004016 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00004017
4018 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004019 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004020
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00004021 if (clang_isAttribute(C.kind))
4022 return getCursorAttr(C)->getRange();
4023
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004024 if (C.kind == CXCursor_PreprocessingDirective)
4025 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00004026
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004027 if (C.kind == CXCursor_MacroExpansion) {
4028 ASTUnit *TU = getCursorASTUnit(C);
4029 SourceRange Range = cxcursor::getCursorMacroExpansion(C)->getSourceRange();
4030 return TU->mapRangeFromPreamble(Range);
4031 }
Douglas Gregor572feb22010-03-18 18:04:21 +00004032
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004033 if (C.kind == CXCursor_MacroDefinition) {
4034 ASTUnit *TU = getCursorASTUnit(C);
4035 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
4036 return TU->mapRangeFromPreamble(Range);
4037 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00004038
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004039 if (C.kind == CXCursor_InclusionDirective) {
4040 ASTUnit *TU = getCursorASTUnit(C);
4041 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
4042 return TU->mapRangeFromPreamble(Range);
4043 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00004044
Argyrios Kyrtzidis0822c5f2012-03-19 23:17:58 +00004045 if (C.kind == CXCursor_TranslationUnit) {
4046 ASTUnit *TU = getCursorASTUnit(C);
4047 FileID MainID = TU->getSourceManager().getMainFileID();
4048 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
4049 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
4050 return SourceRange(Start, End);
4051 }
4052
Ted Kremenek007a7c92010-11-01 23:26:51 +00004053 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
4054 Decl *D = cxcursor::getCursorDecl(C);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00004055 if (!D)
4056 return SourceRange();
4057
Ted Kremenek007a7c92010-11-01 23:26:51 +00004058 SourceRange R = D->getSourceRange();
4059 // FIXME: Multiple variables declared in a single declaration
4060 // currently lack the information needed to correctly determine their
4061 // ranges when accounting for the type-specifier. We use context
4062 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
4063 // and if so, whether it is the first decl.
4064 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4065 if (!cxcursor::isFirstInDeclGroup(C))
4066 R.setBegin(VD->getLocation());
4067 }
4068 return R;
4069 }
Douglas Gregor66537982010-11-17 17:14:07 +00004070 return SourceRange();
4071}
4072
4073/// \brief Retrieves the "raw" cursor extent, which is then extended to include
4074/// the decl-specifier-seq for declarations.
4075static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
4076 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
4077 Decl *D = cxcursor::getCursorDecl(C);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00004078 if (!D)
4079 return SourceRange();
4080
Douglas Gregor66537982010-11-17 17:14:07 +00004081 SourceRange R = D->getSourceRange();
Douglas Gregor66537982010-11-17 17:14:07 +00004082
Douglas Gregor2494dd02011-03-01 01:34:45 +00004083 // Adjust the start of the location for declarations preceded by
4084 // declaration specifiers.
4085 SourceLocation StartLoc;
4086 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
4087 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
Daniel Dunbar96a00142012-03-09 18:35:03 +00004088 StartLoc = TI->getTypeLoc().getLocStart();
Douglas Gregor2494dd02011-03-01 01:34:45 +00004089 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
4090 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
Daniel Dunbar96a00142012-03-09 18:35:03 +00004091 StartLoc = TI->getTypeLoc().getLocStart();
Douglas Gregor2494dd02011-03-01 01:34:45 +00004092 }
4093
4094 if (StartLoc.isValid() && R.getBegin().isValid() &&
4095 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
4096 R.setBegin(StartLoc);
4097
4098 // FIXME: Multiple variables declared in a single declaration
4099 // currently lack the information needed to correctly determine their
4100 // ranges when accounting for the type-specifier. We use context
4101 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
4102 // and if so, whether it is the first decl.
4103 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4104 if (!cxcursor::isFirstInDeclGroup(C))
4105 R.setBegin(VD->getLocation());
Douglas Gregor66537982010-11-17 17:14:07 +00004106 }
4107
4108 return R;
4109 }
4110
4111 return getRawCursorExtent(C);
4112}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004113
4114extern "C" {
4115
4116CXSourceRange clang_getCursorExtent(CXCursor C) {
4117 SourceRange R = getRawCursorExtent(C);
4118 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00004119 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004120
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004121 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00004122}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004123
4124CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00004125 if (clang_isInvalid(C.kind))
4126 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004127
Ted Kremeneka60ed472010-11-16 08:15:36 +00004128 CXTranslationUnit tu = getCursorTU(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004129 if (clang_isDeclaration(C.kind)) {
4130 Decl *D = getCursorDecl(C);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00004131 if (!D)
4132 return clang_getNullCursor();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004133 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004134 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Chris Lattner5f9e2722011-07-23 10:55:15 +00004135 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00004136 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
4137 return MakeCXCursor(Property, tu);
4138
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004139 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004140 }
4141
Douglas Gregor97b98722010-01-19 23:20:36 +00004142 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004143 Expr *E = getCursorExpr(C);
4144 Decl *D = getDeclFromExpr(E);
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00004145 if (D) {
4146 CXCursor declCursor = MakeCXCursor(D, tu);
4147 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
4148 declCursor);
4149 return declCursor;
4150 }
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004151
4152 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004153 return MakeCursorOverloadedDeclRef(Ovl, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004154
Douglas Gregor97b98722010-01-19 23:20:36 +00004155 return clang_getNullCursor();
4156 }
4157
Douglas Gregor36897b02010-09-10 00:22:18 +00004158 if (clang_isStatement(C.kind)) {
4159 Stmt *S = getCursorStmt(C);
4160 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Ted Kremenek37c2e962011-03-15 23:47:49 +00004161 if (LabelDecl *label = Goto->getLabel())
4162 if (LabelStmt *labelS = label->getStmt())
4163 return MakeCXCursor(labelS, getCursorDecl(C), tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00004164
4165 return clang_getNullCursor();
4166 }
4167
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004168 if (C.kind == CXCursor_MacroExpansion) {
Chandler Carruth9e5bb852011-07-14 08:20:46 +00004169 if (MacroDefinition *Def = getCursorMacroExpansion(C)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004170 return MakeMacroDefinitionCursor(Def, tu);
Douglas Gregorbf7efa22010-03-18 18:23:03 +00004171 }
4172
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004173 if (!clang_isReference(C.kind))
4174 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004175
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004176 switch (C.kind) {
4177 case CXCursor_ObjCSuperClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004178 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004179
4180 case CXCursor_ObjCProtocolRef: {
Argyrios Kyrtzidis98c16b82012-01-24 19:40:15 +00004181 ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
4182 if (ObjCProtocolDecl *Def = Prot->getDefinition())
4183 return MakeCXCursor(Def, tu);
4184
Argyrios Kyrtzidisc15707d2012-01-24 21:39:26 +00004185 return MakeCXCursor(Prot, tu);
Argyrios Kyrtzidis98c16b82012-01-24 19:40:15 +00004186 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004187
Douglas Gregor7723fec2011-12-15 20:29:51 +00004188 case CXCursor_ObjCClassRef: {
4189 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
4190 if (ObjCInterfaceDecl *Def = Class->getDefinition())
4191 return MakeCXCursor(Def, tu);
4192
Argyrios Kyrtzidisc15707d2012-01-24 21:39:26 +00004193 return MakeCXCursor(Class, tu);
Douglas Gregor7723fec2011-12-15 20:29:51 +00004194 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00004195
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004196 case CXCursor_TypeRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004197 return MakeCXCursor(getCursorTypeRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00004198
4199 case CXCursor_TemplateRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004200 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00004201
Douglas Gregor69319002010-08-31 23:48:11 +00004202 case CXCursor_NamespaceRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004203 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
Douglas Gregor69319002010-08-31 23:48:11 +00004204
Douglas Gregora67e03f2010-09-09 21:42:20 +00004205 case CXCursor_MemberRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004206 return MakeCXCursor(getCursorMemberRef(C).first, tu );
Douglas Gregora67e03f2010-09-09 21:42:20 +00004207
Ted Kremenek3064ef92010-08-27 21:34:58 +00004208 case CXCursor_CXXBaseSpecifier: {
4209 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
4210 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004211 tu ));
Ted Kremenek3064ef92010-08-27 21:34:58 +00004212 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004213
Douglas Gregor36897b02010-09-10 00:22:18 +00004214 case CXCursor_LabelRef:
4215 // FIXME: We end up faking the "parent" declaration here because we
4216 // don't want to make CXCursor larger.
4217 return MakeCXCursor(getCursorLabelRef(C).first,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004218 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
4219 .getTranslationUnitDecl(),
4220 tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00004221
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004222 case CXCursor_OverloadedDeclRef:
4223 return C;
Douglas Gregor011d8b92012-02-15 00:54:55 +00004224
4225 case CXCursor_VariableRef:
4226 return MakeCXCursor(getCursorVariableRef(C).first, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004227
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004228 default:
4229 // We would prefer to enumerate all non-reference cursor kinds here.
4230 llvm_unreachable("Unhandled reference cursor kind");
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004231 }
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004232}
4233
Douglas Gregorb6998662010-01-19 19:34:47 +00004234CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00004235 if (clang_isInvalid(C.kind))
4236 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004237
Ted Kremeneka60ed472010-11-16 08:15:36 +00004238 CXTranslationUnit TU = getCursorTU(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004239
Douglas Gregorb6998662010-01-19 19:34:47 +00004240 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00004241 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00004242 C = clang_getCursorReferenced(C);
4243 WasReference = true;
4244 }
4245
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004246 if (C.kind == CXCursor_MacroExpansion)
Douglas Gregorbf7efa22010-03-18 18:23:03 +00004247 return clang_getCursorReferenced(C);
4248
Douglas Gregorb6998662010-01-19 19:34:47 +00004249 if (!clang_isDeclaration(C.kind))
4250 return clang_getNullCursor();
4251
4252 Decl *D = getCursorDecl(C);
4253 if (!D)
4254 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004255
Douglas Gregorb6998662010-01-19 19:34:47 +00004256 switch (D->getKind()) {
4257 // Declaration kinds that don't really separate the notions of
4258 // declaration and definition.
4259 case Decl::Namespace:
4260 case Decl::Typedef:
Richard Smith162e1c12011-04-15 14:24:37 +00004261 case Decl::TypeAlias:
Richard Smith3e4c6c42011-05-05 21:57:07 +00004262 case Decl::TypeAliasTemplate:
Douglas Gregorb6998662010-01-19 19:34:47 +00004263 case Decl::TemplateTypeParm:
4264 case Decl::EnumConstant:
4265 case Decl::Field:
Benjamin Kramerd9811462010-11-21 14:11:41 +00004266 case Decl::IndirectField:
Douglas Gregorb6998662010-01-19 19:34:47 +00004267 case Decl::ObjCIvar:
4268 case Decl::ObjCAtDefsField:
4269 case Decl::ImplicitParam:
4270 case Decl::ParmVar:
4271 case Decl::NonTypeTemplateParm:
4272 case Decl::TemplateTemplateParm:
4273 case Decl::ObjCCategoryImpl:
4274 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00004275 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00004276 case Decl::LinkageSpec:
4277 case Decl::ObjCPropertyImpl:
4278 case Decl::FileScopeAsm:
4279 case Decl::StaticAssert:
4280 case Decl::Block:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00004281 case Decl::Label: // FIXME: Is this right??
Francois Pichetaf0f4d02011-08-14 03:52:19 +00004282 case Decl::ClassScopeFunctionSpecialization:
Douglas Gregor15de72c2011-12-02 23:23:56 +00004283 case Decl::Import:
Douglas Gregorb6998662010-01-19 19:34:47 +00004284 return C;
4285
4286 // Declaration kinds that don't make any sense here, but are
4287 // nonetheless harmless.
4288 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00004289 break;
4290
4291 // Declaration kinds for which the definition is not resolvable.
4292 case Decl::UnresolvedUsingTypename:
4293 case Decl::UnresolvedUsingValue:
4294 break;
4295
4296 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00004297 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004298 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004299
4300 case Decl::NamespaceAlias:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004301 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004302
4303 case Decl::Enum:
4304 case Decl::Record:
4305 case Decl::CXXRecord:
4306 case Decl::ClassTemplateSpecialization:
4307 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00004308 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004309 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004310 return clang_getNullCursor();
4311
4312 case Decl::Function:
4313 case Decl::CXXMethod:
4314 case Decl::CXXConstructor:
4315 case Decl::CXXDestructor:
4316 case Decl::CXXConversion: {
4317 const FunctionDecl *Def = 0;
4318 if (cast<FunctionDecl>(D)->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004319 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004320 return clang_getNullCursor();
4321 }
4322
4323 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00004324 // Ask the variable if it has a definition.
4325 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004326 return MakeCXCursor(Def, TU);
Sebastian Redl31310a22010-02-01 20:16:42 +00004327 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00004328 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004329
Douglas Gregorb6998662010-01-19 19:34:47 +00004330 case Decl::FunctionTemplate: {
4331 const FunctionDecl *Def = 0;
4332 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004333 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004334 return clang_getNullCursor();
4335 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004336
Douglas Gregorb6998662010-01-19 19:34:47 +00004337 case Decl::ClassTemplate: {
4338 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00004339 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00004340 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004341 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004342 return clang_getNullCursor();
4343 }
4344
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004345 case Decl::Using:
4346 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004347 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004348
4349 case Decl::UsingShadow:
4350 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004351 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004352 TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004353
4354 case Decl::ObjCMethod: {
4355 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
4356 if (Method->isThisDeclarationADefinition())
4357 return C;
4358
4359 // Dig out the method definition in the associated
4360 // @implementation, if we have it.
4361 // FIXME: The ASTs should make finding the definition easier.
4362 if (ObjCInterfaceDecl *Class
4363 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
4364 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
4365 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
4366 Method->isInstanceMethod()))
4367 if (Def->isThisDeclarationADefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004368 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004369
4370 return clang_getNullCursor();
4371 }
4372
4373 case Decl::ObjCCategory:
4374 if (ObjCCategoryImplDecl *Impl
4375 = cast<ObjCCategoryDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004376 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004377 return clang_getNullCursor();
4378
4379 case Decl::ObjCProtocol:
Douglas Gregor5e2a1ff2012-01-01 19:29:29 +00004380 if (ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
4381 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004382 return clang_getNullCursor();
4383
Douglas Gregor375bb142011-12-27 22:43:10 +00004384 case Decl::ObjCInterface: {
Douglas Gregorb6998662010-01-19 19:34:47 +00004385 // There are two notions of a "definition" for an Objective-C
4386 // class: the interface and its implementation. When we resolved a
4387 // reference to an Objective-C class, produce the @interface as
4388 // the definition; when we were provided with the interface,
4389 // produce the @implementation as the definition.
Douglas Gregor375bb142011-12-27 22:43:10 +00004390 ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
Douglas Gregorb6998662010-01-19 19:34:47 +00004391 if (WasReference) {
Douglas Gregor375bb142011-12-27 22:43:10 +00004392 if (ObjCInterfaceDecl *Def = IFace->getDefinition())
Douglas Gregor7723fec2011-12-15 20:29:51 +00004393 return MakeCXCursor(Def, TU);
Douglas Gregor375bb142011-12-27 22:43:10 +00004394 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004395 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004396 return clang_getNullCursor();
Douglas Gregor375bb142011-12-27 22:43:10 +00004397 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004398
Douglas Gregorb6998662010-01-19 19:34:47 +00004399 case Decl::ObjCProperty:
4400 // FIXME: We don't really know where to find the
4401 // ObjCPropertyImplDecls that implement this property.
4402 return clang_getNullCursor();
4403
4404 case Decl::ObjCCompatibleAlias:
4405 if (ObjCInterfaceDecl *Class
4406 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
Douglas Gregor7723fec2011-12-15 20:29:51 +00004407 if (ObjCInterfaceDecl *Def = Class->getDefinition())
4408 return MakeCXCursor(Def, TU);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004409
Douglas Gregorb6998662010-01-19 19:34:47 +00004410 return clang_getNullCursor();
4411
Douglas Gregorb6998662010-01-19 19:34:47 +00004412 case Decl::Friend:
4413 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004414 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004415 return clang_getNullCursor();
4416
4417 case Decl::FriendTemplate:
4418 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004419 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004420 return clang_getNullCursor();
4421 }
4422
4423 return clang_getNullCursor();
4424}
4425
4426unsigned clang_isCursorDefinition(CXCursor C) {
4427 if (!clang_isDeclaration(C.kind))
4428 return 0;
4429
4430 return clang_getCursorDefinition(C) == C;
4431}
4432
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004433CXCursor clang_getCanonicalCursor(CXCursor C) {
4434 if (!clang_isDeclaration(C.kind))
4435 return C;
4436
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004437 if (Decl *D = getCursorDecl(C)) {
Argyrios Kyrtzidisdebb00f2011-07-15 22:37:58 +00004438 if (ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
4439 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
4440 return MakeCXCursor(CatD, getCursorTU(C));
4441
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004442 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
4443 if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
4444 return MakeCXCursor(IFD, getCursorTU(C));
4445
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004446 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004447 }
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004448
4449 return C;
4450}
Argyrios Kyrtzidis34ebe1e2012-03-30 22:15:48 +00004451
4452int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) {
4453 return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first;
4454}
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004455
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004456unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004457 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004458 return 0;
4459
4460 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
4461 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
4462 return E->getNumDecls();
4463
4464 if (OverloadedTemplateStorage *S
4465 = Storage.dyn_cast<OverloadedTemplateStorage*>())
4466 return S->size();
4467
4468 Decl *D = Storage.get<Decl*>();
4469 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00004470 return Using->shadow_size();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004471
4472 return 0;
4473}
4474
4475CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004476 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004477 return clang_getNullCursor();
4478
4479 if (index >= clang_getNumOverloadedDecls(cursor))
4480 return clang_getNullCursor();
4481
Ted Kremeneka60ed472010-11-16 08:15:36 +00004482 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004483 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
4484 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004485 return MakeCXCursor(E->decls_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004486
4487 if (OverloadedTemplateStorage *S
4488 = Storage.dyn_cast<OverloadedTemplateStorage*>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004489 return MakeCXCursor(S->begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004490
4491 Decl *D = Storage.get<Decl*>();
4492 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
4493 // FIXME: This is, unfortunately, linear time.
4494 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
4495 std::advance(Pos, index);
Ted Kremeneka60ed472010-11-16 08:15:36 +00004496 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004497 }
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004498
4499 return clang_getNullCursor();
4500}
4501
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00004502void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00004503 const char **startBuf,
4504 const char **endBuf,
4505 unsigned *startLine,
4506 unsigned *startColumn,
4507 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00004508 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00004509 assert(getCursorDecl(C) && "CXCursor has null decl");
4510 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00004511 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
4512 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004513
Steve Naroff4ade6d62009-09-23 17:52:52 +00004514 SourceManager &SM = FD->getASTContext().getSourceManager();
4515 *startBuf = SM.getCharacterData(Body->getLBracLoc());
4516 *endBuf = SM.getCharacterData(Body->getRBracLoc());
4517 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
4518 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
4519 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
4520 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
4521}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004522
Douglas Gregor430d7a12011-07-25 17:48:11 +00004523
4524CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
4525 unsigned PieceIndex) {
4526 RefNamePieces Pieces;
4527
4528 switch (C.kind) {
4529 case CXCursor_MemberRefExpr:
4530 if (MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
4531 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
4532 E->getQualifierLoc().getSourceRange());
4533 break;
4534
4535 case CXCursor_DeclRefExpr:
4536 if (DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C)))
4537 Pieces = buildPieces(NameFlags, false, E->getNameInfo(),
4538 E->getQualifierLoc().getSourceRange(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00004539 E->getOptionalExplicitTemplateArgs());
Douglas Gregor430d7a12011-07-25 17:48:11 +00004540 break;
4541
4542 case CXCursor_CallExpr:
4543 if (CXXOperatorCallExpr *OCE =
4544 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
4545 Expr *Callee = OCE->getCallee();
4546 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
4547 Callee = ICE->getSubExpr();
4548
4549 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
4550 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
4551 DRE->getQualifierLoc().getSourceRange());
4552 }
4553 break;
4554
4555 default:
4556 break;
4557 }
4558
4559 if (Pieces.empty()) {
4560 if (PieceIndex == 0)
4561 return clang_getCursorExtent(C);
4562 } else if (PieceIndex < Pieces.size()) {
4563 SourceRange R = Pieces[PieceIndex];
4564 if (R.isValid())
4565 return cxloc::translateSourceRange(getCursorContext(C), R);
4566 }
4567
4568 return clang_getNullRange();
4569}
4570
Douglas Gregor0a812cf2010-02-18 23:07:20 +00004571void clang_enableStackTraces(void) {
4572 llvm::sys::PrintStackTraceOnErrorSignal();
4573}
4574
Daniel Dunbar995aaf92010-11-04 01:26:29 +00004575void clang_executeOnThread(void (*fn)(void*), void *user_data,
4576 unsigned stack_size) {
4577 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
4578}
4579
Ted Kremenekfb480492010-01-13 21:46:36 +00004580} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00004581
Ted Kremenekfb480492010-01-13 21:46:36 +00004582//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004583// Token-based Operations.
4584//===----------------------------------------------------------------------===//
4585
4586/* CXToken layout:
4587 * int_data[0]: a CXTokenKind
4588 * int_data[1]: starting token location
4589 * int_data[2]: token length
4590 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004591 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004592 * otherwise unused.
4593 */
4594extern "C" {
4595
4596CXTokenKind clang_getTokenKind(CXToken CXTok) {
4597 return static_cast<CXTokenKind>(CXTok.int_data[0]);
4598}
4599
4600CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
4601 switch (clang_getTokenKind(CXTok)) {
4602 case CXToken_Identifier:
4603 case CXToken_Keyword:
4604 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004605 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
4606 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004607
4608 case CXToken_Literal: {
4609 // We have stashed the starting pointer in the ptr_data field. Use it.
4610 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Chris Lattner5f9e2722011-07-23 10:55:15 +00004611 return createCXString(StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004612 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004613
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004614 case CXToken_Punctuation:
4615 case CXToken_Comment:
4616 break;
4617 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004618
4619 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004620 // deconstructing the source location.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004621 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004622 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004623 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004624
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004625 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
4626 std::pair<FileID, unsigned> LocInfo
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004627 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00004628 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004629 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004630 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
4631 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00004632 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004633
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004634 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004635}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004636
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004637CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004638 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004639 if (!CXXUnit)
4640 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004641
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004642 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
4643 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4644}
4645
4646CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004647 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor5352ac02010-01-28 00:27:43 +00004648 if (!CXXUnit)
4649 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004650
4651 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004652 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4653}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004654
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004655static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
4656 SmallVectorImpl<CXToken> &CXTokens) {
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004657 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4658 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004659 = SourceMgr.getDecomposedLoc(Range.getBegin());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004660 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004661 = SourceMgr.getDecomposedLoc(Range.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004662
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004663 // Cannot tokenize across files.
4664 if (BeginLocInfo.first != EndLocInfo.first)
4665 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004666
4667 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004668 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004669 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004670 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00004671 if (Invalid)
4672 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00004673
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004674 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
David Blaikie4e4d0842012-03-11 07:00:24 +00004675 CXXUnit->getASTContext().getLangOpts(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004676 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004677 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004678
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004679 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004680 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004681 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00004682 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004683 do {
4684 // Lex the next token
4685 Lex.LexFromRawLexer(Tok);
4686 if (Tok.is(tok::eof))
4687 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004688
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004689 // Initialize the CXToken.
4690 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004691
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004692 // - Common fields
4693 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
4694 CXTok.int_data[2] = Tok.getLength();
4695 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004696
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004697 // - Kind-specific fields
4698 if (Tok.isLiteral()) {
4699 CXTok.int_data[0] = CXToken_Literal;
4700 CXTok.ptr_data = (void *)Tok.getLiteralData();
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004701 } else if (Tok.is(tok::raw_identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00004702 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004703 IdentifierInfo *II
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004704 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004705
David Chisnall096428b2010-10-13 21:44:48 +00004706 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004707 CXTok.int_data[0] = CXToken_Keyword;
4708 }
4709 else {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004710 CXTok.int_data[0] = Tok.is(tok::identifier)
4711 ? CXToken_Identifier
4712 : CXToken_Keyword;
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004713 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004714 CXTok.ptr_data = II;
4715 } else if (Tok.is(tok::comment)) {
4716 CXTok.int_data[0] = CXToken_Comment;
4717 CXTok.ptr_data = 0;
4718 } else {
4719 CXTok.int_data[0] = CXToken_Punctuation;
4720 CXTok.ptr_data = 0;
4721 }
4722 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00004723 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004724 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004725}
4726
4727void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
4728 CXToken **Tokens, unsigned *NumTokens) {
4729 if (Tokens)
4730 *Tokens = 0;
4731 if (NumTokens)
4732 *NumTokens = 0;
4733
4734 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4735 if (!CXXUnit || !Tokens || !NumTokens)
4736 return;
4737
4738 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4739
4740 SourceRange R = cxloc::translateCXSourceRange(Range);
4741 if (R.isInvalid())
4742 return;
4743
4744 SmallVector<CXToken, 32> CXTokens;
4745 getTokens(CXXUnit, R, CXTokens);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004746
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004747 if (CXTokens.empty())
4748 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004749
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004750 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
4751 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
4752 *NumTokens = CXTokens.size();
4753}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004754
Ted Kremenek6db61092010-05-05 00:55:15 +00004755void clang_disposeTokens(CXTranslationUnit TU,
4756 CXToken *Tokens, unsigned NumTokens) {
4757 free(Tokens);
4758}
4759
4760} // end: extern "C"
4761
4762//===----------------------------------------------------------------------===//
4763// Token annotation APIs.
4764//===----------------------------------------------------------------------===//
4765
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004766typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004767static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4768 CXCursor parent,
4769 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00004770namespace {
4771class AnnotateTokensWorker {
4772 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004773 CXToken *Tokens;
4774 CXCursor *Cursors;
4775 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004776 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00004777 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004778 CursorVisitor AnnotateVis;
4779 SourceManager &SrcMgr;
Douglas Gregorf5251602011-03-08 17:10:18 +00004780 bool HasContextSensitiveKeywords;
4781
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004782 bool MoreTokens() const { return TokIdx < NumTokens; }
4783 unsigned NextToken() const { return TokIdx; }
4784 void AdvanceToken() { ++TokIdx; }
4785 SourceLocation GetTokenLoc(unsigned tokI) {
4786 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4787 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004788 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004789 return Tokens[tokI].int_data[3] != 0;
4790 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004791 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004792 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[3]);
4793 }
4794
4795 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004796 void annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
4797 SourceRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004798
Ted Kremenek6db61092010-05-05 00:55:15 +00004799public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00004800 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004801 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004802 CXTranslationUnit tu, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00004803 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00004804 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004805 AnnotateVis(tu,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00004806 AnnotateTokensVisitor, this,
4807 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00004808 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00004809 RegionOfInterest),
Douglas Gregorf5251602011-03-08 17:10:18 +00004810 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()),
4811 HasContextSensitiveKeywords(false) { }
Ted Kremenek11949cb2010-05-05 00:55:17 +00004812
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004813 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00004814 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004815 void AnnotateTokens();
Douglas Gregorf5251602011-03-08 17:10:18 +00004816
4817 /// \brief Determine whether the annotator saw any cursors that have
4818 /// context-sensitive keywords.
4819 bool hasContextSensitiveKeywords() const {
4820 return HasContextSensitiveKeywords;
4821 }
Ted Kremenek6db61092010-05-05 00:55:15 +00004822};
4823}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004824
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004825void AnnotateTokensWorker::AnnotateTokens() {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004826 // Walk the AST within the region of interest, annotating tokens
4827 // along the way.
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004828 AnnotateVis.visitFileRegion();
Ted Kremenek11949cb2010-05-05 00:55:17 +00004829
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004830 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4831 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004832 if (Pos != Annotated.end() &&
4833 (clang_isInvalid(Cursors[I].kind) ||
4834 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004835 Cursors[I] = Pos->second;
4836 }
4837
4838 // Finish up annotating any tokens left.
4839 if (!MoreTokens())
4840 return;
4841
4842 const CXCursor &C = clang_getNullCursor();
4843 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004844 if (I < PreprocessingTokIdx && clang_isPreprocessing(Cursors[I].kind))
4845 continue;
4846
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004847 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4848 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004849 }
4850}
4851
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004852/// \brief It annotates and advances tokens with a cursor until the comparison
4853//// between the cursor location and the source range is the same as
4854/// \arg compResult.
4855///
4856/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
4857/// Pass RangeOverlap to annotate tokens inside a range.
4858void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
4859 RangeComparisonResult compResult,
4860 SourceRange range) {
4861 while (MoreTokens()) {
4862 const unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004863 if (isFunctionMacroToken(I))
4864 return annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004865
4866 SourceLocation TokLoc = GetTokenLoc(I);
4867 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4868 Cursors[I] = updateC;
4869 AdvanceToken();
4870 continue;
4871 }
4872 break;
4873 }
4874}
4875
4876/// \brief Special annotation handling for macro argument tokens.
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004877void AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
4878 CXCursor updateC,
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004879 RangeComparisonResult compResult,
4880 SourceRange range) {
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004881 assert(MoreTokens());
4882 assert(isFunctionMacroToken(NextToken()) &&
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004883 "Should be called only for macro arg tokens");
4884
4885 // This works differently than annotateAndAdvanceTokens; because expanded
4886 // macro arguments can have arbitrary translation-unit source order, we do not
4887 // advance the token index one by one until a token fails the range test.
4888 // We only advance once past all of the macro arg tokens if all of them
4889 // pass the range test. If one of them fails we keep the token index pointing
4890 // at the start of the macro arg tokens so that the failing token will be
4891 // annotated by a subsequent annotation try.
4892
4893 bool atLeastOneCompFail = false;
4894
4895 unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004896 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
4897 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004898 if (TokLoc.isFileID())
4899 continue; // not macro arg token, it's parens or comma.
4900 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4901 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
4902 Cursors[I] = updateC;
4903 } else
4904 atLeastOneCompFail = true;
4905 }
4906
4907 if (!atLeastOneCompFail)
4908 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
4909}
4910
Ted Kremenek6db61092010-05-05 00:55:15 +00004911enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004912AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004913 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004914 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004915 if (cursorRange.isInvalid())
4916 return CXChildVisit_Recurse;
Douglas Gregorf5251602011-03-08 17:10:18 +00004917
4918 if (!HasContextSensitiveKeywords) {
4919 // Objective-C properties can have context-sensitive keywords.
4920 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
4921 if (ObjCPropertyDecl *Property
4922 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
4923 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
4924 }
4925 // Objective-C methods can have context-sensitive keywords.
4926 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
4927 cursor.kind == CXCursor_ObjCClassMethodDecl) {
4928 if (ObjCMethodDecl *Method
4929 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
4930 if (Method->getObjCDeclQualifier())
4931 HasContextSensitiveKeywords = true;
4932 else {
4933 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
4934 PEnd = Method->param_end();
4935 P != PEnd; ++P) {
4936 if ((*P)->getObjCDeclQualifier()) {
4937 HasContextSensitiveKeywords = true;
4938 break;
4939 }
4940 }
4941 }
4942 }
4943 }
4944 // C++ methods can have context-sensitive keywords.
4945 else if (cursor.kind == CXCursor_CXXMethod) {
4946 if (CXXMethodDecl *Method
4947 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
4948 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
4949 HasContextSensitiveKeywords = true;
4950 }
4951 }
4952 // C++ classes can have context-sensitive keywords.
4953 else if (cursor.kind == CXCursor_StructDecl ||
4954 cursor.kind == CXCursor_ClassDecl ||
4955 cursor.kind == CXCursor_ClassTemplate ||
4956 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
4957 if (Decl *D = getCursorDecl(cursor))
4958 if (D->hasAttr<FinalAttr>())
4959 HasContextSensitiveKeywords = true;
4960 }
4961 }
4962
Douglas Gregor4419b672010-10-21 06:10:04 +00004963 if (clang_isPreprocessing(cursor.kind)) {
Chandler Carruthcea731a2011-07-14 16:07:57 +00004964 // For macro expansions, just note where the beginning of the macro
4965 // expansion occurs.
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004966 if (cursor.kind == CXCursor_MacroExpansion) {
Douglas Gregor4419b672010-10-21 06:10:04 +00004967 Annotated[Loc.int_data] = cursor;
4968 return CXChildVisit_Recurse;
4969 }
4970
Douglas Gregor4419b672010-10-21 06:10:04 +00004971 // Items in the preprocessing record are kept separate from items in
4972 // declarations, so we keep a separate token index.
4973 unsigned SavedTokIdx = TokIdx;
4974 TokIdx = PreprocessingTokIdx;
4975
4976 // Skip tokens up until we catch up to the beginning of the preprocessing
4977 // entry.
4978 while (MoreTokens()) {
4979 const unsigned I = NextToken();
4980 SourceLocation TokLoc = GetTokenLoc(I);
4981 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4982 case RangeBefore:
4983 AdvanceToken();
4984 continue;
4985 case RangeAfter:
4986 case RangeOverlap:
4987 break;
4988 }
4989 break;
4990 }
4991
4992 // Look at all of the tokens within this range.
4993 while (MoreTokens()) {
4994 const unsigned I = NextToken();
4995 SourceLocation TokLoc = GetTokenLoc(I);
4996 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4997 case RangeBefore:
David Blaikieb219cfc2011-09-23 05:06:16 +00004998 llvm_unreachable("Infeasible");
Douglas Gregor4419b672010-10-21 06:10:04 +00004999 case RangeAfter:
5000 break;
5001 case RangeOverlap:
5002 Cursors[I] = cursor;
5003 AdvanceToken();
5004 continue;
5005 }
5006 break;
5007 }
5008
5009 // Save the preprocessing token index; restore the non-preprocessing
5010 // token index.
5011 PreprocessingTokIdx = TokIdx;
5012 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005013 return CXChildVisit_Recurse;
5014 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005015
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005016 if (cursorRange.isInvalid())
5017 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00005018
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005019 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
5020
Ted Kremeneka333c662010-05-12 05:29:33 +00005021 // Adjust the annotated range based specific declarations.
5022 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
5023 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00005024 Decl *D = cxcursor::getCursorDecl(cursor);
Douglas Gregor2494dd02011-03-01 01:34:45 +00005025
5026 SourceLocation StartLoc;
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00005027 if (const DeclaratorDecl *DD = dyn_cast_or_null<DeclaratorDecl>(D)) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00005028 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
Daniel Dunbar96a00142012-03-09 18:35:03 +00005029 StartLoc = TI->getTypeLoc().getLocStart();
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00005030 } else if (TypedefDecl *Typedef = dyn_cast_or_null<TypedefDecl>(D)) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00005031 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
Daniel Dunbar96a00142012-03-09 18:35:03 +00005032 StartLoc = TI->getTypeLoc().getLocStart();
Ted Kremeneka333c662010-05-12 05:29:33 +00005033 }
Douglas Gregor2494dd02011-03-01 01:34:45 +00005034
5035 if (StartLoc.isValid() && L.isValid() &&
5036 SrcMgr.isBeforeInTranslationUnit(StartLoc, L))
5037 cursorRange.setBegin(StartLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00005038 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00005039
Ted Kremenek3f404602010-08-14 01:14:06 +00005040 // If the location of the cursor occurs within a macro instantiation, record
5041 // the spelling location of the cursor in our annotation map. We can then
5042 // paper over the token labelings during a post-processing step to try and
5043 // get cursor mappings for tokens that are the *arguments* of a macro
5044 // instantiation.
5045 if (L.isMacroID()) {
5046 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
5047 // Only invalidate the old annotation if it isn't part of a preprocessing
5048 // directive. Here we assume that the default construction of CXCursor
5049 // results in CXCursor.kind being an initialized value (i.e., 0). If
5050 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00005051
Ted Kremenek3f404602010-08-14 01:14:06 +00005052 CXCursor &oldC = Annotated[rawEncoding];
5053 if (!clang_isPreprocessing(oldC.kind))
5054 oldC = cursor;
5055 }
5056
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005057 const enum CXCursorKind K = clang_getCursorKind(parent);
5058 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00005059 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
5060 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005061
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005062 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005063
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00005064 // Avoid having the cursor of an expression "overwrite" the annotation of the
5065 // variable declaration that it belongs to.
5066 // This can happen for C++ constructor expressions whose range generally
5067 // include the variable declaration, e.g.:
5068 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
5069 if (clang_isExpression(cursorK)) {
5070 Expr *E = getCursorExpr(cursor);
Argyrios Kyrtzidis8ccac3d2011-06-29 22:20:07 +00005071 if (Decl *D = getCursorParentDecl(cursor)) {
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00005072 const unsigned I = NextToken();
5073 if (E->getLocStart().isValid() && D->getLocation().isValid() &&
5074 E->getLocStart() == D->getLocation() &&
5075 E->getLocStart() == GetTokenLoc(I)) {
5076 Cursors[I] = updateC;
5077 AdvanceToken();
5078 }
5079 }
5080 }
5081
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005082 // Visit children to get their cursor information.
5083 const unsigned BeforeChildren = NextToken();
5084 VisitChildren(cursor);
5085 const unsigned AfterChildren = NextToken();
5086
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005087 // Scan the tokens that are at the end of the cursor, but are not captured
5088 // but the child cursors.
5089 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
Ted Kremenek6db61092010-05-05 00:55:15 +00005090
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005091 // Scan the tokens that are at the beginning of the cursor, but are not
5092 // capture by the child cursors.
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005093 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
5094 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
5095 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00005096
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005097 Cursors[I] = cursor;
5098 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005099
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005100 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005101}
5102
Ted Kremenek6db61092010-05-05 00:55:15 +00005103static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
5104 CXCursor parent,
5105 CXClientData client_data) {
5106 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
5107}
5108
Ted Kremenek6628a612011-03-18 22:51:30 +00005109namespace {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005110
5111/// \brief Uses the macro expansions in the preprocessing record to find
5112/// and mark tokens that are macro arguments. This info is used by the
5113/// AnnotateTokensWorker.
5114class MarkMacroArgTokensVisitor {
5115 SourceManager &SM;
5116 CXToken *Tokens;
5117 unsigned NumTokens;
5118 unsigned CurIdx;
5119
5120public:
5121 MarkMacroArgTokensVisitor(SourceManager &SM,
5122 CXToken *tokens, unsigned numTokens)
5123 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
5124
5125 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
5126 if (cursor.kind != CXCursor_MacroExpansion)
5127 return CXChildVisit_Continue;
5128
5129 SourceRange macroRange = getCursorMacroExpansion(cursor)->getSourceRange();
5130 if (macroRange.getBegin() == macroRange.getEnd())
5131 return CXChildVisit_Continue; // it's not a function macro.
5132
5133 for (; CurIdx < NumTokens; ++CurIdx) {
5134 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
5135 macroRange.getBegin()))
5136 break;
5137 }
5138
5139 if (CurIdx == NumTokens)
5140 return CXChildVisit_Break;
5141
5142 for (; CurIdx < NumTokens; ++CurIdx) {
5143 SourceLocation tokLoc = getTokenLoc(CurIdx);
5144 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
5145 break;
5146
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00005147 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005148 }
5149
5150 if (CurIdx == NumTokens)
5151 return CXChildVisit_Break;
5152
5153 return CXChildVisit_Continue;
5154 }
5155
5156private:
5157 SourceLocation getTokenLoc(unsigned tokI) {
5158 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
5159 }
5160
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00005161 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005162 // The third field is reserved and currently not used. Use it here
5163 // to mark macro arg expanded tokens with their expanded locations.
5164 Tokens[tokI].int_data[3] = loc.getRawEncoding();
5165 }
5166};
5167
5168} // end anonymous namespace
5169
5170static CXChildVisitResult
5171MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
5172 CXClientData client_data) {
5173 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
5174 parent);
5175}
5176
5177namespace {
Ted Kremenek6628a612011-03-18 22:51:30 +00005178 struct clang_annotateTokens_Data {
5179 CXTranslationUnit TU;
5180 ASTUnit *CXXUnit;
5181 CXToken *Tokens;
5182 unsigned NumTokens;
5183 CXCursor *Cursors;
5184 };
5185}
5186
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005187static void annotatePreprocessorTokens(CXTranslationUnit TU,
5188 SourceRange RegionOfInterest,
5189 AnnotateTokensData &Annotated) {
5190 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
5191
5192 SourceManager &SourceMgr = CXXUnit->getSourceManager();
5193 std::pair<FileID, unsigned> BeginLocInfo
5194 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
5195 std::pair<FileID, unsigned> EndLocInfo
5196 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
5197
5198 if (BeginLocInfo.first != EndLocInfo.first)
5199 return;
5200
5201 StringRef Buffer;
5202 bool Invalid = false;
5203 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
5204 if (Buffer.empty() || Invalid)
5205 return;
5206
5207 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
David Blaikie4e4d0842012-03-11 07:00:24 +00005208 CXXUnit->getASTContext().getLangOpts(),
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005209 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
5210 Buffer.end());
5211 Lex.SetCommentRetentionState(true);
5212
5213 // Lex tokens in raw mode until we hit the end of the range, to avoid
5214 // entering #includes or expanding macros.
5215 while (true) {
5216 Token Tok;
5217 Lex.LexFromRawLexer(Tok);
5218
5219 reprocess:
5220 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
5221 // We have found a preprocessing directive. Gobble it up so that we
5222 // don't see it while preprocessing these tokens later, but keep track
5223 // of all of the token locations inside this preprocessing directive so
5224 // that we can annotate them appropriately.
5225 //
5226 // FIXME: Some simple tests here could identify macro definitions and
5227 // #undefs, to provide specific cursor kinds for those.
5228 SmallVector<SourceLocation, 32> Locations;
5229 do {
5230 Locations.push_back(Tok.getLocation());
5231 Lex.LexFromRawLexer(Tok);
5232 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
5233
5234 using namespace cxcursor;
5235 CXCursor Cursor
5236 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
5237 Locations.back()),
5238 TU);
5239 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
5240 Annotated[Locations[I].getRawEncoding()] = Cursor;
5241 }
5242
5243 if (Tok.isAtStartOfLine())
5244 goto reprocess;
5245
5246 continue;
5247 }
5248
5249 if (Tok.is(tok::eof))
5250 break;
5251 }
5252}
5253
Ted Kremenekab979612010-11-11 08:05:23 +00005254// This gets run a separate thread to avoid stack blowout.
Ted Kremenek6628a612011-03-18 22:51:30 +00005255static void clang_annotateTokensImpl(void *UserData) {
5256 CXTranslationUnit TU = ((clang_annotateTokens_Data*)UserData)->TU;
5257 ASTUnit *CXXUnit = ((clang_annotateTokens_Data*)UserData)->CXXUnit;
5258 CXToken *Tokens = ((clang_annotateTokens_Data*)UserData)->Tokens;
5259 const unsigned NumTokens = ((clang_annotateTokens_Data*)UserData)->NumTokens;
5260 CXCursor *Cursors = ((clang_annotateTokens_Data*)UserData)->Cursors;
5261
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00005262 CIndexer *CXXIdx = (CIndexer*)TU->CIdx;
5263 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
Argyrios Kyrtzidis81b5ac32012-03-28 02:49:54 +00005264 setThreadBackgroundPriority();
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00005265
Ted Kremenek6628a612011-03-18 22:51:30 +00005266 // Determine the region of interest, which contains all of the tokens.
5267 SourceRange RegionOfInterest;
5268 RegionOfInterest.setBegin(
5269 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
5270 RegionOfInterest.setEnd(
5271 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
5272 Tokens[NumTokens-1])));
5273
5274 // A mapping from the source locations found when re-lexing or traversing the
5275 // region of interest to the corresponding cursors.
5276 AnnotateTokensData Annotated;
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005277
Ted Kremenek6628a612011-03-18 22:51:30 +00005278 // Relex the tokens within the source range to look for preprocessing
5279 // directives.
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005280 annotatePreprocessorTokens(TU, RegionOfInterest, Annotated);
Ted Kremenek6628a612011-03-18 22:51:30 +00005281
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005282 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
5283 // Search and mark tokens that are macro argument expansions.
5284 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
5285 Tokens, NumTokens);
5286 CursorVisitor MacroArgMarker(TU,
5287 MarkMacroArgTokensVisitorDelegate, &Visitor,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00005288 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00005289 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00005290 RegionOfInterest);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005291 MacroArgMarker.visitPreprocessedEntitiesInRegion();
5292 }
5293
Ted Kremenek6628a612011-03-18 22:51:30 +00005294 // Annotate all of the source locations in the region of interest that map to
5295 // a specific cursor.
5296 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
5297 TU, RegionOfInterest);
5298
5299 // FIXME: We use a ridiculous stack size here because the data-recursion
5300 // algorithm uses a large stack frame than the non-data recursive version,
5301 // and AnnotationTokensWorker currently transforms the data-recursion
5302 // algorithm back into a traditional recursion by explicitly calling
5303 // VisitChildren(). We will need to remove this explicit recursive call.
5304 W.AnnotateTokens();
5305
5306 // If we ran into any entities that involve context-sensitive keywords,
5307 // take another pass through the tokens to mark them as such.
5308 if (W.hasContextSensitiveKeywords()) {
5309 for (unsigned I = 0; I != NumTokens; ++I) {
5310 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
5311 continue;
5312
5313 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
5314 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5315 if (ObjCPropertyDecl *Property
5316 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
5317 if (Property->getPropertyAttributesAsWritten() != 0 &&
5318 llvm::StringSwitch<bool>(II->getName())
5319 .Case("readonly", true)
5320 .Case("assign", true)
John McCallf85e1932011-06-15 23:02:42 +00005321 .Case("unsafe_unretained", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00005322 .Case("readwrite", true)
5323 .Case("retain", true)
5324 .Case("copy", true)
5325 .Case("nonatomic", true)
5326 .Case("atomic", true)
5327 .Case("getter", true)
5328 .Case("setter", true)
John McCallf85e1932011-06-15 23:02:42 +00005329 .Case("strong", true)
5330 .Case("weak", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00005331 .Default(false))
5332 Tokens[I].int_data[0] = CXToken_Keyword;
5333 }
5334 continue;
5335 }
5336
5337 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
5338 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
5339 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5340 if (llvm::StringSwitch<bool>(II->getName())
5341 .Case("in", true)
5342 .Case("out", true)
5343 .Case("inout", true)
5344 .Case("oneway", true)
5345 .Case("bycopy", true)
5346 .Case("byref", true)
5347 .Default(false))
5348 Tokens[I].int_data[0] = CXToken_Keyword;
5349 continue;
5350 }
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00005351
5352 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
5353 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
5354 Tokens[I].int_data[0] = CXToken_Keyword;
Ted Kremenek6628a612011-03-18 22:51:30 +00005355 continue;
5356 }
5357 }
5358 }
Ted Kremenekab979612010-11-11 08:05:23 +00005359}
5360
Ted Kremenek6db61092010-05-05 00:55:15 +00005361extern "C" {
5362
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005363void clang_annotateTokens(CXTranslationUnit TU,
5364 CXToken *Tokens, unsigned NumTokens,
5365 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005366
5367 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005368 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005369
Douglas Gregor4419b672010-10-21 06:10:04 +00005370 // Any token we don't specifically annotate will have a NULL cursor.
5371 CXCursor C = clang_getNullCursor();
5372 for (unsigned I = 0; I != NumTokens; ++I)
5373 Cursors[I] = C;
5374
Ted Kremeneka60ed472010-11-16 08:15:36 +00005375 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor4419b672010-10-21 06:10:04 +00005376 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005377 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005378
Douglas Gregorbdf60622010-03-05 21:16:25 +00005379 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenek6628a612011-03-18 22:51:30 +00005380
5381 clang_annotateTokens_Data data = { TU, CXXUnit, Tokens, NumTokens, Cursors };
Ted Kremenekab979612010-11-11 08:05:23 +00005382 llvm::CrashRecoveryContext CRC;
Ted Kremenek6628a612011-03-18 22:51:30 +00005383 if (!RunSafely(CRC, clang_annotateTokensImpl, &data,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005384 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00005385 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
5386 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005387}
Ted Kremenek6628a612011-03-18 22:51:30 +00005388
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005389} // end: extern "C"
5390
5391//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00005392// Operations for querying linkage of a cursor.
5393//===----------------------------------------------------------------------===//
5394
5395extern "C" {
5396CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00005397 if (!clang_isDeclaration(cursor.kind))
5398 return CXLinkage_Invalid;
5399
Ted Kremenek16b42592010-03-03 06:36:57 +00005400 Decl *D = cxcursor::getCursorDecl(cursor);
5401 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
5402 switch (ND->getLinkage()) {
5403 case NoLinkage: return CXLinkage_NoLinkage;
5404 case InternalLinkage: return CXLinkage_Internal;
5405 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
5406 case ExternalLinkage: return CXLinkage_External;
5407 };
5408
5409 return CXLinkage_Invalid;
5410}
5411} // end: extern "C"
5412
5413//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005414// Operations for querying language of a cursor.
5415//===----------------------------------------------------------------------===//
5416
5417static CXLanguageKind getDeclLanguage(const Decl *D) {
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00005418 if (!D)
5419 return CXLanguage_C;
5420
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005421 switch (D->getKind()) {
5422 default:
5423 break;
5424 case Decl::ImplicitParam:
5425 case Decl::ObjCAtDefsField:
5426 case Decl::ObjCCategory:
5427 case Decl::ObjCCategoryImpl:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005428 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005429 case Decl::ObjCImplementation:
5430 case Decl::ObjCInterface:
5431 case Decl::ObjCIvar:
5432 case Decl::ObjCMethod:
5433 case Decl::ObjCProperty:
5434 case Decl::ObjCPropertyImpl:
5435 case Decl::ObjCProtocol:
5436 return CXLanguage_ObjC;
5437 case Decl::CXXConstructor:
5438 case Decl::CXXConversion:
5439 case Decl::CXXDestructor:
5440 case Decl::CXXMethod:
5441 case Decl::CXXRecord:
5442 case Decl::ClassTemplate:
5443 case Decl::ClassTemplatePartialSpecialization:
5444 case Decl::ClassTemplateSpecialization:
5445 case Decl::Friend:
5446 case Decl::FriendTemplate:
5447 case Decl::FunctionTemplate:
5448 case Decl::LinkageSpec:
5449 case Decl::Namespace:
5450 case Decl::NamespaceAlias:
5451 case Decl::NonTypeTemplateParm:
5452 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005453 case Decl::TemplateTemplateParm:
5454 case Decl::TemplateTypeParm:
5455 case Decl::UnresolvedUsingTypename:
5456 case Decl::UnresolvedUsingValue:
5457 case Decl::Using:
5458 case Decl::UsingDirective:
5459 case Decl::UsingShadow:
5460 return CXLanguage_CPlusPlus;
5461 }
5462
5463 return CXLanguage_C;
5464}
5465
5466extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00005467
5468enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
5469 if (clang_isDeclaration(cursor.kind))
5470 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005471 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Douglas Gregor58ddb602010-08-23 23:00:57 +00005472 return CXAvailability_Available;
5473
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005474 switch (D->getAvailability()) {
5475 case AR_Available:
5476 case AR_NotYetIntroduced:
5477 return CXAvailability_Available;
5478
5479 case AR_Deprecated:
Douglas Gregor58ddb602010-08-23 23:00:57 +00005480 return CXAvailability_Deprecated;
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005481
5482 case AR_Unavailable:
5483 return CXAvailability_NotAvailable;
5484 }
Douglas Gregor58ddb602010-08-23 23:00:57 +00005485 }
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005486
Douglas Gregor58ddb602010-08-23 23:00:57 +00005487 return CXAvailability_Available;
5488}
5489
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005490CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
5491 if (clang_isDeclaration(cursor.kind))
5492 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
5493
5494 return CXLanguage_Invalid;
5495}
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005496
5497 /// \brief If the given cursor is the "templated" declaration
5498 /// descibing a class or function template, return the class or
5499 /// function template.
5500static Decl *maybeGetTemplateCursor(Decl *D) {
5501 if (!D)
5502 return 0;
5503
5504 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
5505 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
5506 return FunTmpl;
5507
5508 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
5509 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
5510 return ClassTmpl;
5511
5512 return D;
5513}
5514
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005515CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
5516 if (clang_isDeclaration(cursor.kind)) {
5517 if (Decl *D = getCursorDecl(cursor)) {
5518 DeclContext *DC = D->getDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005519 if (!DC)
5520 return clang_getNullCursor();
5521
5522 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5523 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005524 }
5525 }
5526
5527 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
5528 if (Decl *D = getCursorDecl(cursor))
Ted Kremeneka60ed472010-11-16 08:15:36 +00005529 return MakeCXCursor(D, getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005530 }
5531
5532 return clang_getNullCursor();
5533}
5534
5535CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
5536 if (clang_isDeclaration(cursor.kind)) {
5537 if (Decl *D = getCursorDecl(cursor)) {
5538 DeclContext *DC = D->getLexicalDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005539 if (!DC)
5540 return clang_getNullCursor();
5541
5542 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5543 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005544 }
5545 }
5546
5547 // FIXME: Note that we can't easily compute the lexical context of a
5548 // statement or expression, so we return nothing.
5549 return clang_getNullCursor();
5550}
5551
Douglas Gregor9f592342010-10-01 20:25:15 +00005552void clang_getOverriddenCursors(CXCursor cursor,
5553 CXCursor **overridden,
5554 unsigned *num_overridden) {
5555 if (overridden)
5556 *overridden = 0;
5557 if (num_overridden)
5558 *num_overridden = 0;
5559 if (!overridden || !num_overridden)
5560 return;
Argyrios Kyrtzidis15f4c982012-04-10 21:01:03 +00005561 if (!clang_isDeclaration(cursor.kind))
5562 return;
Douglas Gregor9f592342010-10-01 20:25:15 +00005563
Argyrios Kyrtzidisb11be042011-10-06 07:00:46 +00005564 SmallVector<CXCursor, 8> Overridden;
5565 cxcursor::getOverriddenCursors(cursor, Overridden);
Douglas Gregor9f592342010-10-01 20:25:15 +00005566
Ted Kremenek24077122011-11-14 23:51:37 +00005567 // Don't allocate memory if we have no overriden cursors.
5568 if (Overridden.size() == 0)
5569 return;
5570
Argyrios Kyrtzidisb11be042011-10-06 07:00:46 +00005571 *num_overridden = Overridden.size();
5572 *overridden = new CXCursor [Overridden.size()];
5573 std::copy(Overridden.begin(), Overridden.end(), *overridden);
Douglas Gregor9f592342010-10-01 20:25:15 +00005574}
5575
5576void clang_disposeOverriddenCursors(CXCursor *overridden) {
5577 delete [] overridden;
5578}
5579
Douglas Gregorecdcb882010-10-20 22:00:55 +00005580CXFile clang_getIncludedFile(CXCursor cursor) {
5581 if (cursor.kind != CXCursor_InclusionDirective)
5582 return 0;
5583
5584 InclusionDirective *ID = getCursorInclusionDirective(cursor);
5585 return (void *)ID->getFile();
5586}
5587
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005588} // end: extern "C"
5589
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005590
5591//===----------------------------------------------------------------------===//
5592// C++ AST instrospection.
5593//===----------------------------------------------------------------------===//
5594
5595extern "C" {
5596unsigned clang_CXXMethod_isStatic(CXCursor C) {
5597 if (!clang_isDeclaration(C.kind))
5598 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00005599
5600 CXXMethodDecl *Method = 0;
5601 Decl *D = cxcursor::getCursorDecl(C);
5602 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5603 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5604 else
5605 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5606 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00005607}
Ted Kremenekb12903e2010-05-18 22:32:15 +00005608
Douglas Gregor211924b2011-05-12 15:17:24 +00005609unsigned clang_CXXMethod_isVirtual(CXCursor C) {
5610 if (!clang_isDeclaration(C.kind))
5611 return 0;
5612
5613 CXXMethodDecl *Method = 0;
5614 Decl *D = cxcursor::getCursorDecl(C);
5615 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5616 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5617 else
5618 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5619 return (Method && Method->isVirtual()) ? 1 : 0;
5620}
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005621} // end: extern "C"
5622
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005623//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00005624// Attribute introspection.
5625//===----------------------------------------------------------------------===//
5626
5627extern "C" {
5628CXType clang_getIBOutletCollectionType(CXCursor C) {
5629 if (C.kind != CXCursor_IBOutletCollectionAttr)
Ted Kremeneka60ed472010-11-16 08:15:36 +00005630 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005631
5632 IBOutletCollectionAttr *A =
5633 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
5634
Argyrios Kyrtzidis18aa2ff2011-09-13 18:49:52 +00005635 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005636}
5637} // end: extern "C"
5638
5639//===----------------------------------------------------------------------===//
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005640// Inspecting memory usage.
5641//===----------------------------------------------------------------------===//
5642
Ted Kremenekf7870022011-04-20 16:41:07 +00005643typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005644
Ted Kremenekf7870022011-04-20 16:41:07 +00005645static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
5646 enum CXTUResourceUsageKind k,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005647 unsigned long amount) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005648 CXTUResourceUsageEntry entry = { k, amount };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005649 entries.push_back(entry);
5650}
5651
5652extern "C" {
5653
Ted Kremenekf7870022011-04-20 16:41:07 +00005654const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005655 const char *str = "";
5656 switch (kind) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005657 case CXTUResourceUsage_AST:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005658 str = "ASTContext: expressions, declarations, and types";
5659 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005660 case CXTUResourceUsage_Identifiers:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005661 str = "ASTContext: identifiers";
5662 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005663 case CXTUResourceUsage_Selectors:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005664 str = "ASTContext: selectors";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005665 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005666 case CXTUResourceUsage_GlobalCompletionResults:
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005667 str = "Code completion: cached global results";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005668 break;
Ted Kremenek457aaf02011-04-28 04:10:31 +00005669 case CXTUResourceUsage_SourceManagerContentCache:
5670 str = "SourceManager: content cache allocator";
5671 break;
Ted Kremenekba29bd22011-04-28 04:53:38 +00005672 case CXTUResourceUsage_AST_SideTables:
5673 str = "ASTContext: side tables";
5674 break;
Ted Kremenekf61b8312011-04-28 20:36:42 +00005675 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
5676 str = "SourceManager: malloc'ed memory buffers";
5677 break;
5678 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
5679 str = "SourceManager: mmap'ed memory buffers";
5680 break;
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005681 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
5682 str = "ExternalASTSource: malloc'ed memory buffers";
5683 break;
5684 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
5685 str = "ExternalASTSource: mmap'ed memory buffers";
5686 break;
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005687 case CXTUResourceUsage_Preprocessor:
5688 str = "Preprocessor: malloc'ed memory";
5689 break;
5690 case CXTUResourceUsage_PreprocessingRecord:
5691 str = "Preprocessor: PreprocessingRecord";
5692 break;
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005693 case CXTUResourceUsage_SourceManager_DataStructures:
5694 str = "SourceManager: data structures and tables";
5695 break;
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005696 case CXTUResourceUsage_Preprocessor_HeaderSearch:
5697 str = "Preprocessor: header search tables";
5698 break;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005699 }
5700 return str;
5701}
5702
Ted Kremenekf7870022011-04-20 16:41:07 +00005703CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005704 if (!TU) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005705 CXTUResourceUsage usage = { (void*) 0, 0, 0 };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005706 return usage;
5707 }
5708
5709 ASTUnit *astUnit = static_cast<ASTUnit*>(TU->TUData);
Dylan Noblesmith1e4c01b2012-02-13 12:32:21 +00005710 OwningPtr<MemUsageEntries> entries(new MemUsageEntries());
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005711 ASTContext &astContext = astUnit->getASTContext();
5712
5713 // How much memory is used by AST nodes and types?
Ted Kremenekf7870022011-04-20 16:41:07 +00005714 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005715 (unsigned long) astContext.getASTAllocatedMemory());
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005716
5717 // How much memory is used by identifiers?
Ted Kremenekf7870022011-04-20 16:41:07 +00005718 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005719 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
5720
5721 // How much memory is used for selectors?
Ted Kremenekf7870022011-04-20 16:41:07 +00005722 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005723 (unsigned long) astContext.Selectors.getTotalMemory());
5724
Ted Kremenekba29bd22011-04-28 04:53:38 +00005725 // How much memory is used by ASTContext's side tables?
5726 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
5727 (unsigned long) astContext.getSideTableAllocatedMemory());
5728
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005729 // How much memory is used for caching global code completion results?
5730 unsigned long completionBytes = 0;
5731 if (GlobalCodeCompletionAllocator *completionAllocator =
5732 astUnit->getCachedCompletionAllocator().getPtr()) {
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005733 completionBytes = completionAllocator->getTotalMemory();
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005734 }
Ted Kremenek457aaf02011-04-28 04:10:31 +00005735 createCXTUResourceUsageEntry(*entries,
5736 CXTUResourceUsage_GlobalCompletionResults,
5737 completionBytes);
5738
5739 // How much memory is being used by SourceManager's content cache?
5740 createCXTUResourceUsageEntry(*entries,
5741 CXTUResourceUsage_SourceManagerContentCache,
5742 (unsigned long) astContext.getSourceManager().getContentCacheSize());
Ted Kremenekf61b8312011-04-28 20:36:42 +00005743
5744 // How much memory is being used by the MemoryBuffer's in SourceManager?
5745 const SourceManager::MemoryBufferSizes &srcBufs =
5746 astUnit->getSourceManager().getMemoryBufferSizes();
5747
5748 createCXTUResourceUsageEntry(*entries,
5749 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
5750 (unsigned long) srcBufs.malloc_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005751 createCXTUResourceUsageEntry(*entries,
Ted Kremenekf61b8312011-04-28 20:36:42 +00005752 CXTUResourceUsage_SourceManager_Membuffer_MMap,
5753 (unsigned long) srcBufs.mmap_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005754 createCXTUResourceUsageEntry(*entries,
5755 CXTUResourceUsage_SourceManager_DataStructures,
5756 (unsigned long) astContext.getSourceManager()
5757 .getDataStructureSizes());
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005758
5759 // How much memory is being used by the ExternalASTSource?
5760 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
5761 const ExternalASTSource::MemoryBufferSizes &sizes =
5762 esrc->getMemoryBufferSizes();
5763
5764 createCXTUResourceUsageEntry(*entries,
5765 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
5766 (unsigned long) sizes.malloc_bytes);
5767 createCXTUResourceUsageEntry(*entries,
5768 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
5769 (unsigned long) sizes.mmap_bytes);
5770 }
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005771
5772 // How much memory is being used by the Preprocessor?
5773 Preprocessor &pp = astUnit->getPreprocessor();
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005774 createCXTUResourceUsageEntry(*entries,
5775 CXTUResourceUsage_Preprocessor,
Argyrios Kyrtzidisc5c5e922011-06-29 22:20:04 +00005776 pp.getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005777
5778 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
5779 createCXTUResourceUsageEntry(*entries,
5780 CXTUResourceUsage_PreprocessingRecord,
5781 pRec->getTotalMemory());
5782 }
5783
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005784 createCXTUResourceUsageEntry(*entries,
5785 CXTUResourceUsage_Preprocessor_HeaderSearch,
5786 pp.getHeaderSearchInfo().getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005787
Ted Kremenekf7870022011-04-20 16:41:07 +00005788 CXTUResourceUsage usage = { (void*) entries.get(),
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005789 (unsigned) entries->size(),
5790 entries->size() ? &(*entries)[0] : 0 };
5791 entries.take();
5792 return usage;
5793}
5794
Ted Kremenekf7870022011-04-20 16:41:07 +00005795void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005796 if (usage.data)
5797 delete (MemUsageEntries*) usage.data;
5798}
5799
5800} // end extern "C"
5801
Douglas Gregor6df78732011-05-05 20:27:22 +00005802void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
5803 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
5804 for (unsigned I = 0; I != Usage.numEntries; ++I)
5805 fprintf(stderr, " %s: %lu\n",
5806 clang_getTUResourceUsageName(Usage.entries[I].kind),
5807 Usage.entries[I].amount);
5808
5809 clang_disposeCXTUResourceUsage(Usage);
5810}
5811
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005812//===----------------------------------------------------------------------===//
Ted Kremenek04bb7162010-01-22 22:44:15 +00005813// Misc. utility functions.
5814//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00005815
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00005816/// Default to using an 8 MB stack size on "safety" threads.
5817static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005818
5819namespace clang {
5820
5821bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005822 void (*Fn)(void*), void *UserData,
5823 unsigned Size) {
5824 if (!Size)
5825 Size = GetSafetyThreadStackSize();
5826 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005827 return CRC.RunSafelyOnThread(Fn, UserData, Size);
5828 return CRC.RunSafely(Fn, UserData);
5829}
5830
5831unsigned GetSafetyThreadStackSize() {
5832 return SafetyStackThreadSize;
5833}
5834
5835void SetSafetyThreadStackSize(unsigned Value) {
5836 SafetyStackThreadSize = Value;
5837}
5838
Argyrios Kyrtzidis8e7c48a2012-03-28 02:49:50 +00005839}
5840
Argyrios Kyrtzidis81b5ac32012-03-28 02:49:54 +00005841void clang::setThreadBackgroundPriority() {
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00005842 // FIXME: Move to llvm/Support and make it cross-platform.
5843#ifdef __APPLE__
5844 setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG);
5845#endif
5846}
5847
Argyrios Kyrtzidis97934282012-04-11 03:52:18 +00005848void cxindex::printDiagsToStderr(ASTUnit *Unit) {
5849 if (!Unit)
5850 return;
5851
5852 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
5853 DEnd = Unit->stored_diag_end();
5854 D != DEnd; ++D) {
5855 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOpts());
5856 CXString Msg = clang_formatDiagnostic(&Diag,
5857 clang_defaultDiagnosticDisplayOptions());
5858 fprintf(stderr, "%s\n", clang_getCString(Msg));
5859 clang_disposeString(Msg);
5860 }
5861#ifdef LLVM_ON_WIN32
5862 // On Windows, force a flush, since there may be multiple copies of
5863 // stderr and stdout in the file system, all with different buffers
5864 // but writing to the same device.
5865 fflush(stderr);
5866#endif
5867}
5868
Ted Kremenek04bb7162010-01-22 22:44:15 +00005869extern "C" {
5870
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00005871CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00005872 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00005873}
5874
5875} // end: extern "C"
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005876