blob: 25d0c5b6da12bea2c9fdcfeb45ed6652a720864c [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"
Ted Kremenekd8c370c2010-11-02 23:10:24 +000038#include "clang/Analysis/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;
Steve Naroff50398192009-08-28 15:28:48 +000054
Argyrios Kyrtzidis9049cf62011-10-12 07:07:33 +000055CXTranslationUnit cxtu::MakeCXTranslationUnit(ASTUnit *TU) {
Ted Kremeneka60ed472010-11-16 08:15:36 +000056 if (!TU)
57 return 0;
58 CXTranslationUnit D = new CXTranslationUnitImpl();
59 D->TUData = TU;
60 D->StringPool = createCXStringPool();
Ted Kremenek15322172011-11-10 08:43:12 +000061 D->Diagnostics = 0;
Ted Kremeneka60ed472010-11-16 08:15:36 +000062 return D;
63}
64
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +000065cxtu::CXTUOwner::~CXTUOwner() {
66 if (TU)
67 clang_disposeTranslationUnit(TU);
68}
69
Ted Kremenekf0e23e82010-02-17 00:41:40 +000070/// \brief Compare two source ranges to determine their relative position in
Douglas Gregor33e9abd2010-01-22 19:49:59 +000071/// the translation unit.
Ted Kremenekf0e23e82010-02-17 00:41:40 +000072static RangeComparisonResult RangeCompare(SourceManager &SM,
73 SourceRange R1,
Douglas Gregor33e9abd2010-01-22 19:49:59 +000074 SourceRange R2) {
75 assert(R1.isValid() && "First range is invalid?");
76 assert(R2.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000077 if (R1.getEnd() != R2.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000078 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000079 return RangeBefore;
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000080 if (R2.getEnd() != R1.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000081 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000082 return RangeAfter;
83 return RangeOverlap;
84}
85
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000086/// \brief Determine if a source location falls within, before, or after a
87/// a given source range.
88static RangeComparisonResult LocationCompare(SourceManager &SM,
89 SourceLocation L, SourceRange R) {
90 assert(R.isValid() && "First range is invalid?");
91 assert(L.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000092 if (L == R.getBegin() || L == R.getEnd())
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000093 return RangeOverlap;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000094 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
95 return RangeBefore;
96 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
97 return RangeAfter;
98 return RangeOverlap;
99}
100
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000101/// \brief Translate a Clang source range into a CIndex source range.
102///
103/// Clang internally represents ranges where the end location points to the
104/// start of the token at the end. However, for external clients it is more
105/// useful to have a CXSourceRange be a proper half-open interval. This routine
106/// does the appropriate translation.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000107CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000108 const LangOptions &LangOpts,
Chris Lattner0a76aae2010-06-18 22:45:06 +0000109 const CharSourceRange &R) {
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000110 // We want the last character in this location, so we will adjust the
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000111 // location accordingly.
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000112 SourceLocation EndLoc = R.getEnd();
Douglas Gregora9b06d42010-11-09 06:24:54 +0000113 if (EndLoc.isValid() && EndLoc.isMacroID())
Chandler Carruthedc3dcc2011-07-25 16:56:02 +0000114 EndLoc = SM.getExpansionRange(EndLoc).second;
Chris Lattner0a76aae2010-06-18 22:45:06 +0000115 if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) {
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000116 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000117 EndLoc = EndLoc.getLocWithOffset(Length);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000118 }
119
120 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
121 R.getBegin().getRawEncoding(),
122 EndLoc.getRawEncoding() };
123 return Result;
124}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000125
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000126//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000127// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000128//===----------------------------------------------------------------------===//
129
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000130static SourceRange getRawCursorExtent(CXCursor C);
Douglas Gregor66537982010-11-17 17:14:07 +0000131static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
132
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000133
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000134RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000135 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000136}
137
Douglas Gregorb1373d02010-01-20 20:59:29 +0000138/// \brief Visit the given cursor and, if requested by the visitor,
139/// its children.
140///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000141/// \param Cursor the cursor to visit.
142///
143/// \param CheckRegionOfInterest if true, then the caller already checked that
144/// this cursor is within the region of interest.
145///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000146/// \returns true if the visitation should be aborted, false if it
147/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000148bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000149 if (clang_isInvalid(Cursor.kind))
150 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000151
Douglas Gregorb1373d02010-01-20 20:59:29 +0000152 if (clang_isDeclaration(Cursor.kind)) {
153 Decl *D = getCursorDecl(Cursor);
154 assert(D && "Invalid declaration cursor");
Argyrios Kyrtzidis65ab9072011-09-26 19:05:37 +0000155 // Ignore implicit declarations, unless it's an objc method because
156 // currently we should report implicit methods for properties when indexing.
157 if (D->isImplicit() && !isa<ObjCMethodDecl>(D))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000158 return false;
159 }
160
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000161 // If we have a range of interest, and this cursor doesn't intersect with it,
162 // we're done.
163 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000164 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000165 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000166 return false;
167 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000168
Douglas Gregorb1373d02010-01-20 20:59:29 +0000169 switch (Visitor(Cursor, Parent, ClientData)) {
170 case CXChildVisit_Break:
171 return true;
172
173 case CXChildVisit_Continue:
174 return false;
175
176 case CXChildVisit_Recurse:
177 return VisitChildren(Cursor);
178 }
179
Douglas Gregorfd643772010-01-25 16:45:46 +0000180 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000181}
182
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000183static bool visitPreprocessedEntitiesInRange(SourceRange R,
184 PreprocessingRecord &PPRec,
185 CursorVisitor &Visitor) {
186 SourceManager &SM = Visitor.getASTUnit()->getSourceManager();
187 FileID FID;
188
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +0000189 if (!Visitor.shouldVisitIncludedEntities()) {
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000190 // If the begin/end of the range lie in the same FileID, do the optimization
191 // where we skip preprocessed entities that do not come from the same FileID.
192 FID = SM.getFileID(R.getBegin());
193 if (FID != SM.getFileID(R.getEnd()))
194 FID = FileID();
195 }
196
197 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
198 Entities = PPRec.getPreprocessedEntitiesInRange(R);
199 return Visitor.visitPreprocessedEntities(Entities.first, Entities.second,
200 PPRec, FID);
201}
202
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000203void CursorVisitor::visitFileRegion() {
204 if (RegionOfInterest.isInvalid())
205 return;
206
207 ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData);
208 SourceManager &SM = Unit->getSourceManager();
209
210 std::pair<FileID, unsigned>
211 Begin = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getBegin())),
212 End = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getEnd()));
213
214 if (End.first != Begin.first) {
215 // If the end does not reside in the same file, try to recover by
216 // picking the end of the file of begin location.
217 End.first = Begin.first;
218 End.second = SM.getFileIDSize(Begin.first);
219 }
220
221 assert(Begin.first == End.first);
222 if (Begin.second > End.second)
223 return;
224
225 FileID File = Begin.first;
226 unsigned Offset = Begin.second;
227 unsigned Length = End.second - Begin.second;
228
229 if (!VisitPreprocessorLast &&
230 Unit->getPreprocessor().getPreprocessingRecord())
231 visitPreprocessedEntitiesInRegion();
232
233 visitDeclsFromFileRegion(File, Offset, Length);
234
235 if (VisitPreprocessorLast &&
236 Unit->getPreprocessor().getPreprocessingRecord())
237 visitPreprocessedEntitiesInRegion();
238}
239
Argyrios Kyrtzidise2079cf2011-11-16 08:58:54 +0000240static bool isInLexicalContext(Decl *D, DeclContext *DC) {
241 if (!DC)
242 return false;
243
244 for (DeclContext *DeclDC = D->getLexicalDeclContext();
245 DeclDC; DeclDC = DeclDC->getLexicalParent()) {
246 if (DeclDC == DC)
247 return true;
248 }
249 return false;
250}
251
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000252void CursorVisitor::visitDeclsFromFileRegion(FileID File,
253 unsigned Offset, unsigned Length) {
254 ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData);
255 SourceManager &SM = Unit->getSourceManager();
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000256 SourceRange Range = RegionOfInterest;
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000257
258 SmallVector<Decl *, 16> Decls;
259 Unit->findFileRegionDecls(File, Offset, Length, Decls);
260
261 // If we didn't find any file level decls for the file, try looking at the
262 // file that it was included from.
263 while (Decls.empty()) {
264 bool Invalid = false;
265 const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid);
266 if (Invalid)
267 return;
268
269 SourceLocation Outer;
270 if (SLEntry.isFile())
271 Outer = SLEntry.getFile().getIncludeLoc();
272 else
273 Outer = SLEntry.getExpansion().getExpansionLocStart();
274 if (Outer.isInvalid())
275 return;
276
277 llvm::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer);
278 Length = 0;
279 Unit->findFileRegionDecls(File, Offset, Length, Decls);
280 }
281
282 assert(!Decls.empty());
283
284 bool VisitedAtLeastOnce = false;
Argyrios Kyrtzidise2079cf2011-11-16 08:58:54 +0000285 DeclContext *CurDC = 0;
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000286 SmallVector<Decl *, 16>::iterator DIt = Decls.begin();
287 for (SmallVector<Decl *, 16>::iterator DE = Decls.end(); DIt != DE; ++DIt) {
288 Decl *D = *DIt;
289
Argyrios Kyrtzidise2079cf2011-11-16 08:58:54 +0000290 if (isInLexicalContext(D, CurDC))
291 continue;
292
293 CurDC = dyn_cast<DeclContext>(D);
294
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000295 // We handle forward decls via ObjCClassDecl.
296 if (ObjCInterfaceDecl *InterD = dyn_cast<ObjCInterfaceDecl>(D)) {
297 if (InterD->isForwardDecl())
298 continue;
299 // An interface that started as a forward decl may have changed location
300 // because its @interface was parsed.
301 if (InterD->isInitiallyForwardDecl() &&
302 !SM.isInFileID(SM.getFileLoc(InterD->getLocation()), File))
303 continue;
304 }
305
Argyrios Kyrtzidise2079cf2011-11-16 08:58:54 +0000306 if (TagDecl *TD = dyn_cast<TagDecl>(D))
307 if (!TD->isFreeStanding())
308 continue;
309
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000310 RangeComparisonResult CompRes = RangeCompare(SM, D->getSourceRange(),Range);
311 if (CompRes == RangeBefore)
312 continue;
313 if (CompRes == RangeAfter)
314 break;
315
316 assert(CompRes == RangeOverlap);
317 VisitedAtLeastOnce = true;
Argyrios Kyrtzidisba986172011-11-03 19:02:28 +0000318 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000319 break;
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000320 }
321
322 if (VisitedAtLeastOnce)
323 return;
324
325 // No Decls overlapped with the range. Move up the lexical context until there
326 // is a context that contains the range or we reach the translation unit
327 // level.
328 DeclContext *DC = DIt == Decls.begin() ? (*DIt)->getLexicalDeclContext()
329 : (*(DIt-1))->getLexicalDeclContext();
330
331 while (DC && !DC->isTranslationUnit()) {
332 Decl *D = cast<Decl>(DC);
333 SourceRange CurDeclRange = D->getSourceRange();
334 if (CurDeclRange.isInvalid())
335 break;
336
337 if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) {
Argyrios Kyrtzidisba986172011-11-03 19:02:28 +0000338 Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true);
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000339 break;
340 }
341
342 DC = D->getLexicalDeclContext();
343 }
344}
345
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000346bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
Douglas Gregor788f5a12010-03-20 00:41:21 +0000347 PreprocessingRecord &PPRec
Ted Kremeneka60ed472010-11-16 08:15:36 +0000348 = *AU->getPreprocessor().getPreprocessingRecord();
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000349 SourceManager &SM = AU->getSourceManager();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000350
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000351 if (RegionOfInterest.isValid()) {
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +0000352 SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000353 SourceLocation B = MappedRange.getBegin();
354 SourceLocation E = MappedRange.getEnd();
355
356 if (AU->isInPreambleFileID(B)) {
357 if (SM.isLoadedSourceLocation(E))
358 return visitPreprocessedEntitiesInRange(SourceRange(B, E),
359 PPRec, *this);
360
361 // Beginning of range lies in the preamble but it also extends beyond
362 // it into the main file. Split the range into 2 parts, one covering
363 // the preamble and another covering the main file. This allows subsequent
364 // calls to visitPreprocessedEntitiesInRange to accept a source range that
365 // lies in the same FileID, allowing it to skip preprocessed entities that
366 // do not come from the same FileID.
367 bool breaked =
368 visitPreprocessedEntitiesInRange(
369 SourceRange(B, AU->getEndOfPreambleFileID()),
370 PPRec, *this);
371 if (breaked) return true;
372 return visitPreprocessedEntitiesInRange(
373 SourceRange(AU->getStartOfMainFileID(), E),
374 PPRec, *this);
375 }
376
377 return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this);
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000378 }
379
Douglas Gregor788f5a12010-03-20 00:41:21 +0000380 bool OnlyLocalDecls
Douglas Gregor32038bb2010-12-21 19:07:48 +0000381 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
382
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000383 if (OnlyLocalDecls)
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000384 return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(),
385 PPRec);
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000386
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000387 return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec);
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000388}
389
390template<typename InputIterator>
391bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000392 InputIterator Last,
393 PreprocessingRecord &PPRec,
394 FileID FID) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000395 for (; First != Last; ++First) {
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000396 if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID))
397 continue;
398
399 PreprocessedEntity *PPE = *First;
400 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000401 if (Visit(MakeMacroExpansionCursor(ME, TU)))
402 return true;
403
404 continue;
405 }
406
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000407 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(PPE)) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000408 if (Visit(MakeMacroDefinitionCursor(MD, TU)))
409 return true;
410
411 continue;
412 }
413
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000414 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000415 if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
416 return true;
417
418 continue;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000419 }
420 }
421
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000422 return false;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000423}
424
Douglas Gregorb1373d02010-01-20 20:59:29 +0000425/// \brief Visit the children of the given cursor.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000426///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000427/// \returns true if the visitation should be aborted, false if it
428/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000429bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregorc314aa42011-03-02 19:17:03 +0000430 if (clang_isReference(Cursor.kind) &&
431 Cursor.kind != CXCursor_CXXBaseSpecifier) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000432 // By definition, references have no children.
433 return false;
434 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000435
436 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000437 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000438 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000439
Douglas Gregorb1373d02010-01-20 20:59:29 +0000440 if (clang_isDeclaration(Cursor.kind)) {
441 Decl *D = getCursorDecl(Cursor);
Douglas Gregor06d9b1a2011-04-14 21:41:34 +0000442 if (!D)
443 return false;
444
Ted Kremenek539311e2010-02-18 18:47:01 +0000445 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000446 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000447
Douglas Gregor06d9b1a2011-04-14 21:41:34 +0000448 if (clang_isStatement(Cursor.kind)) {
449 if (Stmt *S = getCursorStmt(Cursor))
450 return Visit(S);
451
452 return false;
453 }
454
455 if (clang_isExpression(Cursor.kind)) {
456 if (Expr *E = getCursorExpr(Cursor))
457 return Visit(E);
458
459 return false;
460 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000461
Douglas Gregorb1373d02010-01-20 20:59:29 +0000462 if (clang_isTranslationUnit(Cursor.kind)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000463 CXTranslationUnit tu = getCursorTU(Cursor);
464 ASTUnit *CXXUnit = static_cast<ASTUnit*>(tu->TUData);
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000465
466 int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
467 for (unsigned I = 0; I != 2; ++I) {
468 if (VisitOrder[I]) {
469 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
470 RegionOfInterest.isInvalid()) {
471 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
472 TLEnd = CXXUnit->top_level_end();
473 TL != TLEnd; ++TL) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000474 if (Visit(MakeCXCursor(*TL, tu, RegionOfInterest), true))
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000475 return true;
476 }
477 } else if (VisitDeclContext(
478 CXXUnit->getASTContext().getTranslationUnitDecl()))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000479 return true;
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000480 continue;
Douglas Gregor7b691f332010-01-20 21:13:59 +0000481 }
Bob Wilson3178cb62010-03-19 03:57:57 +0000482
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000483 // Walk the preprocessing record.
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000484 if (CXXUnit->getPreprocessor().getPreprocessingRecord())
485 visitPreprocessedEntitiesInRegion();
Douglas Gregor0396f462010-03-19 05:22:59 +0000486 }
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000487
Douglas Gregor7b691f332010-01-20 21:13:59 +0000488 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000489 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000490
Douglas Gregorc314aa42011-03-02 19:17:03 +0000491 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
492 if (CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
493 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
494 return Visit(BaseTSInfo->getTypeLoc());
495 }
496 }
497 }
Argyrios Kyrtzidis221d5a52011-09-13 18:49:56 +0000498
499 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
500 IBOutletCollectionAttr *A =
501 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
502 if (const ObjCInterfaceType *InterT = A->getInterface()->getAs<ObjCInterfaceType>())
503 return Visit(cxcursor::MakeCursorObjCClassRef(InterT->getInterface(),
504 A->getInterfaceLoc(), TU));
505 }
506
Douglas Gregorb1373d02010-01-20 20:59:29 +0000507 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000508 return false;
509}
510
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000511bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
Douglas Gregor13c8ccb2011-04-22 23:49:24 +0000512 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
513 if (Visit(TSInfo->getTypeLoc()))
514 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000515
Ted Kremenek664cffd2010-07-22 11:30:19 +0000516 if (Stmt *Body = B->getBody())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000517 return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest));
Ted Kremenek664cffd2010-07-22 11:30:19 +0000518
519 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000520}
521
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000522llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
523 if (RegionOfInterest.isValid()) {
Douglas Gregor66537982010-11-17 17:14:07 +0000524 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000525 if (Range.isInvalid())
526 return llvm::Optional<bool>();
Douglas Gregor66537982010-11-17 17:14:07 +0000527
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000528 switch (CompareRegionOfInterest(Range)) {
529 case RangeBefore:
530 // This declaration comes before the region of interest; skip it.
531 return llvm::Optional<bool>();
532
533 case RangeAfter:
534 // This declaration comes after the region of interest; we're done.
535 return false;
536
537 case RangeOverlap:
538 // This declaration overlaps the region of interest; visit it.
539 break;
540 }
541 }
542 return true;
543}
544
545bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
546 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
547
548 // FIXME: Eventually remove. This part of a hack to support proper
549 // iteration over all Decls contained lexically within an ObjC container.
550 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
551 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
552
553 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000554 Decl *D = *I;
555 if (D->getLexicalDeclContext() != DC)
556 continue;
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000557 CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000558 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
559 if (!V.hasValue())
560 continue;
561 if (!V.getValue())
562 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000563 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000564 return true;
565 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000566 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000567}
568
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000569bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
570 llvm_unreachable("Translation units are visited directly by Visit()");
571 return false;
572}
573
Richard Smith162e1c12011-04-15 14:24:37 +0000574bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
575 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
576 return Visit(TSInfo->getTypeLoc());
577
578 return false;
579}
580
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000581bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
582 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
583 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000584
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000585 return false;
586}
587
588bool CursorVisitor::VisitTagDecl(TagDecl *D) {
589 return VisitDeclContext(D);
590}
591
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000592bool CursorVisitor::VisitClassTemplateSpecializationDecl(
593 ClassTemplateSpecializationDecl *D) {
594 bool ShouldVisitBody = false;
595 switch (D->getSpecializationKind()) {
596 case TSK_Undeclared:
597 case TSK_ImplicitInstantiation:
598 // Nothing to visit
599 return false;
600
601 case TSK_ExplicitInstantiationDeclaration:
602 case TSK_ExplicitInstantiationDefinition:
603 break;
604
605 case TSK_ExplicitSpecialization:
606 ShouldVisitBody = true;
607 break;
608 }
609
610 // Visit the template arguments used in the specialization.
611 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
612 TypeLoc TL = SpecType->getTypeLoc();
613 if (TemplateSpecializationTypeLoc *TSTLoc
614 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
615 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
616 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
617 return true;
618 }
619 }
620
621 if (ShouldVisitBody && VisitCXXRecordDecl(D))
622 return true;
623
624 return false;
625}
626
Douglas Gregor74dbe642010-08-31 19:31:58 +0000627bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
628 ClassTemplatePartialSpecializationDecl *D) {
629 // FIXME: Visit the "outer" template parameter lists on the TagDecl
630 // before visiting these template parameters.
631 if (VisitTemplateParameters(D->getTemplateParameters()))
632 return true;
633
634 // Visit the partial specialization arguments.
635 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
636 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
637 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
638 return true;
639
640 return VisitCXXRecordDecl(D);
641}
642
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000643bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000644 // Visit the default argument.
645 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
646 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
647 if (Visit(DefArg->getTypeLoc()))
648 return true;
649
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000650 return false;
651}
652
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000653bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
654 if (Expr *Init = D->getInitExpr())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000655 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000656 return false;
657}
658
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000659bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
660 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
661 if (Visit(TSInfo->getTypeLoc()))
662 return true;
663
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000664 // Visit the nested-name-specifier, if present.
665 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
666 if (VisitNestedNameSpecifierLoc(QualifierLoc))
667 return true;
668
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000669 return false;
670}
671
Douglas Gregora67e03f2010-09-09 21:42:20 +0000672/// \brief Compare two base or member initializers based on their source order.
Sean Huntcbb67482011-01-08 20:30:50 +0000673static int CompareCXXCtorInitializers(const void* Xp, const void *Yp) {
674 CXXCtorInitializer const * const *X
675 = static_cast<CXXCtorInitializer const * const *>(Xp);
676 CXXCtorInitializer const * const *Y
677 = static_cast<CXXCtorInitializer const * const *>(Yp);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000678
679 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
680 return -1;
681 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
682 return 1;
683 else
684 return 0;
685}
686
Douglas Gregorb1373d02010-01-20 20:59:29 +0000687bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000688 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
689 // Visit the function declaration's syntactic components in the order
690 // written. This requires a bit of work.
Abramo Bagnara723df242010-12-14 22:11:44 +0000691 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
Douglas Gregor01829d32010-08-31 14:41:23 +0000692 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
693
694 // If we have a function declared directly (without the use of a typedef),
695 // visit just the return type. Otherwise, just visit the function's type
696 // now.
697 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
698 (!FTL && Visit(TL)))
699 return true;
700
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000701 // Visit the nested-name-specifier, if present.
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000702 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
703 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000704 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000705
706 // Visit the declaration name.
707 if (VisitDeclarationNameInfo(ND->getNameInfo()))
708 return true;
709
710 // FIXME: Visit explicitly-specified template arguments!
711
712 // Visit the function parameters, if we have a function type.
713 if (FTL && VisitFunctionTypeLoc(*FTL, true))
714 return true;
715
716 // FIXME: Attributes?
717 }
718
Sean Hunt10620eb2011-05-06 20:44:56 +0000719 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
Douglas Gregora67e03f2010-09-09 21:42:20 +0000720 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
721 // Find the initializers that were written in the source.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000722 SmallVector<CXXCtorInitializer *, 4> WrittenInits;
Douglas Gregora67e03f2010-09-09 21:42:20 +0000723 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
724 IEnd = Constructor->init_end();
725 I != IEnd; ++I) {
726 if (!(*I)->isWritten())
727 continue;
728
729 WrittenInits.push_back(*I);
730 }
731
732 // Sort the initializers in source order
733 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
Sean Huntcbb67482011-01-08 20:30:50 +0000734 &CompareCXXCtorInitializers);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000735
736 // Visit the initializers in source order
737 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
Sean Huntcbb67482011-01-08 20:30:50 +0000738 CXXCtorInitializer *Init = WrittenInits[I];
Francois Pichet00eb3f92010-12-04 09:14:42 +0000739 if (Init->isAnyMemberInitializer()) {
740 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
Douglas Gregora67e03f2010-09-09 21:42:20 +0000741 Init->getMemberLocation(), TU)))
742 return true;
Douglas Gregor76852c22011-11-01 01:16:03 +0000743 } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) {
744 if (Visit(TInfo->getTypeLoc()))
Douglas Gregora67e03f2010-09-09 21:42:20 +0000745 return true;
746 }
747
748 // Visit the initializer value.
749 if (Expr *Initializer = Init->getInit())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000750 if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
Douglas Gregora67e03f2010-09-09 21:42:20 +0000751 return true;
752 }
753 }
754
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000755 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
Douglas Gregora67e03f2010-09-09 21:42:20 +0000756 return true;
757 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000758
Douglas Gregorb1373d02010-01-20 20:59:29 +0000759 return false;
760}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000761
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000762bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
763 if (VisitDeclaratorDecl(D))
764 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000765
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000766 if (Expr *BitWidth = D->getBitWidth())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000767 return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000768
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000769 return false;
770}
771
772bool CursorVisitor::VisitVarDecl(VarDecl *D) {
773 if (VisitDeclaratorDecl(D))
774 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000775
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000776 if (Expr *Init = D->getInit())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000777 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000778
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000779 return false;
780}
781
Douglas Gregor84b51d72010-09-01 20:16:53 +0000782bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
783 if (VisitDeclaratorDecl(D))
784 return true;
785
786 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
787 if (Expr *DefArg = D->getDefaultArgument())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000788 return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
Douglas Gregor84b51d72010-09-01 20:16:53 +0000789
790 return false;
791}
792
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000793bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
794 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
795 // before visiting these template parameters.
796 if (VisitTemplateParameters(D->getTemplateParameters()))
797 return true;
798
799 return VisitFunctionDecl(D->getTemplatedDecl());
800}
801
Douglas Gregor39d6f072010-08-31 19:02:00 +0000802bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
803 // FIXME: Visit the "outer" template parameter lists on the TagDecl
804 // before visiting these template parameters.
805 if (VisitTemplateParameters(D->getTemplateParameters()))
806 return true;
807
808 return VisitCXXRecordDecl(D->getTemplatedDecl());
809}
810
Douglas Gregor84b51d72010-09-01 20:16:53 +0000811bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
812 if (VisitTemplateParameters(D->getTemplateParameters()))
813 return true;
814
815 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
816 VisitTemplateArgumentLoc(D->getDefaultArgument()))
817 return true;
818
819 return false;
820}
821
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000822bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000823 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
824 if (Visit(TSInfo->getTypeLoc()))
825 return true;
826
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000827 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000828 PEnd = ND->param_end();
829 P != PEnd; ++P) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000830 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000831 return true;
832 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000833
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000834 if (ND->isThisDeclarationADefinition() &&
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000835 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000836 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000837
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000838 return false;
839}
840
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000841namespace {
842 struct ContainerDeclsSort {
843 SourceManager &SM;
844 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
845 bool operator()(Decl *A, Decl *B) {
846 SourceLocation L_A = A->getLocStart();
847 SourceLocation L_B = B->getLocStart();
848 assert(L_A.isValid() && L_B.isValid());
849 return SM.isBeforeInTranslationUnit(L_A, L_B);
850 }
851 };
852}
853
Douglas Gregora59e3902010-01-21 23:27:09 +0000854bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000855 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
856 // an @implementation can lexically contain Decls that are not properly
857 // nested in the AST. When we identify such cases, we need to retrofit
858 // this nesting here.
859 if (!DI_current)
860 return VisitDeclContext(D);
861
862 // Scan the Decls that immediately come after the container
863 // in the current DeclContext. If any fall within the
864 // container's lexical region, stash them into a vector
865 // for later processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000866 SmallVector<Decl *, 24> DeclsInContainer;
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000867 SourceLocation EndLoc = D->getSourceRange().getEnd();
Ted Kremeneka60ed472010-11-16 08:15:36 +0000868 SourceManager &SM = AU->getSourceManager();
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000869 if (EndLoc.isValid()) {
870 DeclContext::decl_iterator next = *DI_current;
871 while (++next != DE_current) {
872 Decl *D_next = *next;
873 if (!D_next)
874 break;
875 SourceLocation L = D_next->getLocStart();
876 if (!L.isValid())
877 break;
878 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
879 *DI_current = next;
880 DeclsInContainer.push_back(D_next);
881 continue;
882 }
883 break;
884 }
885 }
886
887 // The common case.
888 if (DeclsInContainer.empty())
889 return VisitDeclContext(D);
890
891 // Get all the Decls in the DeclContext, and sort them with the
892 // additional ones we've collected. Then visit them.
893 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
894 I!=E; ++I) {
895 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000896 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
897 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000898 continue;
899 DeclsInContainer.push_back(subDecl);
900 }
901
902 // Now sort the Decls so that they appear in lexical order.
903 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
904 ContainerDeclsSort(SM));
905
906 // Now visit the decls.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000907 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000908 E = DeclsInContainer.end(); I != E; ++I) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000909 CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000910 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
911 if (!V.hasValue())
912 continue;
913 if (!V.getValue())
914 return false;
915 if (Visit(Cursor, true))
916 return true;
917 }
918 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000919}
920
Douglas Gregorb1373d02010-01-20 20:59:29 +0000921bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000922 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
923 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000924 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000925
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000926 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
927 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
928 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000929 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000930 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000931
Douglas Gregora59e3902010-01-21 23:27:09 +0000932 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000933}
934
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000935bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
936 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
937 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
938 E = PID->protocol_end(); I != E; ++I, ++PL)
939 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
940 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000941
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000942 return VisitObjCContainerDecl(PID);
943}
944
Ted Kremenek23173d72010-05-18 21:09:07 +0000945bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000946 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000947 return true;
948
Ted Kremenek23173d72010-05-18 21:09:07 +0000949 // FIXME: This implements a workaround with @property declarations also being
950 // installed in the DeclContext for the @interface. Eventually this code
951 // should be removed.
952 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
953 if (!CDecl || !CDecl->IsClassExtension())
954 return false;
955
956 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
957 if (!ID)
958 return false;
959
960 IdentifierInfo *PropertyId = PD->getIdentifier();
961 ObjCPropertyDecl *prevDecl =
962 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
963
964 if (!prevDecl)
965 return false;
966
967 // Visit synthesized methods since they will be skipped when visiting
968 // the @interface.
969 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000970 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000971 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
Ted Kremenek23173d72010-05-18 21:09:07 +0000972 return true;
973
974 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000975 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000976 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
Ted Kremenek23173d72010-05-18 21:09:07 +0000977 return true;
978
979 return false;
980}
981
Douglas Gregorb1373d02010-01-20 20:59:29 +0000982bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000983 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000984 if (D->getSuperClass() &&
985 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000986 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000987 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000988 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000989
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000990 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
991 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
992 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000993 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000994 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000995
Douglas Gregora59e3902010-01-21 23:27:09 +0000996 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000997}
998
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000999bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1000 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001001}
1002
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001003bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +00001004 // 'ID' could be null when dealing with invalid code.
1005 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1006 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1007 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001008
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001009 return VisitObjCImplDecl(D);
1010}
1011
1012bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1013#if 0
1014 // Issue callbacks for super class.
1015 // FIXME: No source location information!
1016 if (D->getSuperClass() &&
1017 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001018 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001019 TU)))
1020 return true;
1021#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001022
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001023 return VisitObjCImplDecl(D);
1024}
1025
1026bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1027 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1028 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1029 E = D->protocol_end();
1030 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001031 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001032 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001033
1034 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001035}
1036
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001037bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00001038 if (Visit(MakeCursorObjCClassRef(D->getForwardInterfaceDecl(),
1039 D->getForwardDecl()->getLocation(), TU)))
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001040 return true;
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001041 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001042}
1043
Douglas Gregora4ffd852010-11-17 01:03:52 +00001044bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1045 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1046 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1047
1048 return false;
1049}
1050
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001051bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1052 return VisitDeclContext(D);
1053}
1054
Douglas Gregor69319002010-08-31 23:48:11 +00001055bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001056 // Visit nested-name-specifier.
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00001057 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1058 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001059 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001060
1061 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1062 D->getTargetNameLoc(), TU));
1063}
1064
Douglas Gregor7e242562010-09-01 19:52:22 +00001065bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001066 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001067 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1068 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001069 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001070 }
Douglas Gregor7e242562010-09-01 19:52:22 +00001071
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001072 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1073 return true;
1074
Douglas Gregor7e242562010-09-01 19:52:22 +00001075 return VisitDeclarationNameInfo(D->getNameInfo());
1076}
1077
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001078bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001079 // Visit nested-name-specifier.
Douglas Gregordb992412011-02-25 16:33:46 +00001080 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1081 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001082 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001083
1084 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1085 D->getIdentLocation(), TU));
1086}
1087
Douglas Gregor7e242562010-09-01 19:52:22 +00001088bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001089 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001090 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1091 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001092 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001093 }
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001094
Douglas Gregor7e242562010-09-01 19:52:22 +00001095 return VisitDeclarationNameInfo(D->getNameInfo());
1096}
1097
1098bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1099 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001100 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001101 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1102 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001103 return true;
1104
Douglas Gregor7e242562010-09-01 19:52:22 +00001105 return false;
1106}
1107
Douglas Gregor01829d32010-08-31 14:41:23 +00001108bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1109 switch (Name.getName().getNameKind()) {
1110 case clang::DeclarationName::Identifier:
1111 case clang::DeclarationName::CXXLiteralOperatorName:
1112 case clang::DeclarationName::CXXOperatorName:
1113 case clang::DeclarationName::CXXUsingDirective:
1114 return false;
1115
1116 case clang::DeclarationName::CXXConstructorName:
1117 case clang::DeclarationName::CXXDestructorName:
1118 case clang::DeclarationName::CXXConversionFunctionName:
1119 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1120 return Visit(TSInfo->getTypeLoc());
1121 return false;
1122
1123 case clang::DeclarationName::ObjCZeroArgSelector:
1124 case clang::DeclarationName::ObjCOneArgSelector:
1125 case clang::DeclarationName::ObjCMultiArgSelector:
1126 // FIXME: Per-identifier location info?
1127 return false;
1128 }
1129
1130 return false;
1131}
1132
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001133bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1134 SourceRange Range) {
1135 // FIXME: This whole routine is a hack to work around the lack of proper
1136 // source information in nested-name-specifiers (PR5791). Since we do have
1137 // a beginning source location, we can visit the first component of the
1138 // nested-name-specifier, if it's a single-token component.
1139 if (!NNS)
1140 return false;
1141
1142 // Get the first component in the nested-name-specifier.
1143 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1144 NNS = Prefix;
1145
1146 switch (NNS->getKind()) {
1147 case NestedNameSpecifier::Namespace:
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001148 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1149 TU));
1150
Douglas Gregor14aba762011-02-24 02:36:08 +00001151 case NestedNameSpecifier::NamespaceAlias:
1152 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1153 Range.getBegin(), TU));
1154
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001155 case NestedNameSpecifier::TypeSpec: {
1156 // If the type has a form where we know that the beginning of the source
1157 // range matches up with a reference cursor. Visit the appropriate reference
1158 // cursor.
John McCallf4c73712011-01-19 06:33:43 +00001159 const Type *T = NNS->getAsType();
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001160 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1161 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1162 if (const TagType *Tag = dyn_cast<TagType>(T))
1163 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1164 if (const TemplateSpecializationType *TST
1165 = dyn_cast<TemplateSpecializationType>(T))
1166 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1167 break;
1168 }
1169
1170 case NestedNameSpecifier::TypeSpecWithTemplate:
1171 case NestedNameSpecifier::Global:
1172 case NestedNameSpecifier::Identifier:
1173 break;
1174 }
1175
1176 return false;
1177}
1178
Douglas Gregordc355712011-02-25 00:36:19 +00001179bool
1180CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001181 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
Douglas Gregordc355712011-02-25 00:36:19 +00001182 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1183 Qualifiers.push_back(Qualifier);
1184
1185 while (!Qualifiers.empty()) {
1186 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1187 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1188 switch (NNS->getKind()) {
1189 case NestedNameSpecifier::Namespace:
1190 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001191 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001192 TU)))
1193 return true;
1194
1195 break;
1196
1197 case NestedNameSpecifier::NamespaceAlias:
1198 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001199 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001200 TU)))
1201 return true;
1202
1203 break;
1204
1205 case NestedNameSpecifier::TypeSpec:
1206 case NestedNameSpecifier::TypeSpecWithTemplate:
1207 if (Visit(Q.getTypeLoc()))
1208 return true;
1209
1210 break;
1211
1212 case NestedNameSpecifier::Global:
1213 case NestedNameSpecifier::Identifier:
1214 break;
1215 }
1216 }
1217
1218 return false;
1219}
1220
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001221bool CursorVisitor::VisitTemplateParameters(
1222 const TemplateParameterList *Params) {
1223 if (!Params)
1224 return false;
1225
1226 for (TemplateParameterList::const_iterator P = Params->begin(),
1227 PEnd = Params->end();
1228 P != PEnd; ++P) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001229 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001230 return true;
1231 }
1232
1233 return false;
1234}
1235
Douglas Gregor0b36e612010-08-31 20:37:03 +00001236bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1237 switch (Name.getKind()) {
1238 case TemplateName::Template:
1239 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1240
1241 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001242 // Visit the overloaded template set.
1243 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1244 return true;
1245
Douglas Gregor0b36e612010-08-31 20:37:03 +00001246 return false;
1247
1248 case TemplateName::DependentTemplate:
1249 // FIXME: Visit nested-name-specifier.
1250 return false;
1251
1252 case TemplateName::QualifiedTemplate:
1253 // FIXME: Visit nested-name-specifier.
1254 return Visit(MakeCursorTemplateRef(
1255 Name.getAsQualifiedTemplateName()->getDecl(),
1256 Loc, TU));
John McCall14606042011-06-30 08:33:18 +00001257
1258 case TemplateName::SubstTemplateTemplateParm:
1259 return Visit(MakeCursorTemplateRef(
1260 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1261 Loc, TU));
Douglas Gregor1aee05d2011-01-15 06:45:20 +00001262
1263 case TemplateName::SubstTemplateTemplateParmPack:
1264 return Visit(MakeCursorTemplateRef(
1265 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1266 Loc, TU));
Douglas Gregor0b36e612010-08-31 20:37:03 +00001267 }
1268
1269 return false;
1270}
1271
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001272bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1273 switch (TAL.getArgument().getKind()) {
1274 case TemplateArgument::Null:
1275 case TemplateArgument::Integral:
Douglas Gregor87dd6972010-12-20 16:52:59 +00001276 case TemplateArgument::Pack:
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001277 return false;
1278
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001279 case TemplateArgument::Type:
1280 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1281 return Visit(TSInfo->getTypeLoc());
1282 return false;
1283
1284 case TemplateArgument::Declaration:
1285 if (Expr *E = TAL.getSourceDeclExpression())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001286 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001287 return false;
1288
1289 case TemplateArgument::Expression:
1290 if (Expr *E = TAL.getSourceExpression())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001291 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001292 return false;
1293
1294 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001295 case TemplateArgument::TemplateExpansion:
Douglas Gregorb6744ef2011-03-02 17:09:35 +00001296 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1297 return true;
1298
Douglas Gregora7fc9012011-01-05 18:58:31 +00001299 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
Douglas Gregor0b36e612010-08-31 20:37:03 +00001300 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001301 }
1302
1303 return false;
1304}
1305
Ted Kremeneka0536d82010-05-07 01:04:29 +00001306bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1307 return VisitDeclContext(D);
1308}
1309
Douglas Gregor01829d32010-08-31 14:41:23 +00001310bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1311 return Visit(TL.getUnqualifiedLoc());
1312}
1313
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001314bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00001315 ASTContext &Context = AU->getASTContext();
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001316
1317 // Some builtin types (such as Objective-C's "id", "sel", and
1318 // "Class") have associated declarations. Create cursors for those.
1319 QualType VisitType;
John McCalle0a22d02011-10-18 21:02:43 +00001320 switch (TL.getTypePtr()->getKind()) {
John McCall2dde35b2011-10-18 22:28:37 +00001321
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001322 case BuiltinType::Void:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001323 case BuiltinType::NullPtr:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001324 case BuiltinType::Dependent:
John McCall2dde35b2011-10-18 22:28:37 +00001325#define BUILTIN_TYPE(Id, SingletonId)
1326#define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1327#define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1328#define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
1329#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
1330#include "clang/AST/BuiltinTypes.def"
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001331 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001332
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001333 case BuiltinType::ObjCId:
1334 VisitType = Context.getObjCIdType();
1335 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001336
1337 case BuiltinType::ObjCClass:
1338 VisitType = Context.getObjCClassType();
1339 break;
1340
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001341 case BuiltinType::ObjCSel:
1342 VisitType = Context.getObjCSelType();
1343 break;
1344 }
1345
1346 if (!VisitType.isNull()) {
1347 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001348 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001349 TU));
1350 }
1351
1352 return false;
1353}
1354
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001355bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
Richard Smith162e1c12011-04-15 14:24:37 +00001356 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001357}
1358
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001359bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1360 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1361}
1362
1363bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
Argyrios Kyrtzidis6f155de2011-08-25 22:24:47 +00001364 if (TL.isDefinition())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001365 return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
Argyrios Kyrtzidis6f155de2011-08-25 22:24:47 +00001366
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001367 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1368}
1369
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001370bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Chandler Carruth960d13d2011-05-01 09:53:37 +00001371 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001372}
1373
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001374bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1375 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1376 return true;
1377
John McCallc12c5bb2010-05-15 11:32:37 +00001378 return false;
1379}
1380
1381bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1382 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1383 return true;
1384
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001385 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1386 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1387 TU)))
1388 return true;
1389 }
1390
1391 return false;
1392}
1393
1394bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001395 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001396}
1397
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001398bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1399 return Visit(TL.getInnerLoc());
1400}
1401
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001402bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1403 return Visit(TL.getPointeeLoc());
1404}
1405
1406bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1407 return Visit(TL.getPointeeLoc());
1408}
1409
1410bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1411 return Visit(TL.getPointeeLoc());
1412}
1413
1414bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001415 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001416}
1417
1418bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001419 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001420}
1421
Argyrios Kyrtzidis3422fbc2011-08-15 18:44:43 +00001422bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1423 return Visit(TL.getModifiedLoc());
1424}
1425
Douglas Gregor01829d32010-08-31 14:41:23 +00001426bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1427 bool SkipResultType) {
1428 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001429 return true;
1430
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001431 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001432 if (Decl *D = TL.getArg(I))
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001433 if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001434 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001435
1436 return false;
1437}
1438
1439bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1440 if (Visit(TL.getElementLoc()))
1441 return true;
1442
1443 if (Expr *Size = TL.getSizeExpr())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001444 return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001445
1446 return false;
1447}
1448
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001449bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1450 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001451 // Visit the template name.
1452 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1453 TL.getTemplateNameLoc()))
1454 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001455
1456 // Visit the template arguments.
1457 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1458 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1459 return true;
1460
1461 return false;
1462}
1463
Douglas Gregor2332c112010-01-21 20:48:56 +00001464bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1465 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1466}
1467
1468bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1469 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1470 return Visit(TSInfo->getTypeLoc());
1471
1472 return false;
1473}
1474
Sean Huntca63c202011-05-24 22:41:36 +00001475bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1476 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1477 return Visit(TSInfo->getTypeLoc());
1478
1479 return false;
1480}
1481
Douglas Gregor2494dd02011-03-01 01:34:45 +00001482bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
1483 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1484 return true;
1485
1486 return false;
1487}
1488
Douglas Gregor94fdffa2011-03-01 20:11:18 +00001489bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1490 DependentTemplateSpecializationTypeLoc TL) {
1491 // Visit the nested-name-specifier, if there is one.
1492 if (TL.getQualifierLoc() &&
1493 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1494 return true;
1495
1496 // Visit the template arguments.
1497 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1498 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1499 return true;
1500
1501 return false;
1502}
1503
Douglas Gregor9e876872011-03-01 18:12:44 +00001504bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1505 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1506 return true;
1507
1508 return Visit(TL.getNamedTypeLoc());
1509}
1510
Douglas Gregor7536dd52010-12-20 02:24:11 +00001511bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1512 return Visit(TL.getPatternLoc());
1513}
1514
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +00001515bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1516 if (Expr *E = TL.getUnderlyingExpr())
1517 return Visit(MakeCXCursor(E, StmtParent, TU));
1518
1519 return false;
1520}
1521
1522bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1523 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1524}
1525
Eli Friedmanb001de72011-10-06 23:00:33 +00001526bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1527 return Visit(TL.getValueLoc());
1528}
1529
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +00001530#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1531bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1532 return Visit##PARENT##Loc(TL); \
1533}
1534
1535DEFAULT_TYPELOC_IMPL(Complex, Type)
1536DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1537DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1538DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1539DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
1540DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1541DEFAULT_TYPELOC_IMPL(Vector, Type)
1542DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1543DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1544DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1545DEFAULT_TYPELOC_IMPL(Record, TagType)
1546DEFAULT_TYPELOC_IMPL(Enum, TagType)
1547DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1548DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1549DEFAULT_TYPELOC_IMPL(Auto, Type)
1550
Ted Kremenek3064ef92010-08-27 21:34:58 +00001551bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001552 // Visit the nested-name-specifier, if present.
1553 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1554 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1555 return true;
1556
John McCall5e1cdac2011-10-07 06:10:15 +00001557 if (D->isCompleteDefinition()) {
Ted Kremenek3064ef92010-08-27 21:34:58 +00001558 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1559 E = D->bases_end(); I != E; ++I) {
1560 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1561 return true;
1562 }
1563 }
1564
1565 return VisitTagDecl(D);
1566}
1567
Ted Kremenek09dfa372010-02-18 05:46:33 +00001568bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001569 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1570 i != e; ++i)
1571 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001572 return true;
1573
1574 return false;
1575}
1576
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001577//===----------------------------------------------------------------------===//
1578// Data-recursive visitor methods.
1579//===----------------------------------------------------------------------===//
1580
Ted Kremenek28a71942010-11-13 00:36:47 +00001581namespace {
Ted Kremenek035dc412010-11-13 00:36:50 +00001582#define DEF_JOB(NAME, DATA, KIND)\
1583class NAME : public VisitorJob {\
1584public:\
1585 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1586 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Ted Kremenekf64d8032010-11-18 00:02:32 +00001587 DATA *get() const { return static_cast<DATA*>(data[0]); }\
Ted Kremenek035dc412010-11-13 00:36:50 +00001588};
1589
1590DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1591DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001592DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001593DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001594DEF_JOB(ExplicitTemplateArgsVisit, ASTTemplateArgumentListInfo,
Ted Kremenek60608ec2010-11-17 00:50:47 +00001595 ExplicitTemplateArgsVisitKind)
Douglas Gregor94d96292011-01-19 20:34:17 +00001596DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001597#undef DEF_JOB
1598
1599class DeclVisit : public VisitorJob {
1600public:
1601 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1602 VisitorJob(parent, VisitorJob::DeclVisitKind,
1603 d, isFirst ? (void*) 1 : (void*) 0) {}
1604 static bool classof(const VisitorJob *VJ) {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001605 return VJ->getKind() == DeclVisitKind;
Ted Kremenek035dc412010-11-13 00:36:50 +00001606 }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001607 Decl *get() const { return static_cast<Decl*>(data[0]); }
1608 bool isFirst() const { return data[1] ? true : false; }
Ted Kremenek035dc412010-11-13 00:36:50 +00001609};
Ted Kremenek035dc412010-11-13 00:36:50 +00001610class TypeLocVisit : public VisitorJob {
1611public:
1612 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1613 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1614 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1615
1616 static bool classof(const VisitorJob *VJ) {
1617 return VJ->getKind() == TypeLocVisitKind;
1618 }
1619
Ted Kremenek82f3c502010-11-15 22:23:26 +00001620 TypeLoc get() const {
Ted Kremenekf64d8032010-11-18 00:02:32 +00001621 QualType T = QualType::getFromOpaquePtr(data[0]);
1622 return TypeLoc(T, data[1]);
Ted Kremenek035dc412010-11-13 00:36:50 +00001623 }
1624};
1625
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001626class LabelRefVisit : public VisitorJob {
1627public:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001628 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1629 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001630 labelLoc.getPtrEncoding()) {}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001631
1632 static bool classof(const VisitorJob *VJ) {
1633 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1634 }
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001635 LabelDecl *get() const { return static_cast<LabelDecl*>(data[0]); }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001636 SourceLocation getLoc() const {
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001637 return SourceLocation::getFromPtrEncoding(data[1]); }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001638};
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001639
1640class NestedNameSpecifierLocVisit : public VisitorJob {
1641public:
1642 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1643 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1644 Qualifier.getNestedNameSpecifier(),
1645 Qualifier.getOpaqueData()) { }
1646
1647 static bool classof(const VisitorJob *VJ) {
1648 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1649 }
1650
1651 NestedNameSpecifierLoc get() const {
1652 return NestedNameSpecifierLoc(static_cast<NestedNameSpecifier*>(data[0]),
1653 data[1]);
1654 }
1655};
1656
Ted Kremenekf64d8032010-11-18 00:02:32 +00001657class DeclarationNameInfoVisit : public VisitorJob {
1658public:
1659 DeclarationNameInfoVisit(Stmt *S, CXCursor parent)
1660 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
1661 static bool classof(const VisitorJob *VJ) {
1662 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1663 }
1664 DeclarationNameInfo get() const {
1665 Stmt *S = static_cast<Stmt*>(data[0]);
1666 switch (S->getStmtClass()) {
1667 default:
1668 llvm_unreachable("Unhandled Stmt");
Douglas Gregorba0513d2011-10-25 01:33:02 +00001669 case clang::Stmt::MSDependentExistsStmtClass:
1670 return cast<MSDependentExistsStmt>(S)->getNameInfo();
Ted Kremenekf64d8032010-11-18 00:02:32 +00001671 case Stmt::CXXDependentScopeMemberExprClass:
1672 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1673 case Stmt::DependentScopeDeclRefExprClass:
1674 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
1675 }
1676 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001677};
Ted Kremenekcdba6592010-11-18 00:42:18 +00001678class MemberRefVisit : public VisitorJob {
1679public:
1680 MemberRefVisit(FieldDecl *D, SourceLocation L, CXCursor parent)
1681 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001682 L.getPtrEncoding()) {}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001683 static bool classof(const VisitorJob *VJ) {
1684 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1685 }
1686 FieldDecl *get() const {
1687 return static_cast<FieldDecl*>(data[0]);
1688 }
1689 SourceLocation getLoc() const {
1690 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1691 }
1692};
Ted Kremenek28a71942010-11-13 00:36:47 +00001693class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1694 VisitorWorkList &WL;
1695 CXCursor Parent;
1696public:
1697 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1698 : WL(wl), Parent(parent) {}
1699
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001700 void VisitAddrLabelExpr(AddrLabelExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001701 void VisitBlockExpr(BlockExpr *B);
Ted Kremenek28a71942010-11-13 00:36:47 +00001702 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek083c7e22010-11-13 05:38:03 +00001703 void VisitCompoundStmt(CompoundStmt *S);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001704 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
Douglas Gregorba0513d2011-10-25 01:33:02 +00001705 void VisitMSDependentExistsStmt(MSDependentExistsStmt *S);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001706 void VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001707 void VisitCXXNewExpr(CXXNewExpr *E);
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001708 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001709 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001710 void VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001711 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001712 void VisitCXXTypeidExpr(CXXTypeidExpr *E);
Ted Kremenek55b933a2010-11-17 00:50:36 +00001713 void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001714 void VisitCXXUuidofExpr(CXXUuidofExpr *E);
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001715 void VisitDeclRefExpr(DeclRefExpr *D);
Ted Kremenek035dc412010-11-13 00:36:50 +00001716 void VisitDeclStmt(DeclStmt *S);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001717 void VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001718 void VisitDesignatedInitExpr(DesignatedInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001719 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1720 void VisitForStmt(ForStmt *FS);
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001721 void VisitGotoStmt(GotoStmt *GS);
Ted Kremenek28a71942010-11-13 00:36:47 +00001722 void VisitIfStmt(IfStmt *If);
1723 void VisitInitListExpr(InitListExpr *IE);
1724 void VisitMemberExpr(MemberExpr *M);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001725 void VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001726 void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001727 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1728 void VisitOverloadExpr(OverloadExpr *E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001729 void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001730 void VisitStmt(Stmt *S);
1731 void VisitSwitchStmt(SwitchStmt *S);
1732 void VisitWhileStmt(WhileStmt *W);
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001733 void VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Francois Pichet6ad6f282010-12-07 00:08:36 +00001734 void VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E);
John Wiegley21ff2e52011-04-28 00:16:57 +00001735 void VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E);
John Wiegley55262202011-04-25 06:54:41 +00001736 void VisitExpressionTraitExpr(ExpressionTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001737 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001738 void VisitVAArgExpr(VAArgExpr *E);
Douglas Gregor94d96292011-01-19 20:34:17 +00001739 void VisitSizeOfPackExpr(SizeOfPackExpr *E);
John McCall4b9c2d22011-11-06 09:01:30 +00001740 void VisitPseudoObjectExpr(PseudoObjectExpr *E);
1741 void VisitOpaqueValueExpr(OpaqueValueExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00001742
Ted Kremenek28a71942010-11-13 00:36:47 +00001743private:
Ted Kremenekf64d8032010-11-18 00:02:32 +00001744 void AddDeclarationNameInfo(Stmt *S);
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001745 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001746 void AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001747 void AddMemberRef(FieldDecl *D, SourceLocation L);
Ted Kremenek28a71942010-11-13 00:36:47 +00001748 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001749 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001750 void AddTypeLoc(TypeSourceInfo *TI);
1751 void EnqueueChildren(Stmt *S);
1752};
1753} // end anonyous namespace
1754
Ted Kremenekf64d8032010-11-18 00:02:32 +00001755void EnqueueVisitor::AddDeclarationNameInfo(Stmt *S) {
1756 // 'S' should always be non-null, since it comes from the
1757 // statement we are visiting.
1758 WL.push_back(DeclarationNameInfoVisit(S, Parent));
1759}
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001760
1761void
1762EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1763 if (Qualifier)
1764 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
1765}
1766
Ted Kremenek28a71942010-11-13 00:36:47 +00001767void EnqueueVisitor::AddStmt(Stmt *S) {
1768 if (S)
1769 WL.push_back(StmtVisit(S, Parent));
1770}
Ted Kremenek035dc412010-11-13 00:36:50 +00001771void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001772 if (D)
Ted Kremenek035dc412010-11-13 00:36:50 +00001773 WL.push_back(DeclVisit(D, Parent, isFirst));
Ted Kremenek28a71942010-11-13 00:36:47 +00001774}
Ted Kremenek60608ec2010-11-17 00:50:47 +00001775void EnqueueVisitor::
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001776 AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001777 if (A)
1778 WL.push_back(ExplicitTemplateArgsVisit(
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001779 const_cast<ASTTemplateArgumentListInfo*>(A), Parent));
Ted Kremenek60608ec2010-11-17 00:50:47 +00001780}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001781void EnqueueVisitor::AddMemberRef(FieldDecl *D, SourceLocation L) {
1782 if (D)
1783 WL.push_back(MemberRefVisit(D, L, Parent));
1784}
Ted Kremenek28a71942010-11-13 00:36:47 +00001785void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1786 if (TI)
1787 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1788 }
1789void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001790 unsigned size = WL.size();
John McCall7502c1d2011-02-13 04:07:26 +00001791 for (Stmt::child_range Child = S->children(); Child; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001792 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001793 }
1794 if (size == WL.size())
1795 return;
1796 // Now reverse the entries we just added. This will match the DFS
1797 // ordering performed by the worklist.
1798 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1799 std::reverse(I, E);
1800}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001801void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1802 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
1803}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001804void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1805 AddDecl(B->getBlockDecl());
1806}
Ted Kremenek28a71942010-11-13 00:36:47 +00001807void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1808 EnqueueChildren(E);
1809 AddTypeLoc(E->getTypeSourceInfo());
1810}
Ted Kremenek083c7e22010-11-13 05:38:03 +00001811void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1812 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1813 E = S->body_rend(); I != E; ++I) {
1814 AddStmt(*I);
1815 }
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001816}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001817void EnqueueVisitor::
Douglas Gregorba0513d2011-10-25 01:33:02 +00001818VisitMSDependentExistsStmt(MSDependentExistsStmt *S) {
1819 AddStmt(S->getSubStmt());
1820 AddDeclarationNameInfo(S);
1821 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
1822 AddNestedNameSpecifierLoc(QualifierLoc);
1823}
1824
1825void EnqueueVisitor::
Ted Kremenekf64d8032010-11-18 00:02:32 +00001826VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
1827 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1828 AddDeclarationNameInfo(E);
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001829 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1830 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001831 if (!E->isImplicitAccess())
1832 AddStmt(E->getBase());
1833}
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001834void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1835 // Enqueue the initializer or constructor arguments.
1836 for (unsigned I = E->getNumConstructorArgs(); I > 0; --I)
1837 AddStmt(E->getConstructorArg(I-1));
1838 // Enqueue the array size, if any.
1839 AddStmt(E->getArraySize());
1840 // Enqueue the allocated type.
1841 AddTypeLoc(E->getAllocatedTypeSourceInfo());
1842 // Enqueue the placement arguments.
1843 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1844 AddStmt(E->getPlacementArg(I-1));
1845}
Ted Kremenek28a71942010-11-13 00:36:47 +00001846void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
Ted Kremenek8b8d8c92010-11-13 05:55:56 +00001847 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1848 AddStmt(CE->getArg(I-1));
Ted Kremenek28a71942010-11-13 00:36:47 +00001849 AddStmt(CE->getCallee());
1850 AddStmt(CE->getArg(0));
1851}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001852void EnqueueVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1853 // Visit the name of the type being destroyed.
1854 AddTypeLoc(E->getDestroyedTypeInfo());
1855 // Visit the scope type that looks disturbingly like the nested-name-specifier
1856 // but isn't.
1857 AddTypeLoc(E->getScopeTypeInfo());
1858 // Visit the nested-name-specifier.
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001859 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1860 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001861 // Visit base expression.
1862 AddStmt(E->getBase());
1863}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001864void EnqueueVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1865 AddTypeLoc(E->getTypeSourceInfo());
1866}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001867void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1868 EnqueueChildren(E);
1869 AddTypeLoc(E->getTypeSourceInfo());
1870}
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001871void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1872 EnqueueChildren(E);
1873 if (E->isTypeOperand())
1874 AddTypeLoc(E->getTypeOperandSourceInfo());
1875}
Ted Kremenek55b933a2010-11-17 00:50:36 +00001876
1877void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
1878 *E) {
1879 EnqueueChildren(E);
1880 AddTypeLoc(E->getTypeSourceInfo());
1881}
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001882void EnqueueVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1883 EnqueueChildren(E);
1884 if (E->isTypeOperand())
1885 AddTypeLoc(E->getTypeOperandSourceInfo());
1886}
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001887void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001888 if (DR->hasExplicitTemplateArgs()) {
1889 AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
1890 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001891 WL.push_back(DeclRefExprParts(DR, Parent));
1892}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001893void EnqueueVisitor::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
1894 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1895 AddDeclarationNameInfo(E);
Douglas Gregor00cf3cc2011-02-25 20:49:16 +00001896 AddNestedNameSpecifierLoc(E->getQualifierLoc());
Ted Kremenekf64d8032010-11-18 00:02:32 +00001897}
Ted Kremenek035dc412010-11-13 00:36:50 +00001898void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1899 unsigned size = WL.size();
1900 bool isFirst = true;
1901 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1902 D != DEnd; ++D) {
1903 AddDecl(*D, isFirst);
1904 isFirst = false;
1905 }
1906 if (size == WL.size())
1907 return;
1908 // Now reverse the entries we just added. This will match the DFS
1909 // ordering performed by the worklist.
1910 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1911 std::reverse(I, E);
1912}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001913void EnqueueVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1914 AddStmt(E->getInit());
1915 typedef DesignatedInitExpr::Designator Designator;
1916 for (DesignatedInitExpr::reverse_designators_iterator
1917 D = E->designators_rbegin(), DEnd = E->designators_rend();
1918 D != DEnd; ++D) {
1919 if (D->isFieldDesignator()) {
1920 if (FieldDecl *Field = D->getField())
1921 AddMemberRef(Field, D->getFieldLoc());
1922 continue;
1923 }
1924 if (D->isArrayDesignator()) {
1925 AddStmt(E->getArrayIndex(*D));
1926 continue;
1927 }
1928 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1929 AddStmt(E->getArrayRangeEnd(*D));
1930 AddStmt(E->getArrayRangeStart(*D));
1931 }
1932}
Ted Kremenek28a71942010-11-13 00:36:47 +00001933void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1934 EnqueueChildren(E);
1935 AddTypeLoc(E->getTypeInfoAsWritten());
1936}
1937void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1938 AddStmt(FS->getBody());
1939 AddStmt(FS->getInc());
1940 AddStmt(FS->getCond());
1941 AddDecl(FS->getConditionVariable());
1942 AddStmt(FS->getInit());
1943}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001944void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) {
1945 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
1946}
Ted Kremenek28a71942010-11-13 00:36:47 +00001947void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
1948 AddStmt(If->getElse());
1949 AddStmt(If->getThen());
1950 AddStmt(If->getCond());
1951 AddDecl(If->getConditionVariable());
1952}
1953void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
1954 // We care about the syntactic form of the initializer list, only.
1955 if (InitListExpr *Syntactic = IE->getSyntacticForm())
1956 IE = Syntactic;
1957 EnqueueChildren(IE);
1958}
1959void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
Douglas Gregor89629a72010-11-17 17:15:08 +00001960 WL.push_back(MemberExprParts(M, Parent));
1961
1962 // If the base of the member access expression is an implicit 'this', don't
1963 // visit it.
1964 // FIXME: If we ever want to show these implicit accesses, this will be
1965 // unfortunate. However, clang_getCursor() relies on this behavior.
Douglas Gregor75e85042011-03-02 21:06:53 +00001966 if (!M->isImplicitAccess())
1967 AddStmt(M->getBase());
Ted Kremenek28a71942010-11-13 00:36:47 +00001968}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001969void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1970 AddTypeLoc(E->getEncodedTypeSourceInfo());
1971}
Ted Kremenek28a71942010-11-13 00:36:47 +00001972void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
1973 EnqueueChildren(M);
1974 AddTypeLoc(M->getClassReceiverTypeInfo());
1975}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001976void EnqueueVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
1977 // Visit the components of the offsetof expression.
1978 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
1979 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
1980 const OffsetOfNode &Node = E->getComponent(I-1);
1981 switch (Node.getKind()) {
1982 case OffsetOfNode::Array:
1983 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
1984 break;
1985 case OffsetOfNode::Field:
Abramo Bagnara06dec892011-03-12 09:45:03 +00001986 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
Ted Kremenekcdba6592010-11-18 00:42:18 +00001987 break;
1988 case OffsetOfNode::Identifier:
1989 case OffsetOfNode::Base:
1990 continue;
1991 }
1992 }
1993 // Visit the type into which we're computing the offset.
1994 AddTypeLoc(E->getTypeSourceInfo());
1995}
Ted Kremenek28a71942010-11-13 00:36:47 +00001996void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001997 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
Ted Kremenek60458782010-11-12 21:34:16 +00001998 WL.push_back(OverloadExprParts(E, Parent));
1999}
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002000void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
2001 UnaryExprOrTypeTraitExpr *E) {
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00002002 EnqueueChildren(E);
2003 if (E->isArgumentType())
2004 AddTypeLoc(E->getArgumentTypeInfo());
2005}
Ted Kremenek28a71942010-11-13 00:36:47 +00002006void EnqueueVisitor::VisitStmt(Stmt *S) {
2007 EnqueueChildren(S);
2008}
2009void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
2010 AddStmt(S->getBody());
2011 AddStmt(S->getCond());
2012 AddDecl(S->getConditionVariable());
2013}
Ted Kremenekfafa75a2010-11-17 00:50:39 +00002014
Ted Kremenek28a71942010-11-13 00:36:47 +00002015void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
2016 AddStmt(W->getBody());
2017 AddStmt(W->getCond());
2018 AddDecl(W->getConditionVariable());
2019}
John Wiegley21ff2e52011-04-28 00:16:57 +00002020
Ted Kremenek2939b6f2010-11-17 00:50:50 +00002021void EnqueueVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
2022 AddTypeLoc(E->getQueriedTypeSourceInfo());
2023}
Francois Pichet6ad6f282010-12-07 00:08:36 +00002024
2025void EnqueueVisitor::VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
Francois Pichet6ad6f282010-12-07 00:08:36 +00002026 AddTypeLoc(E->getRhsTypeSourceInfo());
Francois Pichet0a03a3f2010-12-08 09:11:05 +00002027 AddTypeLoc(E->getLhsTypeSourceInfo());
Francois Pichet6ad6f282010-12-07 00:08:36 +00002028}
2029
John Wiegley21ff2e52011-04-28 00:16:57 +00002030void EnqueueVisitor::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
2031 AddTypeLoc(E->getQueriedTypeSourceInfo());
2032}
2033
John Wiegley55262202011-04-25 06:54:41 +00002034void EnqueueVisitor::VisitExpressionTraitExpr(ExpressionTraitExpr *E) {
2035 EnqueueChildren(E);
2036}
2037
Ted Kremenek28a71942010-11-13 00:36:47 +00002038void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
2039 VisitOverloadExpr(U);
2040 if (!U->isImplicitAccess())
2041 AddStmt(U->getBase());
2042}
Ted Kremenek9d3bf792010-11-17 00:50:43 +00002043void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) {
2044 AddStmt(E->getSubExpr());
2045 AddTypeLoc(E->getWrittenTypeInfo());
2046}
Douglas Gregor94d96292011-01-19 20:34:17 +00002047void EnqueueVisitor::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
2048 WL.push_back(SizeOfPackExprParts(E, Parent));
2049}
John McCall4b9c2d22011-11-06 09:01:30 +00002050void EnqueueVisitor::VisitOpaqueValueExpr(OpaqueValueExpr *E) {
2051 // If the opaque value has a source expression, just transparently
2052 // visit that. This is useful for (e.g.) pseudo-object expressions.
2053 if (Expr *SourceExpr = E->getSourceExpr())
2054 return Visit(SourceExpr);
2055 AddStmt(E);
2056}
2057void EnqueueVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *E) {
2058 // Treat the expression like its syntactic form.
2059 Visit(E->getSyntacticForm());
2060}
Ted Kremenek60458782010-11-12 21:34:16 +00002061
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002062void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002063 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002064}
2065
2066bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2067 if (RegionOfInterest.isValid()) {
2068 SourceRange Range = getRawCursorExtent(C);
2069 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2070 return false;
2071 }
2072 return true;
2073}
2074
2075bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2076 while (!WL.empty()) {
2077 // Dequeue the worklist item.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002078 VisitorJob LI = WL.back();
2079 WL.pop_back();
2080
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002081 // Set the Parent field, then back to its old value once we're done.
2082 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2083
2084 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00002085 case VisitorJob::DeclVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002086 Decl *D = cast<DeclVisit>(&LI)->get();
Ted Kremenekf1107452010-11-12 18:26:56 +00002087 if (!D)
2088 continue;
2089
2090 // For now, perform default visitation for Decls.
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002091 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2092 cast<DeclVisit>(&LI)->isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00002093 return true;
2094
2095 continue;
2096 }
Ted Kremenek60608ec2010-11-17 00:50:47 +00002097 case VisitorJob::ExplicitTemplateArgsVisitKind: {
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00002098 const ASTTemplateArgumentListInfo *ArgList =
Ted Kremenek60608ec2010-11-17 00:50:47 +00002099 cast<ExplicitTemplateArgsVisit>(&LI)->get();
2100 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2101 *ArgEnd = Arg + ArgList->NumTemplateArgs;
2102 Arg != ArgEnd; ++Arg) {
2103 if (VisitTemplateArgumentLoc(*Arg))
2104 return true;
2105 }
2106 continue;
2107 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002108 case VisitorJob::TypeLocVisitKind: {
2109 // Perform default visitation for TypeLocs.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002110 if (Visit(cast<TypeLocVisit>(&LI)->get()))
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002111 return true;
2112 continue;
2113 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002114 case VisitorJob::LabelRefVisitKind: {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002115 LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Ted Kremeneke7455012011-02-23 04:54:51 +00002116 if (LabelStmt *stmt = LS->getStmt()) {
2117 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2118 TU))) {
2119 return true;
2120 }
2121 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002122 continue;
2123 }
Ted Kremenek47695c82011-08-18 22:25:21 +00002124
Douglas Gregorf3db29f2011-02-25 18:19:59 +00002125 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2126 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2127 if (VisitNestedNameSpecifierLoc(V->get()))
2128 return true;
2129 continue;
2130 }
2131
Ted Kremenekf64d8032010-11-18 00:02:32 +00002132 case VisitorJob::DeclarationNameInfoVisitKind: {
2133 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2134 ->get()))
2135 return true;
2136 continue;
2137 }
Ted Kremenekcdba6592010-11-18 00:42:18 +00002138 case VisitorJob::MemberRefVisitKind: {
2139 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2140 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2141 return true;
2142 continue;
2143 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002144 case VisitorJob::StmtVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002145 Stmt *S = cast<StmtVisit>(&LI)->get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00002146 if (!S)
2147 continue;
2148
Ted Kremenekf1107452010-11-12 18:26:56 +00002149 // Update the current cursor.
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002150 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
Ted Kremenekcdba6592010-11-18 00:42:18 +00002151 if (!IsInRegionOfInterest(Cursor))
2152 continue;
2153 switch (Visitor(Cursor, Parent, ClientData)) {
2154 case CXChildVisit_Break: return true;
2155 case CXChildVisit_Continue: break;
2156 case CXChildVisit_Recurse:
2157 EnqueueWorkList(WL, S);
Ted Kremenek82f3c502010-11-15 22:23:26 +00002158 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002159 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00002160 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002161 }
2162 case VisitorJob::MemberExprPartsKind: {
2163 // Handle the other pieces in the MemberExpr besides the base.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002164 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002165
2166 // Visit the nested-name-specifier
Douglas Gregor40d96a62011-02-28 21:54:11 +00002167 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
2168 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002169 return true;
2170
2171 // Visit the declaration name.
2172 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2173 return true;
2174
2175 // Visit the explicitly-specified template arguments, if any.
2176 if (M->hasExplicitTemplateArgs()) {
2177 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2178 *ArgEnd = Arg + M->getNumTemplateArgs();
2179 Arg != ArgEnd; ++Arg) {
2180 if (VisitTemplateArgumentLoc(*Arg))
2181 return true;
2182 }
2183 }
2184 continue;
2185 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002186 case VisitorJob::DeclRefExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002187 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002188 // Visit nested-name-specifier, if present.
Douglas Gregor40d96a62011-02-28 21:54:11 +00002189 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
2190 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002191 return true;
2192 // Visit declaration name.
2193 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2194 return true;
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002195 continue;
2196 }
Ted Kremenek60458782010-11-12 21:34:16 +00002197 case VisitorJob::OverloadExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002198 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Ted Kremenek60458782010-11-12 21:34:16 +00002199 // Visit the nested-name-specifier.
Douglas Gregor4c9be892011-02-28 20:01:57 +00002200 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
2201 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenek60458782010-11-12 21:34:16 +00002202 return true;
2203 // Visit the declaration name.
2204 if (VisitDeclarationNameInfo(O->getNameInfo()))
2205 return true;
2206 // Visit the overloaded declaration reference.
2207 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2208 return true;
Ted Kremenek60458782010-11-12 21:34:16 +00002209 continue;
2210 }
Douglas Gregor94d96292011-01-19 20:34:17 +00002211 case VisitorJob::SizeOfPackExprPartsKind: {
2212 SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
2213 NamedDecl *Pack = E->getPack();
2214 if (isa<TemplateTypeParmDecl>(Pack)) {
2215 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
2216 E->getPackLoc(), TU)))
2217 return true;
2218
2219 continue;
2220 }
2221
2222 if (isa<TemplateTemplateParmDecl>(Pack)) {
2223 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
2224 E->getPackLoc(), TU)))
2225 return true;
2226
2227 continue;
2228 }
2229
2230 // Non-type template parameter packs and function parameter packs are
2231 // treated like DeclRefExpr cursors.
2232 continue;
2233 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002234 }
2235 }
2236 return false;
2237}
2238
Ted Kremenekcdba6592010-11-18 00:42:18 +00002239bool CursorVisitor::Visit(Stmt *S) {
Ted Kremenekd1ded662010-11-15 23:31:32 +00002240 VisitorWorkList *WL = 0;
2241 if (!WorkListFreeList.empty()) {
2242 WL = WorkListFreeList.back();
2243 WL->clear();
2244 WorkListFreeList.pop_back();
2245 }
2246 else {
2247 WL = new VisitorWorkList();
2248 WorkListCache.push_back(WL);
2249 }
2250 EnqueueWorkList(*WL, S);
2251 bool result = RunVisitorWorkList(*WL);
2252 WorkListFreeList.push_back(WL);
2253 return result;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002254}
2255
Francois Pichet48a8d142011-07-25 22:00:44 +00002256namespace {
2257typedef llvm::SmallVector<SourceRange, 4> RefNamePieces;
2258RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
2259 const DeclarationNameInfo &NI,
2260 const SourceRange &QLoc,
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00002261 const ASTTemplateArgumentListInfo *TemplateArgs = 0){
Francois Pichet48a8d142011-07-25 22:00:44 +00002262 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
2263 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
2264 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
2265
2266 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
2267
2268 RefNamePieces Pieces;
2269
2270 if (WantQualifier && QLoc.isValid())
2271 Pieces.push_back(QLoc);
2272
2273 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
2274 Pieces.push_back(NI.getLoc());
2275
2276 if (WantTemplateArgs && TemplateArgs)
2277 Pieces.push_back(SourceRange(TemplateArgs->LAngleLoc,
2278 TemplateArgs->RAngleLoc));
2279
2280 if (Kind == DeclarationName::CXXOperatorName) {
2281 Pieces.push_back(SourceLocation::getFromRawEncoding(
2282 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
2283 Pieces.push_back(SourceLocation::getFromRawEncoding(
2284 NI.getInfo().CXXOperatorName.EndOpNameLoc));
2285 }
2286
2287 if (WantSinglePiece) {
2288 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
2289 Pieces.clear();
2290 Pieces.push_back(R);
2291 }
2292
2293 return Pieces;
2294}
2295}
2296
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002297//===----------------------------------------------------------------------===//
2298// Misc. API hooks.
2299//===----------------------------------------------------------------------===//
2300
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002301static llvm::sys::Mutex EnableMultithreadingMutex;
2302static bool EnabledMultithreading;
2303
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002304extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002305CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2306 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002307 // Disable pretty stack trace functionality, which will otherwise be a very
2308 // poor citizen of the world and set up all sorts of signal handlers.
2309 llvm::DisablePrettyStackTrace = true;
2310
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002311 // We use crash recovery to make some of our APIs more reliable, implicitly
2312 // enable it.
2313 llvm::CrashRecoveryContext::Enable();
2314
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002315 // Enable support for multithreading in LLVM.
2316 {
2317 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2318 if (!EnabledMultithreading) {
2319 llvm::llvm_start_multithreaded();
2320 EnabledMultithreading = true;
2321 }
2322 }
2323
Douglas Gregora030b7c2010-01-22 20:35:53 +00002324 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002325 if (excludeDeclarationsFromPCH)
2326 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002327 if (displayDiagnostics)
2328 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002329 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002330}
2331
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002332void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002333 if (CIdx)
2334 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002335}
2336
Ted Kremenekd2427dd2011-03-18 23:05:39 +00002337void clang_toggleCrashRecovery(unsigned isEnabled) {
2338 if (isEnabled)
2339 llvm::CrashRecoveryContext::Enable();
2340 else
2341 llvm::CrashRecoveryContext::Disable();
2342}
2343
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002344CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002345 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002346 if (!CIdx)
2347 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002348
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002349 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002350 FileSystemOptions FileSystemOpts;
2351 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002352
David Blaikied6471f72011-09-25 23:23:43 +00002353 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002354 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002355 CXXIdx->getOnlyLocalDecls(),
2356 0, 0, true);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002357 return MakeCXTranslationUnit(TU);
Steve Naroff600866c2009-08-27 19:51:58 +00002358}
2359
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002360unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002361 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregorb5af8432011-08-25 22:54:01 +00002362 CXTranslationUnit_CacheCompletionResults;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002363}
2364
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002365CXTranslationUnit
2366clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2367 const char *source_filename,
2368 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002369 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002370 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002371 struct CXUnsavedFile *unsaved_files) {
Douglas Gregordca8ee82011-05-06 16:33:08 +00002372 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord |
Chandler Carruthba7537f2011-07-14 09:02:10 +00002373 CXTranslationUnit_NestedMacroExpansions;
Douglas Gregor5a430212010-07-21 18:52:53 +00002374 return clang_parseTranslationUnit(CIdx, source_filename,
2375 command_line_args, num_command_line_args,
2376 unsaved_files, num_unsaved_files,
Douglas Gregordca8ee82011-05-06 16:33:08 +00002377 Options);
Douglas Gregor5a430212010-07-21 18:52:53 +00002378}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002379
2380struct ParseTranslationUnitInfo {
2381 CXIndex CIdx;
2382 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002383 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002384 int num_command_line_args;
2385 struct CXUnsavedFile *unsaved_files;
2386 unsigned num_unsaved_files;
2387 unsigned options;
2388 CXTranslationUnit result;
2389};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002390static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002391 ParseTranslationUnitInfo *PTUI =
2392 static_cast<ParseTranslationUnitInfo*>(UserData);
2393 CXIndex CIdx = PTUI->CIdx;
2394 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002395 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002396 int num_command_line_args = PTUI->num_command_line_args;
2397 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2398 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2399 unsigned options = PTUI->options;
2400 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002401
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002402 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002403 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002404
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002405 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2406
Douglas Gregor44c181a2010-07-23 00:33:23 +00002407 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregor467dc882011-08-25 22:30:56 +00002408 // FIXME: Add a flag for modules.
2409 TranslationUnitKind TUKind
2410 = (options & CXTranslationUnit_Incomplete)? TU_Prefix : TU_Complete;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002411 bool CacheCodeCompetionResults
2412 = options & CXTranslationUnit_CacheCompletionResults;
2413
Douglas Gregor5352ac02010-01-28 00:27:43 +00002414 // Configure the diagnostics.
2415 DiagnosticOptions DiagOpts;
David Blaikied6471f72011-09-25 23:23:43 +00002416 llvm::IntrusiveRefCntPtr<DiagnosticsEngine>
Ted Kremenek25a11e12011-03-22 01:15:24 +00002417 Diags(CompilerInstance::createDiagnostics(DiagOpts, num_command_line_args,
2418 command_line_args));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002419
Ted Kremenek25a11e12011-03-22 01:15:24 +00002420 // Recover resources if we crash before exiting this function.
David Blaikied6471f72011-09-25 23:23:43 +00002421 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
2422 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00002423 DiagCleanup(Diags.getPtr());
2424
2425 llvm::OwningPtr<std::vector<ASTUnit::RemappedFile> >
2426 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2427
2428 // Recover resources if we crash before exiting this function.
2429 llvm::CrashRecoveryContextCleanupRegistrar<
2430 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2431
Douglas Gregor4db64a42010-01-23 00:14:00 +00002432 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002433 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002434 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002435 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002436 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2437 Buffer));
Douglas Gregor4db64a42010-01-23 00:14:00 +00002438 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002439
Ted Kremenek25a11e12011-03-22 01:15:24 +00002440 llvm::OwningPtr<std::vector<const char *> >
2441 Args(new std::vector<const char*>());
2442
2443 // Recover resources if we crash before exiting this method.
2444 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
2445 ArgsCleanup(Args.get());
2446
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002447 // Since the Clang C library is primarily used by batch tools dealing with
2448 // (often very broken) source code, where spell-checking can have a
2449 // significant negative impact on performance (particularly when
2450 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002451 // Only do this if we haven't found a spell-checking-related argument.
2452 bool FoundSpellCheckingArgument = false;
2453 for (int I = 0; I != num_command_line_args; ++I) {
2454 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2455 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2456 FoundSpellCheckingArgument = true;
2457 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002458 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002459 }
2460 if (!FoundSpellCheckingArgument)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002461 Args->push_back("-fno-spell-checking");
Douglas Gregorb10daed2010-10-11 16:52:23 +00002462
Ted Kremenek25a11e12011-03-22 01:15:24 +00002463 Args->insert(Args->end(), command_line_args,
2464 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002465
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002466 // The 'source_filename' argument is optional. If the caller does not
2467 // specify it then it is assumed that the source file is specified
2468 // in the actual argument list.
2469 // Put the source file after command_line_args otherwise if '-x' flag is
2470 // present it will be unused.
2471 if (source_filename)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002472 Args->push_back(source_filename);
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002473
Douglas Gregor44c181a2010-07-23 00:33:23 +00002474 // Do we need the detailed preprocessing record?
Chandler Carruthba7537f2011-07-14 09:02:10 +00002475 bool NestedMacroExpansions = false;
Douglas Gregor44c181a2010-07-23 00:33:23 +00002476 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Ted Kremenek25a11e12011-03-22 01:15:24 +00002477 Args->push_back("-Xclang");
2478 Args->push_back("-detailed-preprocessing-record");
Chandler Carruthba7537f2011-07-14 09:02:10 +00002479 NestedMacroExpansions
2480 = (options & CXTranslationUnit_NestedMacroExpansions);
Douglas Gregor44c181a2010-07-23 00:33:23 +00002481 }
2482
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002483 unsigned NumErrors = Diags->getClient()->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002484 llvm::OwningPtr<ASTUnit> Unit(
Ted Kremenek4ee99262011-03-22 20:16:19 +00002485 ASTUnit::LoadFromCommandLine(Args->size() ? &(*Args)[0] : 0
2486 /* vector::data() not portable */,
2487 Args->size() ? (&(*Args)[0] + Args->size()) :0,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002488 Diags,
2489 CXXIdx->getClangResourcesPath(),
2490 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002491 /*CaptureDiagnostics=*/true,
Ted Kremenek4ee99262011-03-22 20:16:19 +00002492 RemappedFiles->size() ? &(*RemappedFiles)[0]:0,
Ted Kremenek25a11e12011-03-22 01:15:24 +00002493 RemappedFiles->size(),
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00002494 /*RemappedFilesKeepOriginalName=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002495 PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00002496 TUKind,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002497 CacheCodeCompetionResults,
Chandler Carruthba7537f2011-07-14 09:02:10 +00002498 NestedMacroExpansions));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002499
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002500 if (NumErrors != Diags->getClient()->getNumErrors()) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002501 // Make sure to check that 'Unit' is non-NULL.
2502 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2503 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2504 DEnd = Unit->stored_diag_end();
2505 D != DEnd; ++D) {
2506 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2507 CXString Msg = clang_formatDiagnostic(&Diag,
2508 clang_defaultDiagnosticDisplayOptions());
2509 fprintf(stderr, "%s\n", clang_getCString(Msg));
2510 clang_disposeString(Msg);
2511 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002512#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002513 // On Windows, force a flush, since there may be multiple copies of
2514 // stderr and stdout in the file system, all with different buffers
2515 // but writing to the same device.
2516 fflush(stderr);
2517#endif
2518 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002519 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002520
Ted Kremeneka60ed472010-11-16 08:15:36 +00002521 PTUI->result = MakeCXTranslationUnit(Unit.take());
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002522}
2523CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2524 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002525 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002526 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002527 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002528 unsigned num_unsaved_files,
2529 unsigned options) {
2530 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002531 num_command_line_args, unsaved_files,
2532 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002533 llvm::CrashRecoveryContext CRC;
2534
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002535 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002536 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2537 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2538 fprintf(stderr, " 'command_line_args' : [");
2539 for (int i = 0; i != num_command_line_args; ++i) {
2540 if (i)
2541 fprintf(stderr, ", ");
2542 fprintf(stderr, "'%s'", command_line_args[i]);
2543 }
2544 fprintf(stderr, "],\n");
2545 fprintf(stderr, " 'unsaved_files' : [");
2546 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2547 if (i)
2548 fprintf(stderr, ", ");
2549 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2550 unsaved_files[i].Length);
2551 }
2552 fprintf(stderr, "],\n");
2553 fprintf(stderr, " 'options' : %d,\n", options);
2554 fprintf(stderr, "}\n");
2555
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002556 return 0;
Douglas Gregor6df78732011-05-05 20:27:22 +00002557 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
2558 PrintLibclangResourceUsage(PTUI.result);
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002559 }
Douglas Gregor6df78732011-05-05 20:27:22 +00002560
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002561 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002562}
2563
Douglas Gregor19998442010-08-13 15:35:05 +00002564unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2565 return CXSaveTranslationUnit_None;
2566}
2567
2568int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2569 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002570 if (!TU)
Douglas Gregor39c411f2011-07-06 16:43:36 +00002571 return CXSaveError_InvalidTU;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002572
Douglas Gregor39c411f2011-07-06 16:43:36 +00002573 CXSaveError result = static_cast<ASTUnit *>(TU->TUData)->Save(FileName);
Douglas Gregor6df78732011-05-05 20:27:22 +00002574 if (getenv("LIBCLANG_RESOURCE_USAGE"))
2575 PrintLibclangResourceUsage(TU);
2576 return result;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002577}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002578
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002579void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002580 if (CTUnit) {
2581 // If the translation unit has been marked as unsafe to free, just discard
2582 // it.
Ted Kremeneka60ed472010-11-16 08:15:36 +00002583 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002584 return;
2585
Ted Kremeneka60ed472010-11-16 08:15:36 +00002586 delete static_cast<ASTUnit *>(CTUnit->TUData);
2587 disposeCXStringPool(CTUnit->StringPool);
Ted Kremenek15322172011-11-10 08:43:12 +00002588 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002589 delete CTUnit;
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002590 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002591}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002592
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002593unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2594 return CXReparse_None;
2595}
2596
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002597struct ReparseTranslationUnitInfo {
2598 CXTranslationUnit TU;
2599 unsigned num_unsaved_files;
2600 struct CXUnsavedFile *unsaved_files;
2601 unsigned options;
2602 int result;
2603};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002604
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002605static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002606 ReparseTranslationUnitInfo *RTUI =
2607 static_cast<ReparseTranslationUnitInfo*>(UserData);
2608 CXTranslationUnit TU = RTUI->TU;
Ted Kremenek15322172011-11-10 08:43:12 +00002609
2610 // Reset the associated diagnostics.
2611 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
2612 TU->Diagnostics = 0;
2613
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002614 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2615 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2616 unsigned options = RTUI->options;
2617 (void) options;
2618 RTUI->result = 1;
2619
Douglas Gregorabc563f2010-07-19 21:46:24 +00002620 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002621 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002622
Ted Kremeneka60ed472010-11-16 08:15:36 +00002623 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor593b0c12010-09-23 18:47:53 +00002624 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002625
Ted Kremenek25a11e12011-03-22 01:15:24 +00002626 llvm::OwningPtr<std::vector<ASTUnit::RemappedFile> >
2627 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2628
2629 // Recover resources if we crash before exiting this function.
2630 llvm::CrashRecoveryContextCleanupRegistrar<
2631 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2632
Douglas Gregorabc563f2010-07-19 21:46:24 +00002633 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002634 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002635 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002636 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002637 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2638 Buffer));
Douglas Gregorabc563f2010-07-19 21:46:24 +00002639 }
2640
Ted Kremenek4ee99262011-03-22 20:16:19 +00002641 if (!CXXUnit->Reparse(RemappedFiles->size() ? &(*RemappedFiles)[0] : 0,
2642 RemappedFiles->size()))
Douglas Gregor593b0c12010-09-23 18:47:53 +00002643 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002644}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002645
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002646int clang_reparseTranslationUnit(CXTranslationUnit TU,
2647 unsigned num_unsaved_files,
2648 struct CXUnsavedFile *unsaved_files,
2649 unsigned options) {
2650 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2651 options, 0 };
Argyrios Kyrtzidis8c4b47e2011-10-28 22:54:33 +00002652
Argyrios Kyrtzidise7de9b42011-10-29 19:32:39 +00002653 if (getenv("LIBCLANG_NOTHREADS")) {
Argyrios Kyrtzidis8c4b47e2011-10-28 22:54:33 +00002654 clang_reparseTranslationUnit_Impl(&RTUI);
2655 return RTUI.result;
2656 }
2657
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002658 llvm::CrashRecoveryContext CRC;
2659
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002660 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002661 fprintf(stderr, "libclang: crash detected during reparsing\n");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002662 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002663 return 1;
Douglas Gregor6df78732011-05-05 20:27:22 +00002664 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
2665 PrintLibclangResourceUsage(TU);
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002666
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002667 return RTUI.result;
2668}
2669
Douglas Gregordf95a132010-08-09 20:45:32 +00002670
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002671CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002672 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002673 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002674
Ted Kremeneka60ed472010-11-16 08:15:36 +00002675 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002676 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002677}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002678
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002679CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002680 CXCursor Result = { CXCursor_TranslationUnit, 0, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002681 return Result;
2682}
2683
Ted Kremenekfb480492010-01-13 21:46:36 +00002684} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002685
Ted Kremenekfb480492010-01-13 21:46:36 +00002686//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002687// CXFile Operations.
2688//===----------------------------------------------------------------------===//
2689
2690extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002691CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002692 if (!SFile)
Ted Kremeneka60ed472010-11-16 08:15:36 +00002693 return createCXString((const char*)NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002694
Steve Naroff88145032009-10-27 14:35:18 +00002695 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002696 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002697}
2698
2699time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002700 if (!SFile)
2701 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002702
Steve Naroff88145032009-10-27 14:35:18 +00002703 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2704 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002705}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002706
Douglas Gregorb9790342010-01-22 21:44:22 +00002707CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2708 if (!tu)
2709 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002710
Ted Kremeneka60ed472010-11-16 08:15:36 +00002711 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002712
Douglas Gregorb9790342010-01-22 21:44:22 +00002713 FileManager &FMgr = CXXUnit->getFileManager();
Chris Lattner39b49bc2010-11-23 08:35:12 +00002714 return const_cast<FileEntry *>(FMgr.getFile(file_name));
Douglas Gregorb9790342010-01-22 21:44:22 +00002715}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002716
Douglas Gregordd3e5542011-05-04 00:14:37 +00002717unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit tu, CXFile file) {
2718 if (!tu || !file)
2719 return 0;
2720
2721 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
2722 FileEntry *FEnt = static_cast<FileEntry *>(file);
2723 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
2724 .isFileMultipleIncludeGuarded(FEnt);
2725}
2726
Ted Kremenekfb480492010-01-13 21:46:36 +00002727} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002728
Ted Kremenekfb480492010-01-13 21:46:36 +00002729//===----------------------------------------------------------------------===//
2730// CXCursor Operations.
2731//===----------------------------------------------------------------------===//
2732
Ted Kremenekfb480492010-01-13 21:46:36 +00002733static Decl *getDeclFromExpr(Stmt *E) {
Argyrios Kyrtzidisc2954612011-09-12 22:17:26 +00002734 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Douglas Gregordb1314e2010-10-01 21:11:22 +00002735 return getDeclFromExpr(CE->getSubExpr());
2736
Ted Kremenekfb480492010-01-13 21:46:36 +00002737 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2738 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002739 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2740 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002741 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2742 return ME->getMemberDecl();
2743 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2744 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002745 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
John McCall12f78a62010-12-02 01:19:52 +00002746 return PRE->isExplicitProperty() ? PRE->getExplicitProperty() : 0;
John McCall4b9c2d22011-11-06 09:01:30 +00002747 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
2748 return getDeclFromExpr(POE->getSyntacticForm());
2749 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
2750 if (Expr *Src = OVE->getSourceExpr())
2751 return getDeclFromExpr(Src);
Douglas Gregordb1314e2010-10-01 21:11:22 +00002752
Ted Kremenekfb480492010-01-13 21:46:36 +00002753 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2754 return getDeclFromExpr(CE->getCallee());
Chris Lattner5f9e2722011-07-23 10:55:15 +00002755 if (CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Douglas Gregor93798e22010-11-05 21:11:19 +00002756 if (!CE->isElidable())
2757 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002758 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2759 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002760
Douglas Gregordb1314e2010-10-01 21:11:22 +00002761 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2762 return PE->getProtocol();
Douglas Gregorc7793c72011-01-15 01:15:58 +00002763 if (SubstNonTypeTemplateParmPackExpr *NTTP
2764 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
2765 return NTTP->getParameterPack();
Douglas Gregor94d96292011-01-19 20:34:17 +00002766 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2767 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
2768 isa<ParmVarDecl>(SizeOfPack->getPack()))
2769 return SizeOfPack->getPack();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002770
Ted Kremenekfb480492010-01-13 21:46:36 +00002771 return 0;
2772}
2773
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002774static SourceLocation getLocationFromExpr(Expr *E) {
Argyrios Kyrtzidisc2954612011-09-12 22:17:26 +00002775 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
2776 return getLocationFromExpr(CE->getSubExpr());
2777
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002778 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2779 return /*FIXME:*/Msg->getLeftLoc();
2780 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2781 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002782 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2783 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002784 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2785 return Member->getMemberLoc();
2786 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2787 return Ivar->getLocation();
Douglas Gregor94d96292011-01-19 20:34:17 +00002788 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2789 return SizeOfPack->getPackLoc();
2790
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002791 return E->getLocStart();
2792}
2793
Ted Kremenekfb480492010-01-13 21:46:36 +00002794extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002795
2796unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002797 CXCursorVisitor visitor,
2798 CXClientData client_data) {
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00002799 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
2800 /*VisitPreprocessorLast=*/false);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002801 return CursorVis.VisitChildren(parent);
2802}
2803
David Chisnall3387c652010-11-03 14:12:26 +00002804#ifndef __has_feature
2805#define __has_feature(x) 0
2806#endif
2807#if __has_feature(blocks)
2808typedef enum CXChildVisitResult
2809 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2810
2811static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2812 CXClientData client_data) {
2813 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2814 return block(cursor, parent);
2815}
2816#else
2817// If we are compiled with a compiler that doesn't have native blocks support,
2818// define and call the block manually, so the
2819typedef struct _CXChildVisitResult
2820{
2821 void *isa;
2822 int flags;
2823 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002824 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2825 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00002826} *CXCursorVisitorBlock;
2827
2828static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2829 CXClientData client_data) {
2830 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2831 return block->invoke(block, cursor, parent);
2832}
2833#endif
2834
2835
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002836unsigned clang_visitChildrenWithBlock(CXCursor parent,
2837 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00002838 return clang_visitChildren(parent, visitWithBlock, block);
2839}
2840
Douglas Gregor78205d42010-01-20 21:45:58 +00002841static CXString getDeclSpelling(Decl *D) {
2842 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
Douglas Gregore3c60a72010-11-17 00:13:31 +00002843 if (!ND) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002844 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00002845 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
2846 return createCXString(Property->getIdentifier()->getName());
2847
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002848 return createCXString("");
Douglas Gregore3c60a72010-11-17 00:13:31 +00002849 }
2850
Douglas Gregor78205d42010-01-20 21:45:58 +00002851 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002852 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002853
Douglas Gregor78205d42010-01-20 21:45:58 +00002854 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2855 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2856 // and returns different names. NamedDecl returns the class name and
2857 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002858 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002859
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002860 if (isa<UsingDirectiveDecl>(D))
2861 return createCXString("");
2862
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002863 llvm::SmallString<1024> S;
2864 llvm::raw_svector_ostream os(S);
2865 ND->printName(os);
2866
2867 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002868}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002869
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002870CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002871 if (clang_isTranslationUnit(C.kind))
Ted Kremeneka60ed472010-11-16 08:15:36 +00002872 return clang_getTranslationUnitSpelling(
2873 static_cast<CXTranslationUnit>(C.data[2]));
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002874
Steve Narofff334b4e2009-09-02 18:26:48 +00002875 if (clang_isReference(C.kind)) {
2876 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002877 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002878 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002879 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002880 }
2881 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002882 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002883 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002884 }
2885 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002886 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002887 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002888 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002889 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002890 case CXCursor_CXXBaseSpecifier: {
2891 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2892 return createCXString(B->getType().getAsString());
2893 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002894 case CXCursor_TypeRef: {
2895 TypeDecl *Type = getCursorTypeRef(C).first;
2896 assert(Type && "Missing type decl");
2897
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002898 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2899 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002900 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002901 case CXCursor_TemplateRef: {
2902 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002903 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002904
2905 return createCXString(Template->getNameAsString());
2906 }
Douglas Gregor69319002010-08-31 23:48:11 +00002907
2908 case CXCursor_NamespaceRef: {
2909 NamedDecl *NS = getCursorNamespaceRef(C).first;
2910 assert(NS && "Missing namespace decl");
2911
2912 return createCXString(NS->getNameAsString());
2913 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002914
Douglas Gregora67e03f2010-09-09 21:42:20 +00002915 case CXCursor_MemberRef: {
2916 FieldDecl *Field = getCursorMemberRef(C).first;
2917 assert(Field && "Missing member decl");
2918
2919 return createCXString(Field->getNameAsString());
2920 }
2921
Douglas Gregor36897b02010-09-10 00:22:18 +00002922 case CXCursor_LabelRef: {
2923 LabelStmt *Label = getCursorLabelRef(C).first;
2924 assert(Label && "Missing label");
2925
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002926 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00002927 }
2928
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002929 case CXCursor_OverloadedDeclRef: {
2930 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2931 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2932 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2933 return createCXString(ND->getNameAsString());
2934 return createCXString("");
2935 }
2936 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2937 return createCXString(E->getName().getAsString());
2938 OverloadedTemplateStorage *Ovl
2939 = Storage.get<OverloadedTemplateStorage*>();
2940 if (Ovl->size() == 0)
2941 return createCXString("");
2942 return createCXString((*Ovl->begin())->getNameAsString());
2943 }
2944
Daniel Dunbaracca7252009-11-30 20:42:49 +00002945 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002946 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002947 }
2948 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002949
2950 if (clang_isExpression(C.kind)) {
2951 Decl *D = getDeclFromExpr(getCursorExpr(C));
2952 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002953 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002954 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002955 }
2956
Douglas Gregor36897b02010-09-10 00:22:18 +00002957 if (clang_isStatement(C.kind)) {
2958 Stmt *S = getCursorStmt(C);
2959 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002960 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00002961
2962 return createCXString("");
2963 }
2964
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00002965 if (C.kind == CXCursor_MacroExpansion)
Chandler Carruth9e5bb852011-07-14 08:20:46 +00002966 return createCXString(getCursorMacroExpansion(C)->getName()
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002967 ->getNameStart());
2968
Douglas Gregor572feb22010-03-18 18:04:21 +00002969 if (C.kind == CXCursor_MacroDefinition)
2970 return createCXString(getCursorMacroDefinition(C)->getName()
2971 ->getNameStart());
2972
Douglas Gregorecdcb882010-10-20 22:00:55 +00002973 if (C.kind == CXCursor_InclusionDirective)
2974 return createCXString(getCursorInclusionDirective(C)->getFileName());
2975
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002976 if (clang_isDeclaration(C.kind))
2977 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002978
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00002979 if (C.kind == CXCursor_AnnotateAttr) {
2980 AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
2981 return createCXString(AA->getAnnotation());
2982 }
2983
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002984 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002985}
2986
Douglas Gregor358559d2010-10-02 22:49:11 +00002987CXString clang_getCursorDisplayName(CXCursor C) {
2988 if (!clang_isDeclaration(C.kind))
2989 return clang_getCursorSpelling(C);
2990
2991 Decl *D = getCursorDecl(C);
2992 if (!D)
2993 return createCXString("");
2994
Douglas Gregor30c42402011-09-27 22:38:19 +00002995 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
Douglas Gregor358559d2010-10-02 22:49:11 +00002996 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2997 D = FunTmpl->getTemplatedDecl();
2998
2999 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
3000 llvm::SmallString<64> Str;
3001 llvm::raw_svector_ostream OS(Str);
3002 OS << Function->getNameAsString();
3003 if (Function->getPrimaryTemplate())
3004 OS << "<>";
3005 OS << "(";
3006 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
3007 if (I)
3008 OS << ", ";
3009 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
3010 }
3011
3012 if (Function->isVariadic()) {
3013 if (Function->getNumParams())
3014 OS << ", ";
3015 OS << "...";
3016 }
3017 OS << ")";
3018 return createCXString(OS.str());
3019 }
3020
3021 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
3022 llvm::SmallString<64> Str;
3023 llvm::raw_svector_ostream OS(Str);
3024 OS << ClassTemplate->getNameAsString();
3025 OS << "<";
3026 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
3027 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3028 if (I)
3029 OS << ", ";
3030
3031 NamedDecl *Param = Params->getParam(I);
3032 if (Param->getIdentifier()) {
3033 OS << Param->getIdentifier()->getName();
3034 continue;
3035 }
3036
3037 // There is no parameter name, which makes this tricky. Try to come up
3038 // with something useful that isn't too long.
3039 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3040 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
3041 else if (NonTypeTemplateParmDecl *NTTP
3042 = dyn_cast<NonTypeTemplateParmDecl>(Param))
3043 OS << NTTP->getType().getAsString(Policy);
3044 else
3045 OS << "template<...> class";
3046 }
3047
3048 OS << ">";
3049 return createCXString(OS.str());
3050 }
3051
3052 if (ClassTemplateSpecializationDecl *ClassSpec
3053 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
3054 // If the type was explicitly written, use that.
3055 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
3056 return createCXString(TSInfo->getType().getAsString(Policy));
3057
3058 llvm::SmallString<64> Str;
3059 llvm::raw_svector_ostream OS(Str);
3060 OS << ClassSpec->getNameAsString();
3061 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00003062 ClassSpec->getTemplateArgs().data(),
3063 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00003064 Policy);
3065 return createCXString(OS.str());
3066 }
3067
3068 return clang_getCursorSpelling(C);
3069}
3070
Ted Kremeneke68fff62010-02-17 00:41:32 +00003071CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00003072 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00003073 case CXCursor_FunctionDecl:
3074 return createCXString("FunctionDecl");
3075 case CXCursor_TypedefDecl:
3076 return createCXString("TypedefDecl");
3077 case CXCursor_EnumDecl:
3078 return createCXString("EnumDecl");
3079 case CXCursor_EnumConstantDecl:
3080 return createCXString("EnumConstantDecl");
3081 case CXCursor_StructDecl:
3082 return createCXString("StructDecl");
3083 case CXCursor_UnionDecl:
3084 return createCXString("UnionDecl");
3085 case CXCursor_ClassDecl:
3086 return createCXString("ClassDecl");
3087 case CXCursor_FieldDecl:
3088 return createCXString("FieldDecl");
3089 case CXCursor_VarDecl:
3090 return createCXString("VarDecl");
3091 case CXCursor_ParmDecl:
3092 return createCXString("ParmDecl");
3093 case CXCursor_ObjCInterfaceDecl:
3094 return createCXString("ObjCInterfaceDecl");
3095 case CXCursor_ObjCCategoryDecl:
3096 return createCXString("ObjCCategoryDecl");
3097 case CXCursor_ObjCProtocolDecl:
3098 return createCXString("ObjCProtocolDecl");
3099 case CXCursor_ObjCPropertyDecl:
3100 return createCXString("ObjCPropertyDecl");
3101 case CXCursor_ObjCIvarDecl:
3102 return createCXString("ObjCIvarDecl");
3103 case CXCursor_ObjCInstanceMethodDecl:
3104 return createCXString("ObjCInstanceMethodDecl");
3105 case CXCursor_ObjCClassMethodDecl:
3106 return createCXString("ObjCClassMethodDecl");
3107 case CXCursor_ObjCImplementationDecl:
3108 return createCXString("ObjCImplementationDecl");
3109 case CXCursor_ObjCCategoryImplDecl:
3110 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00003111 case CXCursor_CXXMethod:
3112 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003113 case CXCursor_UnexposedDecl:
3114 return createCXString("UnexposedDecl");
3115 case CXCursor_ObjCSuperClassRef:
3116 return createCXString("ObjCSuperClassRef");
3117 case CXCursor_ObjCProtocolRef:
3118 return createCXString("ObjCProtocolRef");
3119 case CXCursor_ObjCClassRef:
3120 return createCXString("ObjCClassRef");
3121 case CXCursor_TypeRef:
3122 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003123 case CXCursor_TemplateRef:
3124 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00003125 case CXCursor_NamespaceRef:
3126 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00003127 case CXCursor_MemberRef:
3128 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00003129 case CXCursor_LabelRef:
3130 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003131 case CXCursor_OverloadedDeclRef:
3132 return createCXString("OverloadedDeclRef");
Douglas Gregor42b29842011-10-05 19:00:14 +00003133 case CXCursor_IntegerLiteral:
3134 return createCXString("IntegerLiteral");
3135 case CXCursor_FloatingLiteral:
3136 return createCXString("FloatingLiteral");
3137 case CXCursor_ImaginaryLiteral:
3138 return createCXString("ImaginaryLiteral");
3139 case CXCursor_StringLiteral:
3140 return createCXString("StringLiteral");
3141 case CXCursor_CharacterLiteral:
3142 return createCXString("CharacterLiteral");
3143 case CXCursor_ParenExpr:
3144 return createCXString("ParenExpr");
3145 case CXCursor_UnaryOperator:
3146 return createCXString("UnaryOperator");
3147 case CXCursor_ArraySubscriptExpr:
3148 return createCXString("ArraySubscriptExpr");
3149 case CXCursor_BinaryOperator:
3150 return createCXString("BinaryOperator");
3151 case CXCursor_CompoundAssignOperator:
3152 return createCXString("CompoundAssignOperator");
3153 case CXCursor_ConditionalOperator:
3154 return createCXString("ConditionalOperator");
3155 case CXCursor_CStyleCastExpr:
3156 return createCXString("CStyleCastExpr");
3157 case CXCursor_CompoundLiteralExpr:
3158 return createCXString("CompoundLiteralExpr");
3159 case CXCursor_InitListExpr:
3160 return createCXString("InitListExpr");
3161 case CXCursor_AddrLabelExpr:
3162 return createCXString("AddrLabelExpr");
3163 case CXCursor_StmtExpr:
3164 return createCXString("StmtExpr");
3165 case CXCursor_GenericSelectionExpr:
3166 return createCXString("GenericSelectionExpr");
3167 case CXCursor_GNUNullExpr:
3168 return createCXString("GNUNullExpr");
3169 case CXCursor_CXXStaticCastExpr:
3170 return createCXString("CXXStaticCastExpr");
3171 case CXCursor_CXXDynamicCastExpr:
3172 return createCXString("CXXDynamicCastExpr");
3173 case CXCursor_CXXReinterpretCastExpr:
3174 return createCXString("CXXReinterpretCastExpr");
3175 case CXCursor_CXXConstCastExpr:
3176 return createCXString("CXXConstCastExpr");
3177 case CXCursor_CXXFunctionalCastExpr:
3178 return createCXString("CXXFunctionalCastExpr");
3179 case CXCursor_CXXTypeidExpr:
3180 return createCXString("CXXTypeidExpr");
3181 case CXCursor_CXXBoolLiteralExpr:
3182 return createCXString("CXXBoolLiteralExpr");
3183 case CXCursor_CXXNullPtrLiteralExpr:
3184 return createCXString("CXXNullPtrLiteralExpr");
3185 case CXCursor_CXXThisExpr:
3186 return createCXString("CXXThisExpr");
3187 case CXCursor_CXXThrowExpr:
3188 return createCXString("CXXThrowExpr");
3189 case CXCursor_CXXNewExpr:
3190 return createCXString("CXXNewExpr");
3191 case CXCursor_CXXDeleteExpr:
3192 return createCXString("CXXDeleteExpr");
3193 case CXCursor_UnaryExpr:
3194 return createCXString("UnaryExpr");
3195 case CXCursor_ObjCStringLiteral:
3196 return createCXString("ObjCStringLiteral");
3197 case CXCursor_ObjCEncodeExpr:
3198 return createCXString("ObjCEncodeExpr");
3199 case CXCursor_ObjCSelectorExpr:
3200 return createCXString("ObjCSelectorExpr");
3201 case CXCursor_ObjCProtocolExpr:
3202 return createCXString("ObjCProtocolExpr");
3203 case CXCursor_ObjCBridgedCastExpr:
3204 return createCXString("ObjCBridgedCastExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00003205 case CXCursor_BlockExpr:
3206 return createCXString("BlockExpr");
Douglas Gregor42b29842011-10-05 19:00:14 +00003207 case CXCursor_PackExpansionExpr:
3208 return createCXString("PackExpansionExpr");
3209 case CXCursor_SizeOfPackExpr:
3210 return createCXString("SizeOfPackExpr");
3211 case CXCursor_UnexposedExpr:
3212 return createCXString("UnexposedExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003213 case CXCursor_DeclRefExpr:
3214 return createCXString("DeclRefExpr");
3215 case CXCursor_MemberRefExpr:
3216 return createCXString("MemberRefExpr");
3217 case CXCursor_CallExpr:
3218 return createCXString("CallExpr");
3219 case CXCursor_ObjCMessageExpr:
3220 return createCXString("ObjCMessageExpr");
3221 case CXCursor_UnexposedStmt:
3222 return createCXString("UnexposedStmt");
Douglas Gregor42b29842011-10-05 19:00:14 +00003223 case CXCursor_DeclStmt:
3224 return createCXString("DeclStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00003225 case CXCursor_LabelStmt:
3226 return createCXString("LabelStmt");
Douglas Gregor42b29842011-10-05 19:00:14 +00003227 case CXCursor_CompoundStmt:
3228 return createCXString("CompoundStmt");
3229 case CXCursor_CaseStmt:
3230 return createCXString("CaseStmt");
3231 case CXCursor_DefaultStmt:
3232 return createCXString("DefaultStmt");
3233 case CXCursor_IfStmt:
3234 return createCXString("IfStmt");
3235 case CXCursor_SwitchStmt:
3236 return createCXString("SwitchStmt");
3237 case CXCursor_WhileStmt:
3238 return createCXString("WhileStmt");
3239 case CXCursor_DoStmt:
3240 return createCXString("DoStmt");
3241 case CXCursor_ForStmt:
3242 return createCXString("ForStmt");
3243 case CXCursor_GotoStmt:
3244 return createCXString("GotoStmt");
3245 case CXCursor_IndirectGotoStmt:
3246 return createCXString("IndirectGotoStmt");
3247 case CXCursor_ContinueStmt:
3248 return createCXString("ContinueStmt");
3249 case CXCursor_BreakStmt:
3250 return createCXString("BreakStmt");
3251 case CXCursor_ReturnStmt:
3252 return createCXString("ReturnStmt");
3253 case CXCursor_AsmStmt:
3254 return createCXString("AsmStmt");
3255 case CXCursor_ObjCAtTryStmt:
3256 return createCXString("ObjCAtTryStmt");
3257 case CXCursor_ObjCAtCatchStmt:
3258 return createCXString("ObjCAtCatchStmt");
3259 case CXCursor_ObjCAtFinallyStmt:
3260 return createCXString("ObjCAtFinallyStmt");
3261 case CXCursor_ObjCAtThrowStmt:
3262 return createCXString("ObjCAtThrowStmt");
3263 case CXCursor_ObjCAtSynchronizedStmt:
3264 return createCXString("ObjCAtSynchronizedStmt");
3265 case CXCursor_ObjCAutoreleasePoolStmt:
3266 return createCXString("ObjCAutoreleasePoolStmt");
3267 case CXCursor_ObjCForCollectionStmt:
3268 return createCXString("ObjCForCollectionStmt");
3269 case CXCursor_CXXCatchStmt:
3270 return createCXString("CXXCatchStmt");
3271 case CXCursor_CXXTryStmt:
3272 return createCXString("CXXTryStmt");
3273 case CXCursor_CXXForRangeStmt:
3274 return createCXString("CXXForRangeStmt");
3275 case CXCursor_SEHTryStmt:
3276 return createCXString("SEHTryStmt");
3277 case CXCursor_SEHExceptStmt:
3278 return createCXString("SEHExceptStmt");
3279 case CXCursor_SEHFinallyStmt:
3280 return createCXString("SEHFinallyStmt");
3281 case CXCursor_NullStmt:
3282 return createCXString("NullStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003283 case CXCursor_InvalidFile:
3284 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00003285 case CXCursor_InvalidCode:
3286 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003287 case CXCursor_NoDeclFound:
3288 return createCXString("NoDeclFound");
3289 case CXCursor_NotImplemented:
3290 return createCXString("NotImplemented");
3291 case CXCursor_TranslationUnit:
3292 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00003293 case CXCursor_UnexposedAttr:
3294 return createCXString("UnexposedAttr");
3295 case CXCursor_IBActionAttr:
3296 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003297 case CXCursor_IBOutletAttr:
3298 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003299 case CXCursor_IBOutletCollectionAttr:
3300 return createCXString("attribute(iboutletcollection)");
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00003301 case CXCursor_CXXFinalAttr:
3302 return createCXString("attribute(final)");
3303 case CXCursor_CXXOverrideAttr:
3304 return createCXString("attribute(override)");
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00003305 case CXCursor_AnnotateAttr:
3306 return createCXString("attribute(annotate)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003307 case CXCursor_PreprocessingDirective:
3308 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003309 case CXCursor_MacroDefinition:
3310 return createCXString("macro definition");
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003311 case CXCursor_MacroExpansion:
3312 return createCXString("macro expansion");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003313 case CXCursor_InclusionDirective:
3314 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003315 case CXCursor_Namespace:
3316 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003317 case CXCursor_LinkageSpec:
3318 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003319 case CXCursor_CXXBaseSpecifier:
3320 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003321 case CXCursor_Constructor:
3322 return createCXString("CXXConstructor");
3323 case CXCursor_Destructor:
3324 return createCXString("CXXDestructor");
3325 case CXCursor_ConversionFunction:
3326 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003327 case CXCursor_TemplateTypeParameter:
3328 return createCXString("TemplateTypeParameter");
3329 case CXCursor_NonTypeTemplateParameter:
3330 return createCXString("NonTypeTemplateParameter");
3331 case CXCursor_TemplateTemplateParameter:
3332 return createCXString("TemplateTemplateParameter");
3333 case CXCursor_FunctionTemplate:
3334 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003335 case CXCursor_ClassTemplate:
3336 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003337 case CXCursor_ClassTemplatePartialSpecialization:
3338 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003339 case CXCursor_NamespaceAlias:
3340 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003341 case CXCursor_UsingDirective:
3342 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003343 case CXCursor_UsingDeclaration:
3344 return createCXString("UsingDeclaration");
Richard Smith162e1c12011-04-15 14:24:37 +00003345 case CXCursor_TypeAliasDecl:
Douglas Gregor352697a2011-06-03 23:08:58 +00003346 return createCXString("TypeAliasDecl");
3347 case CXCursor_ObjCSynthesizeDecl:
3348 return createCXString("ObjCSynthesizeDecl");
3349 case CXCursor_ObjCDynamicDecl:
3350 return createCXString("ObjCDynamicDecl");
Argyrios Kyrtzidis2dfdb942011-09-30 17:58:23 +00003351 case CXCursor_CXXAccessSpecifier:
3352 return createCXString("CXXAccessSpecifier");
Steve Naroff89922f82009-08-31 00:59:03 +00003353 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003354
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003355 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneka60ed472010-11-16 08:15:36 +00003356 return createCXString((const char*) 0);
Steve Naroff600866c2009-08-27 19:51:58 +00003357}
Steve Naroff89922f82009-08-31 00:59:03 +00003358
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003359struct GetCursorData {
3360 SourceLocation TokenBeginLoc;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003361 bool PointsAtMacroArgExpansion;
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003362 CXCursor &BestCursor;
3363
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003364 GetCursorData(SourceManager &SM,
3365 SourceLocation tokenBegin, CXCursor &outputCursor)
3366 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
3367 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
3368 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003369};
3370
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003371static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3372 CXCursor parent,
3373 CXClientData client_data) {
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003374 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
3375 CXCursor *BestCursor = &Data->BestCursor;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003376
3377 // If we point inside a macro argument we should provide info of what the
3378 // token is so use the actual cursor, don't replace it with a macro expansion
3379 // cursor.
3380 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
3381 return CXChildVisit_Recurse;
Argyrios Kyrtzidis65ab9072011-09-26 19:05:37 +00003382
3383 if (clang_isDeclaration(cursor.kind)) {
3384 // Avoid having the implicit methods override the property decls.
3385 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(getCursorDecl(cursor)))
3386 if (MD->isImplicit())
3387 return CXChildVisit_Break;
3388 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003389
3390 if (clang_isExpression(cursor.kind) &&
3391 clang_isDeclaration(BestCursor->kind)) {
3392 Decl *D = getCursorDecl(*BestCursor);
3393
3394 // Avoid having the cursor of an expression replace the declaration cursor
3395 // when the expression source range overlaps the declaration range.
3396 // This can happen for C++ constructor expressions whose range generally
3397 // include the variable declaration, e.g.:
3398 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
3399 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
3400 D->getLocation() == Data->TokenBeginLoc)
3401 return CXChildVisit_Break;
3402 }
3403
Douglas Gregor93798e22010-11-05 21:11:19 +00003404 // If our current best cursor is the construction of a temporary object,
3405 // don't replace that cursor with a type reference, because we want
3406 // clang_getCursor() to point at the constructor.
3407 if (clang_isExpression(BestCursor->kind) &&
3408 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003409 cursor.kind == CXCursor_TypeRef) {
3410 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
3411 // as having the actual point on the type reference.
3412 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
Douglas Gregor93798e22010-11-05 21:11:19 +00003413 return CXChildVisit_Recurse;
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003414 }
Douglas Gregor93798e22010-11-05 21:11:19 +00003415
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003416 *BestCursor = cursor;
3417 return CXChildVisit_Recurse;
3418}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003419
Douglas Gregorb9790342010-01-22 21:44:22 +00003420CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3421 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003422 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003423
Ted Kremeneka60ed472010-11-16 08:15:36 +00003424 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003425 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3426
Ted Kremeneka297de22010-01-25 22:34:44 +00003427 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003428 CXCursor Result = cxcursor::getCursor(TU, SLoc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003429
Douglas Gregor40749ee2010-11-03 00:35:38 +00003430 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregor40749ee2010-11-03 00:35:38 +00003431 if (Logging) {
3432 CXFile SearchFile;
3433 unsigned SearchLine, SearchColumn;
3434 CXFile ResultFile;
3435 unsigned ResultLine, ResultColumn;
Douglas Gregor66537982010-11-17 17:14:07 +00003436 CXString SearchFileName, ResultFileName, KindSpelling, USR;
3437 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
Douglas Gregor40749ee2010-11-03 00:35:38 +00003438 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3439
Chandler Carruth20174222011-08-31 16:53:37 +00003440 clang_getExpansionLocation(Loc, &SearchFile, &SearchLine, &SearchColumn, 0);
3441 clang_getExpansionLocation(ResultLoc, &ResultFile, &ResultLine,
3442 &ResultColumn, 0);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003443 SearchFileName = clang_getFileName(SearchFile);
3444 ResultFileName = clang_getFileName(ResultFile);
3445 KindSpelling = clang_getCursorKindSpelling(Result.kind);
Douglas Gregor66537982010-11-17 17:14:07 +00003446 USR = clang_getCursorUSR(Result);
3447 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n",
Douglas Gregor40749ee2010-11-03 00:35:38 +00003448 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3449 clang_getCString(KindSpelling),
Douglas Gregor66537982010-11-17 17:14:07 +00003450 clang_getCString(ResultFileName), ResultLine, ResultColumn,
3451 clang_getCString(USR), IsDef);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003452 clang_disposeString(SearchFileName);
3453 clang_disposeString(ResultFileName);
3454 clang_disposeString(KindSpelling);
Douglas Gregor66537982010-11-17 17:14:07 +00003455 clang_disposeString(USR);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003456
3457 CXCursor Definition = clang_getCursorDefinition(Result);
3458 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
3459 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
3460 CXString DefinitionKindSpelling
3461 = clang_getCursorKindSpelling(Definition.kind);
3462 CXFile DefinitionFile;
3463 unsigned DefinitionLine, DefinitionColumn;
Chandler Carruth20174222011-08-31 16:53:37 +00003464 clang_getExpansionLocation(DefinitionLoc, &DefinitionFile,
3465 &DefinitionLine, &DefinitionColumn, 0);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003466 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
3467 fprintf(stderr, " -> %s(%s:%d:%d)\n",
3468 clang_getCString(DefinitionKindSpelling),
3469 clang_getCString(DefinitionFileName),
3470 DefinitionLine, DefinitionColumn);
3471 clang_disposeString(DefinitionFileName);
3472 clang_disposeString(DefinitionKindSpelling);
3473 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003474 }
3475
Ted Kremeneke68fff62010-02-17 00:41:32 +00003476 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003477}
3478
Ted Kremenek73885552009-11-17 19:28:59 +00003479CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003480 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003481}
3482
3483unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003484 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003485}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003486
Douglas Gregor9ce55842010-11-20 00:09:34 +00003487unsigned clang_hashCursor(CXCursor C) {
3488 unsigned Index = 0;
3489 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
3490 Index = 1;
3491
3492 return llvm::DenseMapInfo<std::pair<unsigned, void*> >::getHashValue(
3493 std::make_pair(C.kind, C.data[Index]));
3494}
3495
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003496unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003497 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3498}
3499
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003500unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003501 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3502}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003503
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003504unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003505 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3506}
3507
Douglas Gregor97b98722010-01-19 23:20:36 +00003508unsigned clang_isExpression(enum CXCursorKind K) {
3509 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3510}
3511
3512unsigned clang_isStatement(enum CXCursorKind K) {
3513 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3514}
3515
Douglas Gregor8be80e12011-07-06 03:00:34 +00003516unsigned clang_isAttribute(enum CXCursorKind K) {
3517 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
3518}
3519
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003520unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3521 return K == CXCursor_TranslationUnit;
3522}
3523
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003524unsigned clang_isPreprocessing(enum CXCursorKind K) {
3525 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3526}
3527
Ted Kremenekad6eff62010-03-08 21:17:29 +00003528unsigned clang_isUnexposed(enum CXCursorKind K) {
3529 switch (K) {
3530 case CXCursor_UnexposedDecl:
3531 case CXCursor_UnexposedExpr:
3532 case CXCursor_UnexposedStmt:
3533 case CXCursor_UnexposedAttr:
3534 return true;
3535 default:
3536 return false;
3537 }
3538}
3539
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003540CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003541 return C.kind;
3542}
3543
Douglas Gregor98258af2010-01-18 22:46:11 +00003544CXSourceLocation clang_getCursorLocation(CXCursor C) {
3545 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003546 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003547 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003548 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3549 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003550 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003551 }
3552
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003553 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003554 std::pair<ObjCProtocolDecl *, SourceLocation> P
3555 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003556 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003557 }
3558
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003559 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003560 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3561 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003562 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003563 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003564
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003565 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003566 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003567 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003568 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003569
3570 case CXCursor_TemplateRef: {
3571 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3572 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3573 }
3574
Douglas Gregor69319002010-08-31 23:48:11 +00003575 case CXCursor_NamespaceRef: {
3576 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3577 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3578 }
3579
Douglas Gregora67e03f2010-09-09 21:42:20 +00003580 case CXCursor_MemberRef: {
3581 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3582 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3583 }
3584
Ted Kremenek3064ef92010-08-27 21:34:58 +00003585 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003586 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3587 if (!BaseSpec)
3588 return clang_getNullLocation();
3589
3590 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3591 return cxloc::translateSourceLocation(getCursorContext(C),
3592 TSInfo->getTypeLoc().getBeginLoc());
3593
3594 return cxloc::translateSourceLocation(getCursorContext(C),
3595 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003596 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003597
Douglas Gregor36897b02010-09-10 00:22:18 +00003598 case CXCursor_LabelRef: {
3599 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3600 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3601 }
3602
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003603 case CXCursor_OverloadedDeclRef:
3604 return cxloc::translateSourceLocation(getCursorContext(C),
3605 getCursorOverloadedDeclRef(C).second);
3606
Douglas Gregorf46034a2010-01-18 23:41:10 +00003607 default:
3608 // FIXME: Need a way to enumerate all non-reference cases.
3609 llvm_unreachable("Missed a reference kind");
3610 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003611 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003612
3613 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003614 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003615 getLocationFromExpr(getCursorExpr(C)));
3616
Douglas Gregor36897b02010-09-10 00:22:18 +00003617 if (clang_isStatement(C.kind))
3618 return cxloc::translateSourceLocation(getCursorContext(C),
3619 getCursorStmt(C)->getLocStart());
3620
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003621 if (C.kind == CXCursor_PreprocessingDirective) {
3622 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3623 return cxloc::translateSourceLocation(getCursorContext(C), L);
3624 }
Douglas Gregor48072312010-03-18 15:23:44 +00003625
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003626 if (C.kind == CXCursor_MacroExpansion) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003627 SourceLocation L
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003628 = cxcursor::getCursorMacroExpansion(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003629 return cxloc::translateSourceLocation(getCursorContext(C), L);
3630 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003631
3632 if (C.kind == CXCursor_MacroDefinition) {
3633 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3634 return cxloc::translateSourceLocation(getCursorContext(C), L);
3635 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003636
3637 if (C.kind == CXCursor_InclusionDirective) {
3638 SourceLocation L
3639 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3640 return cxloc::translateSourceLocation(getCursorContext(C), L);
3641 }
3642
Ted Kremenek9a700d22010-05-12 06:16:13 +00003643 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003644 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003645
Douglas Gregorf46034a2010-01-18 23:41:10 +00003646 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003647 SourceLocation Loc = D->getLocation();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003648 // FIXME: Multiple variables declared in a single declaration
3649 // currently lack the information needed to correctly determine their
3650 // ranges when accounting for the type-specifier. We use context
3651 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3652 // and if so, whether it is the first decl.
3653 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3654 if (!cxcursor::isFirstInDeclGroup(C))
3655 Loc = VD->getLocation();
3656 }
3657
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003658 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003659}
Douglas Gregora7bde202010-01-19 00:34:46 +00003660
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003661} // end extern "C"
3662
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003663CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
3664 assert(TU);
3665
3666 // Guard against an invalid SourceLocation, or we may assert in one
3667 // of the following calls.
3668 if (SLoc.isInvalid())
3669 return clang_getNullCursor();
3670
3671 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
3672
3673 // Translate the given source location to make it point at the beginning of
3674 // the token under the cursor.
3675 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3676 CXXUnit->getASTContext().getLangOptions());
3677
3678 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3679 if (SLoc.isValid()) {
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003680 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003681 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
3682 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00003683 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003684 SourceLocation(SLoc));
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00003685 CursorVis.visitFileRegion();
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003686 }
3687
3688 return Result;
3689}
3690
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003691static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003692 if (clang_isReference(C.kind)) {
3693 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003694 case CXCursor_ObjCSuperClassRef:
3695 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003696
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003697 case CXCursor_ObjCProtocolRef:
3698 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003699
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003700 case CXCursor_ObjCClassRef:
3701 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003702
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003703 case CXCursor_TypeRef:
3704 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003705
3706 case CXCursor_TemplateRef:
3707 return getCursorTemplateRef(C).second;
3708
Douglas Gregor69319002010-08-31 23:48:11 +00003709 case CXCursor_NamespaceRef:
3710 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003711
3712 case CXCursor_MemberRef:
3713 return getCursorMemberRef(C).second;
3714
Ted Kremenek3064ef92010-08-27 21:34:58 +00003715 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003716 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003717
Douglas Gregor36897b02010-09-10 00:22:18 +00003718 case CXCursor_LabelRef:
3719 return getCursorLabelRef(C).second;
3720
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003721 case CXCursor_OverloadedDeclRef:
3722 return getCursorOverloadedDeclRef(C).second;
3723
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003724 default:
3725 // FIXME: Need a way to enumerate all non-reference cases.
3726 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003727 }
3728 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003729
3730 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003731 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003732
3733 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003734 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003735
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00003736 if (clang_isAttribute(C.kind))
3737 return getCursorAttr(C)->getRange();
3738
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003739 if (C.kind == CXCursor_PreprocessingDirective)
3740 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003741
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00003742 if (C.kind == CXCursor_MacroExpansion) {
3743 ASTUnit *TU = getCursorASTUnit(C);
3744 SourceRange Range = cxcursor::getCursorMacroExpansion(C)->getSourceRange();
3745 return TU->mapRangeFromPreamble(Range);
3746 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003747
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00003748 if (C.kind == CXCursor_MacroDefinition) {
3749 ASTUnit *TU = getCursorASTUnit(C);
3750 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
3751 return TU->mapRangeFromPreamble(Range);
3752 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003753
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00003754 if (C.kind == CXCursor_InclusionDirective) {
3755 ASTUnit *TU = getCursorASTUnit(C);
3756 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3757 return TU->mapRangeFromPreamble(Range);
3758 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003759
Ted Kremenek007a7c92010-11-01 23:26:51 +00003760 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3761 Decl *D = cxcursor::getCursorDecl(C);
3762 SourceRange R = D->getSourceRange();
3763 // FIXME: Multiple variables declared in a single declaration
3764 // currently lack the information needed to correctly determine their
3765 // ranges when accounting for the type-specifier. We use context
3766 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3767 // and if so, whether it is the first decl.
3768 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3769 if (!cxcursor::isFirstInDeclGroup(C))
3770 R.setBegin(VD->getLocation());
3771 }
3772 return R;
3773 }
Douglas Gregor66537982010-11-17 17:14:07 +00003774 return SourceRange();
3775}
3776
3777/// \brief Retrieves the "raw" cursor extent, which is then extended to include
3778/// the decl-specifier-seq for declarations.
3779static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
3780 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3781 Decl *D = cxcursor::getCursorDecl(C);
3782 SourceRange R = D->getSourceRange();
Douglas Gregor66537982010-11-17 17:14:07 +00003783
Douglas Gregor2494dd02011-03-01 01:34:45 +00003784 // Adjust the start of the location for declarations preceded by
3785 // declaration specifiers.
3786 SourceLocation StartLoc;
3787 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
3788 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
3789 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
3790 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
3791 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
3792 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
3793 }
3794
3795 if (StartLoc.isValid() && R.getBegin().isValid() &&
3796 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
3797 R.setBegin(StartLoc);
3798
3799 // FIXME: Multiple variables declared in a single declaration
3800 // currently lack the information needed to correctly determine their
3801 // ranges when accounting for the type-specifier. We use context
3802 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3803 // and if so, whether it is the first decl.
3804 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3805 if (!cxcursor::isFirstInDeclGroup(C))
3806 R.setBegin(VD->getLocation());
Douglas Gregor66537982010-11-17 17:14:07 +00003807 }
3808
3809 return R;
3810 }
3811
3812 return getRawCursorExtent(C);
3813}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003814
3815extern "C" {
3816
3817CXSourceRange clang_getCursorExtent(CXCursor C) {
3818 SourceRange R = getRawCursorExtent(C);
3819 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003820 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003821
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003822 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003823}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003824
3825CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003826 if (clang_isInvalid(C.kind))
3827 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003828
Ted Kremeneka60ed472010-11-16 08:15:36 +00003829 CXTranslationUnit tu = getCursorTU(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003830 if (clang_isDeclaration(C.kind)) {
3831 Decl *D = getCursorDecl(C);
3832 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003833 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003834 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003835 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003836 if (ObjCForwardProtocolDecl *Protocols
3837 = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003838 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), tu);
Chris Lattner5f9e2722011-07-23 10:55:15 +00003839 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00003840 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3841 return MakeCXCursor(Property, tu);
3842
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003843 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003844 }
3845
Douglas Gregor97b98722010-01-19 23:20:36 +00003846 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003847 Expr *E = getCursorExpr(C);
3848 Decl *D = getDeclFromExpr(E);
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003849 if (D) {
3850 CXCursor declCursor = MakeCXCursor(D, tu);
3851 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
3852 declCursor);
3853 return declCursor;
3854 }
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003855
3856 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003857 return MakeCursorOverloadedDeclRef(Ovl, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003858
Douglas Gregor97b98722010-01-19 23:20:36 +00003859 return clang_getNullCursor();
3860 }
3861
Douglas Gregor36897b02010-09-10 00:22:18 +00003862 if (clang_isStatement(C.kind)) {
3863 Stmt *S = getCursorStmt(C);
3864 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Ted Kremenek37c2e962011-03-15 23:47:49 +00003865 if (LabelDecl *label = Goto->getLabel())
3866 if (LabelStmt *labelS = label->getStmt())
3867 return MakeCXCursor(labelS, getCursorDecl(C), tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003868
3869 return clang_getNullCursor();
3870 }
3871
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003872 if (C.kind == CXCursor_MacroExpansion) {
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003873 if (MacroDefinition *Def = getCursorMacroExpansion(C)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003874 return MakeMacroDefinitionCursor(Def, tu);
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003875 }
3876
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003877 if (!clang_isReference(C.kind))
3878 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003879
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003880 switch (C.kind) {
3881 case CXCursor_ObjCSuperClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003882 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003883
3884 case CXCursor_ObjCProtocolRef: {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003885 return MakeCXCursor(getCursorObjCProtocolRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003886
3887 case CXCursor_ObjCClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003888 return MakeCXCursor(getCursorObjCClassRef(C).first, tu );
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003889
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003890 case CXCursor_TypeRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003891 return MakeCXCursor(getCursorTypeRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003892
3893 case CXCursor_TemplateRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003894 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003895
Douglas Gregor69319002010-08-31 23:48:11 +00003896 case CXCursor_NamespaceRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003897 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
Douglas Gregor69319002010-08-31 23:48:11 +00003898
Douglas Gregora67e03f2010-09-09 21:42:20 +00003899 case CXCursor_MemberRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003900 return MakeCXCursor(getCursorMemberRef(C).first, tu );
Douglas Gregora67e03f2010-09-09 21:42:20 +00003901
Ted Kremenek3064ef92010-08-27 21:34:58 +00003902 case CXCursor_CXXBaseSpecifier: {
3903 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3904 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003905 tu ));
Ted Kremenek3064ef92010-08-27 21:34:58 +00003906 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003907
Douglas Gregor36897b02010-09-10 00:22:18 +00003908 case CXCursor_LabelRef:
3909 // FIXME: We end up faking the "parent" declaration here because we
3910 // don't want to make CXCursor larger.
3911 return MakeCXCursor(getCursorLabelRef(C).first,
Ted Kremeneka60ed472010-11-16 08:15:36 +00003912 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
3913 .getTranslationUnitDecl(),
3914 tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003915
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003916 case CXCursor_OverloadedDeclRef:
3917 return C;
3918
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003919 default:
3920 // We would prefer to enumerate all non-reference cursor kinds here.
3921 llvm_unreachable("Unhandled reference cursor kind");
3922 break;
3923 }
3924 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003925
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003926 return clang_getNullCursor();
3927}
3928
Douglas Gregorb6998662010-01-19 19:34:47 +00003929CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003930 if (clang_isInvalid(C.kind))
3931 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003932
Ted Kremeneka60ed472010-11-16 08:15:36 +00003933 CXTranslationUnit TU = getCursorTU(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003934
Douglas Gregorb6998662010-01-19 19:34:47 +00003935 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003936 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003937 C = clang_getCursorReferenced(C);
3938 WasReference = true;
3939 }
3940
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003941 if (C.kind == CXCursor_MacroExpansion)
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003942 return clang_getCursorReferenced(C);
3943
Douglas Gregorb6998662010-01-19 19:34:47 +00003944 if (!clang_isDeclaration(C.kind))
3945 return clang_getNullCursor();
3946
3947 Decl *D = getCursorDecl(C);
3948 if (!D)
3949 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003950
Douglas Gregorb6998662010-01-19 19:34:47 +00003951 switch (D->getKind()) {
3952 // Declaration kinds that don't really separate the notions of
3953 // declaration and definition.
3954 case Decl::Namespace:
3955 case Decl::Typedef:
Richard Smith162e1c12011-04-15 14:24:37 +00003956 case Decl::TypeAlias:
Richard Smith3e4c6c42011-05-05 21:57:07 +00003957 case Decl::TypeAliasTemplate:
Douglas Gregorb6998662010-01-19 19:34:47 +00003958 case Decl::TemplateTypeParm:
3959 case Decl::EnumConstant:
3960 case Decl::Field:
Benjamin Kramerd9811462010-11-21 14:11:41 +00003961 case Decl::IndirectField:
Douglas Gregorb6998662010-01-19 19:34:47 +00003962 case Decl::ObjCIvar:
3963 case Decl::ObjCAtDefsField:
3964 case Decl::ImplicitParam:
3965 case Decl::ParmVar:
3966 case Decl::NonTypeTemplateParm:
3967 case Decl::TemplateTemplateParm:
3968 case Decl::ObjCCategoryImpl:
3969 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00003970 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00003971 case Decl::LinkageSpec:
3972 case Decl::ObjCPropertyImpl:
3973 case Decl::FileScopeAsm:
3974 case Decl::StaticAssert:
3975 case Decl::Block:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003976 case Decl::Label: // FIXME: Is this right??
Francois Pichetaf0f4d02011-08-14 03:52:19 +00003977 case Decl::ClassScopeFunctionSpecialization:
Douglas Gregorb6998662010-01-19 19:34:47 +00003978 return C;
3979
3980 // Declaration kinds that don't make any sense here, but are
3981 // nonetheless harmless.
3982 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00003983 break;
3984
3985 // Declaration kinds for which the definition is not resolvable.
3986 case Decl::UnresolvedUsingTypename:
3987 case Decl::UnresolvedUsingValue:
3988 break;
3989
3990 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003991 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003992 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003993
3994 case Decl::NamespaceAlias:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003995 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003996
3997 case Decl::Enum:
3998 case Decl::Record:
3999 case Decl::CXXRecord:
4000 case Decl::ClassTemplateSpecialization:
4001 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00004002 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004003 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004004 return clang_getNullCursor();
4005
4006 case Decl::Function:
4007 case Decl::CXXMethod:
4008 case Decl::CXXConstructor:
4009 case Decl::CXXDestructor:
4010 case Decl::CXXConversion: {
4011 const FunctionDecl *Def = 0;
4012 if (cast<FunctionDecl>(D)->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004013 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004014 return clang_getNullCursor();
4015 }
4016
4017 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00004018 // Ask the variable if it has a definition.
4019 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004020 return MakeCXCursor(Def, TU);
Sebastian Redl31310a22010-02-01 20:16:42 +00004021 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00004022 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004023
Douglas Gregorb6998662010-01-19 19:34:47 +00004024 case Decl::FunctionTemplate: {
4025 const FunctionDecl *Def = 0;
4026 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004027 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004028 return clang_getNullCursor();
4029 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004030
Douglas Gregorb6998662010-01-19 19:34:47 +00004031 case Decl::ClassTemplate: {
4032 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00004033 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00004034 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004035 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004036 return clang_getNullCursor();
4037 }
4038
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004039 case Decl::Using:
4040 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004041 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004042
4043 case Decl::UsingShadow:
4044 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004045 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004046 TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004047
4048 case Decl::ObjCMethod: {
4049 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
4050 if (Method->isThisDeclarationADefinition())
4051 return C;
4052
4053 // Dig out the method definition in the associated
4054 // @implementation, if we have it.
4055 // FIXME: The ASTs should make finding the definition easier.
4056 if (ObjCInterfaceDecl *Class
4057 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
4058 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
4059 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
4060 Method->isInstanceMethod()))
4061 if (Def->isThisDeclarationADefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004062 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004063
4064 return clang_getNullCursor();
4065 }
4066
4067 case Decl::ObjCCategory:
4068 if (ObjCCategoryImplDecl *Impl
4069 = cast<ObjCCategoryDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004070 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004071 return clang_getNullCursor();
4072
4073 case Decl::ObjCProtocol:
4074 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
4075 return C;
4076 return clang_getNullCursor();
4077
4078 case Decl::ObjCInterface:
4079 // There are two notions of a "definition" for an Objective-C
4080 // class: the interface and its implementation. When we resolved a
4081 // reference to an Objective-C class, produce the @interface as
4082 // the definition; when we were provided with the interface,
4083 // produce the @implementation as the definition.
4084 if (WasReference) {
4085 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
4086 return C;
4087 } else if (ObjCImplementationDecl *Impl
4088 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004089 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004090 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004091
Douglas Gregorb6998662010-01-19 19:34:47 +00004092 case Decl::ObjCProperty:
4093 // FIXME: We don't really know where to find the
4094 // ObjCPropertyImplDecls that implement this property.
4095 return clang_getNullCursor();
4096
4097 case Decl::ObjCCompatibleAlias:
4098 if (ObjCInterfaceDecl *Class
4099 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
4100 if (!Class->isForwardDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004101 return MakeCXCursor(Class, TU);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004102
Douglas Gregorb6998662010-01-19 19:34:47 +00004103 return clang_getNullCursor();
4104
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004105 case Decl::ObjCForwardProtocol:
4106 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004107 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004108
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004109 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004110 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004111 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004112
4113 case Decl::Friend:
4114 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004115 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004116 return clang_getNullCursor();
4117
4118 case Decl::FriendTemplate:
4119 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004120 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004121 return clang_getNullCursor();
4122 }
4123
4124 return clang_getNullCursor();
4125}
4126
4127unsigned clang_isCursorDefinition(CXCursor C) {
4128 if (!clang_isDeclaration(C.kind))
4129 return 0;
4130
4131 return clang_getCursorDefinition(C) == C;
4132}
4133
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004134CXCursor clang_getCanonicalCursor(CXCursor C) {
4135 if (!clang_isDeclaration(C.kind))
4136 return C;
4137
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004138 if (Decl *D = getCursorDecl(C)) {
Argyrios Kyrtzidisdebb00f2011-07-15 22:37:58 +00004139 if (ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
4140 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
4141 return MakeCXCursor(CatD, getCursorTU(C));
4142
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004143 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
4144 if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
4145 return MakeCXCursor(IFD, getCursorTU(C));
4146
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004147 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004148 }
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004149
4150 return C;
4151}
4152
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004153unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004154 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004155 return 0;
4156
4157 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
4158 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
4159 return E->getNumDecls();
4160
4161 if (OverloadedTemplateStorage *S
4162 = Storage.dyn_cast<OverloadedTemplateStorage*>())
4163 return S->size();
4164
4165 Decl *D = Storage.get<Decl*>();
4166 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00004167 return Using->shadow_size();
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00004168 if (isa<ObjCClassDecl>(D))
4169 return 1;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004170 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
4171 return Protocols->protocol_size();
4172
4173 return 0;
4174}
4175
4176CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004177 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004178 return clang_getNullCursor();
4179
4180 if (index >= clang_getNumOverloadedDecls(cursor))
4181 return clang_getNullCursor();
4182
Ted Kremeneka60ed472010-11-16 08:15:36 +00004183 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004184 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
4185 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004186 return MakeCXCursor(E->decls_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004187
4188 if (OverloadedTemplateStorage *S
4189 = Storage.dyn_cast<OverloadedTemplateStorage*>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004190 return MakeCXCursor(S->begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004191
4192 Decl *D = Storage.get<Decl*>();
4193 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
4194 // FIXME: This is, unfortunately, linear time.
4195 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
4196 std::advance(Pos, index);
Ted Kremeneka60ed472010-11-16 08:15:36 +00004197 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004198 }
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004199 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00004200 return MakeCXCursor(Classes->getForwardInterfaceDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004201 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004202 return MakeCXCursor(Protocols->protocol_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004203
4204 return clang_getNullCursor();
4205}
4206
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00004207void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00004208 const char **startBuf,
4209 const char **endBuf,
4210 unsigned *startLine,
4211 unsigned *startColumn,
4212 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00004213 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00004214 assert(getCursorDecl(C) && "CXCursor has null decl");
4215 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00004216 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
4217 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004218
Steve Naroff4ade6d62009-09-23 17:52:52 +00004219 SourceManager &SM = FD->getASTContext().getSourceManager();
4220 *startBuf = SM.getCharacterData(Body->getLBracLoc());
4221 *endBuf = SM.getCharacterData(Body->getRBracLoc());
4222 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
4223 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
4224 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
4225 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
4226}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004227
Douglas Gregor430d7a12011-07-25 17:48:11 +00004228
4229CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
4230 unsigned PieceIndex) {
4231 RefNamePieces Pieces;
4232
4233 switch (C.kind) {
4234 case CXCursor_MemberRefExpr:
4235 if (MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
4236 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
4237 E->getQualifierLoc().getSourceRange());
4238 break;
4239
4240 case CXCursor_DeclRefExpr:
4241 if (DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C)))
4242 Pieces = buildPieces(NameFlags, false, E->getNameInfo(),
4243 E->getQualifierLoc().getSourceRange(),
4244 E->getExplicitTemplateArgsOpt());
4245 break;
4246
4247 case CXCursor_CallExpr:
4248 if (CXXOperatorCallExpr *OCE =
4249 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
4250 Expr *Callee = OCE->getCallee();
4251 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
4252 Callee = ICE->getSubExpr();
4253
4254 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
4255 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
4256 DRE->getQualifierLoc().getSourceRange());
4257 }
4258 break;
4259
4260 default:
4261 break;
4262 }
4263
4264 if (Pieces.empty()) {
4265 if (PieceIndex == 0)
4266 return clang_getCursorExtent(C);
4267 } else if (PieceIndex < Pieces.size()) {
4268 SourceRange R = Pieces[PieceIndex];
4269 if (R.isValid())
4270 return cxloc::translateSourceRange(getCursorContext(C), R);
4271 }
4272
4273 return clang_getNullRange();
4274}
4275
Douglas Gregor0a812cf2010-02-18 23:07:20 +00004276void clang_enableStackTraces(void) {
4277 llvm::sys::PrintStackTraceOnErrorSignal();
4278}
4279
Daniel Dunbar995aaf92010-11-04 01:26:29 +00004280void clang_executeOnThread(void (*fn)(void*), void *user_data,
4281 unsigned stack_size) {
4282 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
4283}
4284
Ted Kremenekfb480492010-01-13 21:46:36 +00004285} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00004286
Ted Kremenekfb480492010-01-13 21:46:36 +00004287//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004288// Token-based Operations.
4289//===----------------------------------------------------------------------===//
4290
4291/* CXToken layout:
4292 * int_data[0]: a CXTokenKind
4293 * int_data[1]: starting token location
4294 * int_data[2]: token length
4295 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004296 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004297 * otherwise unused.
4298 */
4299extern "C" {
4300
4301CXTokenKind clang_getTokenKind(CXToken CXTok) {
4302 return static_cast<CXTokenKind>(CXTok.int_data[0]);
4303}
4304
4305CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
4306 switch (clang_getTokenKind(CXTok)) {
4307 case CXToken_Identifier:
4308 case CXToken_Keyword:
4309 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004310 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
4311 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004312
4313 case CXToken_Literal: {
4314 // We have stashed the starting pointer in the ptr_data field. Use it.
4315 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Chris Lattner5f9e2722011-07-23 10:55:15 +00004316 return createCXString(StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004317 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004318
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004319 case CXToken_Punctuation:
4320 case CXToken_Comment:
4321 break;
4322 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004323
4324 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004325 // deconstructing the source location.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004326 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004327 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004328 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004329
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004330 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
4331 std::pair<FileID, unsigned> LocInfo
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004332 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00004333 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004334 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004335 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
4336 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00004337 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004338
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004339 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004340}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004341
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004342CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004343 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004344 if (!CXXUnit)
4345 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004346
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004347 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
4348 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4349}
4350
4351CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004352 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor5352ac02010-01-28 00:27:43 +00004353 if (!CXXUnit)
4354 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004355
4356 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004357 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4358}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004359
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004360static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
4361 SmallVectorImpl<CXToken> &CXTokens) {
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004362 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4363 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004364 = SourceMgr.getDecomposedLoc(Range.getBegin());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004365 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004366 = SourceMgr.getDecomposedLoc(Range.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004367
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004368 // Cannot tokenize across files.
4369 if (BeginLocInfo.first != EndLocInfo.first)
4370 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004371
4372 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004373 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004374 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004375 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00004376 if (Invalid)
4377 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00004378
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004379 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4380 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004381 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004382 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004383
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004384 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004385 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004386 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00004387 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004388 do {
4389 // Lex the next token
4390 Lex.LexFromRawLexer(Tok);
4391 if (Tok.is(tok::eof))
4392 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004393
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004394 // Initialize the CXToken.
4395 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004396
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004397 // - Common fields
4398 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
4399 CXTok.int_data[2] = Tok.getLength();
4400 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004401
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004402 // - Kind-specific fields
4403 if (Tok.isLiteral()) {
4404 CXTok.int_data[0] = CXToken_Literal;
4405 CXTok.ptr_data = (void *)Tok.getLiteralData();
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004406 } else if (Tok.is(tok::raw_identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00004407 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004408 IdentifierInfo *II
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004409 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004410
David Chisnall096428b2010-10-13 21:44:48 +00004411 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004412 CXTok.int_data[0] = CXToken_Keyword;
4413 }
4414 else {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004415 CXTok.int_data[0] = Tok.is(tok::identifier)
4416 ? CXToken_Identifier
4417 : CXToken_Keyword;
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004418 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004419 CXTok.ptr_data = II;
4420 } else if (Tok.is(tok::comment)) {
4421 CXTok.int_data[0] = CXToken_Comment;
4422 CXTok.ptr_data = 0;
4423 } else {
4424 CXTok.int_data[0] = CXToken_Punctuation;
4425 CXTok.ptr_data = 0;
4426 }
4427 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00004428 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004429 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004430}
4431
4432void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
4433 CXToken **Tokens, unsigned *NumTokens) {
4434 if (Tokens)
4435 *Tokens = 0;
4436 if (NumTokens)
4437 *NumTokens = 0;
4438
4439 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4440 if (!CXXUnit || !Tokens || !NumTokens)
4441 return;
4442
4443 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4444
4445 SourceRange R = cxloc::translateCXSourceRange(Range);
4446 if (R.isInvalid())
4447 return;
4448
4449 SmallVector<CXToken, 32> CXTokens;
4450 getTokens(CXXUnit, R, CXTokens);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004451
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004452 if (CXTokens.empty())
4453 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004454
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004455 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
4456 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
4457 *NumTokens = CXTokens.size();
4458}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004459
Ted Kremenek6db61092010-05-05 00:55:15 +00004460void clang_disposeTokens(CXTranslationUnit TU,
4461 CXToken *Tokens, unsigned NumTokens) {
4462 free(Tokens);
4463}
4464
4465} // end: extern "C"
4466
4467//===----------------------------------------------------------------------===//
4468// Token annotation APIs.
4469//===----------------------------------------------------------------------===//
4470
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004471typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004472static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4473 CXCursor parent,
4474 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00004475namespace {
4476class AnnotateTokensWorker {
4477 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004478 CXToken *Tokens;
4479 CXCursor *Cursors;
4480 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004481 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00004482 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004483 CursorVisitor AnnotateVis;
4484 SourceManager &SrcMgr;
Douglas Gregorf5251602011-03-08 17:10:18 +00004485 bool HasContextSensitiveKeywords;
4486
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004487 bool MoreTokens() const { return TokIdx < NumTokens; }
4488 unsigned NextToken() const { return TokIdx; }
4489 void AdvanceToken() { ++TokIdx; }
4490 SourceLocation GetTokenLoc(unsigned tokI) {
4491 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4492 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004493 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004494 return Tokens[tokI].int_data[3] != 0;
4495 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004496 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004497 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[3]);
4498 }
4499
4500 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004501 void annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
4502 SourceRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004503
Ted Kremenek6db61092010-05-05 00:55:15 +00004504public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00004505 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004506 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004507 CXTranslationUnit tu, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00004508 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00004509 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004510 AnnotateVis(tu,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00004511 AnnotateTokensVisitor, this,
4512 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00004513 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00004514 RegionOfInterest),
Douglas Gregorf5251602011-03-08 17:10:18 +00004515 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()),
4516 HasContextSensitiveKeywords(false) { }
Ted Kremenek11949cb2010-05-05 00:55:17 +00004517
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004518 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00004519 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004520 void AnnotateTokens(CXCursor parent);
Ted Kremenekab979612010-11-11 08:05:23 +00004521 void AnnotateTokens() {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004522 AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getTU()));
Ted Kremenekab979612010-11-11 08:05:23 +00004523 }
Douglas Gregorf5251602011-03-08 17:10:18 +00004524
4525 /// \brief Determine whether the annotator saw any cursors that have
4526 /// context-sensitive keywords.
4527 bool hasContextSensitiveKeywords() const {
4528 return HasContextSensitiveKeywords;
4529 }
Ted Kremenek6db61092010-05-05 00:55:15 +00004530};
4531}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004532
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004533void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
4534 // Walk the AST within the region of interest, annotating tokens
4535 // along the way.
4536 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00004537
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004538 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4539 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004540 if (Pos != Annotated.end() &&
4541 (clang_isInvalid(Cursors[I].kind) ||
4542 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004543 Cursors[I] = Pos->second;
4544 }
4545
4546 // Finish up annotating any tokens left.
4547 if (!MoreTokens())
4548 return;
4549
4550 const CXCursor &C = clang_getNullCursor();
4551 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
4552 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4553 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004554 }
4555}
4556
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004557/// \brief It annotates and advances tokens with a cursor until the comparison
4558//// between the cursor location and the source range is the same as
4559/// \arg compResult.
4560///
4561/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
4562/// Pass RangeOverlap to annotate tokens inside a range.
4563void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
4564 RangeComparisonResult compResult,
4565 SourceRange range) {
4566 while (MoreTokens()) {
4567 const unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004568 if (isFunctionMacroToken(I))
4569 return annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004570
4571 SourceLocation TokLoc = GetTokenLoc(I);
4572 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4573 Cursors[I] = updateC;
4574 AdvanceToken();
4575 continue;
4576 }
4577 break;
4578 }
4579}
4580
4581/// \brief Special annotation handling for macro argument tokens.
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004582void AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
4583 CXCursor updateC,
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004584 RangeComparisonResult compResult,
4585 SourceRange range) {
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004586 assert(MoreTokens());
4587 assert(isFunctionMacroToken(NextToken()) &&
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004588 "Should be called only for macro arg tokens");
4589
4590 // This works differently than annotateAndAdvanceTokens; because expanded
4591 // macro arguments can have arbitrary translation-unit source order, we do not
4592 // advance the token index one by one until a token fails the range test.
4593 // We only advance once past all of the macro arg tokens if all of them
4594 // pass the range test. If one of them fails we keep the token index pointing
4595 // at the start of the macro arg tokens so that the failing token will be
4596 // annotated by a subsequent annotation try.
4597
4598 bool atLeastOneCompFail = false;
4599
4600 unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004601 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
4602 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004603 if (TokLoc.isFileID())
4604 continue; // not macro arg token, it's parens or comma.
4605 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4606 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
4607 Cursors[I] = updateC;
4608 } else
4609 atLeastOneCompFail = true;
4610 }
4611
4612 if (!atLeastOneCompFail)
4613 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
4614}
4615
Ted Kremenek6db61092010-05-05 00:55:15 +00004616enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004617AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004618 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004619 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004620 if (cursorRange.isInvalid())
4621 return CXChildVisit_Recurse;
Douglas Gregorf5251602011-03-08 17:10:18 +00004622
4623 if (!HasContextSensitiveKeywords) {
4624 // Objective-C properties can have context-sensitive keywords.
4625 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
4626 if (ObjCPropertyDecl *Property
4627 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
4628 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
4629 }
4630 // Objective-C methods can have context-sensitive keywords.
4631 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
4632 cursor.kind == CXCursor_ObjCClassMethodDecl) {
4633 if (ObjCMethodDecl *Method
4634 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
4635 if (Method->getObjCDeclQualifier())
4636 HasContextSensitiveKeywords = true;
4637 else {
4638 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
4639 PEnd = Method->param_end();
4640 P != PEnd; ++P) {
4641 if ((*P)->getObjCDeclQualifier()) {
4642 HasContextSensitiveKeywords = true;
4643 break;
4644 }
4645 }
4646 }
4647 }
4648 }
4649 // C++ methods can have context-sensitive keywords.
4650 else if (cursor.kind == CXCursor_CXXMethod) {
4651 if (CXXMethodDecl *Method
4652 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
4653 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
4654 HasContextSensitiveKeywords = true;
4655 }
4656 }
4657 // C++ classes can have context-sensitive keywords.
4658 else if (cursor.kind == CXCursor_StructDecl ||
4659 cursor.kind == CXCursor_ClassDecl ||
4660 cursor.kind == CXCursor_ClassTemplate ||
4661 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
4662 if (Decl *D = getCursorDecl(cursor))
4663 if (D->hasAttr<FinalAttr>())
4664 HasContextSensitiveKeywords = true;
4665 }
4666 }
4667
Douglas Gregor4419b672010-10-21 06:10:04 +00004668 if (clang_isPreprocessing(cursor.kind)) {
Chandler Carruthcea731a2011-07-14 16:07:57 +00004669 // For macro expansions, just note where the beginning of the macro
4670 // expansion occurs.
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004671 if (cursor.kind == CXCursor_MacroExpansion) {
Douglas Gregor4419b672010-10-21 06:10:04 +00004672 Annotated[Loc.int_data] = cursor;
4673 return CXChildVisit_Recurse;
4674 }
4675
Douglas Gregor4419b672010-10-21 06:10:04 +00004676 // Items in the preprocessing record are kept separate from items in
4677 // declarations, so we keep a separate token index.
4678 unsigned SavedTokIdx = TokIdx;
4679 TokIdx = PreprocessingTokIdx;
4680
4681 // Skip tokens up until we catch up to the beginning of the preprocessing
4682 // entry.
4683 while (MoreTokens()) {
4684 const unsigned I = NextToken();
4685 SourceLocation TokLoc = GetTokenLoc(I);
4686 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4687 case RangeBefore:
4688 AdvanceToken();
4689 continue;
4690 case RangeAfter:
4691 case RangeOverlap:
4692 break;
4693 }
4694 break;
4695 }
4696
4697 // Look at all of the tokens within this range.
4698 while (MoreTokens()) {
4699 const unsigned I = NextToken();
4700 SourceLocation TokLoc = GetTokenLoc(I);
4701 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4702 case RangeBefore:
David Blaikieb219cfc2011-09-23 05:06:16 +00004703 llvm_unreachable("Infeasible");
Douglas Gregor4419b672010-10-21 06:10:04 +00004704 case RangeAfter:
4705 break;
4706 case RangeOverlap:
4707 Cursors[I] = cursor;
4708 AdvanceToken();
4709 continue;
4710 }
4711 break;
4712 }
4713
4714 // Save the preprocessing token index; restore the non-preprocessing
4715 // token index.
4716 PreprocessingTokIdx = TokIdx;
4717 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004718 return CXChildVisit_Recurse;
4719 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004720
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004721 if (cursorRange.isInvalid())
4722 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004723
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004724 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4725
Ted Kremeneka333c662010-05-12 05:29:33 +00004726 // Adjust the annotated range based specific declarations.
4727 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4728 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004729 Decl *D = cxcursor::getCursorDecl(cursor);
Douglas Gregor2494dd02011-03-01 01:34:45 +00004730
4731 SourceLocation StartLoc;
Ted Kremenek23173d72010-05-18 21:09:07 +00004732 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00004733 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
4734 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
4735 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
4736 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
4737 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
Ted Kremeneka333c662010-05-12 05:29:33 +00004738 }
Douglas Gregor2494dd02011-03-01 01:34:45 +00004739
4740 if (StartLoc.isValid() && L.isValid() &&
4741 SrcMgr.isBeforeInTranslationUnit(StartLoc, L))
4742 cursorRange.setBegin(StartLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004743 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004744
Ted Kremenek3f404602010-08-14 01:14:06 +00004745 // If the location of the cursor occurs within a macro instantiation, record
4746 // the spelling location of the cursor in our annotation map. We can then
4747 // paper over the token labelings during a post-processing step to try and
4748 // get cursor mappings for tokens that are the *arguments* of a macro
4749 // instantiation.
4750 if (L.isMacroID()) {
4751 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4752 // Only invalidate the old annotation if it isn't part of a preprocessing
4753 // directive. Here we assume that the default construction of CXCursor
4754 // results in CXCursor.kind being an initialized value (i.e., 0). If
4755 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004756
Ted Kremenek3f404602010-08-14 01:14:06 +00004757 CXCursor &oldC = Annotated[rawEncoding];
4758 if (!clang_isPreprocessing(oldC.kind))
4759 oldC = cursor;
4760 }
4761
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004762 const enum CXCursorKind K = clang_getCursorKind(parent);
4763 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004764 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4765 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004766
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004767 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004768
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00004769 // Avoid having the cursor of an expression "overwrite" the annotation of the
4770 // variable declaration that it belongs to.
4771 // This can happen for C++ constructor expressions whose range generally
4772 // include the variable declaration, e.g.:
4773 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
4774 if (clang_isExpression(cursorK)) {
4775 Expr *E = getCursorExpr(cursor);
Argyrios Kyrtzidis8ccac3d2011-06-29 22:20:07 +00004776 if (Decl *D = getCursorParentDecl(cursor)) {
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00004777 const unsigned I = NextToken();
4778 if (E->getLocStart().isValid() && D->getLocation().isValid() &&
4779 E->getLocStart() == D->getLocation() &&
4780 E->getLocStart() == GetTokenLoc(I)) {
4781 Cursors[I] = updateC;
4782 AdvanceToken();
4783 }
4784 }
4785 }
4786
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004787 // Visit children to get their cursor information.
4788 const unsigned BeforeChildren = NextToken();
4789 VisitChildren(cursor);
4790 const unsigned AfterChildren = NextToken();
4791
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004792 // Scan the tokens that are at the end of the cursor, but are not captured
4793 // but the child cursors.
4794 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
Ted Kremenek6db61092010-05-05 00:55:15 +00004795
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004796 // Scan the tokens that are at the beginning of the cursor, but are not
4797 // capture by the child cursors.
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004798 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4799 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4800 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004801
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004802 Cursors[I] = cursor;
4803 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004804
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004805 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004806}
4807
Ted Kremenek6db61092010-05-05 00:55:15 +00004808static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4809 CXCursor parent,
4810 CXClientData client_data) {
4811 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4812}
4813
Ted Kremenek6628a612011-03-18 22:51:30 +00004814namespace {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004815
4816/// \brief Uses the macro expansions in the preprocessing record to find
4817/// and mark tokens that are macro arguments. This info is used by the
4818/// AnnotateTokensWorker.
4819class MarkMacroArgTokensVisitor {
4820 SourceManager &SM;
4821 CXToken *Tokens;
4822 unsigned NumTokens;
4823 unsigned CurIdx;
4824
4825public:
4826 MarkMacroArgTokensVisitor(SourceManager &SM,
4827 CXToken *tokens, unsigned numTokens)
4828 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
4829
4830 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
4831 if (cursor.kind != CXCursor_MacroExpansion)
4832 return CXChildVisit_Continue;
4833
4834 SourceRange macroRange = getCursorMacroExpansion(cursor)->getSourceRange();
4835 if (macroRange.getBegin() == macroRange.getEnd())
4836 return CXChildVisit_Continue; // it's not a function macro.
4837
4838 for (; CurIdx < NumTokens; ++CurIdx) {
4839 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
4840 macroRange.getBegin()))
4841 break;
4842 }
4843
4844 if (CurIdx == NumTokens)
4845 return CXChildVisit_Break;
4846
4847 for (; CurIdx < NumTokens; ++CurIdx) {
4848 SourceLocation tokLoc = getTokenLoc(CurIdx);
4849 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
4850 break;
4851
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004852 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004853 }
4854
4855 if (CurIdx == NumTokens)
4856 return CXChildVisit_Break;
4857
4858 return CXChildVisit_Continue;
4859 }
4860
4861private:
4862 SourceLocation getTokenLoc(unsigned tokI) {
4863 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4864 }
4865
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004866 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004867 // The third field is reserved and currently not used. Use it here
4868 // to mark macro arg expanded tokens with their expanded locations.
4869 Tokens[tokI].int_data[3] = loc.getRawEncoding();
4870 }
4871};
4872
4873} // end anonymous namespace
4874
4875static CXChildVisitResult
4876MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
4877 CXClientData client_data) {
4878 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
4879 parent);
4880}
4881
4882namespace {
Ted Kremenek6628a612011-03-18 22:51:30 +00004883 struct clang_annotateTokens_Data {
4884 CXTranslationUnit TU;
4885 ASTUnit *CXXUnit;
4886 CXToken *Tokens;
4887 unsigned NumTokens;
4888 CXCursor *Cursors;
4889 };
4890}
4891
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004892static void annotatePreprocessorTokens(CXTranslationUnit TU,
4893 SourceRange RegionOfInterest,
4894 AnnotateTokensData &Annotated) {
4895 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4896
4897 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4898 std::pair<FileID, unsigned> BeginLocInfo
4899 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4900 std::pair<FileID, unsigned> EndLocInfo
4901 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
4902
4903 if (BeginLocInfo.first != EndLocInfo.first)
4904 return;
4905
4906 StringRef Buffer;
4907 bool Invalid = false;
4908 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
4909 if (Buffer.empty() || Invalid)
4910 return;
4911
4912 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4913 CXXUnit->getASTContext().getLangOptions(),
4914 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
4915 Buffer.end());
4916 Lex.SetCommentRetentionState(true);
4917
4918 // Lex tokens in raw mode until we hit the end of the range, to avoid
4919 // entering #includes or expanding macros.
4920 while (true) {
4921 Token Tok;
4922 Lex.LexFromRawLexer(Tok);
4923
4924 reprocess:
4925 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4926 // We have found a preprocessing directive. Gobble it up so that we
4927 // don't see it while preprocessing these tokens later, but keep track
4928 // of all of the token locations inside this preprocessing directive so
4929 // that we can annotate them appropriately.
4930 //
4931 // FIXME: Some simple tests here could identify macro definitions and
4932 // #undefs, to provide specific cursor kinds for those.
4933 SmallVector<SourceLocation, 32> Locations;
4934 do {
4935 Locations.push_back(Tok.getLocation());
4936 Lex.LexFromRawLexer(Tok);
4937 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
4938
4939 using namespace cxcursor;
4940 CXCursor Cursor
4941 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4942 Locations.back()),
4943 TU);
4944 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4945 Annotated[Locations[I].getRawEncoding()] = Cursor;
4946 }
4947
4948 if (Tok.isAtStartOfLine())
4949 goto reprocess;
4950
4951 continue;
4952 }
4953
4954 if (Tok.is(tok::eof))
4955 break;
4956 }
4957}
4958
Ted Kremenekab979612010-11-11 08:05:23 +00004959// This gets run a separate thread to avoid stack blowout.
Ted Kremenek6628a612011-03-18 22:51:30 +00004960static void clang_annotateTokensImpl(void *UserData) {
4961 CXTranslationUnit TU = ((clang_annotateTokens_Data*)UserData)->TU;
4962 ASTUnit *CXXUnit = ((clang_annotateTokens_Data*)UserData)->CXXUnit;
4963 CXToken *Tokens = ((clang_annotateTokens_Data*)UserData)->Tokens;
4964 const unsigned NumTokens = ((clang_annotateTokens_Data*)UserData)->NumTokens;
4965 CXCursor *Cursors = ((clang_annotateTokens_Data*)UserData)->Cursors;
4966
4967 // Determine the region of interest, which contains all of the tokens.
4968 SourceRange RegionOfInterest;
4969 RegionOfInterest.setBegin(
4970 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
4971 RegionOfInterest.setEnd(
4972 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
4973 Tokens[NumTokens-1])));
4974
4975 // A mapping from the source locations found when re-lexing or traversing the
4976 // region of interest to the corresponding cursors.
4977 AnnotateTokensData Annotated;
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004978
Ted Kremenek6628a612011-03-18 22:51:30 +00004979 // Relex the tokens within the source range to look for preprocessing
4980 // directives.
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004981 annotatePreprocessorTokens(TU, RegionOfInterest, Annotated);
Ted Kremenek6628a612011-03-18 22:51:30 +00004982
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004983 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
4984 // Search and mark tokens that are macro argument expansions.
4985 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
4986 Tokens, NumTokens);
4987 CursorVisitor MacroArgMarker(TU,
4988 MarkMacroArgTokensVisitorDelegate, &Visitor,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00004989 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00004990 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00004991 RegionOfInterest);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004992 MacroArgMarker.visitPreprocessedEntitiesInRegion();
4993 }
4994
Ted Kremenek6628a612011-03-18 22:51:30 +00004995 // Annotate all of the source locations in the region of interest that map to
4996 // a specific cursor.
4997 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
4998 TU, RegionOfInterest);
4999
5000 // FIXME: We use a ridiculous stack size here because the data-recursion
5001 // algorithm uses a large stack frame than the non-data recursive version,
5002 // and AnnotationTokensWorker currently transforms the data-recursion
5003 // algorithm back into a traditional recursion by explicitly calling
5004 // VisitChildren(). We will need to remove this explicit recursive call.
5005 W.AnnotateTokens();
5006
5007 // If we ran into any entities that involve context-sensitive keywords,
5008 // take another pass through the tokens to mark them as such.
5009 if (W.hasContextSensitiveKeywords()) {
5010 for (unsigned I = 0; I != NumTokens; ++I) {
5011 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
5012 continue;
5013
5014 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
5015 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5016 if (ObjCPropertyDecl *Property
5017 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
5018 if (Property->getPropertyAttributesAsWritten() != 0 &&
5019 llvm::StringSwitch<bool>(II->getName())
5020 .Case("readonly", true)
5021 .Case("assign", true)
John McCallf85e1932011-06-15 23:02:42 +00005022 .Case("unsafe_unretained", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00005023 .Case("readwrite", true)
5024 .Case("retain", true)
5025 .Case("copy", true)
5026 .Case("nonatomic", true)
5027 .Case("atomic", true)
5028 .Case("getter", true)
5029 .Case("setter", true)
John McCallf85e1932011-06-15 23:02:42 +00005030 .Case("strong", true)
5031 .Case("weak", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00005032 .Default(false))
5033 Tokens[I].int_data[0] = CXToken_Keyword;
5034 }
5035 continue;
5036 }
5037
5038 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
5039 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
5040 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5041 if (llvm::StringSwitch<bool>(II->getName())
5042 .Case("in", true)
5043 .Case("out", true)
5044 .Case("inout", true)
5045 .Case("oneway", true)
5046 .Case("bycopy", true)
5047 .Case("byref", true)
5048 .Default(false))
5049 Tokens[I].int_data[0] = CXToken_Keyword;
5050 continue;
5051 }
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00005052
5053 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
5054 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
5055 Tokens[I].int_data[0] = CXToken_Keyword;
Ted Kremenek6628a612011-03-18 22:51:30 +00005056 continue;
5057 }
5058 }
5059 }
Ted Kremenekab979612010-11-11 08:05:23 +00005060}
5061
Ted Kremenek6db61092010-05-05 00:55:15 +00005062extern "C" {
5063
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005064void clang_annotateTokens(CXTranslationUnit TU,
5065 CXToken *Tokens, unsigned NumTokens,
5066 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005067
5068 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005069 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005070
Douglas Gregor4419b672010-10-21 06:10:04 +00005071 // Any token we don't specifically annotate will have a NULL cursor.
5072 CXCursor C = clang_getNullCursor();
5073 for (unsigned I = 0; I != NumTokens; ++I)
5074 Cursors[I] = C;
5075
Ted Kremeneka60ed472010-11-16 08:15:36 +00005076 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor4419b672010-10-21 06:10:04 +00005077 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005078 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005079
Douglas Gregorbdf60622010-03-05 21:16:25 +00005080 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenek6628a612011-03-18 22:51:30 +00005081
5082 clang_annotateTokens_Data data = { TU, CXXUnit, Tokens, NumTokens, Cursors };
Ted Kremenekab979612010-11-11 08:05:23 +00005083 llvm::CrashRecoveryContext CRC;
Ted Kremenek6628a612011-03-18 22:51:30 +00005084 if (!RunSafely(CRC, clang_annotateTokensImpl, &data,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005085 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00005086 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
5087 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005088}
Ted Kremenek6628a612011-03-18 22:51:30 +00005089
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005090} // end: extern "C"
5091
5092//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00005093// Operations for querying linkage of a cursor.
5094//===----------------------------------------------------------------------===//
5095
5096extern "C" {
5097CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00005098 if (!clang_isDeclaration(cursor.kind))
5099 return CXLinkage_Invalid;
5100
Ted Kremenek16b42592010-03-03 06:36:57 +00005101 Decl *D = cxcursor::getCursorDecl(cursor);
5102 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
5103 switch (ND->getLinkage()) {
5104 case NoLinkage: return CXLinkage_NoLinkage;
5105 case InternalLinkage: return CXLinkage_Internal;
5106 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
5107 case ExternalLinkage: return CXLinkage_External;
5108 };
5109
5110 return CXLinkage_Invalid;
5111}
5112} // end: extern "C"
5113
5114//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005115// Operations for querying language of a cursor.
5116//===----------------------------------------------------------------------===//
5117
5118static CXLanguageKind getDeclLanguage(const Decl *D) {
5119 switch (D->getKind()) {
5120 default:
5121 break;
5122 case Decl::ImplicitParam:
5123 case Decl::ObjCAtDefsField:
5124 case Decl::ObjCCategory:
5125 case Decl::ObjCCategoryImpl:
5126 case Decl::ObjCClass:
5127 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005128 case Decl::ObjCForwardProtocol:
5129 case Decl::ObjCImplementation:
5130 case Decl::ObjCInterface:
5131 case Decl::ObjCIvar:
5132 case Decl::ObjCMethod:
5133 case Decl::ObjCProperty:
5134 case Decl::ObjCPropertyImpl:
5135 case Decl::ObjCProtocol:
5136 return CXLanguage_ObjC;
5137 case Decl::CXXConstructor:
5138 case Decl::CXXConversion:
5139 case Decl::CXXDestructor:
5140 case Decl::CXXMethod:
5141 case Decl::CXXRecord:
5142 case Decl::ClassTemplate:
5143 case Decl::ClassTemplatePartialSpecialization:
5144 case Decl::ClassTemplateSpecialization:
5145 case Decl::Friend:
5146 case Decl::FriendTemplate:
5147 case Decl::FunctionTemplate:
5148 case Decl::LinkageSpec:
5149 case Decl::Namespace:
5150 case Decl::NamespaceAlias:
5151 case Decl::NonTypeTemplateParm:
5152 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005153 case Decl::TemplateTemplateParm:
5154 case Decl::TemplateTypeParm:
5155 case Decl::UnresolvedUsingTypename:
5156 case Decl::UnresolvedUsingValue:
5157 case Decl::Using:
5158 case Decl::UsingDirective:
5159 case Decl::UsingShadow:
5160 return CXLanguage_CPlusPlus;
5161 }
5162
5163 return CXLanguage_C;
5164}
5165
5166extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00005167
5168enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
5169 if (clang_isDeclaration(cursor.kind))
5170 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005171 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Douglas Gregor58ddb602010-08-23 23:00:57 +00005172 return CXAvailability_Available;
5173
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005174 switch (D->getAvailability()) {
5175 case AR_Available:
5176 case AR_NotYetIntroduced:
5177 return CXAvailability_Available;
5178
5179 case AR_Deprecated:
Douglas Gregor58ddb602010-08-23 23:00:57 +00005180 return CXAvailability_Deprecated;
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005181
5182 case AR_Unavailable:
5183 return CXAvailability_NotAvailable;
5184 }
Douglas Gregor58ddb602010-08-23 23:00:57 +00005185 }
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005186
Douglas Gregor58ddb602010-08-23 23:00:57 +00005187 return CXAvailability_Available;
5188}
5189
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005190CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
5191 if (clang_isDeclaration(cursor.kind))
5192 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
5193
5194 return CXLanguage_Invalid;
5195}
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005196
5197 /// \brief If the given cursor is the "templated" declaration
5198 /// descibing a class or function template, return the class or
5199 /// function template.
5200static Decl *maybeGetTemplateCursor(Decl *D) {
5201 if (!D)
5202 return 0;
5203
5204 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
5205 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
5206 return FunTmpl;
5207
5208 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
5209 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
5210 return ClassTmpl;
5211
5212 return D;
5213}
5214
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005215CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
5216 if (clang_isDeclaration(cursor.kind)) {
5217 if (Decl *D = getCursorDecl(cursor)) {
5218 DeclContext *DC = D->getDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005219 if (!DC)
5220 return clang_getNullCursor();
5221
5222 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5223 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005224 }
5225 }
5226
5227 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
5228 if (Decl *D = getCursorDecl(cursor))
Ted Kremeneka60ed472010-11-16 08:15:36 +00005229 return MakeCXCursor(D, getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005230 }
5231
5232 return clang_getNullCursor();
5233}
5234
5235CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
5236 if (clang_isDeclaration(cursor.kind)) {
5237 if (Decl *D = getCursorDecl(cursor)) {
5238 DeclContext *DC = D->getLexicalDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005239 if (!DC)
5240 return clang_getNullCursor();
5241
5242 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5243 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005244 }
5245 }
5246
5247 // FIXME: Note that we can't easily compute the lexical context of a
5248 // statement or expression, so we return nothing.
5249 return clang_getNullCursor();
5250}
5251
Douglas Gregor9f592342010-10-01 20:25:15 +00005252void clang_getOverriddenCursors(CXCursor cursor,
5253 CXCursor **overridden,
5254 unsigned *num_overridden) {
5255 if (overridden)
5256 *overridden = 0;
5257 if (num_overridden)
5258 *num_overridden = 0;
5259 if (!overridden || !num_overridden)
5260 return;
5261
Argyrios Kyrtzidisb11be042011-10-06 07:00:46 +00005262 SmallVector<CXCursor, 8> Overridden;
5263 cxcursor::getOverriddenCursors(cursor, Overridden);
Douglas Gregor9f592342010-10-01 20:25:15 +00005264
Ted Kremenek24077122011-11-14 23:51:37 +00005265 // Don't allocate memory if we have no overriden cursors.
5266 if (Overridden.size() == 0)
5267 return;
5268
Argyrios Kyrtzidisb11be042011-10-06 07:00:46 +00005269 *num_overridden = Overridden.size();
5270 *overridden = new CXCursor [Overridden.size()];
5271 std::copy(Overridden.begin(), Overridden.end(), *overridden);
Douglas Gregor9f592342010-10-01 20:25:15 +00005272}
5273
5274void clang_disposeOverriddenCursors(CXCursor *overridden) {
5275 delete [] overridden;
5276}
5277
Douglas Gregorecdcb882010-10-20 22:00:55 +00005278CXFile clang_getIncludedFile(CXCursor cursor) {
5279 if (cursor.kind != CXCursor_InclusionDirective)
5280 return 0;
5281
5282 InclusionDirective *ID = getCursorInclusionDirective(cursor);
5283 return (void *)ID->getFile();
5284}
5285
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005286} // end: extern "C"
5287
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005288
5289//===----------------------------------------------------------------------===//
5290// C++ AST instrospection.
5291//===----------------------------------------------------------------------===//
5292
5293extern "C" {
5294unsigned clang_CXXMethod_isStatic(CXCursor C) {
5295 if (!clang_isDeclaration(C.kind))
5296 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00005297
5298 CXXMethodDecl *Method = 0;
5299 Decl *D = cxcursor::getCursorDecl(C);
5300 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5301 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5302 else
5303 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5304 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00005305}
Ted Kremenekb12903e2010-05-18 22:32:15 +00005306
Douglas Gregor211924b2011-05-12 15:17:24 +00005307unsigned clang_CXXMethod_isVirtual(CXCursor C) {
5308 if (!clang_isDeclaration(C.kind))
5309 return 0;
5310
5311 CXXMethodDecl *Method = 0;
5312 Decl *D = cxcursor::getCursorDecl(C);
5313 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5314 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5315 else
5316 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5317 return (Method && Method->isVirtual()) ? 1 : 0;
5318}
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005319} // end: extern "C"
5320
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005321//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00005322// Attribute introspection.
5323//===----------------------------------------------------------------------===//
5324
5325extern "C" {
5326CXType clang_getIBOutletCollectionType(CXCursor C) {
5327 if (C.kind != CXCursor_IBOutletCollectionAttr)
Ted Kremeneka60ed472010-11-16 08:15:36 +00005328 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005329
5330 IBOutletCollectionAttr *A =
5331 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
5332
Argyrios Kyrtzidis18aa2ff2011-09-13 18:49:52 +00005333 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005334}
5335} // end: extern "C"
5336
5337//===----------------------------------------------------------------------===//
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005338// Inspecting memory usage.
5339//===----------------------------------------------------------------------===//
5340
Ted Kremenekf7870022011-04-20 16:41:07 +00005341typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005342
Ted Kremenekf7870022011-04-20 16:41:07 +00005343static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
5344 enum CXTUResourceUsageKind k,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005345 unsigned long amount) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005346 CXTUResourceUsageEntry entry = { k, amount };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005347 entries.push_back(entry);
5348}
5349
5350extern "C" {
5351
Ted Kremenekf7870022011-04-20 16:41:07 +00005352const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005353 const char *str = "";
5354 switch (kind) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005355 case CXTUResourceUsage_AST:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005356 str = "ASTContext: expressions, declarations, and types";
5357 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005358 case CXTUResourceUsage_Identifiers:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005359 str = "ASTContext: identifiers";
5360 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005361 case CXTUResourceUsage_Selectors:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005362 str = "ASTContext: selectors";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005363 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005364 case CXTUResourceUsage_GlobalCompletionResults:
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005365 str = "Code completion: cached global results";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005366 break;
Ted Kremenek457aaf02011-04-28 04:10:31 +00005367 case CXTUResourceUsage_SourceManagerContentCache:
5368 str = "SourceManager: content cache allocator";
5369 break;
Ted Kremenekba29bd22011-04-28 04:53:38 +00005370 case CXTUResourceUsage_AST_SideTables:
5371 str = "ASTContext: side tables";
5372 break;
Ted Kremenekf61b8312011-04-28 20:36:42 +00005373 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
5374 str = "SourceManager: malloc'ed memory buffers";
5375 break;
5376 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
5377 str = "SourceManager: mmap'ed memory buffers";
5378 break;
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005379 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
5380 str = "ExternalASTSource: malloc'ed memory buffers";
5381 break;
5382 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
5383 str = "ExternalASTSource: mmap'ed memory buffers";
5384 break;
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005385 case CXTUResourceUsage_Preprocessor:
5386 str = "Preprocessor: malloc'ed memory";
5387 break;
5388 case CXTUResourceUsage_PreprocessingRecord:
5389 str = "Preprocessor: PreprocessingRecord";
5390 break;
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005391 case CXTUResourceUsage_SourceManager_DataStructures:
5392 str = "SourceManager: data structures and tables";
5393 break;
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005394 case CXTUResourceUsage_Preprocessor_HeaderSearch:
5395 str = "Preprocessor: header search tables";
5396 break;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005397 }
5398 return str;
5399}
5400
Ted Kremenekf7870022011-04-20 16:41:07 +00005401CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005402 if (!TU) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005403 CXTUResourceUsage usage = { (void*) 0, 0, 0 };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005404 return usage;
5405 }
5406
5407 ASTUnit *astUnit = static_cast<ASTUnit*>(TU->TUData);
5408 llvm::OwningPtr<MemUsageEntries> entries(new MemUsageEntries());
5409 ASTContext &astContext = astUnit->getASTContext();
5410
5411 // How much memory is used by AST nodes and types?
Ted Kremenekf7870022011-04-20 16:41:07 +00005412 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005413 (unsigned long) astContext.getASTAllocatedMemory());
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005414
5415 // How much memory is used by identifiers?
Ted Kremenekf7870022011-04-20 16:41:07 +00005416 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005417 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
5418
5419 // How much memory is used for selectors?
Ted Kremenekf7870022011-04-20 16:41:07 +00005420 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005421 (unsigned long) astContext.Selectors.getTotalMemory());
5422
Ted Kremenekba29bd22011-04-28 04:53:38 +00005423 // How much memory is used by ASTContext's side tables?
5424 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
5425 (unsigned long) astContext.getSideTableAllocatedMemory());
5426
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005427 // How much memory is used for caching global code completion results?
5428 unsigned long completionBytes = 0;
5429 if (GlobalCodeCompletionAllocator *completionAllocator =
5430 astUnit->getCachedCompletionAllocator().getPtr()) {
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005431 completionBytes = completionAllocator->getTotalMemory();
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005432 }
Ted Kremenek457aaf02011-04-28 04:10:31 +00005433 createCXTUResourceUsageEntry(*entries,
5434 CXTUResourceUsage_GlobalCompletionResults,
5435 completionBytes);
5436
5437 // How much memory is being used by SourceManager's content cache?
5438 createCXTUResourceUsageEntry(*entries,
5439 CXTUResourceUsage_SourceManagerContentCache,
5440 (unsigned long) astContext.getSourceManager().getContentCacheSize());
Ted Kremenekf61b8312011-04-28 20:36:42 +00005441
5442 // How much memory is being used by the MemoryBuffer's in SourceManager?
5443 const SourceManager::MemoryBufferSizes &srcBufs =
5444 astUnit->getSourceManager().getMemoryBufferSizes();
5445
5446 createCXTUResourceUsageEntry(*entries,
5447 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
5448 (unsigned long) srcBufs.malloc_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005449 createCXTUResourceUsageEntry(*entries,
Ted Kremenekf61b8312011-04-28 20:36:42 +00005450 CXTUResourceUsage_SourceManager_Membuffer_MMap,
5451 (unsigned long) srcBufs.mmap_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005452 createCXTUResourceUsageEntry(*entries,
5453 CXTUResourceUsage_SourceManager_DataStructures,
5454 (unsigned long) astContext.getSourceManager()
5455 .getDataStructureSizes());
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005456
5457 // How much memory is being used by the ExternalASTSource?
5458 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
5459 const ExternalASTSource::MemoryBufferSizes &sizes =
5460 esrc->getMemoryBufferSizes();
5461
5462 createCXTUResourceUsageEntry(*entries,
5463 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
5464 (unsigned long) sizes.malloc_bytes);
5465 createCXTUResourceUsageEntry(*entries,
5466 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
5467 (unsigned long) sizes.mmap_bytes);
5468 }
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005469
5470 // How much memory is being used by the Preprocessor?
5471 Preprocessor &pp = astUnit->getPreprocessor();
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005472 createCXTUResourceUsageEntry(*entries,
5473 CXTUResourceUsage_Preprocessor,
Argyrios Kyrtzidisc5c5e922011-06-29 22:20:04 +00005474 pp.getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005475
5476 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
5477 createCXTUResourceUsageEntry(*entries,
5478 CXTUResourceUsage_PreprocessingRecord,
5479 pRec->getTotalMemory());
5480 }
5481
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005482 createCXTUResourceUsageEntry(*entries,
5483 CXTUResourceUsage_Preprocessor_HeaderSearch,
5484 pp.getHeaderSearchInfo().getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005485
Ted Kremenekf7870022011-04-20 16:41:07 +00005486 CXTUResourceUsage usage = { (void*) entries.get(),
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005487 (unsigned) entries->size(),
5488 entries->size() ? &(*entries)[0] : 0 };
5489 entries.take();
5490 return usage;
5491}
5492
Ted Kremenekf7870022011-04-20 16:41:07 +00005493void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005494 if (usage.data)
5495 delete (MemUsageEntries*) usage.data;
5496}
5497
5498} // end extern "C"
5499
Douglas Gregor6df78732011-05-05 20:27:22 +00005500void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
5501 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
5502 for (unsigned I = 0; I != Usage.numEntries; ++I)
5503 fprintf(stderr, " %s: %lu\n",
5504 clang_getTUResourceUsageName(Usage.entries[I].kind),
5505 Usage.entries[I].amount);
5506
5507 clang_disposeCXTUResourceUsage(Usage);
5508}
5509
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005510//===----------------------------------------------------------------------===//
Ted Kremenek04bb7162010-01-22 22:44:15 +00005511// Misc. utility functions.
5512//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00005513
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00005514/// Default to using an 8 MB stack size on "safety" threads.
5515static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005516
5517namespace clang {
5518
5519bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005520 void (*Fn)(void*), void *UserData,
5521 unsigned Size) {
5522 if (!Size)
5523 Size = GetSafetyThreadStackSize();
5524 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005525 return CRC.RunSafelyOnThread(Fn, UserData, Size);
5526 return CRC.RunSafely(Fn, UserData);
5527}
5528
5529unsigned GetSafetyThreadStackSize() {
5530 return SafetyStackThreadSize;
5531}
5532
5533void SetSafetyThreadStackSize(unsigned Value) {
5534 SafetyStackThreadSize = Value;
5535}
5536
5537}
5538
Ted Kremenek04bb7162010-01-22 22:44:15 +00005539extern "C" {
5540
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00005541CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00005542 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00005543}
5544
5545} // end: extern "C"
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005546