blob: 2233a1125ef56dd9a7abca90c4c1a00c71b5457a [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 Kremenekbbf66ca2012-04-30 19:06:49 +000064 D->OverridenCursorsPool = createOverridenCXCursorsPool();
Ted Kremeneka60ed472010-11-16 08:15:36 +000065 return D;
66}
67
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +000068cxtu::CXTUOwner::~CXTUOwner() {
69 if (TU)
70 clang_disposeTranslationUnit(TU);
71}
72
Ted Kremenekf0e23e82010-02-17 00:41:40 +000073/// \brief Compare two source ranges to determine their relative position in
Douglas Gregor33e9abd2010-01-22 19:49:59 +000074/// the translation unit.
Ted Kremenekf0e23e82010-02-17 00:41:40 +000075static RangeComparisonResult RangeCompare(SourceManager &SM,
76 SourceRange R1,
Douglas Gregor33e9abd2010-01-22 19:49:59 +000077 SourceRange R2) {
78 assert(R1.isValid() && "First range is invalid?");
79 assert(R2.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000080 if (R1.getEnd() != R2.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000081 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000082 return RangeBefore;
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000083 if (R2.getEnd() != R1.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000084 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000085 return RangeAfter;
86 return RangeOverlap;
87}
88
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000089/// \brief Determine if a source location falls within, before, or after a
90/// a given source range.
91static RangeComparisonResult LocationCompare(SourceManager &SM,
92 SourceLocation L, SourceRange R) {
93 assert(R.isValid() && "First range is invalid?");
94 assert(L.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000095 if (L == R.getBegin() || L == R.getEnd())
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000096 return RangeOverlap;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000097 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
98 return RangeBefore;
99 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
100 return RangeAfter;
101 return RangeOverlap;
102}
103
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000104/// \brief Translate a Clang source range into a CIndex source range.
105///
106/// Clang internally represents ranges where the end location points to the
107/// start of the token at the end. However, for external clients it is more
108/// useful to have a CXSourceRange be a proper half-open interval. This routine
109/// does the appropriate translation.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000110CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000111 const LangOptions &LangOpts,
Chris Lattner0a76aae2010-06-18 22:45:06 +0000112 const CharSourceRange &R) {
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000113 // We want the last character in this location, so we will adjust the
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000114 // location accordingly.
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000115 SourceLocation EndLoc = R.getEnd();
Argyrios Kyrtzidiseba8cd52012-04-11 18:15:01 +0000116 if (EndLoc.isValid() && EndLoc.isMacroID() && !SM.isMacroArgExpansion(EndLoc))
Chandler Carruthedc3dcc2011-07-25 16:56:02 +0000117 EndLoc = SM.getExpansionRange(EndLoc).second;
Argyrios Kyrtzidiseba8cd52012-04-11 18:15:01 +0000118 if (R.isTokenRange() && !EndLoc.isInvalid()) {
119 unsigned Length = Lexer::MeasureTokenLength(SM.getSpellingLoc(EndLoc),
120 SM, LangOpts);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000121 EndLoc = EndLoc.getLocWithOffset(Length);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000122 }
123
124 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
125 R.getBegin().getRawEncoding(),
126 EndLoc.getRawEncoding() };
127 return Result;
128}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000129
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000130//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000131// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000132//===----------------------------------------------------------------------===//
133
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000134static SourceRange getRawCursorExtent(CXCursor C);
Douglas Gregor66537982010-11-17 17:14:07 +0000135static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
136
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000137
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000138RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000139 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000140}
141
Douglas Gregorb1373d02010-01-20 20:59:29 +0000142/// \brief Visit the given cursor and, if requested by the visitor,
143/// its children.
144///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000145/// \param Cursor the cursor to visit.
146///
147/// \param CheckRegionOfInterest if true, then the caller already checked that
148/// this cursor is within the region of interest.
149///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000150/// \returns true if the visitation should be aborted, false if it
151/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000152bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000153 if (clang_isInvalid(Cursor.kind))
154 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000155
Douglas Gregorb1373d02010-01-20 20:59:29 +0000156 if (clang_isDeclaration(Cursor.kind)) {
157 Decl *D = getCursorDecl(Cursor);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +0000158 if (!D) {
159 assert(0 && "Invalid declaration cursor");
160 return true; // abort.
161 }
162
Argyrios Kyrtzidis65ab9072011-09-26 19:05:37 +0000163 // Ignore implicit declarations, unless it's an objc method because
164 // currently we should report implicit methods for properties when indexing.
165 if (D->isImplicit() && !isa<ObjCMethodDecl>(D))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000166 return false;
167 }
168
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000169 // If we have a range of interest, and this cursor doesn't intersect with it,
170 // we're done.
171 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000172 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000173 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000174 return false;
175 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000176
Douglas Gregorb1373d02010-01-20 20:59:29 +0000177 switch (Visitor(Cursor, Parent, ClientData)) {
178 case CXChildVisit_Break:
179 return true;
180
181 case CXChildVisit_Continue:
182 return false;
183
184 case CXChildVisit_Recurse:
185 return VisitChildren(Cursor);
186 }
187
David Blaikie7530c032012-01-17 06:56:22 +0000188 llvm_unreachable("Invalid CXChildVisitResult!");
Douglas Gregorb1373d02010-01-20 20:59:29 +0000189}
190
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000191static bool visitPreprocessedEntitiesInRange(SourceRange R,
192 PreprocessingRecord &PPRec,
193 CursorVisitor &Visitor) {
194 SourceManager &SM = Visitor.getASTUnit()->getSourceManager();
195 FileID FID;
196
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +0000197 if (!Visitor.shouldVisitIncludedEntities()) {
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000198 // If the begin/end of the range lie in the same FileID, do the optimization
199 // where we skip preprocessed entities that do not come from the same FileID.
Argyrios Kyrtzidisacca4112011-12-21 16:56:38 +0000200 FID = SM.getFileID(SM.getFileLoc(R.getBegin()));
201 if (FID != SM.getFileID(SM.getFileLoc(R.getEnd())))
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000202 FID = FileID();
203 }
204
205 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
206 Entities = PPRec.getPreprocessedEntitiesInRange(R);
207 return Visitor.visitPreprocessedEntities(Entities.first, Entities.second,
208 PPRec, FID);
209}
210
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000211void CursorVisitor::visitFileRegion() {
212 if (RegionOfInterest.isInvalid())
213 return;
214
215 ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData);
216 SourceManager &SM = Unit->getSourceManager();
217
218 std::pair<FileID, unsigned>
219 Begin = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getBegin())),
220 End = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getEnd()));
221
222 if (End.first != Begin.first) {
223 // If the end does not reside in the same file, try to recover by
224 // picking the end of the file of begin location.
225 End.first = Begin.first;
226 End.second = SM.getFileIDSize(Begin.first);
227 }
228
229 assert(Begin.first == End.first);
230 if (Begin.second > End.second)
231 return;
232
233 FileID File = Begin.first;
234 unsigned Offset = Begin.second;
235 unsigned Length = End.second - Begin.second;
236
Argyrios Kyrtzidisb49e7282011-11-29 03:14:11 +0000237 if (!VisitDeclsOnly && !VisitPreprocessorLast)
238 if (visitPreprocessedEntitiesInRegion())
239 return; // visitation break.
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000240
241 visitDeclsFromFileRegion(File, Offset, Length);
242
Argyrios Kyrtzidisb49e7282011-11-29 03:14:11 +0000243 if (!VisitDeclsOnly && VisitPreprocessorLast)
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000244 visitPreprocessedEntitiesInRegion();
245}
246
Argyrios Kyrtzidise2079cf2011-11-16 08:58:54 +0000247static bool isInLexicalContext(Decl *D, DeclContext *DC) {
248 if (!DC)
249 return false;
250
251 for (DeclContext *DeclDC = D->getLexicalDeclContext();
252 DeclDC; DeclDC = DeclDC->getLexicalParent()) {
253 if (DeclDC == DC)
254 return true;
255 }
256 return false;
257}
258
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000259void CursorVisitor::visitDeclsFromFileRegion(FileID File,
260 unsigned Offset, unsigned Length) {
261 ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData);
262 SourceManager &SM = Unit->getSourceManager();
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000263 SourceRange Range = RegionOfInterest;
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000264
265 SmallVector<Decl *, 16> Decls;
266 Unit->findFileRegionDecls(File, Offset, Length, Decls);
267
268 // If we didn't find any file level decls for the file, try looking at the
269 // file that it was included from.
Argyrios Kyrtzidisc14a03d2011-11-23 20:27:36 +0000270 while (Decls.empty() || Decls.front()->isTopLevelDeclInObjCContainer()) {
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000271 bool Invalid = false;
272 const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid);
273 if (Invalid)
274 return;
275
276 SourceLocation Outer;
277 if (SLEntry.isFile())
278 Outer = SLEntry.getFile().getIncludeLoc();
279 else
280 Outer = SLEntry.getExpansion().getExpansionLocStart();
281 if (Outer.isInvalid())
282 return;
283
284 llvm::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer);
285 Length = 0;
286 Unit->findFileRegionDecls(File, Offset, Length, Decls);
287 }
288
289 assert(!Decls.empty());
290
291 bool VisitedAtLeastOnce = false;
Argyrios Kyrtzidise2079cf2011-11-16 08:58:54 +0000292 DeclContext *CurDC = 0;
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000293 SmallVector<Decl *, 16>::iterator DIt = Decls.begin();
294 for (SmallVector<Decl *, 16>::iterator DE = Decls.end(); DIt != DE; ++DIt) {
295 Decl *D = *DIt;
Argyrios Kyrtzidised8bef42011-11-28 22:38:07 +0000296 if (D->getSourceRange().isInvalid())
297 continue;
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000298
Argyrios Kyrtzidise2079cf2011-11-16 08:58:54 +0000299 if (isInLexicalContext(D, CurDC))
300 continue;
301
302 CurDC = dyn_cast<DeclContext>(D);
303
Argyrios Kyrtzidise2079cf2011-11-16 08:58:54 +0000304 if (TagDecl *TD = dyn_cast<TagDecl>(D))
305 if (!TD->isFreeStanding())
306 continue;
307
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000308 RangeComparisonResult CompRes = RangeCompare(SM, D->getSourceRange(),Range);
309 if (CompRes == RangeBefore)
310 continue;
311 if (CompRes == RangeAfter)
312 break;
313
314 assert(CompRes == RangeOverlap);
315 VisitedAtLeastOnce = true;
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +0000316
317 if (isa<ObjCContainerDecl>(D)) {
318 FileDI_current = &DIt;
319 FileDE_current = DE;
320 } else {
321 FileDI_current = 0;
322 }
323
Argyrios Kyrtzidisba986172011-11-03 19:02:28 +0000324 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000325 break;
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000326 }
327
328 if (VisitedAtLeastOnce)
329 return;
330
331 // No Decls overlapped with the range. Move up the lexical context until there
332 // is a context that contains the range or we reach the translation unit
333 // level.
334 DeclContext *DC = DIt == Decls.begin() ? (*DIt)->getLexicalDeclContext()
335 : (*(DIt-1))->getLexicalDeclContext();
336
337 while (DC && !DC->isTranslationUnit()) {
338 Decl *D = cast<Decl>(DC);
339 SourceRange CurDeclRange = D->getSourceRange();
340 if (CurDeclRange.isInvalid())
341 break;
342
343 if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) {
Argyrios Kyrtzidisba986172011-11-03 19:02:28 +0000344 Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true);
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000345 break;
346 }
347
348 DC = D->getLexicalDeclContext();
349 }
350}
351
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000352bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
Argyrios Kyrtzidisb49e7282011-11-29 03:14:11 +0000353 if (!AU->getPreprocessor().getPreprocessingRecord())
354 return false;
355
Douglas Gregor788f5a12010-03-20 00:41:21 +0000356 PreprocessingRecord &PPRec
Ted Kremeneka60ed472010-11-16 08:15:36 +0000357 = *AU->getPreprocessor().getPreprocessingRecord();
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000358 SourceManager &SM = AU->getSourceManager();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000359
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000360 if (RegionOfInterest.isValid()) {
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +0000361 SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000362 SourceLocation B = MappedRange.getBegin();
363 SourceLocation E = MappedRange.getEnd();
364
365 if (AU->isInPreambleFileID(B)) {
366 if (SM.isLoadedSourceLocation(E))
367 return visitPreprocessedEntitiesInRange(SourceRange(B, E),
368 PPRec, *this);
369
370 // Beginning of range lies in the preamble but it also extends beyond
371 // it into the main file. Split the range into 2 parts, one covering
372 // the preamble and another covering the main file. This allows subsequent
373 // calls to visitPreprocessedEntitiesInRange to accept a source range that
374 // lies in the same FileID, allowing it to skip preprocessed entities that
375 // do not come from the same FileID.
376 bool breaked =
377 visitPreprocessedEntitiesInRange(
378 SourceRange(B, AU->getEndOfPreambleFileID()),
379 PPRec, *this);
380 if (breaked) return true;
381 return visitPreprocessedEntitiesInRange(
382 SourceRange(AU->getStartOfMainFileID(), E),
383 PPRec, *this);
384 }
385
386 return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this);
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000387 }
388
Douglas Gregor788f5a12010-03-20 00:41:21 +0000389 bool OnlyLocalDecls
Douglas Gregor32038bb2010-12-21 19:07:48 +0000390 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
391
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000392 if (OnlyLocalDecls)
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000393 return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(),
394 PPRec);
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000395
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000396 return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec);
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000397}
398
399template<typename InputIterator>
400bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000401 InputIterator Last,
402 PreprocessingRecord &PPRec,
403 FileID FID) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000404 for (; First != Last; ++First) {
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000405 if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID))
406 continue;
407
408 PreprocessedEntity *PPE = *First;
409 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000410 if (Visit(MakeMacroExpansionCursor(ME, TU)))
411 return true;
412
413 continue;
414 }
415
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000416 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(PPE)) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000417 if (Visit(MakeMacroDefinitionCursor(MD, TU)))
418 return true;
419
420 continue;
421 }
422
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000423 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000424 if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
425 return true;
426
427 continue;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000428 }
429 }
430
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000431 return false;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000432}
433
Douglas Gregorb1373d02010-01-20 20:59:29 +0000434/// \brief Visit the children of the given cursor.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000435///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000436/// \returns true if the visitation should be aborted, false if it
437/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000438bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregorc314aa42011-03-02 19:17:03 +0000439 if (clang_isReference(Cursor.kind) &&
440 Cursor.kind != CXCursor_CXXBaseSpecifier) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000441 // By definition, references have no children.
442 return false;
443 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000444
445 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000446 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000447 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000448
Douglas Gregorb1373d02010-01-20 20:59:29 +0000449 if (clang_isDeclaration(Cursor.kind)) {
450 Decl *D = getCursorDecl(Cursor);
Douglas Gregor06d9b1a2011-04-14 21:41:34 +0000451 if (!D)
452 return false;
453
Ted Kremenek539311e2010-02-18 18:47:01 +0000454 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000455 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000456
Douglas Gregor06d9b1a2011-04-14 21:41:34 +0000457 if (clang_isStatement(Cursor.kind)) {
458 if (Stmt *S = getCursorStmt(Cursor))
459 return Visit(S);
460
461 return false;
462 }
463
464 if (clang_isExpression(Cursor.kind)) {
465 if (Expr *E = getCursorExpr(Cursor))
466 return Visit(E);
467
468 return false;
469 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000470
Douglas Gregorb1373d02010-01-20 20:59:29 +0000471 if (clang_isTranslationUnit(Cursor.kind)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000472 CXTranslationUnit tu = getCursorTU(Cursor);
473 ASTUnit *CXXUnit = static_cast<ASTUnit*>(tu->TUData);
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000474
475 int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
476 for (unsigned I = 0; I != 2; ++I) {
477 if (VisitOrder[I]) {
478 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
479 RegionOfInterest.isInvalid()) {
480 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
481 TLEnd = CXXUnit->top_level_end();
482 TL != TLEnd; ++TL) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000483 if (Visit(MakeCXCursor(*TL, tu, RegionOfInterest), true))
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000484 return true;
485 }
486 } else if (VisitDeclContext(
487 CXXUnit->getASTContext().getTranslationUnitDecl()))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000488 return true;
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000489 continue;
Douglas Gregor7b691f332010-01-20 21:13:59 +0000490 }
Bob Wilson3178cb62010-03-19 03:57:57 +0000491
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000492 // Walk the preprocessing record.
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000493 if (CXXUnit->getPreprocessor().getPreprocessingRecord())
494 visitPreprocessedEntitiesInRegion();
Douglas Gregor0396f462010-03-19 05:22:59 +0000495 }
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000496
Douglas Gregor7b691f332010-01-20 21:13:59 +0000497 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000498 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000499
Douglas Gregorc314aa42011-03-02 19:17:03 +0000500 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
501 if (CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
502 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
503 return Visit(BaseTSInfo->getTypeLoc());
504 }
505 }
506 }
Argyrios Kyrtzidis221d5a52011-09-13 18:49:56 +0000507
508 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
509 IBOutletCollectionAttr *A =
510 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
511 if (const ObjCInterfaceType *InterT = A->getInterface()->getAs<ObjCInterfaceType>())
512 return Visit(cxcursor::MakeCursorObjCClassRef(InterT->getInterface(),
513 A->getInterfaceLoc(), TU));
514 }
515
Douglas Gregorb1373d02010-01-20 20:59:29 +0000516 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000517 return false;
518}
519
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000520bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
Douglas Gregor13c8ccb2011-04-22 23:49:24 +0000521 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
522 if (Visit(TSInfo->getTypeLoc()))
523 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000524
Ted Kremenek664cffd2010-07-22 11:30:19 +0000525 if (Stmt *Body = B->getBody())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000526 return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest));
Ted Kremenek664cffd2010-07-22 11:30:19 +0000527
528 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000529}
530
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000531llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
532 if (RegionOfInterest.isValid()) {
Douglas Gregor66537982010-11-17 17:14:07 +0000533 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000534 if (Range.isInvalid())
535 return llvm::Optional<bool>();
Douglas Gregor66537982010-11-17 17:14:07 +0000536
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000537 switch (CompareRegionOfInterest(Range)) {
538 case RangeBefore:
539 // This declaration comes before the region of interest; skip it.
540 return llvm::Optional<bool>();
541
542 case RangeAfter:
543 // This declaration comes after the region of interest; we're done.
544 return false;
545
546 case RangeOverlap:
547 // This declaration overlaps the region of interest; visit it.
548 break;
549 }
550 }
551 return true;
552}
553
554bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
555 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
556
557 // FIXME: Eventually remove. This part of a hack to support proper
558 // iteration over all Decls contained lexically within an ObjC container.
559 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
560 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
561
562 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000563 Decl *D = *I;
564 if (D->getLexicalDeclContext() != DC)
565 continue;
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000566 CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
Argyrios Kyrtzidis1836db02012-02-04 01:04:58 +0000567
568 // FIXME: ObjCClassRef/ObjCProtocolRef for forward class/protocol
569 // declarations is a mismatch with the compiler semantics.
570 if (Cursor.kind == CXCursor_ObjCInterfaceDecl) {
571 ObjCInterfaceDecl *ID = cast<ObjCInterfaceDecl>(D);
572 if (!ID->isThisDeclarationADefinition())
573 Cursor = MakeCursorObjCClassRef(ID, ID->getLocation(), TU);
574
575 } else if (Cursor.kind == CXCursor_ObjCProtocolDecl) {
576 ObjCProtocolDecl *PD = cast<ObjCProtocolDecl>(D);
577 if (!PD->isThisDeclarationADefinition())
578 Cursor = MakeCursorObjCProtocolRef(PD, PD->getLocation(), TU);
579 }
580
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000581 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
582 if (!V.hasValue())
583 continue;
584 if (!V.getValue())
585 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000586 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000587 return true;
588 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000589 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000590}
591
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000592bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
593 llvm_unreachable("Translation units are visited directly by Visit()");
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000594}
595
Richard Smith162e1c12011-04-15 14:24:37 +0000596bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
597 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
598 return Visit(TSInfo->getTypeLoc());
599
600 return false;
601}
602
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000603bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
604 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
605 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000606
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000607 return false;
608}
609
610bool CursorVisitor::VisitTagDecl(TagDecl *D) {
611 return VisitDeclContext(D);
612}
613
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000614bool CursorVisitor::VisitClassTemplateSpecializationDecl(
615 ClassTemplateSpecializationDecl *D) {
616 bool ShouldVisitBody = false;
617 switch (D->getSpecializationKind()) {
618 case TSK_Undeclared:
619 case TSK_ImplicitInstantiation:
620 // Nothing to visit
621 return false;
622
623 case TSK_ExplicitInstantiationDeclaration:
624 case TSK_ExplicitInstantiationDefinition:
625 break;
626
627 case TSK_ExplicitSpecialization:
628 ShouldVisitBody = true;
629 break;
630 }
631
632 // Visit the template arguments used in the specialization.
633 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
634 TypeLoc TL = SpecType->getTypeLoc();
635 if (TemplateSpecializationTypeLoc *TSTLoc
636 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
637 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
638 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
639 return true;
640 }
641 }
642
643 if (ShouldVisitBody && VisitCXXRecordDecl(D))
644 return true;
645
646 return false;
647}
648
Douglas Gregor74dbe642010-08-31 19:31:58 +0000649bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
650 ClassTemplatePartialSpecializationDecl *D) {
651 // FIXME: Visit the "outer" template parameter lists on the TagDecl
652 // before visiting these template parameters.
653 if (VisitTemplateParameters(D->getTemplateParameters()))
654 return true;
655
656 // Visit the partial specialization arguments.
657 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
658 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
659 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
660 return true;
661
662 return VisitCXXRecordDecl(D);
663}
664
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000665bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000666 // Visit the default argument.
667 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
668 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
669 if (Visit(DefArg->getTypeLoc()))
670 return true;
671
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000672 return false;
673}
674
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000675bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
676 if (Expr *Init = D->getInitExpr())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000677 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000678 return false;
679}
680
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000681bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
682 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
683 if (Visit(TSInfo->getTypeLoc()))
684 return true;
685
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000686 // Visit the nested-name-specifier, if present.
687 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
688 if (VisitNestedNameSpecifierLoc(QualifierLoc))
689 return true;
690
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000691 return false;
692}
693
Douglas Gregora67e03f2010-09-09 21:42:20 +0000694/// \brief Compare two base or member initializers based on their source order.
Sean Huntcbb67482011-01-08 20:30:50 +0000695static int CompareCXXCtorInitializers(const void* Xp, const void *Yp) {
696 CXXCtorInitializer const * const *X
697 = static_cast<CXXCtorInitializer const * const *>(Xp);
698 CXXCtorInitializer const * const *Y
699 = static_cast<CXXCtorInitializer const * const *>(Yp);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000700
701 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
702 return -1;
703 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
704 return 1;
705 else
706 return 0;
707}
708
Douglas Gregorb1373d02010-01-20 20:59:29 +0000709bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000710 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
711 // Visit the function declaration's syntactic components in the order
712 // written. This requires a bit of work.
Abramo Bagnara723df242010-12-14 22:11:44 +0000713 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
Douglas Gregor01829d32010-08-31 14:41:23 +0000714 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
715
716 // If we have a function declared directly (without the use of a typedef),
717 // visit just the return type. Otherwise, just visit the function's type
718 // now.
719 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
720 (!FTL && Visit(TL)))
721 return true;
722
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000723 // Visit the nested-name-specifier, if present.
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000724 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
725 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000726 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000727
728 // Visit the declaration name.
729 if (VisitDeclarationNameInfo(ND->getNameInfo()))
730 return true;
731
732 // FIXME: Visit explicitly-specified template arguments!
733
734 // Visit the function parameters, if we have a function type.
735 if (FTL && VisitFunctionTypeLoc(*FTL, true))
736 return true;
737
738 // FIXME: Attributes?
739 }
740
Sean Hunt10620eb2011-05-06 20:44:56 +0000741 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
Douglas Gregora67e03f2010-09-09 21:42:20 +0000742 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
743 // Find the initializers that were written in the source.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000744 SmallVector<CXXCtorInitializer *, 4> WrittenInits;
Douglas Gregora67e03f2010-09-09 21:42:20 +0000745 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
746 IEnd = Constructor->init_end();
747 I != IEnd; ++I) {
748 if (!(*I)->isWritten())
749 continue;
750
751 WrittenInits.push_back(*I);
752 }
753
754 // Sort the initializers in source order
755 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
Sean Huntcbb67482011-01-08 20:30:50 +0000756 &CompareCXXCtorInitializers);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000757
758 // Visit the initializers in source order
759 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
Sean Huntcbb67482011-01-08 20:30:50 +0000760 CXXCtorInitializer *Init = WrittenInits[I];
Francois Pichet00eb3f92010-12-04 09:14:42 +0000761 if (Init->isAnyMemberInitializer()) {
762 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
Douglas Gregora67e03f2010-09-09 21:42:20 +0000763 Init->getMemberLocation(), TU)))
764 return true;
Douglas Gregor76852c22011-11-01 01:16:03 +0000765 } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) {
766 if (Visit(TInfo->getTypeLoc()))
Douglas Gregora67e03f2010-09-09 21:42:20 +0000767 return true;
768 }
769
770 // Visit the initializer value.
771 if (Expr *Initializer = Init->getInit())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000772 if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
Douglas Gregora67e03f2010-09-09 21:42:20 +0000773 return true;
774 }
775 }
776
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000777 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
Douglas Gregora67e03f2010-09-09 21:42:20 +0000778 return true;
779 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000780
Douglas Gregorb1373d02010-01-20 20:59:29 +0000781 return false;
782}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000783
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000784bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
785 if (VisitDeclaratorDecl(D))
786 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000787
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000788 if (Expr *BitWidth = D->getBitWidth())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000789 return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000790
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000791 return false;
792}
793
794bool CursorVisitor::VisitVarDecl(VarDecl *D) {
795 if (VisitDeclaratorDecl(D))
796 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000797
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000798 if (Expr *Init = D->getInit())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000799 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000800
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000801 return false;
802}
803
Douglas Gregor84b51d72010-09-01 20:16:53 +0000804bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
805 if (VisitDeclaratorDecl(D))
806 return true;
807
808 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
809 if (Expr *DefArg = D->getDefaultArgument())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000810 return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
Douglas Gregor84b51d72010-09-01 20:16:53 +0000811
812 return false;
813}
814
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000815bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
816 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
817 // before visiting these template parameters.
818 if (VisitTemplateParameters(D->getTemplateParameters()))
819 return true;
820
821 return VisitFunctionDecl(D->getTemplatedDecl());
822}
823
Douglas Gregor39d6f072010-08-31 19:02:00 +0000824bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
825 // FIXME: Visit the "outer" template parameter lists on the TagDecl
826 // before visiting these template parameters.
827 if (VisitTemplateParameters(D->getTemplateParameters()))
828 return true;
829
830 return VisitCXXRecordDecl(D->getTemplatedDecl());
831}
832
Douglas Gregor84b51d72010-09-01 20:16:53 +0000833bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
834 if (VisitTemplateParameters(D->getTemplateParameters()))
835 return true;
836
837 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
838 VisitTemplateArgumentLoc(D->getDefaultArgument()))
839 return true;
840
841 return false;
842}
843
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000844bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000845 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
846 if (Visit(TSInfo->getTypeLoc()))
847 return true;
848
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000849 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000850 PEnd = ND->param_end();
851 P != PEnd; ++P) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000852 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000853 return true;
854 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000855
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000856 if (ND->isThisDeclarationADefinition() &&
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000857 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000858 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000859
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000860 return false;
861}
862
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +0000863template <typename DeclIt>
864static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current,
865 SourceManager &SM, SourceLocation EndLoc,
866 SmallVectorImpl<Decl *> &Decls) {
867 DeclIt next = *DI_current;
868 while (++next != DE_current) {
869 Decl *D_next = *next;
870 if (!D_next)
871 break;
872 SourceLocation L = D_next->getLocStart();
873 if (!L.isValid())
874 break;
875 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
876 *DI_current = next;
877 Decls.push_back(D_next);
878 continue;
879 }
880 break;
881 }
882}
883
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000884namespace {
885 struct ContainerDeclsSort {
886 SourceManager &SM;
887 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
888 bool operator()(Decl *A, Decl *B) {
889 SourceLocation L_A = A->getLocStart();
890 SourceLocation L_B = B->getLocStart();
891 assert(L_A.isValid() && L_B.isValid());
892 return SM.isBeforeInTranslationUnit(L_A, L_B);
893 }
894 };
895}
896
Douglas Gregora59e3902010-01-21 23:27:09 +0000897bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000898 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
899 // an @implementation can lexically contain Decls that are not properly
900 // nested in the AST. When we identify such cases, we need to retrofit
901 // this nesting here.
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +0000902 if (!DI_current && !FileDI_current)
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000903 return VisitDeclContext(D);
904
905 // Scan the Decls that immediately come after the container
906 // in the current DeclContext. If any fall within the
907 // container's lexical region, stash them into a vector
908 // for later processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000909 SmallVector<Decl *, 24> DeclsInContainer;
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000910 SourceLocation EndLoc = D->getSourceRange().getEnd();
Ted Kremeneka60ed472010-11-16 08:15:36 +0000911 SourceManager &SM = AU->getSourceManager();
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000912 if (EndLoc.isValid()) {
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +0000913 if (DI_current) {
914 addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc,
915 DeclsInContainer);
916 } else {
917 addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc,
918 DeclsInContainer);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000919 }
920 }
921
922 // The common case.
923 if (DeclsInContainer.empty())
924 return VisitDeclContext(D);
925
926 // Get all the Decls in the DeclContext, and sort them with the
927 // additional ones we've collected. Then visit them.
928 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
929 I!=E; ++I) {
930 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000931 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
932 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000933 continue;
934 DeclsInContainer.push_back(subDecl);
935 }
936
937 // Now sort the Decls so that they appear in lexical order.
938 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
939 ContainerDeclsSort(SM));
940
941 // Now visit the decls.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000942 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000943 E = DeclsInContainer.end(); I != E; ++I) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000944 CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000945 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
946 if (!V.hasValue())
947 continue;
948 if (!V.getValue())
949 return false;
950 if (Visit(Cursor, true))
951 return true;
952 }
953 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000954}
955
Douglas Gregorb1373d02010-01-20 20:59:29 +0000956bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000957 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
958 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000959 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000960
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000961 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
962 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
963 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000964 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000965 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000966
Douglas Gregora59e3902010-01-21 23:27:09 +0000967 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000968}
969
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000970bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000971 if (!PID->isThisDeclarationADefinition())
972 return Visit(MakeCursorObjCProtocolRef(PID, PID->getLocation(), TU));
973
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000974 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
975 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
976 E = PID->protocol_end(); I != E; ++I, ++PL)
977 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
978 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000979
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000980 return VisitObjCContainerDecl(PID);
981}
982
Ted Kremenek23173d72010-05-18 21:09:07 +0000983bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000984 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000985 return true;
986
Ted Kremenek23173d72010-05-18 21:09:07 +0000987 // FIXME: This implements a workaround with @property declarations also being
988 // installed in the DeclContext for the @interface. Eventually this code
989 // should be removed.
990 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
991 if (!CDecl || !CDecl->IsClassExtension())
992 return false;
993
994 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
995 if (!ID)
996 return false;
997
998 IdentifierInfo *PropertyId = PD->getIdentifier();
999 ObjCPropertyDecl *prevDecl =
1000 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
1001
1002 if (!prevDecl)
1003 return false;
1004
1005 // Visit synthesized methods since they will be skipped when visiting
1006 // the @interface.
1007 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +00001008 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001009 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
Ted Kremenek23173d72010-05-18 21:09:07 +00001010 return true;
1011
1012 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +00001013 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001014 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
Ted Kremenek23173d72010-05-18 21:09:07 +00001015 return true;
1016
1017 return false;
1018}
1019
Douglas Gregorb1373d02010-01-20 20:59:29 +00001020bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Douglas Gregor375bb142011-12-27 22:43:10 +00001021 if (!D->isThisDeclarationADefinition()) {
1022 // Forward declaration is treated like a reference.
1023 return Visit(MakeCursorObjCClassRef(D, D->getLocation(), TU));
1024 }
1025
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001026 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +00001027 if (D->getSuperClass() &&
1028 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001029 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001030 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001031 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001032
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001033 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1034 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1035 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001036 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001037 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001038
Douglas Gregora59e3902010-01-21 23:27:09 +00001039 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001040}
1041
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001042bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1043 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001044}
1045
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001046bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +00001047 // 'ID' could be null when dealing with invalid code.
1048 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1049 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1050 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001051
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001052 return VisitObjCImplDecl(D);
1053}
1054
1055bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1056#if 0
1057 // Issue callbacks for super class.
1058 // FIXME: No source location information!
1059 if (D->getSuperClass() &&
1060 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001061 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001062 TU)))
1063 return true;
1064#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001065
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001066 return VisitObjCImplDecl(D);
1067}
1068
Douglas Gregora4ffd852010-11-17 01:03:52 +00001069bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1070 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
Argyrios Kyrtzidis135bf8e2012-06-09 03:03:02 +00001071 if (PD->isIvarNameSpecified())
1072 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
Douglas Gregora4ffd852010-11-17 01:03:52 +00001073
1074 return false;
1075}
1076
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001077bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1078 return VisitDeclContext(D);
1079}
1080
Douglas Gregor69319002010-08-31 23:48:11 +00001081bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001082 // Visit nested-name-specifier.
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00001083 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1084 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001085 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001086
1087 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1088 D->getTargetNameLoc(), TU));
1089}
1090
Douglas Gregor7e242562010-09-01 19:52:22 +00001091bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001092 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001093 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1094 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001095 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001096 }
Douglas Gregor7e242562010-09-01 19:52:22 +00001097
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001098 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1099 return true;
1100
Douglas Gregor7e242562010-09-01 19:52:22 +00001101 return VisitDeclarationNameInfo(D->getNameInfo());
1102}
1103
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001104bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001105 // Visit nested-name-specifier.
Douglas Gregordb992412011-02-25 16:33:46 +00001106 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1107 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001108 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001109
1110 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1111 D->getIdentLocation(), TU));
1112}
1113
Douglas Gregor7e242562010-09-01 19:52:22 +00001114bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001115 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001116 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1117 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001118 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001119 }
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001120
Douglas Gregor7e242562010-09-01 19:52:22 +00001121 return VisitDeclarationNameInfo(D->getNameInfo());
1122}
1123
1124bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1125 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001126 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001127 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1128 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001129 return true;
1130
Douglas Gregor7e242562010-09-01 19:52:22 +00001131 return false;
1132}
1133
Douglas Gregor01829d32010-08-31 14:41:23 +00001134bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1135 switch (Name.getName().getNameKind()) {
1136 case clang::DeclarationName::Identifier:
1137 case clang::DeclarationName::CXXLiteralOperatorName:
1138 case clang::DeclarationName::CXXOperatorName:
1139 case clang::DeclarationName::CXXUsingDirective:
1140 return false;
1141
1142 case clang::DeclarationName::CXXConstructorName:
1143 case clang::DeclarationName::CXXDestructorName:
1144 case clang::DeclarationName::CXXConversionFunctionName:
1145 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1146 return Visit(TSInfo->getTypeLoc());
1147 return false;
1148
1149 case clang::DeclarationName::ObjCZeroArgSelector:
1150 case clang::DeclarationName::ObjCOneArgSelector:
1151 case clang::DeclarationName::ObjCMultiArgSelector:
1152 // FIXME: Per-identifier location info?
1153 return false;
1154 }
David Blaikie7530c032012-01-17 06:56:22 +00001155
1156 llvm_unreachable("Invalid DeclarationName::Kind!");
Douglas Gregor01829d32010-08-31 14:41:23 +00001157}
1158
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001159bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1160 SourceRange Range) {
1161 // FIXME: This whole routine is a hack to work around the lack of proper
1162 // source information in nested-name-specifiers (PR5791). Since we do have
1163 // a beginning source location, we can visit the first component of the
1164 // nested-name-specifier, if it's a single-token component.
1165 if (!NNS)
1166 return false;
1167
1168 // Get the first component in the nested-name-specifier.
1169 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1170 NNS = Prefix;
1171
1172 switch (NNS->getKind()) {
1173 case NestedNameSpecifier::Namespace:
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001174 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1175 TU));
1176
Douglas Gregor14aba762011-02-24 02:36:08 +00001177 case NestedNameSpecifier::NamespaceAlias:
1178 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1179 Range.getBegin(), TU));
1180
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001181 case NestedNameSpecifier::TypeSpec: {
1182 // If the type has a form where we know that the beginning of the source
1183 // range matches up with a reference cursor. Visit the appropriate reference
1184 // cursor.
John McCallf4c73712011-01-19 06:33:43 +00001185 const Type *T = NNS->getAsType();
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001186 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1187 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1188 if (const TagType *Tag = dyn_cast<TagType>(T))
1189 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1190 if (const TemplateSpecializationType *TST
1191 = dyn_cast<TemplateSpecializationType>(T))
1192 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1193 break;
1194 }
1195
1196 case NestedNameSpecifier::TypeSpecWithTemplate:
1197 case NestedNameSpecifier::Global:
1198 case NestedNameSpecifier::Identifier:
1199 break;
1200 }
1201
1202 return false;
1203}
1204
Douglas Gregordc355712011-02-25 00:36:19 +00001205bool
1206CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001207 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
Douglas Gregordc355712011-02-25 00:36:19 +00001208 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1209 Qualifiers.push_back(Qualifier);
1210
1211 while (!Qualifiers.empty()) {
1212 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1213 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1214 switch (NNS->getKind()) {
1215 case NestedNameSpecifier::Namespace:
1216 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001217 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001218 TU)))
1219 return true;
1220
1221 break;
1222
1223 case NestedNameSpecifier::NamespaceAlias:
1224 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001225 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001226 TU)))
1227 return true;
1228
1229 break;
1230
1231 case NestedNameSpecifier::TypeSpec:
1232 case NestedNameSpecifier::TypeSpecWithTemplate:
1233 if (Visit(Q.getTypeLoc()))
1234 return true;
1235
1236 break;
1237
1238 case NestedNameSpecifier::Global:
1239 case NestedNameSpecifier::Identifier:
1240 break;
1241 }
1242 }
1243
1244 return false;
1245}
1246
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001247bool CursorVisitor::VisitTemplateParameters(
1248 const TemplateParameterList *Params) {
1249 if (!Params)
1250 return false;
1251
1252 for (TemplateParameterList::const_iterator P = Params->begin(),
1253 PEnd = Params->end();
1254 P != PEnd; ++P) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001255 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001256 return true;
1257 }
1258
1259 return false;
1260}
1261
Douglas Gregor0b36e612010-08-31 20:37:03 +00001262bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1263 switch (Name.getKind()) {
1264 case TemplateName::Template:
1265 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1266
1267 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001268 // Visit the overloaded template set.
1269 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1270 return true;
1271
Douglas Gregor0b36e612010-08-31 20:37:03 +00001272 return false;
1273
1274 case TemplateName::DependentTemplate:
1275 // FIXME: Visit nested-name-specifier.
1276 return false;
1277
1278 case TemplateName::QualifiedTemplate:
1279 // FIXME: Visit nested-name-specifier.
1280 return Visit(MakeCursorTemplateRef(
1281 Name.getAsQualifiedTemplateName()->getDecl(),
1282 Loc, TU));
John McCall14606042011-06-30 08:33:18 +00001283
1284 case TemplateName::SubstTemplateTemplateParm:
1285 return Visit(MakeCursorTemplateRef(
1286 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1287 Loc, TU));
Douglas Gregor1aee05d2011-01-15 06:45:20 +00001288
1289 case TemplateName::SubstTemplateTemplateParmPack:
1290 return Visit(MakeCursorTemplateRef(
1291 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1292 Loc, TU));
Douglas Gregor0b36e612010-08-31 20:37:03 +00001293 }
David Blaikie7530c032012-01-17 06:56:22 +00001294
1295 llvm_unreachable("Invalid TemplateName::Kind!");
Douglas Gregor0b36e612010-08-31 20:37:03 +00001296}
1297
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001298bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1299 switch (TAL.getArgument().getKind()) {
1300 case TemplateArgument::Null:
1301 case TemplateArgument::Integral:
Douglas Gregor87dd6972010-12-20 16:52:59 +00001302 case TemplateArgument::Pack:
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001303 return false;
1304
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001305 case TemplateArgument::Type:
1306 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1307 return Visit(TSInfo->getTypeLoc());
1308 return false;
1309
1310 case TemplateArgument::Declaration:
1311 if (Expr *E = TAL.getSourceDeclExpression())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001312 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001313 return false;
1314
1315 case TemplateArgument::Expression:
1316 if (Expr *E = TAL.getSourceExpression())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001317 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001318 return false;
1319
1320 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001321 case TemplateArgument::TemplateExpansion:
Douglas Gregorb6744ef2011-03-02 17:09:35 +00001322 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1323 return true;
1324
Douglas Gregora7fc9012011-01-05 18:58:31 +00001325 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
Douglas Gregor0b36e612010-08-31 20:37:03 +00001326 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001327 }
David Blaikie7530c032012-01-17 06:56:22 +00001328
1329 llvm_unreachable("Invalid TemplateArgument::Kind!");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001330}
1331
Ted Kremeneka0536d82010-05-07 01:04:29 +00001332bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1333 return VisitDeclContext(D);
1334}
1335
Douglas Gregor01829d32010-08-31 14:41:23 +00001336bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1337 return Visit(TL.getUnqualifiedLoc());
1338}
1339
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001340bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00001341 ASTContext &Context = AU->getASTContext();
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001342
1343 // Some builtin types (such as Objective-C's "id", "sel", and
1344 // "Class") have associated declarations. Create cursors for those.
1345 QualType VisitType;
John McCalle0a22d02011-10-18 21:02:43 +00001346 switch (TL.getTypePtr()->getKind()) {
John McCall2dde35b2011-10-18 22:28:37 +00001347
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001348 case BuiltinType::Void:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001349 case BuiltinType::NullPtr:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001350 case BuiltinType::Dependent:
John McCall2dde35b2011-10-18 22:28:37 +00001351#define BUILTIN_TYPE(Id, SingletonId)
1352#define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1353#define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1354#define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
1355#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
1356#include "clang/AST/BuiltinTypes.def"
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001357 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001358
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001359 case BuiltinType::ObjCId:
1360 VisitType = Context.getObjCIdType();
1361 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001362
1363 case BuiltinType::ObjCClass:
1364 VisitType = Context.getObjCClassType();
1365 break;
1366
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001367 case BuiltinType::ObjCSel:
1368 VisitType = Context.getObjCSelType();
1369 break;
1370 }
1371
1372 if (!VisitType.isNull()) {
1373 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001374 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001375 TU));
1376 }
1377
1378 return false;
1379}
1380
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001381bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
Richard Smith162e1c12011-04-15 14:24:37 +00001382 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001383}
1384
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001385bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1386 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1387}
1388
1389bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
Argyrios Kyrtzidis6f155de2011-08-25 22:24:47 +00001390 if (TL.isDefinition())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001391 return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
Argyrios Kyrtzidis6f155de2011-08-25 22:24:47 +00001392
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001393 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1394}
1395
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001396bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Chandler Carruth960d13d2011-05-01 09:53:37 +00001397 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001398}
1399
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001400bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1401 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1402 return true;
1403
John McCallc12c5bb2010-05-15 11:32:37 +00001404 return false;
1405}
1406
1407bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1408 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1409 return true;
1410
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001411 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1412 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1413 TU)))
1414 return true;
1415 }
1416
1417 return false;
1418}
1419
1420bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001421 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001422}
1423
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001424bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1425 return Visit(TL.getInnerLoc());
1426}
1427
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001428bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1429 return Visit(TL.getPointeeLoc());
1430}
1431
1432bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1433 return Visit(TL.getPointeeLoc());
1434}
1435
1436bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1437 return Visit(TL.getPointeeLoc());
1438}
1439
1440bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001441 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001442}
1443
1444bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001445 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001446}
1447
Argyrios Kyrtzidis3422fbc2011-08-15 18:44:43 +00001448bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1449 return Visit(TL.getModifiedLoc());
1450}
1451
Douglas Gregor01829d32010-08-31 14:41:23 +00001452bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1453 bool SkipResultType) {
1454 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001455 return true;
1456
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001457 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001458 if (Decl *D = TL.getArg(I))
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001459 if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001460 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001461
1462 return false;
1463}
1464
1465bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1466 if (Visit(TL.getElementLoc()))
1467 return true;
1468
1469 if (Expr *Size = TL.getSizeExpr())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001470 return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001471
1472 return false;
1473}
1474
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001475bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1476 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001477 // Visit the template name.
1478 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1479 TL.getTemplateNameLoc()))
1480 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001481
1482 // Visit the template arguments.
1483 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1484 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1485 return true;
1486
1487 return false;
1488}
1489
Douglas Gregor2332c112010-01-21 20:48:56 +00001490bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1491 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1492}
1493
1494bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1495 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1496 return Visit(TSInfo->getTypeLoc());
1497
1498 return false;
1499}
1500
Sean Huntca63c202011-05-24 22:41:36 +00001501bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1502 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1503 return Visit(TSInfo->getTypeLoc());
1504
1505 return false;
1506}
1507
Douglas Gregor2494dd02011-03-01 01:34:45 +00001508bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
1509 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1510 return true;
1511
1512 return false;
1513}
1514
Douglas Gregor94fdffa2011-03-01 20:11:18 +00001515bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1516 DependentTemplateSpecializationTypeLoc TL) {
1517 // Visit the nested-name-specifier, if there is one.
1518 if (TL.getQualifierLoc() &&
1519 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1520 return true;
1521
1522 // Visit the template arguments.
1523 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1524 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1525 return true;
1526
1527 return false;
1528}
1529
Douglas Gregor9e876872011-03-01 18:12:44 +00001530bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1531 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1532 return true;
1533
1534 return Visit(TL.getNamedTypeLoc());
1535}
1536
Douglas Gregor7536dd52010-12-20 02:24:11 +00001537bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1538 return Visit(TL.getPatternLoc());
1539}
1540
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +00001541bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1542 if (Expr *E = TL.getUnderlyingExpr())
1543 return Visit(MakeCXCursor(E, StmtParent, TU));
1544
1545 return false;
1546}
1547
1548bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1549 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1550}
1551
Eli Friedmanb001de72011-10-06 23:00:33 +00001552bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1553 return Visit(TL.getValueLoc());
1554}
1555
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +00001556#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1557bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1558 return Visit##PARENT##Loc(TL); \
1559}
1560
1561DEFAULT_TYPELOC_IMPL(Complex, Type)
1562DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1563DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1564DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1565DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
1566DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1567DEFAULT_TYPELOC_IMPL(Vector, Type)
1568DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1569DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1570DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1571DEFAULT_TYPELOC_IMPL(Record, TagType)
1572DEFAULT_TYPELOC_IMPL(Enum, TagType)
1573DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1574DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1575DEFAULT_TYPELOC_IMPL(Auto, Type)
1576
Ted Kremenek3064ef92010-08-27 21:34:58 +00001577bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001578 // Visit the nested-name-specifier, if present.
1579 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1580 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1581 return true;
1582
John McCall5e1cdac2011-10-07 06:10:15 +00001583 if (D->isCompleteDefinition()) {
Ted Kremenek3064ef92010-08-27 21:34:58 +00001584 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1585 E = D->bases_end(); I != E; ++I) {
1586 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1587 return true;
1588 }
1589 }
1590
1591 return VisitTagDecl(D);
1592}
1593
Ted Kremenek09dfa372010-02-18 05:46:33 +00001594bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001595 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1596 i != e; ++i)
1597 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001598 return true;
1599
1600 return false;
1601}
1602
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001603//===----------------------------------------------------------------------===//
1604// Data-recursive visitor methods.
1605//===----------------------------------------------------------------------===//
1606
Ted Kremenek28a71942010-11-13 00:36:47 +00001607namespace {
Ted Kremenek035dc412010-11-13 00:36:50 +00001608#define DEF_JOB(NAME, DATA, KIND)\
1609class NAME : public VisitorJob {\
1610public:\
1611 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1612 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Ted Kremenekf64d8032010-11-18 00:02:32 +00001613 DATA *get() const { return static_cast<DATA*>(data[0]); }\
Ted Kremenek035dc412010-11-13 00:36:50 +00001614};
1615
1616DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1617DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001618DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001619DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001620DEF_JOB(ExplicitTemplateArgsVisit, ASTTemplateArgumentListInfo,
Ted Kremenek60608ec2010-11-17 00:50:47 +00001621 ExplicitTemplateArgsVisitKind)
Douglas Gregor94d96292011-01-19 20:34:17 +00001622DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
Douglas Gregor011d8b92012-02-15 00:54:55 +00001623DEF_JOB(LambdaExprParts, LambdaExpr, LambdaExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001624#undef DEF_JOB
1625
1626class DeclVisit : public VisitorJob {
1627public:
1628 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1629 VisitorJob(parent, VisitorJob::DeclVisitKind,
1630 d, isFirst ? (void*) 1 : (void*) 0) {}
1631 static bool classof(const VisitorJob *VJ) {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001632 return VJ->getKind() == DeclVisitKind;
Ted Kremenek035dc412010-11-13 00:36:50 +00001633 }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001634 Decl *get() const { return static_cast<Decl*>(data[0]); }
1635 bool isFirst() const { return data[1] ? true : false; }
Ted Kremenek035dc412010-11-13 00:36:50 +00001636};
Ted Kremenek035dc412010-11-13 00:36:50 +00001637class TypeLocVisit : public VisitorJob {
1638public:
1639 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1640 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1641 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1642
1643 static bool classof(const VisitorJob *VJ) {
1644 return VJ->getKind() == TypeLocVisitKind;
1645 }
1646
Ted Kremenek82f3c502010-11-15 22:23:26 +00001647 TypeLoc get() const {
Ted Kremenekf64d8032010-11-18 00:02:32 +00001648 QualType T = QualType::getFromOpaquePtr(data[0]);
1649 return TypeLoc(T, data[1]);
Ted Kremenek035dc412010-11-13 00:36:50 +00001650 }
1651};
1652
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001653class LabelRefVisit : public VisitorJob {
1654public:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001655 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1656 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001657 labelLoc.getPtrEncoding()) {}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001658
1659 static bool classof(const VisitorJob *VJ) {
1660 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1661 }
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001662 LabelDecl *get() const { return static_cast<LabelDecl*>(data[0]); }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001663 SourceLocation getLoc() const {
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001664 return SourceLocation::getFromPtrEncoding(data[1]); }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001665};
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001666
1667class NestedNameSpecifierLocVisit : public VisitorJob {
1668public:
1669 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1670 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1671 Qualifier.getNestedNameSpecifier(),
1672 Qualifier.getOpaqueData()) { }
1673
1674 static bool classof(const VisitorJob *VJ) {
1675 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1676 }
1677
1678 NestedNameSpecifierLoc get() const {
1679 return NestedNameSpecifierLoc(static_cast<NestedNameSpecifier*>(data[0]),
1680 data[1]);
1681 }
1682};
1683
Ted Kremenekf64d8032010-11-18 00:02:32 +00001684class DeclarationNameInfoVisit : public VisitorJob {
1685public:
1686 DeclarationNameInfoVisit(Stmt *S, CXCursor parent)
1687 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
1688 static bool classof(const VisitorJob *VJ) {
1689 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1690 }
1691 DeclarationNameInfo get() const {
1692 Stmt *S = static_cast<Stmt*>(data[0]);
1693 switch (S->getStmtClass()) {
1694 default:
1695 llvm_unreachable("Unhandled Stmt");
Douglas Gregorba0513d2011-10-25 01:33:02 +00001696 case clang::Stmt::MSDependentExistsStmtClass:
1697 return cast<MSDependentExistsStmt>(S)->getNameInfo();
Ted Kremenekf64d8032010-11-18 00:02:32 +00001698 case Stmt::CXXDependentScopeMemberExprClass:
1699 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1700 case Stmt::DependentScopeDeclRefExprClass:
1701 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
1702 }
1703 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001704};
Ted Kremenekcdba6592010-11-18 00:42:18 +00001705class MemberRefVisit : public VisitorJob {
1706public:
1707 MemberRefVisit(FieldDecl *D, SourceLocation L, CXCursor parent)
1708 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001709 L.getPtrEncoding()) {}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001710 static bool classof(const VisitorJob *VJ) {
1711 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1712 }
1713 FieldDecl *get() const {
1714 return static_cast<FieldDecl*>(data[0]);
1715 }
1716 SourceLocation getLoc() const {
1717 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1718 }
1719};
Ted Kremenek28a71942010-11-13 00:36:47 +00001720class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1721 VisitorWorkList &WL;
1722 CXCursor Parent;
1723public:
1724 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1725 : WL(wl), Parent(parent) {}
1726
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001727 void VisitAddrLabelExpr(AddrLabelExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001728 void VisitBlockExpr(BlockExpr *B);
Ted Kremenek28a71942010-11-13 00:36:47 +00001729 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek083c7e22010-11-13 05:38:03 +00001730 void VisitCompoundStmt(CompoundStmt *S);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001731 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
Douglas Gregorba0513d2011-10-25 01:33:02 +00001732 void VisitMSDependentExistsStmt(MSDependentExistsStmt *S);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001733 void VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001734 void VisitCXXNewExpr(CXXNewExpr *E);
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001735 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001736 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001737 void VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001738 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001739 void VisitCXXTypeidExpr(CXXTypeidExpr *E);
Ted Kremenek55b933a2010-11-17 00:50:36 +00001740 void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001741 void VisitCXXUuidofExpr(CXXUuidofExpr *E);
Argyrios Kyrtzidisdcbb2fb2011-12-03 03:49:44 +00001742 void VisitCXXCatchStmt(CXXCatchStmt *S);
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001743 void VisitDeclRefExpr(DeclRefExpr *D);
Ted Kremenek035dc412010-11-13 00:36:50 +00001744 void VisitDeclStmt(DeclStmt *S);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001745 void VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001746 void VisitDesignatedInitExpr(DesignatedInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001747 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1748 void VisitForStmt(ForStmt *FS);
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001749 void VisitGotoStmt(GotoStmt *GS);
Ted Kremenek28a71942010-11-13 00:36:47 +00001750 void VisitIfStmt(IfStmt *If);
1751 void VisitInitListExpr(InitListExpr *IE);
1752 void VisitMemberExpr(MemberExpr *M);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001753 void VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001754 void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001755 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1756 void VisitOverloadExpr(OverloadExpr *E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001757 void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001758 void VisitStmt(Stmt *S);
1759 void VisitSwitchStmt(SwitchStmt *S);
1760 void VisitWhileStmt(WhileStmt *W);
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001761 void VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Francois Pichet6ad6f282010-12-07 00:08:36 +00001762 void VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E);
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00001763 void VisitTypeTraitExpr(TypeTraitExpr *E);
John Wiegley21ff2e52011-04-28 00:16:57 +00001764 void VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E);
John Wiegley55262202011-04-25 06:54:41 +00001765 void VisitExpressionTraitExpr(ExpressionTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001766 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001767 void VisitVAArgExpr(VAArgExpr *E);
Douglas Gregor94d96292011-01-19 20:34:17 +00001768 void VisitSizeOfPackExpr(SizeOfPackExpr *E);
John McCall4b9c2d22011-11-06 09:01:30 +00001769 void VisitPseudoObjectExpr(PseudoObjectExpr *E);
1770 void VisitOpaqueValueExpr(OpaqueValueExpr *E);
Douglas Gregor011d8b92012-02-15 00:54:55 +00001771 void VisitLambdaExpr(LambdaExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00001772
Ted Kremenek28a71942010-11-13 00:36:47 +00001773private:
Ted Kremenekf64d8032010-11-18 00:02:32 +00001774 void AddDeclarationNameInfo(Stmt *S);
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001775 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001776 void AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001777 void AddMemberRef(FieldDecl *D, SourceLocation L);
Ted Kremenek28a71942010-11-13 00:36:47 +00001778 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001779 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001780 void AddTypeLoc(TypeSourceInfo *TI);
1781 void EnqueueChildren(Stmt *S);
1782};
1783} // end anonyous namespace
1784
Ted Kremenekf64d8032010-11-18 00:02:32 +00001785void EnqueueVisitor::AddDeclarationNameInfo(Stmt *S) {
1786 // 'S' should always be non-null, since it comes from the
1787 // statement we are visiting.
1788 WL.push_back(DeclarationNameInfoVisit(S, Parent));
1789}
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001790
1791void
1792EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1793 if (Qualifier)
1794 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
1795}
1796
Ted Kremenek28a71942010-11-13 00:36:47 +00001797void EnqueueVisitor::AddStmt(Stmt *S) {
1798 if (S)
1799 WL.push_back(StmtVisit(S, Parent));
1800}
Ted Kremenek035dc412010-11-13 00:36:50 +00001801void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001802 if (D)
Ted Kremenek035dc412010-11-13 00:36:50 +00001803 WL.push_back(DeclVisit(D, Parent, isFirst));
Ted Kremenek28a71942010-11-13 00:36:47 +00001804}
Ted Kremenek60608ec2010-11-17 00:50:47 +00001805void EnqueueVisitor::
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001806 AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001807 if (A)
1808 WL.push_back(ExplicitTemplateArgsVisit(
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001809 const_cast<ASTTemplateArgumentListInfo*>(A), Parent));
Ted Kremenek60608ec2010-11-17 00:50:47 +00001810}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001811void EnqueueVisitor::AddMemberRef(FieldDecl *D, SourceLocation L) {
1812 if (D)
1813 WL.push_back(MemberRefVisit(D, L, Parent));
1814}
Ted Kremenek28a71942010-11-13 00:36:47 +00001815void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1816 if (TI)
1817 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1818 }
1819void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001820 unsigned size = WL.size();
John McCall7502c1d2011-02-13 04:07:26 +00001821 for (Stmt::child_range Child = S->children(); Child; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001822 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001823 }
1824 if (size == WL.size())
1825 return;
1826 // Now reverse the entries we just added. This will match the DFS
1827 // ordering performed by the worklist.
1828 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1829 std::reverse(I, E);
1830}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001831void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1832 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
1833}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001834void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1835 AddDecl(B->getBlockDecl());
1836}
Ted Kremenek28a71942010-11-13 00:36:47 +00001837void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1838 EnqueueChildren(E);
1839 AddTypeLoc(E->getTypeSourceInfo());
1840}
Ted Kremenek083c7e22010-11-13 05:38:03 +00001841void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1842 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1843 E = S->body_rend(); I != E; ++I) {
1844 AddStmt(*I);
1845 }
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001846}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001847void EnqueueVisitor::
Douglas Gregorba0513d2011-10-25 01:33:02 +00001848VisitMSDependentExistsStmt(MSDependentExistsStmt *S) {
1849 AddStmt(S->getSubStmt());
1850 AddDeclarationNameInfo(S);
1851 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
1852 AddNestedNameSpecifierLoc(QualifierLoc);
1853}
1854
1855void EnqueueVisitor::
Ted Kremenekf64d8032010-11-18 00:02:32 +00001856VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
1857 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1858 AddDeclarationNameInfo(E);
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001859 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1860 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001861 if (!E->isImplicitAccess())
1862 AddStmt(E->getBase());
1863}
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001864void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001865 // Enqueue the initializer , if any.
1866 AddStmt(E->getInitializer());
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001867 // Enqueue the array size, if any.
1868 AddStmt(E->getArraySize());
1869 // Enqueue the allocated type.
1870 AddTypeLoc(E->getAllocatedTypeSourceInfo());
1871 // Enqueue the placement arguments.
1872 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1873 AddStmt(E->getPlacementArg(I-1));
1874}
Ted Kremenek28a71942010-11-13 00:36:47 +00001875void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
Ted Kremenek8b8d8c92010-11-13 05:55:56 +00001876 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1877 AddStmt(CE->getArg(I-1));
Ted Kremenek28a71942010-11-13 00:36:47 +00001878 AddStmt(CE->getCallee());
1879 AddStmt(CE->getArg(0));
1880}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001881void EnqueueVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1882 // Visit the name of the type being destroyed.
1883 AddTypeLoc(E->getDestroyedTypeInfo());
1884 // Visit the scope type that looks disturbingly like the nested-name-specifier
1885 // but isn't.
1886 AddTypeLoc(E->getScopeTypeInfo());
1887 // Visit the nested-name-specifier.
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001888 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1889 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001890 // Visit base expression.
1891 AddStmt(E->getBase());
1892}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001893void EnqueueVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1894 AddTypeLoc(E->getTypeSourceInfo());
1895}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001896void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1897 EnqueueChildren(E);
1898 AddTypeLoc(E->getTypeSourceInfo());
1899}
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001900void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1901 EnqueueChildren(E);
1902 if (E->isTypeOperand())
1903 AddTypeLoc(E->getTypeOperandSourceInfo());
1904}
Ted Kremenek55b933a2010-11-17 00:50:36 +00001905
1906void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
1907 *E) {
1908 EnqueueChildren(E);
1909 AddTypeLoc(E->getTypeSourceInfo());
1910}
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001911void EnqueueVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1912 EnqueueChildren(E);
1913 if (E->isTypeOperand())
1914 AddTypeLoc(E->getTypeOperandSourceInfo());
1915}
Argyrios Kyrtzidisdcbb2fb2011-12-03 03:49:44 +00001916
1917void EnqueueVisitor::VisitCXXCatchStmt(CXXCatchStmt *S) {
1918 EnqueueChildren(S);
1919 AddDecl(S->getExceptionDecl());
1920}
1921
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001922void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001923 if (DR->hasExplicitTemplateArgs()) {
1924 AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
1925 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001926 WL.push_back(DeclRefExprParts(DR, Parent));
1927}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001928void EnqueueVisitor::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
1929 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1930 AddDeclarationNameInfo(E);
Douglas Gregor00cf3cc2011-02-25 20:49:16 +00001931 AddNestedNameSpecifierLoc(E->getQualifierLoc());
Ted Kremenekf64d8032010-11-18 00:02:32 +00001932}
Ted Kremenek035dc412010-11-13 00:36:50 +00001933void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1934 unsigned size = WL.size();
1935 bool isFirst = true;
1936 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1937 D != DEnd; ++D) {
1938 AddDecl(*D, isFirst);
1939 isFirst = false;
1940 }
1941 if (size == WL.size())
1942 return;
1943 // Now reverse the entries we just added. This will match the DFS
1944 // ordering performed by the worklist.
1945 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1946 std::reverse(I, E);
1947}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001948void EnqueueVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1949 AddStmt(E->getInit());
1950 typedef DesignatedInitExpr::Designator Designator;
1951 for (DesignatedInitExpr::reverse_designators_iterator
1952 D = E->designators_rbegin(), DEnd = E->designators_rend();
1953 D != DEnd; ++D) {
1954 if (D->isFieldDesignator()) {
1955 if (FieldDecl *Field = D->getField())
1956 AddMemberRef(Field, D->getFieldLoc());
1957 continue;
1958 }
1959 if (D->isArrayDesignator()) {
1960 AddStmt(E->getArrayIndex(*D));
1961 continue;
1962 }
1963 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1964 AddStmt(E->getArrayRangeEnd(*D));
1965 AddStmt(E->getArrayRangeStart(*D));
1966 }
1967}
Ted Kremenek28a71942010-11-13 00:36:47 +00001968void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1969 EnqueueChildren(E);
1970 AddTypeLoc(E->getTypeInfoAsWritten());
1971}
1972void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1973 AddStmt(FS->getBody());
1974 AddStmt(FS->getInc());
1975 AddStmt(FS->getCond());
1976 AddDecl(FS->getConditionVariable());
1977 AddStmt(FS->getInit());
1978}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001979void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) {
1980 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
1981}
Ted Kremenek28a71942010-11-13 00:36:47 +00001982void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
1983 AddStmt(If->getElse());
1984 AddStmt(If->getThen());
1985 AddStmt(If->getCond());
1986 AddDecl(If->getConditionVariable());
1987}
1988void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
1989 // We care about the syntactic form of the initializer list, only.
1990 if (InitListExpr *Syntactic = IE->getSyntacticForm())
1991 IE = Syntactic;
1992 EnqueueChildren(IE);
1993}
1994void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
Douglas Gregor89629a72010-11-17 17:15:08 +00001995 WL.push_back(MemberExprParts(M, Parent));
1996
1997 // If the base of the member access expression is an implicit 'this', don't
1998 // visit it.
1999 // FIXME: If we ever want to show these implicit accesses, this will be
2000 // unfortunate. However, clang_getCursor() relies on this behavior.
Douglas Gregor75e85042011-03-02 21:06:53 +00002001 if (!M->isImplicitAccess())
2002 AddStmt(M->getBase());
Ted Kremenek28a71942010-11-13 00:36:47 +00002003}
Ted Kremenek73d15c42010-11-13 01:09:29 +00002004void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
2005 AddTypeLoc(E->getEncodedTypeSourceInfo());
2006}
Ted Kremenek28a71942010-11-13 00:36:47 +00002007void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
2008 EnqueueChildren(M);
2009 AddTypeLoc(M->getClassReceiverTypeInfo());
2010}
Ted Kremenekcdba6592010-11-18 00:42:18 +00002011void EnqueueVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
2012 // Visit the components of the offsetof expression.
2013 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
2014 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
2015 const OffsetOfNode &Node = E->getComponent(I-1);
2016 switch (Node.getKind()) {
2017 case OffsetOfNode::Array:
2018 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2019 break;
2020 case OffsetOfNode::Field:
Abramo Bagnara06dec892011-03-12 09:45:03 +00002021 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
Ted Kremenekcdba6592010-11-18 00:42:18 +00002022 break;
2023 case OffsetOfNode::Identifier:
2024 case OffsetOfNode::Base:
2025 continue;
2026 }
2027 }
2028 // Visit the type into which we're computing the offset.
2029 AddTypeLoc(E->getTypeSourceInfo());
2030}
Ted Kremenek28a71942010-11-13 00:36:47 +00002031void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00002032 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
Ted Kremenek60458782010-11-12 21:34:16 +00002033 WL.push_back(OverloadExprParts(E, Parent));
2034}
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002035void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
2036 UnaryExprOrTypeTraitExpr *E) {
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00002037 EnqueueChildren(E);
2038 if (E->isArgumentType())
2039 AddTypeLoc(E->getArgumentTypeInfo());
2040}
Ted Kremenek28a71942010-11-13 00:36:47 +00002041void EnqueueVisitor::VisitStmt(Stmt *S) {
2042 EnqueueChildren(S);
2043}
2044void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
2045 AddStmt(S->getBody());
2046 AddStmt(S->getCond());
2047 AddDecl(S->getConditionVariable());
2048}
Ted Kremenekfafa75a2010-11-17 00:50:39 +00002049
Ted Kremenek28a71942010-11-13 00:36:47 +00002050void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
2051 AddStmt(W->getBody());
2052 AddStmt(W->getCond());
2053 AddDecl(W->getConditionVariable());
2054}
John Wiegley21ff2e52011-04-28 00:16:57 +00002055
Ted Kremenek2939b6f2010-11-17 00:50:50 +00002056void EnqueueVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
2057 AddTypeLoc(E->getQueriedTypeSourceInfo());
2058}
Francois Pichet6ad6f282010-12-07 00:08:36 +00002059
2060void EnqueueVisitor::VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
Francois Pichet6ad6f282010-12-07 00:08:36 +00002061 AddTypeLoc(E->getRhsTypeSourceInfo());
Francois Pichet0a03a3f2010-12-08 09:11:05 +00002062 AddTypeLoc(E->getLhsTypeSourceInfo());
Francois Pichet6ad6f282010-12-07 00:08:36 +00002063}
2064
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00002065void EnqueueVisitor::VisitTypeTraitExpr(TypeTraitExpr *E) {
2066 for (unsigned I = E->getNumArgs(); I > 0; --I)
2067 AddTypeLoc(E->getArg(I-1));
2068}
2069
John Wiegley21ff2e52011-04-28 00:16:57 +00002070void EnqueueVisitor::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
2071 AddTypeLoc(E->getQueriedTypeSourceInfo());
2072}
2073
John Wiegley55262202011-04-25 06:54:41 +00002074void EnqueueVisitor::VisitExpressionTraitExpr(ExpressionTraitExpr *E) {
2075 EnqueueChildren(E);
2076}
2077
Ted Kremenek28a71942010-11-13 00:36:47 +00002078void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
2079 VisitOverloadExpr(U);
2080 if (!U->isImplicitAccess())
2081 AddStmt(U->getBase());
2082}
Ted Kremenek9d3bf792010-11-17 00:50:43 +00002083void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) {
2084 AddStmt(E->getSubExpr());
2085 AddTypeLoc(E->getWrittenTypeInfo());
2086}
Douglas Gregor94d96292011-01-19 20:34:17 +00002087void EnqueueVisitor::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
2088 WL.push_back(SizeOfPackExprParts(E, Parent));
2089}
John McCall4b9c2d22011-11-06 09:01:30 +00002090void EnqueueVisitor::VisitOpaqueValueExpr(OpaqueValueExpr *E) {
2091 // If the opaque value has a source expression, just transparently
2092 // visit that. This is useful for (e.g.) pseudo-object expressions.
2093 if (Expr *SourceExpr = E->getSourceExpr())
2094 return Visit(SourceExpr);
John McCall4b9c2d22011-11-06 09:01:30 +00002095}
Douglas Gregor011d8b92012-02-15 00:54:55 +00002096void EnqueueVisitor::VisitLambdaExpr(LambdaExpr *E) {
2097 AddStmt(E->getBody());
2098 WL.push_back(LambdaExprParts(E, Parent));
2099}
John McCall4b9c2d22011-11-06 09:01:30 +00002100void EnqueueVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *E) {
2101 // Treat the expression like its syntactic form.
2102 Visit(E->getSyntacticForm());
2103}
Ted Kremenek60458782010-11-12 21:34:16 +00002104
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002105void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002106 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002107}
2108
2109bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2110 if (RegionOfInterest.isValid()) {
2111 SourceRange Range = getRawCursorExtent(C);
2112 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2113 return false;
2114 }
2115 return true;
2116}
2117
2118bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2119 while (!WL.empty()) {
2120 // Dequeue the worklist item.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002121 VisitorJob LI = WL.back();
2122 WL.pop_back();
2123
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002124 // Set the Parent field, then back to its old value once we're done.
2125 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2126
2127 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00002128 case VisitorJob::DeclVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002129 Decl *D = cast<DeclVisit>(&LI)->get();
Ted Kremenekf1107452010-11-12 18:26:56 +00002130 if (!D)
2131 continue;
2132
2133 // For now, perform default visitation for Decls.
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002134 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2135 cast<DeclVisit>(&LI)->isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00002136 return true;
2137
2138 continue;
2139 }
Ted Kremenek60608ec2010-11-17 00:50:47 +00002140 case VisitorJob::ExplicitTemplateArgsVisitKind: {
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00002141 const ASTTemplateArgumentListInfo *ArgList =
Ted Kremenek60608ec2010-11-17 00:50:47 +00002142 cast<ExplicitTemplateArgsVisit>(&LI)->get();
2143 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2144 *ArgEnd = Arg + ArgList->NumTemplateArgs;
2145 Arg != ArgEnd; ++Arg) {
2146 if (VisitTemplateArgumentLoc(*Arg))
2147 return true;
2148 }
2149 continue;
2150 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002151 case VisitorJob::TypeLocVisitKind: {
2152 // Perform default visitation for TypeLocs.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002153 if (Visit(cast<TypeLocVisit>(&LI)->get()))
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002154 return true;
2155 continue;
2156 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002157 case VisitorJob::LabelRefVisitKind: {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002158 LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Ted Kremeneke7455012011-02-23 04:54:51 +00002159 if (LabelStmt *stmt = LS->getStmt()) {
2160 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2161 TU))) {
2162 return true;
2163 }
2164 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002165 continue;
2166 }
Ted Kremenek47695c82011-08-18 22:25:21 +00002167
Douglas Gregorf3db29f2011-02-25 18:19:59 +00002168 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2169 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2170 if (VisitNestedNameSpecifierLoc(V->get()))
2171 return true;
2172 continue;
2173 }
2174
Ted Kremenekf64d8032010-11-18 00:02:32 +00002175 case VisitorJob::DeclarationNameInfoVisitKind: {
2176 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2177 ->get()))
2178 return true;
2179 continue;
2180 }
Ted Kremenekcdba6592010-11-18 00:42:18 +00002181 case VisitorJob::MemberRefVisitKind: {
2182 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2183 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2184 return true;
2185 continue;
2186 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002187 case VisitorJob::StmtVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002188 Stmt *S = cast<StmtVisit>(&LI)->get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00002189 if (!S)
2190 continue;
2191
Ted Kremenekf1107452010-11-12 18:26:56 +00002192 // Update the current cursor.
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002193 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
Ted Kremenekcdba6592010-11-18 00:42:18 +00002194 if (!IsInRegionOfInterest(Cursor))
2195 continue;
2196 switch (Visitor(Cursor, Parent, ClientData)) {
2197 case CXChildVisit_Break: return true;
2198 case CXChildVisit_Continue: break;
2199 case CXChildVisit_Recurse:
2200 EnqueueWorkList(WL, S);
Ted Kremenek82f3c502010-11-15 22:23:26 +00002201 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002202 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00002203 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002204 }
2205 case VisitorJob::MemberExprPartsKind: {
2206 // Handle the other pieces in the MemberExpr besides the base.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002207 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002208
2209 // Visit the nested-name-specifier
Douglas Gregor40d96a62011-02-28 21:54:11 +00002210 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
2211 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002212 return true;
2213
2214 // Visit the declaration name.
2215 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2216 return true;
2217
2218 // Visit the explicitly-specified template arguments, if any.
2219 if (M->hasExplicitTemplateArgs()) {
2220 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2221 *ArgEnd = Arg + M->getNumTemplateArgs();
2222 Arg != ArgEnd; ++Arg) {
2223 if (VisitTemplateArgumentLoc(*Arg))
2224 return true;
2225 }
2226 }
2227 continue;
2228 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002229 case VisitorJob::DeclRefExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002230 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002231 // Visit nested-name-specifier, if present.
Douglas Gregor40d96a62011-02-28 21:54:11 +00002232 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
2233 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002234 return true;
2235 // Visit declaration name.
2236 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2237 return true;
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002238 continue;
2239 }
Ted Kremenek60458782010-11-12 21:34:16 +00002240 case VisitorJob::OverloadExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002241 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Ted Kremenek60458782010-11-12 21:34:16 +00002242 // Visit the nested-name-specifier.
Douglas Gregor4c9be892011-02-28 20:01:57 +00002243 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
2244 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenek60458782010-11-12 21:34:16 +00002245 return true;
2246 // Visit the declaration name.
2247 if (VisitDeclarationNameInfo(O->getNameInfo()))
2248 return true;
2249 // Visit the overloaded declaration reference.
2250 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2251 return true;
Ted Kremenek60458782010-11-12 21:34:16 +00002252 continue;
2253 }
Douglas Gregor94d96292011-01-19 20:34:17 +00002254 case VisitorJob::SizeOfPackExprPartsKind: {
2255 SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
2256 NamedDecl *Pack = E->getPack();
2257 if (isa<TemplateTypeParmDecl>(Pack)) {
2258 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
2259 E->getPackLoc(), TU)))
2260 return true;
2261
2262 continue;
2263 }
2264
2265 if (isa<TemplateTemplateParmDecl>(Pack)) {
2266 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
2267 E->getPackLoc(), TU)))
2268 return true;
2269
2270 continue;
2271 }
2272
2273 // Non-type template parameter packs and function parameter packs are
2274 // treated like DeclRefExpr cursors.
2275 continue;
2276 }
Douglas Gregor011d8b92012-02-15 00:54:55 +00002277
2278 case VisitorJob::LambdaExprPartsKind: {
2279 // Visit captures.
2280 LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
2281 for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
2282 CEnd = E->explicit_capture_end();
2283 C != CEnd; ++C) {
2284 if (C->capturesThis())
2285 continue;
2286
2287 if (Visit(MakeCursorVariableRef(C->getCapturedVar(),
2288 C->getLocation(),
2289 TU)))
2290 return true;
2291 }
2292
2293 // Visit parameters and return type, if present.
2294 if (E->hasExplicitParameters() || E->hasExplicitResultType()) {
2295 TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
2296 if (E->hasExplicitParameters() && E->hasExplicitResultType()) {
2297 // Visit the whole type.
2298 if (Visit(TL))
2299 return true;
2300 } else if (isa<FunctionProtoTypeLoc>(TL)) {
2301 FunctionProtoTypeLoc Proto = cast<FunctionProtoTypeLoc>(TL);
2302 if (E->hasExplicitParameters()) {
2303 // Visit parameters.
2304 for (unsigned I = 0, N = Proto.getNumArgs(); I != N; ++I)
2305 if (Visit(MakeCXCursor(Proto.getArg(I), TU)))
2306 return true;
2307 } else {
2308 // Visit result type.
2309 if (Visit(Proto.getResultLoc()))
2310 return true;
2311 }
2312 }
2313 }
2314 break;
2315 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002316 }
2317 }
2318 return false;
2319}
2320
Ted Kremenekcdba6592010-11-18 00:42:18 +00002321bool CursorVisitor::Visit(Stmt *S) {
Ted Kremenekd1ded662010-11-15 23:31:32 +00002322 VisitorWorkList *WL = 0;
2323 if (!WorkListFreeList.empty()) {
2324 WL = WorkListFreeList.back();
2325 WL->clear();
2326 WorkListFreeList.pop_back();
2327 }
2328 else {
2329 WL = new VisitorWorkList();
2330 WorkListCache.push_back(WL);
2331 }
2332 EnqueueWorkList(*WL, S);
2333 bool result = RunVisitorWorkList(*WL);
2334 WorkListFreeList.push_back(WL);
2335 return result;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002336}
2337
Francois Pichet48a8d142011-07-25 22:00:44 +00002338namespace {
2339typedef llvm::SmallVector<SourceRange, 4> RefNamePieces;
2340RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
2341 const DeclarationNameInfo &NI,
2342 const SourceRange &QLoc,
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00002343 const ASTTemplateArgumentListInfo *TemplateArgs = 0){
Francois Pichet48a8d142011-07-25 22:00:44 +00002344 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
2345 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
2346 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
2347
2348 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
2349
2350 RefNamePieces Pieces;
2351
2352 if (WantQualifier && QLoc.isValid())
2353 Pieces.push_back(QLoc);
2354
2355 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
2356 Pieces.push_back(NI.getLoc());
2357
2358 if (WantTemplateArgs && TemplateArgs)
2359 Pieces.push_back(SourceRange(TemplateArgs->LAngleLoc,
2360 TemplateArgs->RAngleLoc));
2361
2362 if (Kind == DeclarationName::CXXOperatorName) {
2363 Pieces.push_back(SourceLocation::getFromRawEncoding(
2364 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
2365 Pieces.push_back(SourceLocation::getFromRawEncoding(
2366 NI.getInfo().CXXOperatorName.EndOpNameLoc));
2367 }
2368
2369 if (WantSinglePiece) {
2370 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
2371 Pieces.clear();
2372 Pieces.push_back(R);
2373 }
2374
2375 return Pieces;
2376}
2377}
2378
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002379//===----------------------------------------------------------------------===//
2380// Misc. API hooks.
2381//===----------------------------------------------------------------------===//
2382
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002383static llvm::sys::Mutex EnableMultithreadingMutex;
2384static bool EnabledMultithreading;
2385
Argyrios Kyrtzidisfa39f5b2011-12-15 04:52:41 +00002386static void fatal_error_handler(void *user_data, const std::string& reason) {
Argyrios Kyrtzidisfa39f5b2011-12-15 04:52:41 +00002387 // Write the result out to stderr avoiding errs() because raw_ostreams can
2388 // call report_fatal_error.
Argyrios Kyrtzidisdb7a8002011-12-15 06:51:30 +00002389 fprintf(stderr, "LIBCLANG FATAL ERROR: %s\n", reason.c_str());
Argyrios Kyrtzidisfa39f5b2011-12-15 04:52:41 +00002390 ::abort();
2391}
2392
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002393extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002394CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2395 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002396 // Disable pretty stack trace functionality, which will otherwise be a very
2397 // poor citizen of the world and set up all sorts of signal handlers.
2398 llvm::DisablePrettyStackTrace = true;
2399
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002400 // We use crash recovery to make some of our APIs more reliable, implicitly
2401 // enable it.
2402 llvm::CrashRecoveryContext::Enable();
2403
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002404 // Enable support for multithreading in LLVM.
2405 {
2406 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2407 if (!EnabledMultithreading) {
Argyrios Kyrtzidisfa39f5b2011-12-15 04:52:41 +00002408 llvm::install_fatal_error_handler(fatal_error_handler, 0);
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002409 llvm::llvm_start_multithreaded();
2410 EnabledMultithreading = true;
2411 }
2412 }
2413
Douglas Gregora030b7c2010-01-22 20:35:53 +00002414 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002415 if (excludeDeclarationsFromPCH)
2416 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002417 if (displayDiagnostics)
2418 CIdxr->setDisplayDiagnostics();
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002419
2420 if (getenv("LIBCLANG_BGPRIO_INDEX"))
2421 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
2422 CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
2423 if (getenv("LIBCLANG_BGPRIO_EDIT"))
2424 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
2425 CXGlobalOpt_ThreadBackgroundPriorityForEditing);
2426
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002427 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002428}
2429
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002430void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002431 if (CIdx)
2432 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002433}
2434
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002435void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
2436 if (CIdx)
2437 static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
2438}
2439
2440unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
2441 if (CIdx)
2442 return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
2443 return 0;
2444}
2445
Ted Kremenekd2427dd2011-03-18 23:05:39 +00002446void clang_toggleCrashRecovery(unsigned isEnabled) {
2447 if (isEnabled)
2448 llvm::CrashRecoveryContext::Enable();
2449 else
2450 llvm::CrashRecoveryContext::Disable();
2451}
2452
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002453CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002454 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002455 if (!CIdx)
2456 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002457
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002458 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002459 FileSystemOptions FileSystemOpts;
2460 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002461
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00002462 IntrusiveRefCntPtr<DiagnosticsEngine> Diags;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002463 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002464 CXXIdx->getOnlyLocalDecls(),
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00002465 0, 0,
2466 /*CaptureDiagnostics=*/true,
2467 /*AllowPCHWithCompilerErrors=*/true);
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002468 return MakeCXTranslationUnit(CXXIdx, TU);
Steve Naroff600866c2009-08-27 19:51:58 +00002469}
2470
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002471unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002472 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregorb5af8432011-08-25 22:54:01 +00002473 CXTranslationUnit_CacheCompletionResults;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002474}
2475
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002476CXTranslationUnit
2477clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2478 const char *source_filename,
2479 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002480 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002481 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002482 struct CXUnsavedFile *unsaved_files) {
Argyrios Kyrtzidise1d43302012-02-25 02:41:16 +00002483 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
Douglas Gregor5a430212010-07-21 18:52:53 +00002484 return clang_parseTranslationUnit(CIdx, source_filename,
2485 command_line_args, num_command_line_args,
2486 unsaved_files, num_unsaved_files,
Douglas Gregordca8ee82011-05-06 16:33:08 +00002487 Options);
Douglas Gregor5a430212010-07-21 18:52:53 +00002488}
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00002489
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002490struct ParseTranslationUnitInfo {
2491 CXIndex CIdx;
2492 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002493 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002494 int num_command_line_args;
2495 struct CXUnsavedFile *unsaved_files;
2496 unsigned num_unsaved_files;
2497 unsigned options;
2498 CXTranslationUnit result;
2499};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002500static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002501 ParseTranslationUnitInfo *PTUI =
2502 static_cast<ParseTranslationUnitInfo*>(UserData);
2503 CXIndex CIdx = PTUI->CIdx;
2504 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002505 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002506 int num_command_line_args = PTUI->num_command_line_args;
2507 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2508 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2509 unsigned options = PTUI->options;
2510 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002511
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002512 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002513 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002514
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002515 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2516
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002517 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
Argyrios Kyrtzidis81b5ac32012-03-28 02:49:54 +00002518 setThreadBackgroundPriority();
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002519
Douglas Gregor44c181a2010-07-23 00:33:23 +00002520 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregor467dc882011-08-25 22:30:56 +00002521 // FIXME: Add a flag for modules.
2522 TranslationUnitKind TUKind
2523 = (options & CXTranslationUnit_Incomplete)? TU_Prefix : TU_Complete;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002524 bool CacheCodeCompetionResults
2525 = options & CXTranslationUnit_CacheCompletionResults;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002526 bool IncludeBriefCommentsInCodeCompletion
2527 = options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
Erik Verbruggen6a91d382012-04-12 10:11:59 +00002528 bool SkipFunctionBodies = options & CXTranslationUnit_SkipFunctionBodies;
2529
Douglas Gregor5352ac02010-01-28 00:27:43 +00002530 // Configure the diagnostics.
2531 DiagnosticOptions DiagOpts;
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00002532 IntrusiveRefCntPtr<DiagnosticsEngine>
Ted Kremenek25a11e12011-03-22 01:15:24 +00002533 Diags(CompilerInstance::createDiagnostics(DiagOpts, num_command_line_args,
2534 command_line_args));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002535
Ted Kremenek25a11e12011-03-22 01:15:24 +00002536 // Recover resources if we crash before exiting this function.
David Blaikied6471f72011-09-25 23:23:43 +00002537 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
2538 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00002539 DiagCleanup(Diags.getPtr());
2540
Dylan Noblesmith1e4c01b2012-02-13 12:32:21 +00002541 OwningPtr<std::vector<ASTUnit::RemappedFile> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00002542 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2543
2544 // Recover resources if we crash before exiting this function.
2545 llvm::CrashRecoveryContextCleanupRegistrar<
2546 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2547
Douglas Gregor4db64a42010-01-23 00:14:00 +00002548 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002549 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002550 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002551 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002552 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2553 Buffer));
Douglas Gregor4db64a42010-01-23 00:14:00 +00002554 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002555
Dylan Noblesmith1e4c01b2012-02-13 12:32:21 +00002556 OwningPtr<std::vector<const char *> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00002557 Args(new std::vector<const char*>());
2558
2559 // Recover resources if we crash before exiting this method.
2560 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
2561 ArgsCleanup(Args.get());
2562
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002563 // Since the Clang C library is primarily used by batch tools dealing with
2564 // (often very broken) source code, where spell-checking can have a
2565 // significant negative impact on performance (particularly when
2566 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002567 // Only do this if we haven't found a spell-checking-related argument.
2568 bool FoundSpellCheckingArgument = false;
2569 for (int I = 0; I != num_command_line_args; ++I) {
2570 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2571 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2572 FoundSpellCheckingArgument = true;
2573 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002574 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002575 }
2576 if (!FoundSpellCheckingArgument)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002577 Args->push_back("-fno-spell-checking");
Douglas Gregorb10daed2010-10-11 16:52:23 +00002578
Ted Kremenek25a11e12011-03-22 01:15:24 +00002579 Args->insert(Args->end(), command_line_args,
2580 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002581
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002582 // The 'source_filename' argument is optional. If the caller does not
2583 // specify it then it is assumed that the source file is specified
2584 // in the actual argument list.
2585 // Put the source file after command_line_args otherwise if '-x' flag is
2586 // present it will be unused.
2587 if (source_filename)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002588 Args->push_back(source_filename);
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002589
Douglas Gregor44c181a2010-07-23 00:33:23 +00002590 // Do we need the detailed preprocessing record?
2591 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Ted Kremenek25a11e12011-03-22 01:15:24 +00002592 Args->push_back("-Xclang");
2593 Args->push_back("-detailed-preprocessing-record");
Douglas Gregor44c181a2010-07-23 00:33:23 +00002594 }
2595
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002596 unsigned NumErrors = Diags->getClient()->getNumErrors();
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00002597 OwningPtr<ASTUnit> ErrUnit;
Dylan Noblesmith1e4c01b2012-02-13 12:32:21 +00002598 OwningPtr<ASTUnit> Unit(
Ted Kremenek4ee99262011-03-22 20:16:19 +00002599 ASTUnit::LoadFromCommandLine(Args->size() ? &(*Args)[0] : 0
2600 /* vector::data() not portable */,
2601 Args->size() ? (&(*Args)[0] + Args->size()) :0,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002602 Diags,
2603 CXXIdx->getClangResourcesPath(),
2604 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002605 /*CaptureDiagnostics=*/true,
Ted Kremenek4ee99262011-03-22 20:16:19 +00002606 RemappedFiles->size() ? &(*RemappedFiles)[0]:0,
Ted Kremenek25a11e12011-03-22 01:15:24 +00002607 RemappedFiles->size(),
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00002608 /*RemappedFilesKeepOriginalName=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002609 PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00002610 TUKind,
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00002611 CacheCodeCompetionResults,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002612 IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00002613 /*AllowPCHWithCompilerErrors=*/true,
Erik Verbruggen6a91d382012-04-12 10:11:59 +00002614 SkipFunctionBodies,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00002615 &ErrUnit));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002616
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002617 if (NumErrors != Diags->getClient()->getNumErrors()) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002618 // Make sure to check that 'Unit' is non-NULL.
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00002619 if (CXXIdx->getDisplayDiagnostics())
2620 printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
Douglas Gregora88084b2010-02-18 18:08:43 +00002621 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002622
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002623 PTUI->result = MakeCXTranslationUnit(CXXIdx, Unit.take());
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002624}
2625CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2626 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002627 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002628 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002629 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002630 unsigned num_unsaved_files,
2631 unsigned options) {
2632 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002633 num_command_line_args, unsaved_files,
2634 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002635 llvm::CrashRecoveryContext CRC;
2636
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002637 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002638 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2639 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2640 fprintf(stderr, " 'command_line_args' : [");
2641 for (int i = 0; i != num_command_line_args; ++i) {
2642 if (i)
2643 fprintf(stderr, ", ");
2644 fprintf(stderr, "'%s'", command_line_args[i]);
2645 }
2646 fprintf(stderr, "],\n");
2647 fprintf(stderr, " 'unsaved_files' : [");
2648 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2649 if (i)
2650 fprintf(stderr, ", ");
2651 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2652 unsaved_files[i].Length);
2653 }
2654 fprintf(stderr, "],\n");
2655 fprintf(stderr, " 'options' : %d,\n", options);
2656 fprintf(stderr, "}\n");
2657
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002658 return 0;
Douglas Gregor6df78732011-05-05 20:27:22 +00002659 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
2660 PrintLibclangResourceUsage(PTUI.result);
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002661 }
Douglas Gregor6df78732011-05-05 20:27:22 +00002662
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002663 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002664}
2665
Douglas Gregor19998442010-08-13 15:35:05 +00002666unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2667 return CXSaveTranslationUnit_None;
2668}
Argyrios Kyrtzidis142bcb52012-03-28 02:17:59 +00002669
2670namespace {
2671
2672struct SaveTranslationUnitInfo {
2673 CXTranslationUnit TU;
2674 const char *FileName;
2675 unsigned options;
2676 CXSaveError result;
2677};
2678
2679}
2680
2681static void clang_saveTranslationUnit_Impl(void *UserData) {
2682 SaveTranslationUnitInfo *STUI =
2683 static_cast<SaveTranslationUnitInfo*>(UserData);
2684
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002685 CIndexer *CXXIdx = (CIndexer*)STUI->TU->CIdx;
2686 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
Argyrios Kyrtzidis81b5ac32012-03-28 02:49:54 +00002687 setThreadBackgroundPriority();
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002688
Argyrios Kyrtzidis142bcb52012-03-28 02:17:59 +00002689 STUI->result = static_cast<ASTUnit *>(STUI->TU->TUData)->Save(STUI->FileName);
2690}
2691
Douglas Gregor19998442010-08-13 15:35:05 +00002692int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2693 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002694 if (!TU)
Douglas Gregor39c411f2011-07-06 16:43:36 +00002695 return CXSaveError_InvalidTU;
Argyrios Kyrtzidis142bcb52012-03-28 02:17:59 +00002696
2697 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
2698 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Argyrios Kyrtzidis374a00b2012-06-08 05:48:06 +00002699 if (!CXXUnit->hasSema())
2700 return CXSaveError_InvalidTU;
Argyrios Kyrtzidis142bcb52012-03-28 02:17:59 +00002701
2702 SaveTranslationUnitInfo STUI = { TU, FileName, options, CXSaveError_None };
2703
2704 if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred() ||
2705 getenv("LIBCLANG_NOTHREADS")) {
2706 clang_saveTranslationUnit_Impl(&STUI);
2707
2708 if (getenv("LIBCLANG_RESOURCE_USAGE"))
2709 PrintLibclangResourceUsage(TU);
2710
2711 return STUI.result;
2712 }
2713
2714 // We have an AST that has invalid nodes due to compiler errors.
2715 // Use a crash recovery thread for protection.
2716
2717 llvm::CrashRecoveryContext CRC;
2718
2719 if (!RunSafely(CRC, clang_saveTranslationUnit_Impl, &STUI)) {
2720 fprintf(stderr, "libclang: crash detected during AST saving: {\n");
2721 fprintf(stderr, " 'filename' : '%s'\n", FileName);
2722 fprintf(stderr, " 'options' : %d,\n", options);
2723 fprintf(stderr, "}\n");
2724
2725 return CXSaveError_Unknown;
2726
2727 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
Douglas Gregor6df78732011-05-05 20:27:22 +00002728 PrintLibclangResourceUsage(TU);
Argyrios Kyrtzidis142bcb52012-03-28 02:17:59 +00002729 }
2730
2731 return STUI.result;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002732}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002733
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002734void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002735 if (CTUnit) {
2736 // If the translation unit has been marked as unsafe to free, just discard
2737 // it.
Ted Kremeneka60ed472010-11-16 08:15:36 +00002738 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002739 return;
2740
Ted Kremeneka60ed472010-11-16 08:15:36 +00002741 delete static_cast<ASTUnit *>(CTUnit->TUData);
2742 disposeCXStringPool(CTUnit->StringPool);
Ted Kremenek15322172011-11-10 08:43:12 +00002743 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
Ted Kremenekbbf66ca2012-04-30 19:06:49 +00002744 disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002745 delete CTUnit;
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002746 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002747}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002748
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002749unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2750 return CXReparse_None;
2751}
2752
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002753struct ReparseTranslationUnitInfo {
2754 CXTranslationUnit TU;
2755 unsigned num_unsaved_files;
2756 struct CXUnsavedFile *unsaved_files;
2757 unsigned options;
2758 int result;
2759};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002760
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002761static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002762 ReparseTranslationUnitInfo *RTUI =
2763 static_cast<ReparseTranslationUnitInfo*>(UserData);
2764 CXTranslationUnit TU = RTUI->TU;
Ted Kremenek15322172011-11-10 08:43:12 +00002765
2766 // Reset the associated diagnostics.
2767 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
2768 TU->Diagnostics = 0;
2769
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002770 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2771 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2772 unsigned options = RTUI->options;
2773 (void) options;
2774 RTUI->result = 1;
2775
Douglas Gregorabc563f2010-07-19 21:46:24 +00002776 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002777 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002778
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002779 CIndexer *CXXIdx = (CIndexer*)TU->CIdx;
2780 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
Argyrios Kyrtzidis81b5ac32012-03-28 02:49:54 +00002781 setThreadBackgroundPriority();
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002782
Ted Kremeneka60ed472010-11-16 08:15:36 +00002783 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor593b0c12010-09-23 18:47:53 +00002784 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002785
Dylan Noblesmith1e4c01b2012-02-13 12:32:21 +00002786 OwningPtr<std::vector<ASTUnit::RemappedFile> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00002787 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2788
2789 // Recover resources if we crash before exiting this function.
2790 llvm::CrashRecoveryContextCleanupRegistrar<
2791 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2792
Douglas Gregorabc563f2010-07-19 21:46:24 +00002793 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002794 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002795 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002796 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002797 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2798 Buffer));
Douglas Gregorabc563f2010-07-19 21:46:24 +00002799 }
2800
Ted Kremenek4ee99262011-03-22 20:16:19 +00002801 if (!CXXUnit->Reparse(RemappedFiles->size() ? &(*RemappedFiles)[0] : 0,
2802 RemappedFiles->size()))
Douglas Gregor593b0c12010-09-23 18:47:53 +00002803 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002804}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002805
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002806int clang_reparseTranslationUnit(CXTranslationUnit TU,
2807 unsigned num_unsaved_files,
2808 struct CXUnsavedFile *unsaved_files,
2809 unsigned options) {
2810 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2811 options, 0 };
Argyrios Kyrtzidis8c4b47e2011-10-28 22:54:33 +00002812
Argyrios Kyrtzidise7de9b42011-10-29 19:32:39 +00002813 if (getenv("LIBCLANG_NOTHREADS")) {
Argyrios Kyrtzidis8c4b47e2011-10-28 22:54:33 +00002814 clang_reparseTranslationUnit_Impl(&RTUI);
2815 return RTUI.result;
2816 }
2817
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002818 llvm::CrashRecoveryContext CRC;
2819
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002820 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002821 fprintf(stderr, "libclang: crash detected during reparsing\n");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002822 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002823 return 1;
Douglas Gregor6df78732011-05-05 20:27:22 +00002824 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
2825 PrintLibclangResourceUsage(TU);
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002826
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002827 return RTUI.result;
2828}
2829
Douglas Gregordf95a132010-08-09 20:45:32 +00002830
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002831CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002832 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002833 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002834
Ted Kremeneka60ed472010-11-16 08:15:36 +00002835 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002836 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002837}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002838
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002839CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregor8e5900c2012-04-30 23:41:16 +00002840 ASTUnit *CXXUnit = static_cast<ASTUnit*>(TU->TUData);
2841 return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002842}
2843
Ted Kremenekfb480492010-01-13 21:46:36 +00002844} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002845
Ted Kremenekfb480492010-01-13 21:46:36 +00002846//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002847// CXFile Operations.
2848//===----------------------------------------------------------------------===//
2849
2850extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002851CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002852 if (!SFile)
Ted Kremeneka60ed472010-11-16 08:15:36 +00002853 return createCXString((const char*)NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002854
Steve Naroff88145032009-10-27 14:35:18 +00002855 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002856 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002857}
2858
2859time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002860 if (!SFile)
2861 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002862
Steve Naroff88145032009-10-27 14:35:18 +00002863 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2864 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002865}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002866
Douglas Gregorb9790342010-01-22 21:44:22 +00002867CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2868 if (!tu)
2869 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002870
Ted Kremeneka60ed472010-11-16 08:15:36 +00002871 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002872
Douglas Gregorb9790342010-01-22 21:44:22 +00002873 FileManager &FMgr = CXXUnit->getFileManager();
Chris Lattner39b49bc2010-11-23 08:35:12 +00002874 return const_cast<FileEntry *>(FMgr.getFile(file_name));
Douglas Gregorb9790342010-01-22 21:44:22 +00002875}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002876
Douglas Gregordd3e5542011-05-04 00:14:37 +00002877unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit tu, CXFile file) {
2878 if (!tu || !file)
2879 return 0;
2880
2881 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
2882 FileEntry *FEnt = static_cast<FileEntry *>(file);
2883 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
2884 .isFileMultipleIncludeGuarded(FEnt);
2885}
2886
Ted Kremenekfb480492010-01-13 21:46:36 +00002887} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002888
Ted Kremenekfb480492010-01-13 21:46:36 +00002889//===----------------------------------------------------------------------===//
2890// CXCursor Operations.
2891//===----------------------------------------------------------------------===//
2892
Ted Kremenekfb480492010-01-13 21:46:36 +00002893static Decl *getDeclFromExpr(Stmt *E) {
Argyrios Kyrtzidisc2954612011-09-12 22:17:26 +00002894 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Douglas Gregordb1314e2010-10-01 21:11:22 +00002895 return getDeclFromExpr(CE->getSubExpr());
2896
Ted Kremenekfb480492010-01-13 21:46:36 +00002897 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2898 return RefExpr->getDecl();
2899 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2900 return ME->getMemberDecl();
2901 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2902 return RE->getDecl();
Argyrios Kyrtzidisb085d892012-03-30 00:19:18 +00002903 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
2904 if (PRE->isExplicitProperty())
2905 return PRE->getExplicitProperty();
2906 // It could be messaging both getter and setter as in:
2907 // ++myobj.myprop;
2908 // in which case prefer to associate the setter since it is less obvious
2909 // from inspecting the source that the setter is going to get called.
2910 if (PRE->isMessagingSetter())
2911 return PRE->getImplicitPropertySetter();
2912 return PRE->getImplicitPropertyGetter();
2913 }
John McCall4b9c2d22011-11-06 09:01:30 +00002914 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
2915 return getDeclFromExpr(POE->getSyntacticForm());
2916 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
2917 if (Expr *Src = OVE->getSourceExpr())
2918 return getDeclFromExpr(Src);
Douglas Gregordb1314e2010-10-01 21:11:22 +00002919
Ted Kremenekfb480492010-01-13 21:46:36 +00002920 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2921 return getDeclFromExpr(CE->getCallee());
Chris Lattner5f9e2722011-07-23 10:55:15 +00002922 if (CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Douglas Gregor93798e22010-11-05 21:11:19 +00002923 if (!CE->isElidable())
2924 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002925 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2926 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002927
Douglas Gregordb1314e2010-10-01 21:11:22 +00002928 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2929 return PE->getProtocol();
Douglas Gregorc7793c72011-01-15 01:15:58 +00002930 if (SubstNonTypeTemplateParmPackExpr *NTTP
2931 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
2932 return NTTP->getParameterPack();
Douglas Gregor94d96292011-01-19 20:34:17 +00002933 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2934 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
2935 isa<ParmVarDecl>(SizeOfPack->getPack()))
2936 return SizeOfPack->getPack();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002937
Ted Kremenekfb480492010-01-13 21:46:36 +00002938 return 0;
2939}
2940
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002941static SourceLocation getLocationFromExpr(Expr *E) {
Argyrios Kyrtzidisc2954612011-09-12 22:17:26 +00002942 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
2943 return getLocationFromExpr(CE->getSubExpr());
2944
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002945 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2946 return /*FIXME:*/Msg->getLeftLoc();
2947 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2948 return DRE->getLocation();
2949 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2950 return Member->getMemberLoc();
2951 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2952 return Ivar->getLocation();
Douglas Gregor94d96292011-01-19 20:34:17 +00002953 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2954 return SizeOfPack->getPackLoc();
Argyrios Kyrtzidisd0469522012-03-30 00:19:13 +00002955 if (ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
2956 return PropRef->getLocation();
Douglas Gregor94d96292011-01-19 20:34:17 +00002957
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002958 return E->getLocStart();
2959}
2960
Ted Kremenekfb480492010-01-13 21:46:36 +00002961extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002962
2963unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002964 CXCursorVisitor visitor,
2965 CXClientData client_data) {
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00002966 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
2967 /*VisitPreprocessorLast=*/false);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002968 return CursorVis.VisitChildren(parent);
2969}
2970
David Chisnall3387c652010-11-03 14:12:26 +00002971#ifndef __has_feature
2972#define __has_feature(x) 0
2973#endif
2974#if __has_feature(blocks)
2975typedef enum CXChildVisitResult
2976 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2977
2978static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2979 CXClientData client_data) {
2980 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2981 return block(cursor, parent);
2982}
2983#else
2984// If we are compiled with a compiler that doesn't have native blocks support,
2985// define and call the block manually, so the
2986typedef struct _CXChildVisitResult
2987{
2988 void *isa;
2989 int flags;
2990 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002991 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2992 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00002993} *CXCursorVisitorBlock;
2994
2995static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2996 CXClientData client_data) {
2997 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2998 return block->invoke(block, cursor, parent);
2999}
3000#endif
3001
3002
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003003unsigned clang_visitChildrenWithBlock(CXCursor parent,
3004 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00003005 return clang_visitChildren(parent, visitWithBlock, block);
3006}
3007
Douglas Gregor78205d42010-01-20 21:45:58 +00003008static CXString getDeclSpelling(Decl *D) {
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00003009 if (!D)
3010 return createCXString("");
3011
3012 NamedDecl *ND = dyn_cast<NamedDecl>(D);
Douglas Gregore3c60a72010-11-17 00:13:31 +00003013 if (!ND) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003014 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00003015 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3016 return createCXString(Property->getIdentifier()->getName());
3017
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003018 return createCXString("");
Douglas Gregore3c60a72010-11-17 00:13:31 +00003019 }
3020
Douglas Gregor78205d42010-01-20 21:45:58 +00003021 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003022 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003023
Douglas Gregor78205d42010-01-20 21:45:58 +00003024 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
3025 // No, this isn't the same as the code below. getIdentifier() is non-virtual
3026 // and returns different names. NamedDecl returns the class name and
3027 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003028 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003029
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003030 if (isa<UsingDirectiveDecl>(D))
3031 return createCXString("");
3032
Dylan Noblesmith36d59272012-02-13 12:32:26 +00003033 SmallString<1024> S;
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00003034 llvm::raw_svector_ostream os(S);
3035 ND->printName(os);
3036
3037 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00003038}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003039
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003040CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003041 if (clang_isTranslationUnit(C.kind))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003042 return clang_getTranslationUnitSpelling(
3043 static_cast<CXTranslationUnit>(C.data[2]));
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003044
Steve Narofff334b4e2009-09-02 18:26:48 +00003045 if (clang_isReference(C.kind)) {
3046 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00003047 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00003048 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003049 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003050 }
3051 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00003052 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003053 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003054 }
3055 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00003056 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00003057 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003058 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003059 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00003060 case CXCursor_CXXBaseSpecifier: {
3061 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
3062 return createCXString(B->getType().getAsString());
3063 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003064 case CXCursor_TypeRef: {
3065 TypeDecl *Type = getCursorTypeRef(C).first;
3066 assert(Type && "Missing type decl");
3067
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003068 return createCXString(getCursorContext(C).getTypeDeclType(Type).
3069 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003070 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003071 case CXCursor_TemplateRef: {
3072 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00003073 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003074
3075 return createCXString(Template->getNameAsString());
3076 }
Douglas Gregor69319002010-08-31 23:48:11 +00003077
3078 case CXCursor_NamespaceRef: {
3079 NamedDecl *NS = getCursorNamespaceRef(C).first;
3080 assert(NS && "Missing namespace decl");
3081
3082 return createCXString(NS->getNameAsString());
3083 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003084
Douglas Gregora67e03f2010-09-09 21:42:20 +00003085 case CXCursor_MemberRef: {
3086 FieldDecl *Field = getCursorMemberRef(C).first;
3087 assert(Field && "Missing member decl");
3088
3089 return createCXString(Field->getNameAsString());
3090 }
3091
Douglas Gregor36897b02010-09-10 00:22:18 +00003092 case CXCursor_LabelRef: {
3093 LabelStmt *Label = getCursorLabelRef(C).first;
3094 assert(Label && "Missing label");
3095
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003096 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00003097 }
3098
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003099 case CXCursor_OverloadedDeclRef: {
3100 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3101 if (Decl *D = Storage.dyn_cast<Decl *>()) {
3102 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
3103 return createCXString(ND->getNameAsString());
3104 return createCXString("");
3105 }
3106 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3107 return createCXString(E->getName().getAsString());
3108 OverloadedTemplateStorage *Ovl
3109 = Storage.get<OverloadedTemplateStorage*>();
3110 if (Ovl->size() == 0)
3111 return createCXString("");
3112 return createCXString((*Ovl->begin())->getNameAsString());
3113 }
3114
Douglas Gregor011d8b92012-02-15 00:54:55 +00003115 case CXCursor_VariableRef: {
3116 VarDecl *Var = getCursorVariableRef(C).first;
3117 assert(Var && "Missing variable decl");
3118
3119 return createCXString(Var->getNameAsString());
3120 }
3121
Daniel Dunbaracca7252009-11-30 20:42:49 +00003122 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003123 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00003124 }
3125 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003126
3127 if (clang_isExpression(C.kind)) {
3128 Decl *D = getDeclFromExpr(getCursorExpr(C));
3129 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00003130 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003131 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00003132 }
3133
Douglas Gregor36897b02010-09-10 00:22:18 +00003134 if (clang_isStatement(C.kind)) {
3135 Stmt *S = getCursorStmt(C);
3136 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003137 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00003138
3139 return createCXString("");
3140 }
3141
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003142 if (C.kind == CXCursor_MacroExpansion)
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003143 return createCXString(getCursorMacroExpansion(C)->getName()
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003144 ->getNameStart());
3145
Douglas Gregor572feb22010-03-18 18:04:21 +00003146 if (C.kind == CXCursor_MacroDefinition)
3147 return createCXString(getCursorMacroDefinition(C)->getName()
3148 ->getNameStart());
3149
Douglas Gregorecdcb882010-10-20 22:00:55 +00003150 if (C.kind == CXCursor_InclusionDirective)
3151 return createCXString(getCursorInclusionDirective(C)->getFileName());
3152
Douglas Gregor60cbfac2010-01-25 16:56:17 +00003153 if (clang_isDeclaration(C.kind))
3154 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00003155
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00003156 if (C.kind == CXCursor_AnnotateAttr) {
3157 AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
3158 return createCXString(AA->getAnnotation());
3159 }
3160
Argyrios Kyrtzidis84b79642011-12-06 22:05:01 +00003161 if (C.kind == CXCursor_AsmLabelAttr) {
3162 AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
3163 return createCXString(AA->getLabel());
3164 }
3165
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003166 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00003167}
3168
Argyrios Kyrtzidisba1da142012-03-30 20:58:35 +00003169CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C,
3170 unsigned pieceIndex,
3171 unsigned options) {
3172 if (clang_Cursor_isNull(C))
3173 return clang_getNullRange();
3174
3175 ASTContext &Ctx = getCursorContext(C);
3176
3177 if (clang_isStatement(C.kind)) {
3178 Stmt *S = getCursorStmt(C);
3179 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
3180 if (pieceIndex > 0)
3181 return clang_getNullRange();
3182 return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
3183 }
3184
3185 return clang_getNullRange();
3186 }
3187
3188 if (C.kind == CXCursor_ObjCMessageExpr) {
3189 if (ObjCMessageExpr *
3190 ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
3191 if (pieceIndex >= ME->getNumSelectorLocs())
3192 return clang_getNullRange();
3193 return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
3194 }
3195 }
3196
3197 if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
3198 C.kind == CXCursor_ObjCClassMethodDecl) {
3199 if (ObjCMethodDecl *
3200 MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
3201 if (pieceIndex >= MD->getNumSelectorLocs())
3202 return clang_getNullRange();
3203 return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
3204 }
3205 }
3206
Argyrios Kyrtzidis9482a182012-04-16 20:01:28 +00003207 if (C.kind == CXCursor_ObjCCategoryDecl ||
3208 C.kind == CXCursor_ObjCCategoryImplDecl) {
3209 if (pieceIndex > 0)
3210 return clang_getNullRange();
3211 if (ObjCCategoryDecl *
3212 CD = dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
3213 return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
3214 if (ObjCCategoryImplDecl *
3215 CID = dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
3216 return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
3217 }
3218
Argyrios Kyrtzidisba1da142012-03-30 20:58:35 +00003219 // FIXME: A CXCursor_InclusionDirective should give the location of the
3220 // filename, but we don't keep track of this.
3221
3222 // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
3223 // but we don't keep track of this.
3224
3225 // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
3226 // but we don't keep track of this.
3227
3228 // Default handling, give the location of the cursor.
3229
3230 if (pieceIndex > 0)
3231 return clang_getNullRange();
3232
3233 CXSourceLocation CXLoc = clang_getCursorLocation(C);
3234 SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
3235 return cxloc::translateSourceRange(Ctx, Loc);
3236}
3237
Douglas Gregor358559d2010-10-02 22:49:11 +00003238CXString clang_getCursorDisplayName(CXCursor C) {
3239 if (!clang_isDeclaration(C.kind))
3240 return clang_getCursorSpelling(C);
3241
3242 Decl *D = getCursorDecl(C);
3243 if (!D)
3244 return createCXString("");
3245
Douglas Gregor30c42402011-09-27 22:38:19 +00003246 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
Douglas Gregor358559d2010-10-02 22:49:11 +00003247 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
3248 D = FunTmpl->getTemplatedDecl();
3249
3250 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Dylan Noblesmith36d59272012-02-13 12:32:26 +00003251 SmallString<64> Str;
Douglas Gregor358559d2010-10-02 22:49:11 +00003252 llvm::raw_svector_ostream OS(Str);
Benjamin Kramera59d20b2012-02-07 11:57:57 +00003253 OS << *Function;
Douglas Gregor358559d2010-10-02 22:49:11 +00003254 if (Function->getPrimaryTemplate())
3255 OS << "<>";
3256 OS << "(";
3257 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
3258 if (I)
3259 OS << ", ";
3260 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
3261 }
3262
3263 if (Function->isVariadic()) {
3264 if (Function->getNumParams())
3265 OS << ", ";
3266 OS << "...";
3267 }
3268 OS << ")";
3269 return createCXString(OS.str());
3270 }
3271
3272 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
Dylan Noblesmith36d59272012-02-13 12:32:26 +00003273 SmallString<64> Str;
Douglas Gregor358559d2010-10-02 22:49:11 +00003274 llvm::raw_svector_ostream OS(Str);
Benjamin Kramera59d20b2012-02-07 11:57:57 +00003275 OS << *ClassTemplate;
Douglas Gregor358559d2010-10-02 22:49:11 +00003276 OS << "<";
3277 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
3278 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3279 if (I)
3280 OS << ", ";
3281
3282 NamedDecl *Param = Params->getParam(I);
3283 if (Param->getIdentifier()) {
3284 OS << Param->getIdentifier()->getName();
3285 continue;
3286 }
3287
3288 // There is no parameter name, which makes this tricky. Try to come up
3289 // with something useful that isn't too long.
3290 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3291 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
3292 else if (NonTypeTemplateParmDecl *NTTP
3293 = dyn_cast<NonTypeTemplateParmDecl>(Param))
3294 OS << NTTP->getType().getAsString(Policy);
3295 else
3296 OS << "template<...> class";
3297 }
3298
3299 OS << ">";
3300 return createCXString(OS.str());
3301 }
3302
3303 if (ClassTemplateSpecializationDecl *ClassSpec
3304 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
3305 // If the type was explicitly written, use that.
3306 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
3307 return createCXString(TSInfo->getType().getAsString(Policy));
3308
Dylan Noblesmith36d59272012-02-13 12:32:26 +00003309 SmallString<64> Str;
Douglas Gregor358559d2010-10-02 22:49:11 +00003310 llvm::raw_svector_ostream OS(Str);
Benjamin Kramera59d20b2012-02-07 11:57:57 +00003311 OS << *ClassSpec;
Douglas Gregor358559d2010-10-02 22:49:11 +00003312 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00003313 ClassSpec->getTemplateArgs().data(),
3314 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00003315 Policy);
3316 return createCXString(OS.str());
3317 }
3318
3319 return clang_getCursorSpelling(C);
3320}
3321
Ted Kremeneke68fff62010-02-17 00:41:32 +00003322CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00003323 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00003324 case CXCursor_FunctionDecl:
3325 return createCXString("FunctionDecl");
3326 case CXCursor_TypedefDecl:
3327 return createCXString("TypedefDecl");
3328 case CXCursor_EnumDecl:
3329 return createCXString("EnumDecl");
3330 case CXCursor_EnumConstantDecl:
3331 return createCXString("EnumConstantDecl");
3332 case CXCursor_StructDecl:
3333 return createCXString("StructDecl");
3334 case CXCursor_UnionDecl:
3335 return createCXString("UnionDecl");
3336 case CXCursor_ClassDecl:
3337 return createCXString("ClassDecl");
3338 case CXCursor_FieldDecl:
3339 return createCXString("FieldDecl");
3340 case CXCursor_VarDecl:
3341 return createCXString("VarDecl");
3342 case CXCursor_ParmDecl:
3343 return createCXString("ParmDecl");
3344 case CXCursor_ObjCInterfaceDecl:
3345 return createCXString("ObjCInterfaceDecl");
3346 case CXCursor_ObjCCategoryDecl:
3347 return createCXString("ObjCCategoryDecl");
3348 case CXCursor_ObjCProtocolDecl:
3349 return createCXString("ObjCProtocolDecl");
3350 case CXCursor_ObjCPropertyDecl:
3351 return createCXString("ObjCPropertyDecl");
3352 case CXCursor_ObjCIvarDecl:
3353 return createCXString("ObjCIvarDecl");
3354 case CXCursor_ObjCInstanceMethodDecl:
3355 return createCXString("ObjCInstanceMethodDecl");
3356 case CXCursor_ObjCClassMethodDecl:
3357 return createCXString("ObjCClassMethodDecl");
3358 case CXCursor_ObjCImplementationDecl:
3359 return createCXString("ObjCImplementationDecl");
3360 case CXCursor_ObjCCategoryImplDecl:
3361 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00003362 case CXCursor_CXXMethod:
3363 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003364 case CXCursor_UnexposedDecl:
3365 return createCXString("UnexposedDecl");
3366 case CXCursor_ObjCSuperClassRef:
3367 return createCXString("ObjCSuperClassRef");
3368 case CXCursor_ObjCProtocolRef:
3369 return createCXString("ObjCProtocolRef");
3370 case CXCursor_ObjCClassRef:
3371 return createCXString("ObjCClassRef");
3372 case CXCursor_TypeRef:
3373 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003374 case CXCursor_TemplateRef:
3375 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00003376 case CXCursor_NamespaceRef:
3377 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00003378 case CXCursor_MemberRef:
3379 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00003380 case CXCursor_LabelRef:
3381 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003382 case CXCursor_OverloadedDeclRef:
3383 return createCXString("OverloadedDeclRef");
Douglas Gregor011d8b92012-02-15 00:54:55 +00003384 case CXCursor_VariableRef:
3385 return createCXString("VariableRef");
Douglas Gregor42b29842011-10-05 19:00:14 +00003386 case CXCursor_IntegerLiteral:
3387 return createCXString("IntegerLiteral");
3388 case CXCursor_FloatingLiteral:
3389 return createCXString("FloatingLiteral");
3390 case CXCursor_ImaginaryLiteral:
3391 return createCXString("ImaginaryLiteral");
3392 case CXCursor_StringLiteral:
3393 return createCXString("StringLiteral");
3394 case CXCursor_CharacterLiteral:
3395 return createCXString("CharacterLiteral");
3396 case CXCursor_ParenExpr:
3397 return createCXString("ParenExpr");
3398 case CXCursor_UnaryOperator:
3399 return createCXString("UnaryOperator");
3400 case CXCursor_ArraySubscriptExpr:
3401 return createCXString("ArraySubscriptExpr");
3402 case CXCursor_BinaryOperator:
3403 return createCXString("BinaryOperator");
3404 case CXCursor_CompoundAssignOperator:
3405 return createCXString("CompoundAssignOperator");
3406 case CXCursor_ConditionalOperator:
3407 return createCXString("ConditionalOperator");
3408 case CXCursor_CStyleCastExpr:
3409 return createCXString("CStyleCastExpr");
3410 case CXCursor_CompoundLiteralExpr:
3411 return createCXString("CompoundLiteralExpr");
3412 case CXCursor_InitListExpr:
3413 return createCXString("InitListExpr");
3414 case CXCursor_AddrLabelExpr:
3415 return createCXString("AddrLabelExpr");
3416 case CXCursor_StmtExpr:
3417 return createCXString("StmtExpr");
3418 case CXCursor_GenericSelectionExpr:
3419 return createCXString("GenericSelectionExpr");
3420 case CXCursor_GNUNullExpr:
3421 return createCXString("GNUNullExpr");
3422 case CXCursor_CXXStaticCastExpr:
3423 return createCXString("CXXStaticCastExpr");
3424 case CXCursor_CXXDynamicCastExpr:
3425 return createCXString("CXXDynamicCastExpr");
3426 case CXCursor_CXXReinterpretCastExpr:
3427 return createCXString("CXXReinterpretCastExpr");
3428 case CXCursor_CXXConstCastExpr:
3429 return createCXString("CXXConstCastExpr");
3430 case CXCursor_CXXFunctionalCastExpr:
3431 return createCXString("CXXFunctionalCastExpr");
3432 case CXCursor_CXXTypeidExpr:
3433 return createCXString("CXXTypeidExpr");
3434 case CXCursor_CXXBoolLiteralExpr:
3435 return createCXString("CXXBoolLiteralExpr");
3436 case CXCursor_CXXNullPtrLiteralExpr:
3437 return createCXString("CXXNullPtrLiteralExpr");
3438 case CXCursor_CXXThisExpr:
3439 return createCXString("CXXThisExpr");
3440 case CXCursor_CXXThrowExpr:
3441 return createCXString("CXXThrowExpr");
3442 case CXCursor_CXXNewExpr:
3443 return createCXString("CXXNewExpr");
3444 case CXCursor_CXXDeleteExpr:
3445 return createCXString("CXXDeleteExpr");
3446 case CXCursor_UnaryExpr:
3447 return createCXString("UnaryExpr");
3448 case CXCursor_ObjCStringLiteral:
3449 return createCXString("ObjCStringLiteral");
Ted Kremenekb3f75422012-03-06 20:06:06 +00003450 case CXCursor_ObjCBoolLiteralExpr:
3451 return createCXString("ObjCBoolLiteralExpr");
Douglas Gregor42b29842011-10-05 19:00:14 +00003452 case CXCursor_ObjCEncodeExpr:
3453 return createCXString("ObjCEncodeExpr");
3454 case CXCursor_ObjCSelectorExpr:
3455 return createCXString("ObjCSelectorExpr");
3456 case CXCursor_ObjCProtocolExpr:
3457 return createCXString("ObjCProtocolExpr");
3458 case CXCursor_ObjCBridgedCastExpr:
3459 return createCXString("ObjCBridgedCastExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00003460 case CXCursor_BlockExpr:
3461 return createCXString("BlockExpr");
Douglas Gregor42b29842011-10-05 19:00:14 +00003462 case CXCursor_PackExpansionExpr:
3463 return createCXString("PackExpansionExpr");
3464 case CXCursor_SizeOfPackExpr:
3465 return createCXString("SizeOfPackExpr");
Douglas Gregor011d8b92012-02-15 00:54:55 +00003466 case CXCursor_LambdaExpr:
3467 return createCXString("LambdaExpr");
Douglas Gregor42b29842011-10-05 19:00:14 +00003468 case CXCursor_UnexposedExpr:
3469 return createCXString("UnexposedExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003470 case CXCursor_DeclRefExpr:
3471 return createCXString("DeclRefExpr");
3472 case CXCursor_MemberRefExpr:
3473 return createCXString("MemberRefExpr");
3474 case CXCursor_CallExpr:
3475 return createCXString("CallExpr");
3476 case CXCursor_ObjCMessageExpr:
3477 return createCXString("ObjCMessageExpr");
3478 case CXCursor_UnexposedStmt:
3479 return createCXString("UnexposedStmt");
Douglas Gregor42b29842011-10-05 19:00:14 +00003480 case CXCursor_DeclStmt:
3481 return createCXString("DeclStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00003482 case CXCursor_LabelStmt:
3483 return createCXString("LabelStmt");
Douglas Gregor42b29842011-10-05 19:00:14 +00003484 case CXCursor_CompoundStmt:
3485 return createCXString("CompoundStmt");
3486 case CXCursor_CaseStmt:
3487 return createCXString("CaseStmt");
3488 case CXCursor_DefaultStmt:
3489 return createCXString("DefaultStmt");
3490 case CXCursor_IfStmt:
3491 return createCXString("IfStmt");
3492 case CXCursor_SwitchStmt:
3493 return createCXString("SwitchStmt");
3494 case CXCursor_WhileStmt:
3495 return createCXString("WhileStmt");
3496 case CXCursor_DoStmt:
3497 return createCXString("DoStmt");
3498 case CXCursor_ForStmt:
3499 return createCXString("ForStmt");
3500 case CXCursor_GotoStmt:
3501 return createCXString("GotoStmt");
3502 case CXCursor_IndirectGotoStmt:
3503 return createCXString("IndirectGotoStmt");
3504 case CXCursor_ContinueStmt:
3505 return createCXString("ContinueStmt");
3506 case CXCursor_BreakStmt:
3507 return createCXString("BreakStmt");
3508 case CXCursor_ReturnStmt:
3509 return createCXString("ReturnStmt");
3510 case CXCursor_AsmStmt:
3511 return createCXString("AsmStmt");
Chad Rosier8cd64b42012-06-11 20:47:18 +00003512 case CXCursor_MSAsmStmt:
3513 return createCXString("MSAsmStmt");
Douglas Gregor42b29842011-10-05 19:00:14 +00003514 case CXCursor_ObjCAtTryStmt:
3515 return createCXString("ObjCAtTryStmt");
3516 case CXCursor_ObjCAtCatchStmt:
3517 return createCXString("ObjCAtCatchStmt");
3518 case CXCursor_ObjCAtFinallyStmt:
3519 return createCXString("ObjCAtFinallyStmt");
3520 case CXCursor_ObjCAtThrowStmt:
3521 return createCXString("ObjCAtThrowStmt");
3522 case CXCursor_ObjCAtSynchronizedStmt:
3523 return createCXString("ObjCAtSynchronizedStmt");
3524 case CXCursor_ObjCAutoreleasePoolStmt:
3525 return createCXString("ObjCAutoreleasePoolStmt");
3526 case CXCursor_ObjCForCollectionStmt:
3527 return createCXString("ObjCForCollectionStmt");
3528 case CXCursor_CXXCatchStmt:
3529 return createCXString("CXXCatchStmt");
3530 case CXCursor_CXXTryStmt:
3531 return createCXString("CXXTryStmt");
3532 case CXCursor_CXXForRangeStmt:
3533 return createCXString("CXXForRangeStmt");
3534 case CXCursor_SEHTryStmt:
3535 return createCXString("SEHTryStmt");
3536 case CXCursor_SEHExceptStmt:
3537 return createCXString("SEHExceptStmt");
3538 case CXCursor_SEHFinallyStmt:
3539 return createCXString("SEHFinallyStmt");
3540 case CXCursor_NullStmt:
3541 return createCXString("NullStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003542 case CXCursor_InvalidFile:
3543 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00003544 case CXCursor_InvalidCode:
3545 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003546 case CXCursor_NoDeclFound:
3547 return createCXString("NoDeclFound");
3548 case CXCursor_NotImplemented:
3549 return createCXString("NotImplemented");
3550 case CXCursor_TranslationUnit:
3551 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00003552 case CXCursor_UnexposedAttr:
3553 return createCXString("UnexposedAttr");
3554 case CXCursor_IBActionAttr:
3555 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003556 case CXCursor_IBOutletAttr:
3557 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003558 case CXCursor_IBOutletCollectionAttr:
3559 return createCXString("attribute(iboutletcollection)");
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00003560 case CXCursor_CXXFinalAttr:
3561 return createCXString("attribute(final)");
3562 case CXCursor_CXXOverrideAttr:
3563 return createCXString("attribute(override)");
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00003564 case CXCursor_AnnotateAttr:
3565 return createCXString("attribute(annotate)");
Argyrios Kyrtzidis84b79642011-12-06 22:05:01 +00003566 case CXCursor_AsmLabelAttr:
3567 return createCXString("asm label");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003568 case CXCursor_PreprocessingDirective:
3569 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003570 case CXCursor_MacroDefinition:
3571 return createCXString("macro definition");
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003572 case CXCursor_MacroExpansion:
3573 return createCXString("macro expansion");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003574 case CXCursor_InclusionDirective:
3575 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003576 case CXCursor_Namespace:
3577 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003578 case CXCursor_LinkageSpec:
3579 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003580 case CXCursor_CXXBaseSpecifier:
3581 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003582 case CXCursor_Constructor:
3583 return createCXString("CXXConstructor");
3584 case CXCursor_Destructor:
3585 return createCXString("CXXDestructor");
3586 case CXCursor_ConversionFunction:
3587 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003588 case CXCursor_TemplateTypeParameter:
3589 return createCXString("TemplateTypeParameter");
3590 case CXCursor_NonTypeTemplateParameter:
3591 return createCXString("NonTypeTemplateParameter");
3592 case CXCursor_TemplateTemplateParameter:
3593 return createCXString("TemplateTemplateParameter");
3594 case CXCursor_FunctionTemplate:
3595 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003596 case CXCursor_ClassTemplate:
3597 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003598 case CXCursor_ClassTemplatePartialSpecialization:
3599 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003600 case CXCursor_NamespaceAlias:
3601 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003602 case CXCursor_UsingDirective:
3603 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003604 case CXCursor_UsingDeclaration:
3605 return createCXString("UsingDeclaration");
Richard Smith162e1c12011-04-15 14:24:37 +00003606 case CXCursor_TypeAliasDecl:
Douglas Gregor352697a2011-06-03 23:08:58 +00003607 return createCXString("TypeAliasDecl");
3608 case CXCursor_ObjCSynthesizeDecl:
3609 return createCXString("ObjCSynthesizeDecl");
3610 case CXCursor_ObjCDynamicDecl:
3611 return createCXString("ObjCDynamicDecl");
Argyrios Kyrtzidis2dfdb942011-09-30 17:58:23 +00003612 case CXCursor_CXXAccessSpecifier:
3613 return createCXString("CXXAccessSpecifier");
Steve Naroff89922f82009-08-31 00:59:03 +00003614 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003615
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003616 llvm_unreachable("Unhandled CXCursorKind");
Steve Naroff600866c2009-08-27 19:51:58 +00003617}
Steve Naroff89922f82009-08-31 00:59:03 +00003618
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003619struct GetCursorData {
3620 SourceLocation TokenBeginLoc;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003621 bool PointsAtMacroArgExpansion;
Argyrios Kyrtzidis135bf8e2012-06-09 03:03:02 +00003622 bool VisitedObjCPropertyImplDecl;
3623 SourceLocation VisitedDeclaratorDeclStartLoc;
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003624 CXCursor &BestCursor;
3625
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003626 GetCursorData(SourceManager &SM,
3627 SourceLocation tokenBegin, CXCursor &outputCursor)
3628 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
3629 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
Argyrios Kyrtzidis135bf8e2012-06-09 03:03:02 +00003630 VisitedObjCPropertyImplDecl = false;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003631 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003632};
3633
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003634static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3635 CXCursor parent,
3636 CXClientData client_data) {
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003637 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
3638 CXCursor *BestCursor = &Data->BestCursor;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003639
3640 // If we point inside a macro argument we should provide info of what the
3641 // token is so use the actual cursor, don't replace it with a macro expansion
3642 // cursor.
3643 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
3644 return CXChildVisit_Recurse;
Argyrios Kyrtzidis65ab9072011-09-26 19:05:37 +00003645
3646 if (clang_isDeclaration(cursor.kind)) {
3647 // Avoid having the implicit methods override the property decls.
Argyrios Kyrtzidisa9d45a32012-04-16 22:42:01 +00003648 if (ObjCMethodDecl *MD
3649 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
Argyrios Kyrtzidis65ab9072011-09-26 19:05:37 +00003650 if (MD->isImplicit())
3651 return CXChildVisit_Break;
Argyrios Kyrtzidisa9d45a32012-04-16 22:42:01 +00003652
3653 } else if (ObjCInterfaceDecl *ID
3654 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) {
3655 // Check that when we have multiple @class references in the same line,
3656 // that later ones do not override the previous ones.
3657 // If we have:
3658 // @class Foo, Bar;
3659 // source ranges for both start at '@', so 'Bar' will end up overriding
3660 // 'Foo' even though the cursor location was at 'Foo'.
3661 if (BestCursor->kind == CXCursor_ObjCInterfaceDecl ||
3662 BestCursor->kind == CXCursor_ObjCClassRef)
3663 if (ObjCInterfaceDecl *PrevID
3664 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(*BestCursor))){
3665 if (PrevID != ID &&
3666 !PrevID->isThisDeclarationADefinition() &&
3667 !ID->isThisDeclarationADefinition())
3668 return CXChildVisit_Break;
3669 }
Argyrios Kyrtzidis135bf8e2012-06-09 03:03:02 +00003670
3671 } else if (DeclaratorDecl *DD
3672 = dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) {
3673 SourceLocation StartLoc = DD->getSourceRange().getBegin();
3674 // Check that when we have multiple declarators in the same line,
3675 // that later ones do not override the previous ones.
3676 // If we have:
3677 // int Foo, Bar;
3678 // source ranges for both start at 'int', so 'Bar' will end up overriding
3679 // 'Foo' even though the cursor location was at 'Foo'.
3680 if (Data->VisitedDeclaratorDeclStartLoc == StartLoc)
3681 return CXChildVisit_Break;
3682 Data->VisitedDeclaratorDeclStartLoc = StartLoc;
3683
3684 } else if (ObjCPropertyImplDecl *PropImp
3685 = dyn_cast_or_null<ObjCPropertyImplDecl>(getCursorDecl(cursor))) {
3686 (void)PropImp;
3687 // Check that when we have multiple @synthesize in the same line,
3688 // that later ones do not override the previous ones.
3689 // If we have:
3690 // @synthesize Foo, Bar;
3691 // source ranges for both start at '@', so 'Bar' will end up overriding
3692 // 'Foo' even though the cursor location was at 'Foo'.
3693 if (Data->VisitedObjCPropertyImplDecl)
3694 return CXChildVisit_Break;
3695 Data->VisitedObjCPropertyImplDecl = true;
Argyrios Kyrtzidisa9d45a32012-04-16 22:42:01 +00003696 }
Argyrios Kyrtzidis65ab9072011-09-26 19:05:37 +00003697 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003698
3699 if (clang_isExpression(cursor.kind) &&
3700 clang_isDeclaration(BestCursor->kind)) {
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00003701 if (Decl *D = getCursorDecl(*BestCursor)) {
3702 // Avoid having the cursor of an expression replace the declaration cursor
3703 // when the expression source range overlaps the declaration range.
3704 // This can happen for C++ constructor expressions whose range generally
3705 // include the variable declaration, e.g.:
3706 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
3707 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
3708 D->getLocation() == Data->TokenBeginLoc)
3709 return CXChildVisit_Break;
3710 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003711 }
3712
Douglas Gregor93798e22010-11-05 21:11:19 +00003713 // If our current best cursor is the construction of a temporary object,
3714 // don't replace that cursor with a type reference, because we want
3715 // clang_getCursor() to point at the constructor.
3716 if (clang_isExpression(BestCursor->kind) &&
3717 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003718 cursor.kind == CXCursor_TypeRef) {
3719 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
3720 // as having the actual point on the type reference.
3721 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
Douglas Gregor93798e22010-11-05 21:11:19 +00003722 return CXChildVisit_Recurse;
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003723 }
Douglas Gregor93798e22010-11-05 21:11:19 +00003724
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003725 *BestCursor = cursor;
3726 return CXChildVisit_Recurse;
3727}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003728
Douglas Gregorb9790342010-01-22 21:44:22 +00003729CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3730 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003731 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003732
Ted Kremeneka60ed472010-11-16 08:15:36 +00003733 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003734 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3735
Ted Kremeneka297de22010-01-25 22:34:44 +00003736 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003737 CXCursor Result = cxcursor::getCursor(TU, SLoc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003738
Douglas Gregor40749ee2010-11-03 00:35:38 +00003739 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregor40749ee2010-11-03 00:35:38 +00003740 if (Logging) {
3741 CXFile SearchFile;
3742 unsigned SearchLine, SearchColumn;
3743 CXFile ResultFile;
3744 unsigned ResultLine, ResultColumn;
Douglas Gregor66537982010-11-17 17:14:07 +00003745 CXString SearchFileName, ResultFileName, KindSpelling, USR;
3746 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
Douglas Gregor40749ee2010-11-03 00:35:38 +00003747 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3748
Chandler Carruth20174222011-08-31 16:53:37 +00003749 clang_getExpansionLocation(Loc, &SearchFile, &SearchLine, &SearchColumn, 0);
3750 clang_getExpansionLocation(ResultLoc, &ResultFile, &ResultLine,
3751 &ResultColumn, 0);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003752 SearchFileName = clang_getFileName(SearchFile);
3753 ResultFileName = clang_getFileName(ResultFile);
3754 KindSpelling = clang_getCursorKindSpelling(Result.kind);
Douglas Gregor66537982010-11-17 17:14:07 +00003755 USR = clang_getCursorUSR(Result);
3756 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n",
Douglas Gregor40749ee2010-11-03 00:35:38 +00003757 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3758 clang_getCString(KindSpelling),
Douglas Gregor66537982010-11-17 17:14:07 +00003759 clang_getCString(ResultFileName), ResultLine, ResultColumn,
3760 clang_getCString(USR), IsDef);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003761 clang_disposeString(SearchFileName);
3762 clang_disposeString(ResultFileName);
3763 clang_disposeString(KindSpelling);
Douglas Gregor66537982010-11-17 17:14:07 +00003764 clang_disposeString(USR);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003765
3766 CXCursor Definition = clang_getCursorDefinition(Result);
3767 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
3768 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
3769 CXString DefinitionKindSpelling
3770 = clang_getCursorKindSpelling(Definition.kind);
3771 CXFile DefinitionFile;
3772 unsigned DefinitionLine, DefinitionColumn;
Chandler Carruth20174222011-08-31 16:53:37 +00003773 clang_getExpansionLocation(DefinitionLoc, &DefinitionFile,
3774 &DefinitionLine, &DefinitionColumn, 0);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003775 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
3776 fprintf(stderr, " -> %s(%s:%d:%d)\n",
3777 clang_getCString(DefinitionKindSpelling),
3778 clang_getCString(DefinitionFileName),
3779 DefinitionLine, DefinitionColumn);
3780 clang_disposeString(DefinitionFileName);
3781 clang_disposeString(DefinitionKindSpelling);
3782 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003783 }
3784
Ted Kremeneke68fff62010-02-17 00:41:32 +00003785 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003786}
3787
Ted Kremenek73885552009-11-17 19:28:59 +00003788CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003789 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003790}
3791
3792unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003793 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003794}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003795
Douglas Gregor9ce55842010-11-20 00:09:34 +00003796unsigned clang_hashCursor(CXCursor C) {
3797 unsigned Index = 0;
3798 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
3799 Index = 1;
3800
3801 return llvm::DenseMapInfo<std::pair<unsigned, void*> >::getHashValue(
3802 std::make_pair(C.kind, C.data[Index]));
3803}
3804
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003805unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003806 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3807}
3808
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003809unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003810 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3811}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003812
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003813unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003814 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3815}
3816
Douglas Gregor97b98722010-01-19 23:20:36 +00003817unsigned clang_isExpression(enum CXCursorKind K) {
3818 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3819}
3820
3821unsigned clang_isStatement(enum CXCursorKind K) {
3822 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3823}
3824
Douglas Gregor8be80e12011-07-06 03:00:34 +00003825unsigned clang_isAttribute(enum CXCursorKind K) {
3826 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
3827}
3828
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003829unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3830 return K == CXCursor_TranslationUnit;
3831}
3832
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003833unsigned clang_isPreprocessing(enum CXCursorKind K) {
3834 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3835}
3836
Ted Kremenekad6eff62010-03-08 21:17:29 +00003837unsigned clang_isUnexposed(enum CXCursorKind K) {
3838 switch (K) {
3839 case CXCursor_UnexposedDecl:
3840 case CXCursor_UnexposedExpr:
3841 case CXCursor_UnexposedStmt:
3842 case CXCursor_UnexposedAttr:
3843 return true;
3844 default:
3845 return false;
3846 }
3847}
3848
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003849CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003850 return C.kind;
3851}
3852
Douglas Gregor98258af2010-01-18 22:46:11 +00003853CXSourceLocation clang_getCursorLocation(CXCursor C) {
3854 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003855 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003856 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003857 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3858 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003859 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003860 }
3861
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003862 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003863 std::pair<ObjCProtocolDecl *, SourceLocation> P
3864 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003865 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003866 }
3867
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003868 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003869 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3870 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003871 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003872 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003873
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003874 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003875 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003876 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003877 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003878
3879 case CXCursor_TemplateRef: {
3880 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3881 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3882 }
3883
Douglas Gregor69319002010-08-31 23:48:11 +00003884 case CXCursor_NamespaceRef: {
3885 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3886 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3887 }
3888
Douglas Gregora67e03f2010-09-09 21:42:20 +00003889 case CXCursor_MemberRef: {
3890 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3891 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3892 }
3893
Douglas Gregor011d8b92012-02-15 00:54:55 +00003894 case CXCursor_VariableRef: {
3895 std::pair<VarDecl *, SourceLocation> P = getCursorVariableRef(C);
3896 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3897 }
3898
Ted Kremenek3064ef92010-08-27 21:34:58 +00003899 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003900 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3901 if (!BaseSpec)
3902 return clang_getNullLocation();
3903
3904 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3905 return cxloc::translateSourceLocation(getCursorContext(C),
3906 TSInfo->getTypeLoc().getBeginLoc());
3907
3908 return cxloc::translateSourceLocation(getCursorContext(C),
Daniel Dunbar96a00142012-03-09 18:35:03 +00003909 BaseSpec->getLocStart());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003910 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003911
Douglas Gregor36897b02010-09-10 00:22:18 +00003912 case CXCursor_LabelRef: {
3913 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3914 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3915 }
3916
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003917 case CXCursor_OverloadedDeclRef:
3918 return cxloc::translateSourceLocation(getCursorContext(C),
3919 getCursorOverloadedDeclRef(C).second);
3920
Douglas Gregorf46034a2010-01-18 23:41:10 +00003921 default:
3922 // FIXME: Need a way to enumerate all non-reference cases.
3923 llvm_unreachable("Missed a reference kind");
3924 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003925 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003926
3927 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003928 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003929 getLocationFromExpr(getCursorExpr(C)));
3930
Douglas Gregor36897b02010-09-10 00:22:18 +00003931 if (clang_isStatement(C.kind))
3932 return cxloc::translateSourceLocation(getCursorContext(C),
3933 getCursorStmt(C)->getLocStart());
3934
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003935 if (C.kind == CXCursor_PreprocessingDirective) {
3936 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3937 return cxloc::translateSourceLocation(getCursorContext(C), L);
3938 }
Douglas Gregor48072312010-03-18 15:23:44 +00003939
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003940 if (C.kind == CXCursor_MacroExpansion) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003941 SourceLocation L
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003942 = cxcursor::getCursorMacroExpansion(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003943 return cxloc::translateSourceLocation(getCursorContext(C), L);
3944 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003945
3946 if (C.kind == CXCursor_MacroDefinition) {
3947 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3948 return cxloc::translateSourceLocation(getCursorContext(C), L);
3949 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003950
3951 if (C.kind == CXCursor_InclusionDirective) {
3952 SourceLocation L
3953 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3954 return cxloc::translateSourceLocation(getCursorContext(C), L);
3955 }
3956
Ted Kremenek9a700d22010-05-12 06:16:13 +00003957 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003958 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003959
Douglas Gregorf46034a2010-01-18 23:41:10 +00003960 Decl *D = getCursorDecl(C);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00003961 if (!D)
3962 return clang_getNullLocation();
3963
Douglas Gregorf46034a2010-01-18 23:41:10 +00003964 SourceLocation Loc = D->getLocation();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003965 // FIXME: Multiple variables declared in a single declaration
3966 // currently lack the information needed to correctly determine their
3967 // ranges when accounting for the type-specifier. We use context
3968 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3969 // and if so, whether it is the first decl.
3970 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3971 if (!cxcursor::isFirstInDeclGroup(C))
3972 Loc = VD->getLocation();
3973 }
3974
Argyrios Kyrtzidisccc6f362012-03-23 03:33:19 +00003975 // For ObjC methods, give the start location of the method name.
3976 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
3977 Loc = MD->getSelectorStartLoc();
3978
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003979 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003980}
Douglas Gregora7bde202010-01-19 00:34:46 +00003981
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003982} // end extern "C"
3983
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003984CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
3985 assert(TU);
3986
3987 // Guard against an invalid SourceLocation, or we may assert in one
3988 // of the following calls.
3989 if (SLoc.isInvalid())
3990 return clang_getNullCursor();
3991
3992 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
3993
3994 // Translate the given source location to make it point at the beginning of
3995 // the token under the cursor.
3996 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +00003997 CXXUnit->getASTContext().getLangOpts());
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003998
3999 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
4000 if (SLoc.isValid()) {
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00004001 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00004002 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
4003 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00004004 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00004005 SourceLocation(SLoc));
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00004006 CursorVis.visitFileRegion();
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00004007 }
4008
4009 return Result;
4010}
4011
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004012static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00004013 if (clang_isReference(C.kind)) {
4014 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004015 case CXCursor_ObjCSuperClassRef:
4016 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004017
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004018 case CXCursor_ObjCProtocolRef:
4019 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004020
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004021 case CXCursor_ObjCClassRef:
4022 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004023
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004024 case CXCursor_TypeRef:
4025 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00004026
4027 case CXCursor_TemplateRef:
4028 return getCursorTemplateRef(C).second;
4029
Douglas Gregor69319002010-08-31 23:48:11 +00004030 case CXCursor_NamespaceRef:
4031 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00004032
4033 case CXCursor_MemberRef:
4034 return getCursorMemberRef(C).second;
4035
Ted Kremenek3064ef92010-08-27 21:34:58 +00004036 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00004037 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00004038
Douglas Gregor36897b02010-09-10 00:22:18 +00004039 case CXCursor_LabelRef:
4040 return getCursorLabelRef(C).second;
4041
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004042 case CXCursor_OverloadedDeclRef:
4043 return getCursorOverloadedDeclRef(C).second;
4044
Douglas Gregor011d8b92012-02-15 00:54:55 +00004045 case CXCursor_VariableRef:
4046 return getCursorVariableRef(C).second;
4047
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004048 default:
4049 // FIXME: Need a way to enumerate all non-reference cases.
4050 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00004051 }
4052 }
Douglas Gregor97b98722010-01-19 23:20:36 +00004053
4054 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004055 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00004056
4057 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004058 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004059
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00004060 if (clang_isAttribute(C.kind))
4061 return getCursorAttr(C)->getRange();
4062
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004063 if (C.kind == CXCursor_PreprocessingDirective)
4064 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00004065
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004066 if (C.kind == CXCursor_MacroExpansion) {
4067 ASTUnit *TU = getCursorASTUnit(C);
4068 SourceRange Range = cxcursor::getCursorMacroExpansion(C)->getSourceRange();
4069 return TU->mapRangeFromPreamble(Range);
4070 }
Douglas Gregor572feb22010-03-18 18:04:21 +00004071
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004072 if (C.kind == CXCursor_MacroDefinition) {
4073 ASTUnit *TU = getCursorASTUnit(C);
4074 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
4075 return TU->mapRangeFromPreamble(Range);
4076 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00004077
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004078 if (C.kind == CXCursor_InclusionDirective) {
4079 ASTUnit *TU = getCursorASTUnit(C);
4080 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
4081 return TU->mapRangeFromPreamble(Range);
4082 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00004083
Argyrios Kyrtzidis0822c5f2012-03-19 23:17:58 +00004084 if (C.kind == CXCursor_TranslationUnit) {
4085 ASTUnit *TU = getCursorASTUnit(C);
4086 FileID MainID = TU->getSourceManager().getMainFileID();
4087 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
4088 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
4089 return SourceRange(Start, End);
4090 }
4091
Ted Kremenek007a7c92010-11-01 23:26:51 +00004092 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
4093 Decl *D = cxcursor::getCursorDecl(C);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00004094 if (!D)
4095 return SourceRange();
4096
Ted Kremenek007a7c92010-11-01 23:26:51 +00004097 SourceRange R = D->getSourceRange();
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());
4106 }
4107 return R;
4108 }
Douglas Gregor66537982010-11-17 17:14:07 +00004109 return SourceRange();
4110}
4111
4112/// \brief Retrieves the "raw" cursor extent, which is then extended to include
4113/// the decl-specifier-seq for declarations.
4114static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
4115 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
4116 Decl *D = cxcursor::getCursorDecl(C);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00004117 if (!D)
4118 return SourceRange();
4119
Douglas Gregor66537982010-11-17 17:14:07 +00004120 SourceRange R = D->getSourceRange();
Douglas Gregor66537982010-11-17 17:14:07 +00004121
Douglas Gregor2494dd02011-03-01 01:34:45 +00004122 // Adjust the start of the location for declarations preceded by
4123 // declaration specifiers.
4124 SourceLocation StartLoc;
4125 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
4126 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
Daniel Dunbar96a00142012-03-09 18:35:03 +00004127 StartLoc = TI->getTypeLoc().getLocStart();
Douglas Gregor2494dd02011-03-01 01:34:45 +00004128 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
4129 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
Daniel Dunbar96a00142012-03-09 18:35:03 +00004130 StartLoc = TI->getTypeLoc().getLocStart();
Douglas Gregor2494dd02011-03-01 01:34:45 +00004131 }
4132
4133 if (StartLoc.isValid() && R.getBegin().isValid() &&
4134 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
4135 R.setBegin(StartLoc);
4136
4137 // FIXME: Multiple variables declared in a single declaration
4138 // currently lack the information needed to correctly determine their
4139 // ranges when accounting for the type-specifier. We use context
4140 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
4141 // and if so, whether it is the first decl.
4142 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4143 if (!cxcursor::isFirstInDeclGroup(C))
4144 R.setBegin(VD->getLocation());
Douglas Gregor66537982010-11-17 17:14:07 +00004145 }
4146
4147 return R;
4148 }
4149
4150 return getRawCursorExtent(C);
4151}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004152
4153extern "C" {
4154
4155CXSourceRange clang_getCursorExtent(CXCursor C) {
4156 SourceRange R = getRawCursorExtent(C);
4157 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00004158 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004159
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004160 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00004161}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004162
4163CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00004164 if (clang_isInvalid(C.kind))
4165 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004166
Ted Kremeneka60ed472010-11-16 08:15:36 +00004167 CXTranslationUnit tu = getCursorTU(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004168 if (clang_isDeclaration(C.kind)) {
4169 Decl *D = getCursorDecl(C);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00004170 if (!D)
4171 return clang_getNullCursor();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004172 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004173 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Chris Lattner5f9e2722011-07-23 10:55:15 +00004174 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00004175 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
4176 return MakeCXCursor(Property, tu);
4177
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004178 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004179 }
4180
Douglas Gregor97b98722010-01-19 23:20:36 +00004181 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004182 Expr *E = getCursorExpr(C);
4183 Decl *D = getDeclFromExpr(E);
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00004184 if (D) {
4185 CXCursor declCursor = MakeCXCursor(D, tu);
4186 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
4187 declCursor);
4188 return declCursor;
4189 }
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004190
4191 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004192 return MakeCursorOverloadedDeclRef(Ovl, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004193
Douglas Gregor97b98722010-01-19 23:20:36 +00004194 return clang_getNullCursor();
4195 }
4196
Douglas Gregor36897b02010-09-10 00:22:18 +00004197 if (clang_isStatement(C.kind)) {
4198 Stmt *S = getCursorStmt(C);
4199 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Ted Kremenek37c2e962011-03-15 23:47:49 +00004200 if (LabelDecl *label = Goto->getLabel())
4201 if (LabelStmt *labelS = label->getStmt())
4202 return MakeCXCursor(labelS, getCursorDecl(C), tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00004203
4204 return clang_getNullCursor();
4205 }
4206
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004207 if (C.kind == CXCursor_MacroExpansion) {
Chandler Carruth9e5bb852011-07-14 08:20:46 +00004208 if (MacroDefinition *Def = getCursorMacroExpansion(C)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004209 return MakeMacroDefinitionCursor(Def, tu);
Douglas Gregorbf7efa22010-03-18 18:23:03 +00004210 }
4211
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004212 if (!clang_isReference(C.kind))
4213 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004214
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004215 switch (C.kind) {
4216 case CXCursor_ObjCSuperClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004217 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004218
4219 case CXCursor_ObjCProtocolRef: {
Argyrios Kyrtzidis98c16b82012-01-24 19:40:15 +00004220 ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
4221 if (ObjCProtocolDecl *Def = Prot->getDefinition())
4222 return MakeCXCursor(Def, tu);
4223
Argyrios Kyrtzidisc15707d2012-01-24 21:39:26 +00004224 return MakeCXCursor(Prot, tu);
Argyrios Kyrtzidis98c16b82012-01-24 19:40:15 +00004225 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004226
Douglas Gregor7723fec2011-12-15 20:29:51 +00004227 case CXCursor_ObjCClassRef: {
4228 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
4229 if (ObjCInterfaceDecl *Def = Class->getDefinition())
4230 return MakeCXCursor(Def, tu);
4231
Argyrios Kyrtzidisc15707d2012-01-24 21:39:26 +00004232 return MakeCXCursor(Class, tu);
Douglas Gregor7723fec2011-12-15 20:29:51 +00004233 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00004234
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004235 case CXCursor_TypeRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004236 return MakeCXCursor(getCursorTypeRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00004237
4238 case CXCursor_TemplateRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004239 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00004240
Douglas Gregor69319002010-08-31 23:48:11 +00004241 case CXCursor_NamespaceRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004242 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
Douglas Gregor69319002010-08-31 23:48:11 +00004243
Douglas Gregora67e03f2010-09-09 21:42:20 +00004244 case CXCursor_MemberRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004245 return MakeCXCursor(getCursorMemberRef(C).first, tu );
Douglas Gregora67e03f2010-09-09 21:42:20 +00004246
Ted Kremenek3064ef92010-08-27 21:34:58 +00004247 case CXCursor_CXXBaseSpecifier: {
4248 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
4249 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004250 tu ));
Ted Kremenek3064ef92010-08-27 21:34:58 +00004251 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004252
Douglas Gregor36897b02010-09-10 00:22:18 +00004253 case CXCursor_LabelRef:
4254 // FIXME: We end up faking the "parent" declaration here because we
4255 // don't want to make CXCursor larger.
4256 return MakeCXCursor(getCursorLabelRef(C).first,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004257 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
4258 .getTranslationUnitDecl(),
4259 tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00004260
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004261 case CXCursor_OverloadedDeclRef:
4262 return C;
Douglas Gregor011d8b92012-02-15 00:54:55 +00004263
4264 case CXCursor_VariableRef:
4265 return MakeCXCursor(getCursorVariableRef(C).first, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004266
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004267 default:
4268 // We would prefer to enumerate all non-reference cursor kinds here.
4269 llvm_unreachable("Unhandled reference cursor kind");
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004270 }
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004271}
4272
Douglas Gregorb6998662010-01-19 19:34:47 +00004273CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00004274 if (clang_isInvalid(C.kind))
4275 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004276
Ted Kremeneka60ed472010-11-16 08:15:36 +00004277 CXTranslationUnit TU = getCursorTU(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004278
Douglas Gregorb6998662010-01-19 19:34:47 +00004279 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00004280 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00004281 C = clang_getCursorReferenced(C);
4282 WasReference = true;
4283 }
4284
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004285 if (C.kind == CXCursor_MacroExpansion)
Douglas Gregorbf7efa22010-03-18 18:23:03 +00004286 return clang_getCursorReferenced(C);
4287
Douglas Gregorb6998662010-01-19 19:34:47 +00004288 if (!clang_isDeclaration(C.kind))
4289 return clang_getNullCursor();
4290
4291 Decl *D = getCursorDecl(C);
4292 if (!D)
4293 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004294
Douglas Gregorb6998662010-01-19 19:34:47 +00004295 switch (D->getKind()) {
4296 // Declaration kinds that don't really separate the notions of
4297 // declaration and definition.
4298 case Decl::Namespace:
4299 case Decl::Typedef:
Richard Smith162e1c12011-04-15 14:24:37 +00004300 case Decl::TypeAlias:
Richard Smith3e4c6c42011-05-05 21:57:07 +00004301 case Decl::TypeAliasTemplate:
Douglas Gregorb6998662010-01-19 19:34:47 +00004302 case Decl::TemplateTypeParm:
4303 case Decl::EnumConstant:
4304 case Decl::Field:
Benjamin Kramerd9811462010-11-21 14:11:41 +00004305 case Decl::IndirectField:
Douglas Gregorb6998662010-01-19 19:34:47 +00004306 case Decl::ObjCIvar:
4307 case Decl::ObjCAtDefsField:
4308 case Decl::ImplicitParam:
4309 case Decl::ParmVar:
4310 case Decl::NonTypeTemplateParm:
4311 case Decl::TemplateTemplateParm:
4312 case Decl::ObjCCategoryImpl:
4313 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00004314 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00004315 case Decl::LinkageSpec:
4316 case Decl::ObjCPropertyImpl:
4317 case Decl::FileScopeAsm:
4318 case Decl::StaticAssert:
4319 case Decl::Block:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00004320 case Decl::Label: // FIXME: Is this right??
Francois Pichetaf0f4d02011-08-14 03:52:19 +00004321 case Decl::ClassScopeFunctionSpecialization:
Douglas Gregor15de72c2011-12-02 23:23:56 +00004322 case Decl::Import:
Douglas Gregorb6998662010-01-19 19:34:47 +00004323 return C;
4324
4325 // Declaration kinds that don't make any sense here, but are
4326 // nonetheless harmless.
4327 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00004328 break;
4329
4330 // Declaration kinds for which the definition is not resolvable.
4331 case Decl::UnresolvedUsingTypename:
4332 case Decl::UnresolvedUsingValue:
4333 break;
4334
4335 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00004336 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004337 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004338
4339 case Decl::NamespaceAlias:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004340 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004341
4342 case Decl::Enum:
4343 case Decl::Record:
4344 case Decl::CXXRecord:
4345 case Decl::ClassTemplateSpecialization:
4346 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00004347 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004348 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004349 return clang_getNullCursor();
4350
4351 case Decl::Function:
4352 case Decl::CXXMethod:
4353 case Decl::CXXConstructor:
4354 case Decl::CXXDestructor:
4355 case Decl::CXXConversion: {
4356 const FunctionDecl *Def = 0;
4357 if (cast<FunctionDecl>(D)->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004358 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004359 return clang_getNullCursor();
4360 }
4361
4362 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00004363 // Ask the variable if it has a definition.
4364 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004365 return MakeCXCursor(Def, TU);
Sebastian Redl31310a22010-02-01 20:16:42 +00004366 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00004367 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004368
Douglas Gregorb6998662010-01-19 19:34:47 +00004369 case Decl::FunctionTemplate: {
4370 const FunctionDecl *Def = 0;
4371 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004372 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004373 return clang_getNullCursor();
4374 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004375
Douglas Gregorb6998662010-01-19 19:34:47 +00004376 case Decl::ClassTemplate: {
4377 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00004378 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00004379 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004380 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004381 return clang_getNullCursor();
4382 }
4383
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004384 case Decl::Using:
4385 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004386 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004387
4388 case Decl::UsingShadow:
4389 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004390 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004391 TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004392
4393 case Decl::ObjCMethod: {
4394 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
4395 if (Method->isThisDeclarationADefinition())
4396 return C;
4397
4398 // Dig out the method definition in the associated
4399 // @implementation, if we have it.
4400 // FIXME: The ASTs should make finding the definition easier.
4401 if (ObjCInterfaceDecl *Class
4402 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
4403 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
4404 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
4405 Method->isInstanceMethod()))
4406 if (Def->isThisDeclarationADefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004407 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004408
4409 return clang_getNullCursor();
4410 }
4411
4412 case Decl::ObjCCategory:
4413 if (ObjCCategoryImplDecl *Impl
4414 = cast<ObjCCategoryDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004415 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004416 return clang_getNullCursor();
4417
4418 case Decl::ObjCProtocol:
Douglas Gregor5e2a1ff2012-01-01 19:29:29 +00004419 if (ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
4420 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004421 return clang_getNullCursor();
4422
Douglas Gregor375bb142011-12-27 22:43:10 +00004423 case Decl::ObjCInterface: {
Douglas Gregorb6998662010-01-19 19:34:47 +00004424 // There are two notions of a "definition" for an Objective-C
4425 // class: the interface and its implementation. When we resolved a
4426 // reference to an Objective-C class, produce the @interface as
4427 // the definition; when we were provided with the interface,
4428 // produce the @implementation as the definition.
Douglas Gregor375bb142011-12-27 22:43:10 +00004429 ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
Douglas Gregorb6998662010-01-19 19:34:47 +00004430 if (WasReference) {
Douglas Gregor375bb142011-12-27 22:43:10 +00004431 if (ObjCInterfaceDecl *Def = IFace->getDefinition())
Douglas Gregor7723fec2011-12-15 20:29:51 +00004432 return MakeCXCursor(Def, TU);
Douglas Gregor375bb142011-12-27 22:43:10 +00004433 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004434 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004435 return clang_getNullCursor();
Douglas Gregor375bb142011-12-27 22:43:10 +00004436 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004437
Douglas Gregorb6998662010-01-19 19:34:47 +00004438 case Decl::ObjCProperty:
4439 // FIXME: We don't really know where to find the
4440 // ObjCPropertyImplDecls that implement this property.
4441 return clang_getNullCursor();
4442
4443 case Decl::ObjCCompatibleAlias:
4444 if (ObjCInterfaceDecl *Class
4445 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
Douglas Gregor7723fec2011-12-15 20:29:51 +00004446 if (ObjCInterfaceDecl *Def = Class->getDefinition())
4447 return MakeCXCursor(Def, TU);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004448
Douglas Gregorb6998662010-01-19 19:34:47 +00004449 return clang_getNullCursor();
4450
Douglas Gregorb6998662010-01-19 19:34:47 +00004451 case Decl::Friend:
4452 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004453 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004454 return clang_getNullCursor();
4455
4456 case Decl::FriendTemplate:
4457 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004458 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004459 return clang_getNullCursor();
4460 }
4461
4462 return clang_getNullCursor();
4463}
4464
4465unsigned clang_isCursorDefinition(CXCursor C) {
4466 if (!clang_isDeclaration(C.kind))
4467 return 0;
4468
4469 return clang_getCursorDefinition(C) == C;
4470}
4471
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004472CXCursor clang_getCanonicalCursor(CXCursor C) {
4473 if (!clang_isDeclaration(C.kind))
4474 return C;
4475
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004476 if (Decl *D = getCursorDecl(C)) {
Argyrios Kyrtzidisdebb00f2011-07-15 22:37:58 +00004477 if (ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
4478 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
4479 return MakeCXCursor(CatD, getCursorTU(C));
4480
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004481 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
4482 if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
4483 return MakeCXCursor(IFD, getCursorTU(C));
4484
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004485 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004486 }
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004487
4488 return C;
4489}
Argyrios Kyrtzidis34ebe1e2012-03-30 22:15:48 +00004490
4491int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) {
4492 return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first;
4493}
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004494
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004495unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004496 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004497 return 0;
4498
4499 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
4500 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
4501 return E->getNumDecls();
4502
4503 if (OverloadedTemplateStorage *S
4504 = Storage.dyn_cast<OverloadedTemplateStorage*>())
4505 return S->size();
4506
4507 Decl *D = Storage.get<Decl*>();
4508 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00004509 return Using->shadow_size();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004510
4511 return 0;
4512}
4513
4514CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004515 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004516 return clang_getNullCursor();
4517
4518 if (index >= clang_getNumOverloadedDecls(cursor))
4519 return clang_getNullCursor();
4520
Ted Kremeneka60ed472010-11-16 08:15:36 +00004521 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004522 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
4523 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004524 return MakeCXCursor(E->decls_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004525
4526 if (OverloadedTemplateStorage *S
4527 = Storage.dyn_cast<OverloadedTemplateStorage*>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004528 return MakeCXCursor(S->begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004529
4530 Decl *D = Storage.get<Decl*>();
4531 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
4532 // FIXME: This is, unfortunately, linear time.
4533 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
4534 std::advance(Pos, index);
Ted Kremeneka60ed472010-11-16 08:15:36 +00004535 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004536 }
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004537
4538 return clang_getNullCursor();
4539}
4540
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00004541void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00004542 const char **startBuf,
4543 const char **endBuf,
4544 unsigned *startLine,
4545 unsigned *startColumn,
4546 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00004547 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00004548 assert(getCursorDecl(C) && "CXCursor has null decl");
4549 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00004550 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
4551 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004552
Steve Naroff4ade6d62009-09-23 17:52:52 +00004553 SourceManager &SM = FD->getASTContext().getSourceManager();
4554 *startBuf = SM.getCharacterData(Body->getLBracLoc());
4555 *endBuf = SM.getCharacterData(Body->getRBracLoc());
4556 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
4557 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
4558 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
4559 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
4560}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004561
Douglas Gregor430d7a12011-07-25 17:48:11 +00004562
4563CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
4564 unsigned PieceIndex) {
4565 RefNamePieces Pieces;
4566
4567 switch (C.kind) {
4568 case CXCursor_MemberRefExpr:
4569 if (MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
4570 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
4571 E->getQualifierLoc().getSourceRange());
4572 break;
4573
4574 case CXCursor_DeclRefExpr:
4575 if (DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C)))
4576 Pieces = buildPieces(NameFlags, false, E->getNameInfo(),
4577 E->getQualifierLoc().getSourceRange(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00004578 E->getOptionalExplicitTemplateArgs());
Douglas Gregor430d7a12011-07-25 17:48:11 +00004579 break;
4580
4581 case CXCursor_CallExpr:
4582 if (CXXOperatorCallExpr *OCE =
4583 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
4584 Expr *Callee = OCE->getCallee();
4585 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
4586 Callee = ICE->getSubExpr();
4587
4588 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
4589 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
4590 DRE->getQualifierLoc().getSourceRange());
4591 }
4592 break;
4593
4594 default:
4595 break;
4596 }
4597
4598 if (Pieces.empty()) {
4599 if (PieceIndex == 0)
4600 return clang_getCursorExtent(C);
4601 } else if (PieceIndex < Pieces.size()) {
4602 SourceRange R = Pieces[PieceIndex];
4603 if (R.isValid())
4604 return cxloc::translateSourceRange(getCursorContext(C), R);
4605 }
4606
4607 return clang_getNullRange();
4608}
4609
Douglas Gregor0a812cf2010-02-18 23:07:20 +00004610void clang_enableStackTraces(void) {
4611 llvm::sys::PrintStackTraceOnErrorSignal();
4612}
4613
Daniel Dunbar995aaf92010-11-04 01:26:29 +00004614void clang_executeOnThread(void (*fn)(void*), void *user_data,
4615 unsigned stack_size) {
4616 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
4617}
4618
Ted Kremenekfb480492010-01-13 21:46:36 +00004619} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00004620
Ted Kremenekfb480492010-01-13 21:46:36 +00004621//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004622// Token-based Operations.
4623//===----------------------------------------------------------------------===//
4624
4625/* CXToken layout:
4626 * int_data[0]: a CXTokenKind
4627 * int_data[1]: starting token location
4628 * int_data[2]: token length
4629 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004630 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004631 * otherwise unused.
4632 */
4633extern "C" {
4634
4635CXTokenKind clang_getTokenKind(CXToken CXTok) {
4636 return static_cast<CXTokenKind>(CXTok.int_data[0]);
4637}
4638
4639CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
4640 switch (clang_getTokenKind(CXTok)) {
4641 case CXToken_Identifier:
4642 case CXToken_Keyword:
4643 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004644 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
4645 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004646
4647 case CXToken_Literal: {
4648 // We have stashed the starting pointer in the ptr_data field. Use it.
4649 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Chris Lattner5f9e2722011-07-23 10:55:15 +00004650 return createCXString(StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004651 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004652
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004653 case CXToken_Punctuation:
4654 case CXToken_Comment:
4655 break;
4656 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004657
4658 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004659 // deconstructing the source location.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004660 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004661 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004662 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004663
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004664 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
4665 std::pair<FileID, unsigned> LocInfo
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004666 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00004667 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004668 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004669 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
4670 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00004671 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004672
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004673 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004674}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004675
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004676CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004677 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004678 if (!CXXUnit)
4679 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004680
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004681 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
4682 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4683}
4684
4685CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004686 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor5352ac02010-01-28 00:27:43 +00004687 if (!CXXUnit)
4688 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004689
4690 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004691 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4692}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004693
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004694static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
4695 SmallVectorImpl<CXToken> &CXTokens) {
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004696 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4697 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004698 = SourceMgr.getDecomposedLoc(Range.getBegin());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004699 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004700 = SourceMgr.getDecomposedLoc(Range.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004701
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004702 // Cannot tokenize across files.
4703 if (BeginLocInfo.first != EndLocInfo.first)
4704 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004705
4706 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004707 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004708 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004709 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00004710 if (Invalid)
4711 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00004712
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004713 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
David Blaikie4e4d0842012-03-11 07:00:24 +00004714 CXXUnit->getASTContext().getLangOpts(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004715 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004716 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004717
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004718 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004719 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004720 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00004721 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004722 do {
4723 // Lex the next token
4724 Lex.LexFromRawLexer(Tok);
4725 if (Tok.is(tok::eof))
4726 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004727
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004728 // Initialize the CXToken.
4729 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004730
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004731 // - Common fields
4732 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
4733 CXTok.int_data[2] = Tok.getLength();
4734 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004735
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004736 // - Kind-specific fields
4737 if (Tok.isLiteral()) {
4738 CXTok.int_data[0] = CXToken_Literal;
4739 CXTok.ptr_data = (void *)Tok.getLiteralData();
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004740 } else if (Tok.is(tok::raw_identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00004741 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004742 IdentifierInfo *II
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004743 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004744
David Chisnall096428b2010-10-13 21:44:48 +00004745 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004746 CXTok.int_data[0] = CXToken_Keyword;
4747 }
4748 else {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004749 CXTok.int_data[0] = Tok.is(tok::identifier)
4750 ? CXToken_Identifier
4751 : CXToken_Keyword;
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004752 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004753 CXTok.ptr_data = II;
4754 } else if (Tok.is(tok::comment)) {
4755 CXTok.int_data[0] = CXToken_Comment;
4756 CXTok.ptr_data = 0;
4757 } else {
4758 CXTok.int_data[0] = CXToken_Punctuation;
4759 CXTok.ptr_data = 0;
4760 }
4761 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00004762 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004763 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004764}
4765
4766void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
4767 CXToken **Tokens, unsigned *NumTokens) {
4768 if (Tokens)
4769 *Tokens = 0;
4770 if (NumTokens)
4771 *NumTokens = 0;
4772
4773 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4774 if (!CXXUnit || !Tokens || !NumTokens)
4775 return;
4776
4777 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4778
4779 SourceRange R = cxloc::translateCXSourceRange(Range);
4780 if (R.isInvalid())
4781 return;
4782
4783 SmallVector<CXToken, 32> CXTokens;
4784 getTokens(CXXUnit, R, CXTokens);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004785
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004786 if (CXTokens.empty())
4787 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004788
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004789 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
4790 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
4791 *NumTokens = CXTokens.size();
4792}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004793
Ted Kremenek6db61092010-05-05 00:55:15 +00004794void clang_disposeTokens(CXTranslationUnit TU,
4795 CXToken *Tokens, unsigned NumTokens) {
4796 free(Tokens);
4797}
4798
4799} // end: extern "C"
4800
4801//===----------------------------------------------------------------------===//
4802// Token annotation APIs.
4803//===----------------------------------------------------------------------===//
4804
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004805typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004806static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4807 CXCursor parent,
4808 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00004809namespace {
4810class AnnotateTokensWorker {
4811 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004812 CXToken *Tokens;
4813 CXCursor *Cursors;
4814 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004815 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00004816 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004817 CursorVisitor AnnotateVis;
4818 SourceManager &SrcMgr;
Douglas Gregorf5251602011-03-08 17:10:18 +00004819 bool HasContextSensitiveKeywords;
4820
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004821 bool MoreTokens() const { return TokIdx < NumTokens; }
4822 unsigned NextToken() const { return TokIdx; }
4823 void AdvanceToken() { ++TokIdx; }
4824 SourceLocation GetTokenLoc(unsigned tokI) {
4825 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4826 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004827 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004828 return Tokens[tokI].int_data[3] != 0;
4829 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004830 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004831 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[3]);
4832 }
4833
4834 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004835 void annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
4836 SourceRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004837
Ted Kremenek6db61092010-05-05 00:55:15 +00004838public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00004839 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004840 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004841 CXTranslationUnit tu, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00004842 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00004843 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004844 AnnotateVis(tu,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00004845 AnnotateTokensVisitor, this,
4846 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00004847 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00004848 RegionOfInterest),
Douglas Gregorf5251602011-03-08 17:10:18 +00004849 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()),
4850 HasContextSensitiveKeywords(false) { }
Ted Kremenek11949cb2010-05-05 00:55:17 +00004851
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004852 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00004853 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004854 void AnnotateTokens();
Douglas Gregorf5251602011-03-08 17:10:18 +00004855
4856 /// \brief Determine whether the annotator saw any cursors that have
4857 /// context-sensitive keywords.
4858 bool hasContextSensitiveKeywords() const {
4859 return HasContextSensitiveKeywords;
4860 }
Ted Kremenek6db61092010-05-05 00:55:15 +00004861};
4862}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004863
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004864void AnnotateTokensWorker::AnnotateTokens() {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004865 // Walk the AST within the region of interest, annotating tokens
4866 // along the way.
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004867 AnnotateVis.visitFileRegion();
Ted Kremenek11949cb2010-05-05 00:55:17 +00004868
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004869 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4870 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004871 if (Pos != Annotated.end() &&
4872 (clang_isInvalid(Cursors[I].kind) ||
4873 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004874 Cursors[I] = Pos->second;
4875 }
4876
4877 // Finish up annotating any tokens left.
4878 if (!MoreTokens())
4879 return;
4880
4881 const CXCursor &C = clang_getNullCursor();
4882 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004883 if (I < PreprocessingTokIdx && clang_isPreprocessing(Cursors[I].kind))
4884 continue;
4885
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004886 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4887 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004888 }
4889}
4890
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004891/// \brief It annotates and advances tokens with a cursor until the comparison
4892//// between the cursor location and the source range is the same as
4893/// \arg compResult.
4894///
4895/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
4896/// Pass RangeOverlap to annotate tokens inside a range.
4897void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
4898 RangeComparisonResult compResult,
4899 SourceRange range) {
4900 while (MoreTokens()) {
4901 const unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004902 if (isFunctionMacroToken(I))
4903 return annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004904
4905 SourceLocation TokLoc = GetTokenLoc(I);
4906 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4907 Cursors[I] = updateC;
4908 AdvanceToken();
4909 continue;
4910 }
4911 break;
4912 }
4913}
4914
4915/// \brief Special annotation handling for macro argument tokens.
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004916void AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
4917 CXCursor updateC,
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004918 RangeComparisonResult compResult,
4919 SourceRange range) {
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004920 assert(MoreTokens());
4921 assert(isFunctionMacroToken(NextToken()) &&
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004922 "Should be called only for macro arg tokens");
4923
4924 // This works differently than annotateAndAdvanceTokens; because expanded
4925 // macro arguments can have arbitrary translation-unit source order, we do not
4926 // advance the token index one by one until a token fails the range test.
4927 // We only advance once past all of the macro arg tokens if all of them
4928 // pass the range test. If one of them fails we keep the token index pointing
4929 // at the start of the macro arg tokens so that the failing token will be
4930 // annotated by a subsequent annotation try.
4931
4932 bool atLeastOneCompFail = false;
4933
4934 unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004935 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
4936 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004937 if (TokLoc.isFileID())
4938 continue; // not macro arg token, it's parens or comma.
4939 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4940 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
4941 Cursors[I] = updateC;
4942 } else
4943 atLeastOneCompFail = true;
4944 }
4945
4946 if (!atLeastOneCompFail)
4947 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
4948}
4949
Ted Kremenek6db61092010-05-05 00:55:15 +00004950enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004951AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004952 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004953 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004954 if (cursorRange.isInvalid())
4955 return CXChildVisit_Recurse;
Douglas Gregorf5251602011-03-08 17:10:18 +00004956
4957 if (!HasContextSensitiveKeywords) {
4958 // Objective-C properties can have context-sensitive keywords.
4959 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
4960 if (ObjCPropertyDecl *Property
4961 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
4962 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
4963 }
4964 // Objective-C methods can have context-sensitive keywords.
4965 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
4966 cursor.kind == CXCursor_ObjCClassMethodDecl) {
4967 if (ObjCMethodDecl *Method
4968 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
4969 if (Method->getObjCDeclQualifier())
4970 HasContextSensitiveKeywords = true;
4971 else {
4972 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
4973 PEnd = Method->param_end();
4974 P != PEnd; ++P) {
4975 if ((*P)->getObjCDeclQualifier()) {
4976 HasContextSensitiveKeywords = true;
4977 break;
4978 }
4979 }
4980 }
4981 }
4982 }
4983 // C++ methods can have context-sensitive keywords.
4984 else if (cursor.kind == CXCursor_CXXMethod) {
4985 if (CXXMethodDecl *Method
4986 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
4987 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
4988 HasContextSensitiveKeywords = true;
4989 }
4990 }
4991 // C++ classes can have context-sensitive keywords.
4992 else if (cursor.kind == CXCursor_StructDecl ||
4993 cursor.kind == CXCursor_ClassDecl ||
4994 cursor.kind == CXCursor_ClassTemplate ||
4995 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
4996 if (Decl *D = getCursorDecl(cursor))
4997 if (D->hasAttr<FinalAttr>())
4998 HasContextSensitiveKeywords = true;
4999 }
5000 }
5001
Douglas Gregor4419b672010-10-21 06:10:04 +00005002 if (clang_isPreprocessing(cursor.kind)) {
Chandler Carruthcea731a2011-07-14 16:07:57 +00005003 // For macro expansions, just note where the beginning of the macro
5004 // expansion occurs.
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00005005 if (cursor.kind == CXCursor_MacroExpansion) {
Douglas Gregor4419b672010-10-21 06:10:04 +00005006 Annotated[Loc.int_data] = cursor;
5007 return CXChildVisit_Recurse;
5008 }
5009
Douglas Gregor4419b672010-10-21 06:10:04 +00005010 // Items in the preprocessing record are kept separate from items in
5011 // declarations, so we keep a separate token index.
5012 unsigned SavedTokIdx = TokIdx;
5013 TokIdx = PreprocessingTokIdx;
5014
5015 // Skip tokens up until we catch up to the beginning of the preprocessing
5016 // entry.
5017 while (MoreTokens()) {
5018 const unsigned I = NextToken();
5019 SourceLocation TokLoc = GetTokenLoc(I);
5020 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
5021 case RangeBefore:
5022 AdvanceToken();
5023 continue;
5024 case RangeAfter:
5025 case RangeOverlap:
5026 break;
5027 }
5028 break;
5029 }
5030
5031 // Look at all of the tokens within this range.
5032 while (MoreTokens()) {
5033 const unsigned I = NextToken();
5034 SourceLocation TokLoc = GetTokenLoc(I);
5035 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
5036 case RangeBefore:
David Blaikieb219cfc2011-09-23 05:06:16 +00005037 llvm_unreachable("Infeasible");
Douglas Gregor4419b672010-10-21 06:10:04 +00005038 case RangeAfter:
5039 break;
5040 case RangeOverlap:
5041 Cursors[I] = cursor;
5042 AdvanceToken();
5043 continue;
5044 }
5045 break;
5046 }
5047
5048 // Save the preprocessing token index; restore the non-preprocessing
5049 // token index.
5050 PreprocessingTokIdx = TokIdx;
5051 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005052 return CXChildVisit_Recurse;
5053 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005054
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005055 if (cursorRange.isInvalid())
5056 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00005057
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005058 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
5059
Ted Kremeneka333c662010-05-12 05:29:33 +00005060 // Adjust the annotated range based specific declarations.
5061 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
5062 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00005063 Decl *D = cxcursor::getCursorDecl(cursor);
Douglas Gregor2494dd02011-03-01 01:34:45 +00005064
5065 SourceLocation StartLoc;
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00005066 if (const DeclaratorDecl *DD = dyn_cast_or_null<DeclaratorDecl>(D)) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00005067 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
Daniel Dunbar96a00142012-03-09 18:35:03 +00005068 StartLoc = TI->getTypeLoc().getLocStart();
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00005069 } else if (TypedefDecl *Typedef = dyn_cast_or_null<TypedefDecl>(D)) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00005070 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
Daniel Dunbar96a00142012-03-09 18:35:03 +00005071 StartLoc = TI->getTypeLoc().getLocStart();
Ted Kremeneka333c662010-05-12 05:29:33 +00005072 }
Douglas Gregor2494dd02011-03-01 01:34:45 +00005073
5074 if (StartLoc.isValid() && L.isValid() &&
5075 SrcMgr.isBeforeInTranslationUnit(StartLoc, L))
5076 cursorRange.setBegin(StartLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00005077 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00005078
Ted Kremenek3f404602010-08-14 01:14:06 +00005079 // If the location of the cursor occurs within a macro instantiation, record
5080 // the spelling location of the cursor in our annotation map. We can then
5081 // paper over the token labelings during a post-processing step to try and
5082 // get cursor mappings for tokens that are the *arguments* of a macro
5083 // instantiation.
5084 if (L.isMacroID()) {
5085 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
5086 // Only invalidate the old annotation if it isn't part of a preprocessing
5087 // directive. Here we assume that the default construction of CXCursor
5088 // results in CXCursor.kind being an initialized value (i.e., 0). If
5089 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00005090
Ted Kremenek3f404602010-08-14 01:14:06 +00005091 CXCursor &oldC = Annotated[rawEncoding];
5092 if (!clang_isPreprocessing(oldC.kind))
5093 oldC = cursor;
5094 }
5095
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005096 const enum CXCursorKind K = clang_getCursorKind(parent);
5097 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00005098 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
5099 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005100
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005101 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005102
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00005103 // Avoid having the cursor of an expression "overwrite" the annotation of the
5104 // variable declaration that it belongs to.
5105 // This can happen for C++ constructor expressions whose range generally
5106 // include the variable declaration, e.g.:
5107 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
5108 if (clang_isExpression(cursorK)) {
5109 Expr *E = getCursorExpr(cursor);
Argyrios Kyrtzidis8ccac3d2011-06-29 22:20:07 +00005110 if (Decl *D = getCursorParentDecl(cursor)) {
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00005111 const unsigned I = NextToken();
5112 if (E->getLocStart().isValid() && D->getLocation().isValid() &&
5113 E->getLocStart() == D->getLocation() &&
5114 E->getLocStart() == GetTokenLoc(I)) {
5115 Cursors[I] = updateC;
5116 AdvanceToken();
5117 }
5118 }
5119 }
5120
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005121 // Visit children to get their cursor information.
5122 const unsigned BeforeChildren = NextToken();
5123 VisitChildren(cursor);
5124 const unsigned AfterChildren = NextToken();
5125
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005126 // Scan the tokens that are at the end of the cursor, but are not captured
5127 // but the child cursors.
5128 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
Ted Kremenek6db61092010-05-05 00:55:15 +00005129
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005130 // Scan the tokens that are at the beginning of the cursor, but are not
5131 // capture by the child cursors.
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005132 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
5133 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
5134 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00005135
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005136 Cursors[I] = cursor;
5137 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005138
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005139 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005140}
5141
Ted Kremenek6db61092010-05-05 00:55:15 +00005142static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
5143 CXCursor parent,
5144 CXClientData client_data) {
5145 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
5146}
5147
Ted Kremenek6628a612011-03-18 22:51:30 +00005148namespace {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005149
5150/// \brief Uses the macro expansions in the preprocessing record to find
5151/// and mark tokens that are macro arguments. This info is used by the
5152/// AnnotateTokensWorker.
5153class MarkMacroArgTokensVisitor {
5154 SourceManager &SM;
5155 CXToken *Tokens;
5156 unsigned NumTokens;
5157 unsigned CurIdx;
5158
5159public:
5160 MarkMacroArgTokensVisitor(SourceManager &SM,
5161 CXToken *tokens, unsigned numTokens)
5162 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
5163
5164 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
5165 if (cursor.kind != CXCursor_MacroExpansion)
5166 return CXChildVisit_Continue;
5167
5168 SourceRange macroRange = getCursorMacroExpansion(cursor)->getSourceRange();
5169 if (macroRange.getBegin() == macroRange.getEnd())
5170 return CXChildVisit_Continue; // it's not a function macro.
5171
5172 for (; CurIdx < NumTokens; ++CurIdx) {
5173 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
5174 macroRange.getBegin()))
5175 break;
5176 }
5177
5178 if (CurIdx == NumTokens)
5179 return CXChildVisit_Break;
5180
5181 for (; CurIdx < NumTokens; ++CurIdx) {
5182 SourceLocation tokLoc = getTokenLoc(CurIdx);
5183 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
5184 break;
5185
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00005186 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005187 }
5188
5189 if (CurIdx == NumTokens)
5190 return CXChildVisit_Break;
5191
5192 return CXChildVisit_Continue;
5193 }
5194
5195private:
5196 SourceLocation getTokenLoc(unsigned tokI) {
5197 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
5198 }
5199
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00005200 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005201 // The third field is reserved and currently not used. Use it here
5202 // to mark macro arg expanded tokens with their expanded locations.
5203 Tokens[tokI].int_data[3] = loc.getRawEncoding();
5204 }
5205};
5206
5207} // end anonymous namespace
5208
5209static CXChildVisitResult
5210MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
5211 CXClientData client_data) {
5212 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
5213 parent);
5214}
5215
5216namespace {
Ted Kremenek6628a612011-03-18 22:51:30 +00005217 struct clang_annotateTokens_Data {
5218 CXTranslationUnit TU;
5219 ASTUnit *CXXUnit;
5220 CXToken *Tokens;
5221 unsigned NumTokens;
5222 CXCursor *Cursors;
5223 };
5224}
5225
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005226static void annotatePreprocessorTokens(CXTranslationUnit TU,
5227 SourceRange RegionOfInterest,
5228 AnnotateTokensData &Annotated) {
5229 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
5230
5231 SourceManager &SourceMgr = CXXUnit->getSourceManager();
5232 std::pair<FileID, unsigned> BeginLocInfo
5233 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
5234 std::pair<FileID, unsigned> EndLocInfo
5235 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
5236
5237 if (BeginLocInfo.first != EndLocInfo.first)
5238 return;
5239
5240 StringRef Buffer;
5241 bool Invalid = false;
5242 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
5243 if (Buffer.empty() || Invalid)
5244 return;
5245
5246 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
David Blaikie4e4d0842012-03-11 07:00:24 +00005247 CXXUnit->getASTContext().getLangOpts(),
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005248 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
5249 Buffer.end());
5250 Lex.SetCommentRetentionState(true);
5251
5252 // Lex tokens in raw mode until we hit the end of the range, to avoid
5253 // entering #includes or expanding macros.
5254 while (true) {
5255 Token Tok;
5256 Lex.LexFromRawLexer(Tok);
5257
5258 reprocess:
5259 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
5260 // We have found a preprocessing directive. Gobble it up so that we
5261 // don't see it while preprocessing these tokens later, but keep track
5262 // of all of the token locations inside this preprocessing directive so
5263 // that we can annotate them appropriately.
5264 //
5265 // FIXME: Some simple tests here could identify macro definitions and
5266 // #undefs, to provide specific cursor kinds for those.
5267 SmallVector<SourceLocation, 32> Locations;
5268 do {
5269 Locations.push_back(Tok.getLocation());
5270 Lex.LexFromRawLexer(Tok);
5271 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
5272
5273 using namespace cxcursor;
5274 CXCursor Cursor
5275 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
5276 Locations.back()),
5277 TU);
5278 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
5279 Annotated[Locations[I].getRawEncoding()] = Cursor;
5280 }
5281
5282 if (Tok.isAtStartOfLine())
5283 goto reprocess;
5284
5285 continue;
5286 }
5287
5288 if (Tok.is(tok::eof))
5289 break;
5290 }
5291}
5292
Ted Kremenekab979612010-11-11 08:05:23 +00005293// This gets run a separate thread to avoid stack blowout.
Ted Kremenek6628a612011-03-18 22:51:30 +00005294static void clang_annotateTokensImpl(void *UserData) {
5295 CXTranslationUnit TU = ((clang_annotateTokens_Data*)UserData)->TU;
5296 ASTUnit *CXXUnit = ((clang_annotateTokens_Data*)UserData)->CXXUnit;
5297 CXToken *Tokens = ((clang_annotateTokens_Data*)UserData)->Tokens;
5298 const unsigned NumTokens = ((clang_annotateTokens_Data*)UserData)->NumTokens;
5299 CXCursor *Cursors = ((clang_annotateTokens_Data*)UserData)->Cursors;
5300
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00005301 CIndexer *CXXIdx = (CIndexer*)TU->CIdx;
5302 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
Argyrios Kyrtzidis81b5ac32012-03-28 02:49:54 +00005303 setThreadBackgroundPriority();
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00005304
Ted Kremenek6628a612011-03-18 22:51:30 +00005305 // Determine the region of interest, which contains all of the tokens.
5306 SourceRange RegionOfInterest;
5307 RegionOfInterest.setBegin(
5308 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
5309 RegionOfInterest.setEnd(
5310 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
5311 Tokens[NumTokens-1])));
5312
5313 // A mapping from the source locations found when re-lexing or traversing the
5314 // region of interest to the corresponding cursors.
5315 AnnotateTokensData Annotated;
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005316
Ted Kremenek6628a612011-03-18 22:51:30 +00005317 // Relex the tokens within the source range to look for preprocessing
5318 // directives.
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005319 annotatePreprocessorTokens(TU, RegionOfInterest, Annotated);
Ted Kremenek6628a612011-03-18 22:51:30 +00005320
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005321 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
5322 // Search and mark tokens that are macro argument expansions.
5323 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
5324 Tokens, NumTokens);
5325 CursorVisitor MacroArgMarker(TU,
5326 MarkMacroArgTokensVisitorDelegate, &Visitor,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00005327 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00005328 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00005329 RegionOfInterest);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005330 MacroArgMarker.visitPreprocessedEntitiesInRegion();
5331 }
5332
Ted Kremenek6628a612011-03-18 22:51:30 +00005333 // Annotate all of the source locations in the region of interest that map to
5334 // a specific cursor.
5335 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
5336 TU, RegionOfInterest);
5337
5338 // FIXME: We use a ridiculous stack size here because the data-recursion
5339 // algorithm uses a large stack frame than the non-data recursive version,
5340 // and AnnotationTokensWorker currently transforms the data-recursion
5341 // algorithm back into a traditional recursion by explicitly calling
5342 // VisitChildren(). We will need to remove this explicit recursive call.
5343 W.AnnotateTokens();
5344
5345 // If we ran into any entities that involve context-sensitive keywords,
5346 // take another pass through the tokens to mark them as such.
5347 if (W.hasContextSensitiveKeywords()) {
5348 for (unsigned I = 0; I != NumTokens; ++I) {
5349 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
5350 continue;
5351
5352 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
5353 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5354 if (ObjCPropertyDecl *Property
5355 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
5356 if (Property->getPropertyAttributesAsWritten() != 0 &&
5357 llvm::StringSwitch<bool>(II->getName())
5358 .Case("readonly", true)
5359 .Case("assign", true)
John McCallf85e1932011-06-15 23:02:42 +00005360 .Case("unsafe_unretained", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00005361 .Case("readwrite", true)
5362 .Case("retain", true)
5363 .Case("copy", true)
5364 .Case("nonatomic", true)
5365 .Case("atomic", true)
5366 .Case("getter", true)
5367 .Case("setter", true)
John McCallf85e1932011-06-15 23:02:42 +00005368 .Case("strong", true)
5369 .Case("weak", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00005370 .Default(false))
5371 Tokens[I].int_data[0] = CXToken_Keyword;
5372 }
5373 continue;
5374 }
5375
5376 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
5377 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
5378 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5379 if (llvm::StringSwitch<bool>(II->getName())
5380 .Case("in", true)
5381 .Case("out", true)
5382 .Case("inout", true)
5383 .Case("oneway", true)
5384 .Case("bycopy", true)
5385 .Case("byref", true)
5386 .Default(false))
5387 Tokens[I].int_data[0] = CXToken_Keyword;
5388 continue;
5389 }
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00005390
5391 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
5392 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
5393 Tokens[I].int_data[0] = CXToken_Keyword;
Ted Kremenek6628a612011-03-18 22:51:30 +00005394 continue;
5395 }
5396 }
5397 }
Ted Kremenekab979612010-11-11 08:05:23 +00005398}
5399
Ted Kremenek6db61092010-05-05 00:55:15 +00005400extern "C" {
5401
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005402void clang_annotateTokens(CXTranslationUnit TU,
5403 CXToken *Tokens, unsigned NumTokens,
5404 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005405
5406 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005407 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005408
Douglas Gregor4419b672010-10-21 06:10:04 +00005409 // Any token we don't specifically annotate will have a NULL cursor.
5410 CXCursor C = clang_getNullCursor();
5411 for (unsigned I = 0; I != NumTokens; ++I)
5412 Cursors[I] = C;
5413
Ted Kremeneka60ed472010-11-16 08:15:36 +00005414 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor4419b672010-10-21 06:10:04 +00005415 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005416 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005417
Douglas Gregorbdf60622010-03-05 21:16:25 +00005418 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenek6628a612011-03-18 22:51:30 +00005419
5420 clang_annotateTokens_Data data = { TU, CXXUnit, Tokens, NumTokens, Cursors };
Ted Kremenekab979612010-11-11 08:05:23 +00005421 llvm::CrashRecoveryContext CRC;
Ted Kremenek6628a612011-03-18 22:51:30 +00005422 if (!RunSafely(CRC, clang_annotateTokensImpl, &data,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005423 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00005424 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
5425 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005426}
Ted Kremenek6628a612011-03-18 22:51:30 +00005427
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005428} // end: extern "C"
5429
5430//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00005431// Operations for querying linkage of a cursor.
5432//===----------------------------------------------------------------------===//
5433
5434extern "C" {
5435CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00005436 if (!clang_isDeclaration(cursor.kind))
5437 return CXLinkage_Invalid;
5438
Ted Kremenek16b42592010-03-03 06:36:57 +00005439 Decl *D = cxcursor::getCursorDecl(cursor);
5440 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
5441 switch (ND->getLinkage()) {
5442 case NoLinkage: return CXLinkage_NoLinkage;
5443 case InternalLinkage: return CXLinkage_Internal;
5444 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
5445 case ExternalLinkage: return CXLinkage_External;
5446 };
5447
5448 return CXLinkage_Invalid;
5449}
5450} // end: extern "C"
5451
5452//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005453// Operations for querying language of a cursor.
5454//===----------------------------------------------------------------------===//
5455
5456static CXLanguageKind getDeclLanguage(const Decl *D) {
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00005457 if (!D)
5458 return CXLanguage_C;
5459
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005460 switch (D->getKind()) {
5461 default:
5462 break;
5463 case Decl::ImplicitParam:
5464 case Decl::ObjCAtDefsField:
5465 case Decl::ObjCCategory:
5466 case Decl::ObjCCategoryImpl:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005467 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005468 case Decl::ObjCImplementation:
5469 case Decl::ObjCInterface:
5470 case Decl::ObjCIvar:
5471 case Decl::ObjCMethod:
5472 case Decl::ObjCProperty:
5473 case Decl::ObjCPropertyImpl:
5474 case Decl::ObjCProtocol:
5475 return CXLanguage_ObjC;
5476 case Decl::CXXConstructor:
5477 case Decl::CXXConversion:
5478 case Decl::CXXDestructor:
5479 case Decl::CXXMethod:
5480 case Decl::CXXRecord:
5481 case Decl::ClassTemplate:
5482 case Decl::ClassTemplatePartialSpecialization:
5483 case Decl::ClassTemplateSpecialization:
5484 case Decl::Friend:
5485 case Decl::FriendTemplate:
5486 case Decl::FunctionTemplate:
5487 case Decl::LinkageSpec:
5488 case Decl::Namespace:
5489 case Decl::NamespaceAlias:
5490 case Decl::NonTypeTemplateParm:
5491 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005492 case Decl::TemplateTemplateParm:
5493 case Decl::TemplateTypeParm:
5494 case Decl::UnresolvedUsingTypename:
5495 case Decl::UnresolvedUsingValue:
5496 case Decl::Using:
5497 case Decl::UsingDirective:
5498 case Decl::UsingShadow:
5499 return CXLanguage_CPlusPlus;
5500 }
5501
5502 return CXLanguage_C;
5503}
5504
5505extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00005506
5507enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
5508 if (clang_isDeclaration(cursor.kind))
5509 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005510 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Douglas Gregor58ddb602010-08-23 23:00:57 +00005511 return CXAvailability_Available;
5512
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005513 switch (D->getAvailability()) {
5514 case AR_Available:
5515 case AR_NotYetIntroduced:
5516 return CXAvailability_Available;
5517
5518 case AR_Deprecated:
Douglas Gregor58ddb602010-08-23 23:00:57 +00005519 return CXAvailability_Deprecated;
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005520
5521 case AR_Unavailable:
5522 return CXAvailability_NotAvailable;
5523 }
Douglas Gregor58ddb602010-08-23 23:00:57 +00005524 }
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005525
Douglas Gregor58ddb602010-08-23 23:00:57 +00005526 return CXAvailability_Available;
5527}
5528
Douglas Gregorcc889662012-05-08 00:14:45 +00005529static CXVersion convertVersion(VersionTuple In) {
5530 CXVersion Out = { -1, -1, -1 };
5531 if (In.empty())
5532 return Out;
5533
5534 Out.Major = In.getMajor();
5535
5536 if (llvm::Optional<unsigned> Minor = In.getMinor())
5537 Out.Minor = *Minor;
5538 else
5539 return Out;
5540
5541 if (llvm::Optional<unsigned> Subminor = In.getSubminor())
5542 Out.Subminor = *Subminor;
5543
5544 return Out;
5545}
5546
5547int clang_getCursorPlatformAvailability(CXCursor cursor,
5548 int *always_deprecated,
5549 CXString *deprecated_message,
5550 int *always_unavailable,
5551 CXString *unavailable_message,
5552 CXPlatformAvailability *availability,
5553 int availability_size) {
5554 if (always_deprecated)
5555 *always_deprecated = 0;
5556 if (deprecated_message)
5557 *deprecated_message = cxstring::createCXString("", /*DupString=*/false);
5558 if (always_unavailable)
5559 *always_unavailable = 0;
5560 if (unavailable_message)
5561 *unavailable_message = cxstring::createCXString("", /*DupString=*/false);
5562
5563 if (!clang_isDeclaration(cursor.kind))
5564 return 0;
5565
5566 Decl *D = cxcursor::getCursorDecl(cursor);
5567 if (!D)
5568 return 0;
5569
5570 int N = 0;
5571 for (Decl::attr_iterator A = D->attr_begin(), AEnd = D->attr_end(); A != AEnd;
5572 ++A) {
5573 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(*A)) {
5574 if (always_deprecated)
5575 *always_deprecated = 1;
5576 if (deprecated_message)
5577 *deprecated_message = cxstring::createCXString(Deprecated->getMessage());
5578 continue;
5579 }
5580
5581 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(*A)) {
5582 if (always_unavailable)
5583 *always_unavailable = 1;
5584 if (unavailable_message) {
5585 *unavailable_message
5586 = cxstring::createCXString(Unavailable->getMessage());
5587 }
5588 continue;
5589 }
5590
5591 if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(*A)) {
5592 if (N < availability_size) {
5593 availability[N].Platform
5594 = cxstring::createCXString(Avail->getPlatform()->getName());
5595 availability[N].Introduced = convertVersion(Avail->getIntroduced());
5596 availability[N].Deprecated = convertVersion(Avail->getDeprecated());
5597 availability[N].Obsoleted = convertVersion(Avail->getObsoleted());
5598 availability[N].Unavailable = Avail->getUnavailable();
5599 availability[N].Message = cxstring::createCXString(Avail->getMessage());
5600 }
5601 ++N;
5602 }
5603 }
5604
5605 return N;
5606}
5607
5608void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) {
5609 clang_disposeString(availability->Platform);
5610 clang_disposeString(availability->Message);
5611}
5612
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005613CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
5614 if (clang_isDeclaration(cursor.kind))
5615 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
5616
5617 return CXLanguage_Invalid;
5618}
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005619
5620 /// \brief If the given cursor is the "templated" declaration
5621 /// descibing a class or function template, return the class or
5622 /// function template.
5623static Decl *maybeGetTemplateCursor(Decl *D) {
5624 if (!D)
5625 return 0;
5626
5627 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
5628 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
5629 return FunTmpl;
5630
5631 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
5632 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
5633 return ClassTmpl;
5634
5635 return D;
5636}
5637
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005638CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
5639 if (clang_isDeclaration(cursor.kind)) {
5640 if (Decl *D = getCursorDecl(cursor)) {
5641 DeclContext *DC = D->getDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005642 if (!DC)
5643 return clang_getNullCursor();
5644
5645 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5646 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005647 }
5648 }
5649
5650 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
5651 if (Decl *D = getCursorDecl(cursor))
Ted Kremeneka60ed472010-11-16 08:15:36 +00005652 return MakeCXCursor(D, getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005653 }
5654
5655 return clang_getNullCursor();
5656}
5657
5658CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
5659 if (clang_isDeclaration(cursor.kind)) {
5660 if (Decl *D = getCursorDecl(cursor)) {
5661 DeclContext *DC = D->getLexicalDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005662 if (!DC)
5663 return clang_getNullCursor();
5664
5665 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5666 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005667 }
5668 }
5669
5670 // FIXME: Note that we can't easily compute the lexical context of a
5671 // statement or expression, so we return nothing.
5672 return clang_getNullCursor();
5673}
5674
Douglas Gregorecdcb882010-10-20 22:00:55 +00005675CXFile clang_getIncludedFile(CXCursor cursor) {
5676 if (cursor.kind != CXCursor_InclusionDirective)
5677 return 0;
5678
5679 InclusionDirective *ID = getCursorInclusionDirective(cursor);
5680 return (void *)ID->getFile();
5681}
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +00005682
5683CXSourceRange clang_Cursor_getCommentRange(CXCursor C) {
5684 if (!clang_isDeclaration(C.kind))
5685 return clang_getNullRange();
5686
5687 const Decl *D = getCursorDecl(C);
5688 ASTContext &Context = getCursorContext(C);
5689 const RawComment *RC = Context.getRawCommentForDecl(D);
5690 if (!RC)
5691 return clang_getNullRange();
5692
5693 return cxloc::translateSourceRange(Context, RC->getSourceRange());
5694}
5695
5696CXString clang_Cursor_getRawCommentText(CXCursor C) {
5697 if (!clang_isDeclaration(C.kind))
5698 return createCXString((const char *) NULL);
5699
5700 const Decl *D = getCursorDecl(C);
5701 ASTContext &Context = getCursorContext(C);
5702 const RawComment *RC = Context.getRawCommentForDecl(D);
5703 StringRef RawText = RC ? RC->getRawText(Context.getSourceManager()) :
5704 StringRef();
5705
5706 // Don't duplicate the string because RawText points directly into source
5707 // code.
5708 return createCXString(RawText, false);
5709}
5710
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005711} // end: extern "C"
5712
Dmitri Gribenko2d44d772012-06-26 20:39:18 +00005713CXString clang_Cursor_getBriefCommentText(CXCursor C) {
5714 if (!clang_isDeclaration(C.kind))
5715 return createCXString((const char *) NULL);
5716
5717 const Decl *D = getCursorDecl(C);
5718 const ASTContext &Context = getCursorContext(C);
5719 const RawComment *RC = Context.getRawCommentForDecl(D);
5720
Dmitri Gribenko8376f592012-06-28 16:25:36 +00005721 if (RC) {
Dmitri Gribenko2d44d772012-06-26 20:39:18 +00005722 StringRef BriefText = RC->getBriefText(Context);
5723
5724 // Don't duplicate the string because RawComment ensures that this memory
5725 // will not go away.
5726 return createCXString(BriefText, false);
5727 }
5728
5729 return createCXString((const char *) NULL);
5730}
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005731
5732//===----------------------------------------------------------------------===//
5733// C++ AST instrospection.
5734//===----------------------------------------------------------------------===//
5735
5736extern "C" {
5737unsigned clang_CXXMethod_isStatic(CXCursor C) {
5738 if (!clang_isDeclaration(C.kind))
5739 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00005740
5741 CXXMethodDecl *Method = 0;
5742 Decl *D = cxcursor::getCursorDecl(C);
5743 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5744 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5745 else
5746 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5747 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00005748}
Ted Kremenekb12903e2010-05-18 22:32:15 +00005749
Douglas Gregor211924b2011-05-12 15:17:24 +00005750unsigned clang_CXXMethod_isVirtual(CXCursor C) {
5751 if (!clang_isDeclaration(C.kind))
5752 return 0;
5753
5754 CXXMethodDecl *Method = 0;
5755 Decl *D = cxcursor::getCursorDecl(C);
5756 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5757 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5758 else
5759 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5760 return (Method && Method->isVirtual()) ? 1 : 0;
5761}
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005762} // end: extern "C"
5763
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005764//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00005765// Attribute introspection.
5766//===----------------------------------------------------------------------===//
5767
5768extern "C" {
5769CXType clang_getIBOutletCollectionType(CXCursor C) {
5770 if (C.kind != CXCursor_IBOutletCollectionAttr)
Ted Kremeneka60ed472010-11-16 08:15:36 +00005771 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005772
5773 IBOutletCollectionAttr *A =
5774 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
5775
Argyrios Kyrtzidis18aa2ff2011-09-13 18:49:52 +00005776 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005777}
5778} // end: extern "C"
5779
5780//===----------------------------------------------------------------------===//
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005781// Inspecting memory usage.
5782//===----------------------------------------------------------------------===//
5783
Ted Kremenekf7870022011-04-20 16:41:07 +00005784typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005785
Ted Kremenekf7870022011-04-20 16:41:07 +00005786static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
5787 enum CXTUResourceUsageKind k,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005788 unsigned long amount) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005789 CXTUResourceUsageEntry entry = { k, amount };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005790 entries.push_back(entry);
5791}
5792
5793extern "C" {
5794
Ted Kremenekf7870022011-04-20 16:41:07 +00005795const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005796 const char *str = "";
5797 switch (kind) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005798 case CXTUResourceUsage_AST:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005799 str = "ASTContext: expressions, declarations, and types";
5800 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005801 case CXTUResourceUsage_Identifiers:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005802 str = "ASTContext: identifiers";
5803 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005804 case CXTUResourceUsage_Selectors:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005805 str = "ASTContext: selectors";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005806 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005807 case CXTUResourceUsage_GlobalCompletionResults:
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005808 str = "Code completion: cached global results";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005809 break;
Ted Kremenek457aaf02011-04-28 04:10:31 +00005810 case CXTUResourceUsage_SourceManagerContentCache:
5811 str = "SourceManager: content cache allocator";
5812 break;
Ted Kremenekba29bd22011-04-28 04:53:38 +00005813 case CXTUResourceUsage_AST_SideTables:
5814 str = "ASTContext: side tables";
5815 break;
Ted Kremenekf61b8312011-04-28 20:36:42 +00005816 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
5817 str = "SourceManager: malloc'ed memory buffers";
5818 break;
5819 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
5820 str = "SourceManager: mmap'ed memory buffers";
5821 break;
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005822 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
5823 str = "ExternalASTSource: malloc'ed memory buffers";
5824 break;
5825 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
5826 str = "ExternalASTSource: mmap'ed memory buffers";
5827 break;
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005828 case CXTUResourceUsage_Preprocessor:
5829 str = "Preprocessor: malloc'ed memory";
5830 break;
5831 case CXTUResourceUsage_PreprocessingRecord:
5832 str = "Preprocessor: PreprocessingRecord";
5833 break;
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005834 case CXTUResourceUsage_SourceManager_DataStructures:
5835 str = "SourceManager: data structures and tables";
5836 break;
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005837 case CXTUResourceUsage_Preprocessor_HeaderSearch:
5838 str = "Preprocessor: header search tables";
5839 break;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005840 }
5841 return str;
5842}
5843
Ted Kremenekf7870022011-04-20 16:41:07 +00005844CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005845 if (!TU) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005846 CXTUResourceUsage usage = { (void*) 0, 0, 0 };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005847 return usage;
5848 }
5849
5850 ASTUnit *astUnit = static_cast<ASTUnit*>(TU->TUData);
Dylan Noblesmith1e4c01b2012-02-13 12:32:21 +00005851 OwningPtr<MemUsageEntries> entries(new MemUsageEntries());
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005852 ASTContext &astContext = astUnit->getASTContext();
5853
5854 // How much memory is used by AST nodes and types?
Ted Kremenekf7870022011-04-20 16:41:07 +00005855 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005856 (unsigned long) astContext.getASTAllocatedMemory());
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005857
5858 // How much memory is used by identifiers?
Ted Kremenekf7870022011-04-20 16:41:07 +00005859 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005860 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
5861
5862 // How much memory is used for selectors?
Ted Kremenekf7870022011-04-20 16:41:07 +00005863 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005864 (unsigned long) astContext.Selectors.getTotalMemory());
5865
Ted Kremenekba29bd22011-04-28 04:53:38 +00005866 // How much memory is used by ASTContext's side tables?
5867 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
5868 (unsigned long) astContext.getSideTableAllocatedMemory());
5869
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005870 // How much memory is used for caching global code completion results?
5871 unsigned long completionBytes = 0;
5872 if (GlobalCodeCompletionAllocator *completionAllocator =
5873 astUnit->getCachedCompletionAllocator().getPtr()) {
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005874 completionBytes = completionAllocator->getTotalMemory();
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005875 }
Ted Kremenek457aaf02011-04-28 04:10:31 +00005876 createCXTUResourceUsageEntry(*entries,
5877 CXTUResourceUsage_GlobalCompletionResults,
5878 completionBytes);
5879
5880 // How much memory is being used by SourceManager's content cache?
5881 createCXTUResourceUsageEntry(*entries,
5882 CXTUResourceUsage_SourceManagerContentCache,
5883 (unsigned long) astContext.getSourceManager().getContentCacheSize());
Ted Kremenekf61b8312011-04-28 20:36:42 +00005884
5885 // How much memory is being used by the MemoryBuffer's in SourceManager?
5886 const SourceManager::MemoryBufferSizes &srcBufs =
5887 astUnit->getSourceManager().getMemoryBufferSizes();
5888
5889 createCXTUResourceUsageEntry(*entries,
5890 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
5891 (unsigned long) srcBufs.malloc_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005892 createCXTUResourceUsageEntry(*entries,
Ted Kremenekf61b8312011-04-28 20:36:42 +00005893 CXTUResourceUsage_SourceManager_Membuffer_MMap,
5894 (unsigned long) srcBufs.mmap_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005895 createCXTUResourceUsageEntry(*entries,
5896 CXTUResourceUsage_SourceManager_DataStructures,
5897 (unsigned long) astContext.getSourceManager()
5898 .getDataStructureSizes());
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005899
5900 // How much memory is being used by the ExternalASTSource?
5901 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
5902 const ExternalASTSource::MemoryBufferSizes &sizes =
5903 esrc->getMemoryBufferSizes();
5904
5905 createCXTUResourceUsageEntry(*entries,
5906 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
5907 (unsigned long) sizes.malloc_bytes);
5908 createCXTUResourceUsageEntry(*entries,
5909 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
5910 (unsigned long) sizes.mmap_bytes);
5911 }
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005912
5913 // How much memory is being used by the Preprocessor?
5914 Preprocessor &pp = astUnit->getPreprocessor();
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005915 createCXTUResourceUsageEntry(*entries,
5916 CXTUResourceUsage_Preprocessor,
Argyrios Kyrtzidisc5c5e922011-06-29 22:20:04 +00005917 pp.getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005918
5919 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
5920 createCXTUResourceUsageEntry(*entries,
5921 CXTUResourceUsage_PreprocessingRecord,
5922 pRec->getTotalMemory());
5923 }
5924
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005925 createCXTUResourceUsageEntry(*entries,
5926 CXTUResourceUsage_Preprocessor_HeaderSearch,
5927 pp.getHeaderSearchInfo().getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005928
Ted Kremenekf7870022011-04-20 16:41:07 +00005929 CXTUResourceUsage usage = { (void*) entries.get(),
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005930 (unsigned) entries->size(),
5931 entries->size() ? &(*entries)[0] : 0 };
5932 entries.take();
5933 return usage;
5934}
5935
Ted Kremenekf7870022011-04-20 16:41:07 +00005936void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005937 if (usage.data)
5938 delete (MemUsageEntries*) usage.data;
5939}
5940
5941} // end extern "C"
5942
Douglas Gregor6df78732011-05-05 20:27:22 +00005943void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
5944 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
5945 for (unsigned I = 0; I != Usage.numEntries; ++I)
5946 fprintf(stderr, " %s: %lu\n",
5947 clang_getTUResourceUsageName(Usage.entries[I].kind),
5948 Usage.entries[I].amount);
5949
5950 clang_disposeCXTUResourceUsage(Usage);
5951}
5952
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005953//===----------------------------------------------------------------------===//
Ted Kremenek04bb7162010-01-22 22:44:15 +00005954// Misc. utility functions.
5955//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00005956
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00005957/// Default to using an 8 MB stack size on "safety" threads.
5958static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005959
5960namespace clang {
5961
5962bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005963 void (*Fn)(void*), void *UserData,
5964 unsigned Size) {
5965 if (!Size)
5966 Size = GetSafetyThreadStackSize();
5967 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005968 return CRC.RunSafelyOnThread(Fn, UserData, Size);
5969 return CRC.RunSafely(Fn, UserData);
5970}
5971
5972unsigned GetSafetyThreadStackSize() {
5973 return SafetyStackThreadSize;
5974}
5975
5976void SetSafetyThreadStackSize(unsigned Value) {
5977 SafetyStackThreadSize = Value;
5978}
5979
Argyrios Kyrtzidis8e7c48a2012-03-28 02:49:50 +00005980}
5981
Argyrios Kyrtzidis81b5ac32012-03-28 02:49:54 +00005982void clang::setThreadBackgroundPriority() {
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00005983 // FIXME: Move to llvm/Support and make it cross-platform.
5984#ifdef __APPLE__
5985 setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG);
5986#endif
5987}
5988
Argyrios Kyrtzidis97934282012-04-11 03:52:18 +00005989void cxindex::printDiagsToStderr(ASTUnit *Unit) {
5990 if (!Unit)
5991 return;
5992
5993 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
5994 DEnd = Unit->stored_diag_end();
5995 D != DEnd; ++D) {
5996 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOpts());
5997 CXString Msg = clang_formatDiagnostic(&Diag,
5998 clang_defaultDiagnosticDisplayOptions());
5999 fprintf(stderr, "%s\n", clang_getCString(Msg));
6000 clang_disposeString(Msg);
6001 }
6002#ifdef LLVM_ON_WIN32
6003 // On Windows, force a flush, since there may be multiple copies of
6004 // stderr and stdout in the file system, all with different buffers
6005 // but writing to the same device.
6006 fflush(stderr);
6007#endif
6008}
6009
Ted Kremenek04bb7162010-01-22 22:44:15 +00006010extern "C" {
6011
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00006012CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00006013 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00006014}
6015
6016} // end: extern "C"
Ted Kremenek59fc1e52011-04-18 22:47:10 +00006017