blob: 72abfa76eae62d4c09c2a29b218c89d08faa338a [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.
Argyrios Kyrtzidisc14a03d2011-11-23 20:27:36 +0000263 while (Decls.empty() || Decls.front()->isTopLevelDeclInObjCContainer()) {
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000264 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;
Argyrios Kyrtzidised8bef42011-11-28 22:38:07 +0000289 if (D->getSourceRange().isInvalid())
290 continue;
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000291
Argyrios Kyrtzidise2079cf2011-11-16 08:58:54 +0000292 if (isInLexicalContext(D, CurDC))
293 continue;
294
295 CurDC = dyn_cast<DeclContext>(D);
296
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000297 // We handle forward decls via ObjCClassDecl.
298 if (ObjCInterfaceDecl *InterD = dyn_cast<ObjCInterfaceDecl>(D)) {
299 if (InterD->isForwardDecl())
300 continue;
301 // An interface that started as a forward decl may have changed location
302 // because its @interface was parsed.
303 if (InterD->isInitiallyForwardDecl() &&
304 !SM.isInFileID(SM.getFileLoc(InterD->getLocation()), File))
305 continue;
306 }
307
Argyrios Kyrtzidise2079cf2011-11-16 08:58:54 +0000308 if (TagDecl *TD = dyn_cast<TagDecl>(D))
309 if (!TD->isFreeStanding())
310 continue;
311
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000312 RangeComparisonResult CompRes = RangeCompare(SM, D->getSourceRange(),Range);
313 if (CompRes == RangeBefore)
314 continue;
315 if (CompRes == RangeAfter)
316 break;
317
318 assert(CompRes == RangeOverlap);
319 VisitedAtLeastOnce = true;
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +0000320
321 if (isa<ObjCContainerDecl>(D)) {
322 FileDI_current = &DIt;
323 FileDE_current = DE;
324 } else {
325 FileDI_current = 0;
326 }
327
Argyrios Kyrtzidisba986172011-11-03 19:02:28 +0000328 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000329 break;
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000330 }
331
332 if (VisitedAtLeastOnce)
333 return;
334
335 // No Decls overlapped with the range. Move up the lexical context until there
336 // is a context that contains the range or we reach the translation unit
337 // level.
338 DeclContext *DC = DIt == Decls.begin() ? (*DIt)->getLexicalDeclContext()
339 : (*(DIt-1))->getLexicalDeclContext();
340
341 while (DC && !DC->isTranslationUnit()) {
342 Decl *D = cast<Decl>(DC);
343 SourceRange CurDeclRange = D->getSourceRange();
344 if (CurDeclRange.isInvalid())
345 break;
346
347 if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) {
Argyrios Kyrtzidisba986172011-11-03 19:02:28 +0000348 Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true);
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000349 break;
350 }
351
352 DC = D->getLexicalDeclContext();
353 }
354}
355
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000356bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
Douglas Gregor788f5a12010-03-20 00:41:21 +0000357 PreprocessingRecord &PPRec
Ted Kremeneka60ed472010-11-16 08:15:36 +0000358 = *AU->getPreprocessor().getPreprocessingRecord();
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000359 SourceManager &SM = AU->getSourceManager();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000360
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000361 if (RegionOfInterest.isValid()) {
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +0000362 SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000363 SourceLocation B = MappedRange.getBegin();
364 SourceLocation E = MappedRange.getEnd();
365
366 if (AU->isInPreambleFileID(B)) {
367 if (SM.isLoadedSourceLocation(E))
368 return visitPreprocessedEntitiesInRange(SourceRange(B, E),
369 PPRec, *this);
370
371 // Beginning of range lies in the preamble but it also extends beyond
372 // it into the main file. Split the range into 2 parts, one covering
373 // the preamble and another covering the main file. This allows subsequent
374 // calls to visitPreprocessedEntitiesInRange to accept a source range that
375 // lies in the same FileID, allowing it to skip preprocessed entities that
376 // do not come from the same FileID.
377 bool breaked =
378 visitPreprocessedEntitiesInRange(
379 SourceRange(B, AU->getEndOfPreambleFileID()),
380 PPRec, *this);
381 if (breaked) return true;
382 return visitPreprocessedEntitiesInRange(
383 SourceRange(AU->getStartOfMainFileID(), E),
384 PPRec, *this);
385 }
386
387 return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this);
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000388 }
389
Douglas Gregor788f5a12010-03-20 00:41:21 +0000390 bool OnlyLocalDecls
Douglas Gregor32038bb2010-12-21 19:07:48 +0000391 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
392
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000393 if (OnlyLocalDecls)
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000394 return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(),
395 PPRec);
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000396
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000397 return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec);
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000398}
399
400template<typename InputIterator>
401bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000402 InputIterator Last,
403 PreprocessingRecord &PPRec,
404 FileID FID) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000405 for (; First != Last; ++First) {
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000406 if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID))
407 continue;
408
409 PreprocessedEntity *PPE = *First;
410 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000411 if (Visit(MakeMacroExpansionCursor(ME, TU)))
412 return true;
413
414 continue;
415 }
416
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000417 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(PPE)) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000418 if (Visit(MakeMacroDefinitionCursor(MD, TU)))
419 return true;
420
421 continue;
422 }
423
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000424 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000425 if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
426 return true;
427
428 continue;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000429 }
430 }
431
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000432 return false;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000433}
434
Douglas Gregorb1373d02010-01-20 20:59:29 +0000435/// \brief Visit the children of the given cursor.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000436///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000437/// \returns true if the visitation should be aborted, false if it
438/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000439bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregorc314aa42011-03-02 19:17:03 +0000440 if (clang_isReference(Cursor.kind) &&
441 Cursor.kind != CXCursor_CXXBaseSpecifier) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000442 // By definition, references have no children.
443 return false;
444 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000445
446 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000447 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000448 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000449
Douglas Gregorb1373d02010-01-20 20:59:29 +0000450 if (clang_isDeclaration(Cursor.kind)) {
451 Decl *D = getCursorDecl(Cursor);
Douglas Gregor06d9b1a2011-04-14 21:41:34 +0000452 if (!D)
453 return false;
454
Ted Kremenek539311e2010-02-18 18:47:01 +0000455 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000456 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000457
Douglas Gregor06d9b1a2011-04-14 21:41:34 +0000458 if (clang_isStatement(Cursor.kind)) {
459 if (Stmt *S = getCursorStmt(Cursor))
460 return Visit(S);
461
462 return false;
463 }
464
465 if (clang_isExpression(Cursor.kind)) {
466 if (Expr *E = getCursorExpr(Cursor))
467 return Visit(E);
468
469 return false;
470 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000471
Douglas Gregorb1373d02010-01-20 20:59:29 +0000472 if (clang_isTranslationUnit(Cursor.kind)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000473 CXTranslationUnit tu = getCursorTU(Cursor);
474 ASTUnit *CXXUnit = static_cast<ASTUnit*>(tu->TUData);
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000475
476 int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
477 for (unsigned I = 0; I != 2; ++I) {
478 if (VisitOrder[I]) {
479 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
480 RegionOfInterest.isInvalid()) {
481 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
482 TLEnd = CXXUnit->top_level_end();
483 TL != TLEnd; ++TL) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000484 if (Visit(MakeCXCursor(*TL, tu, RegionOfInterest), true))
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000485 return true;
486 }
487 } else if (VisitDeclContext(
488 CXXUnit->getASTContext().getTranslationUnitDecl()))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000489 return true;
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000490 continue;
Douglas Gregor7b691f332010-01-20 21:13:59 +0000491 }
Bob Wilson3178cb62010-03-19 03:57:57 +0000492
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000493 // Walk the preprocessing record.
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000494 if (CXXUnit->getPreprocessor().getPreprocessingRecord())
495 visitPreprocessedEntitiesInRegion();
Douglas Gregor0396f462010-03-19 05:22:59 +0000496 }
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000497
Douglas Gregor7b691f332010-01-20 21:13:59 +0000498 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000499 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000500
Douglas Gregorc314aa42011-03-02 19:17:03 +0000501 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
502 if (CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
503 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
504 return Visit(BaseTSInfo->getTypeLoc());
505 }
506 }
507 }
Argyrios Kyrtzidis221d5a52011-09-13 18:49:56 +0000508
509 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
510 IBOutletCollectionAttr *A =
511 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
512 if (const ObjCInterfaceType *InterT = A->getInterface()->getAs<ObjCInterfaceType>())
513 return Visit(cxcursor::MakeCursorObjCClassRef(InterT->getInterface(),
514 A->getInterfaceLoc(), TU));
515 }
516
Douglas Gregorb1373d02010-01-20 20:59:29 +0000517 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000518 return false;
519}
520
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000521bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
Douglas Gregor13c8ccb2011-04-22 23:49:24 +0000522 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
523 if (Visit(TSInfo->getTypeLoc()))
524 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000525
Ted Kremenek664cffd2010-07-22 11:30:19 +0000526 if (Stmt *Body = B->getBody())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000527 return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest));
Ted Kremenek664cffd2010-07-22 11:30:19 +0000528
529 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000530}
531
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000532llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
533 if (RegionOfInterest.isValid()) {
Douglas Gregor66537982010-11-17 17:14:07 +0000534 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000535 if (Range.isInvalid())
536 return llvm::Optional<bool>();
Douglas Gregor66537982010-11-17 17:14:07 +0000537
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000538 switch (CompareRegionOfInterest(Range)) {
539 case RangeBefore:
540 // This declaration comes before the region of interest; skip it.
541 return llvm::Optional<bool>();
542
543 case RangeAfter:
544 // This declaration comes after the region of interest; we're done.
545 return false;
546
547 case RangeOverlap:
548 // This declaration overlaps the region of interest; visit it.
549 break;
550 }
551 }
552 return true;
553}
554
555bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
556 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
557
558 // FIXME: Eventually remove. This part of a hack to support proper
559 // iteration over all Decls contained lexically within an ObjC container.
560 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
561 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
562
563 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000564 Decl *D = *I;
565 if (D->getLexicalDeclContext() != DC)
566 continue;
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000567 CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000568 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
569 if (!V.hasValue())
570 continue;
571 if (!V.getValue())
572 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000573 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000574 return true;
575 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000576 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000577}
578
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000579bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
580 llvm_unreachable("Translation units are visited directly by Visit()");
581 return false;
582}
583
Richard Smith162e1c12011-04-15 14:24:37 +0000584bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
585 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
586 return Visit(TSInfo->getTypeLoc());
587
588 return false;
589}
590
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000591bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
592 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
593 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000594
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000595 return false;
596}
597
598bool CursorVisitor::VisitTagDecl(TagDecl *D) {
599 return VisitDeclContext(D);
600}
601
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000602bool CursorVisitor::VisitClassTemplateSpecializationDecl(
603 ClassTemplateSpecializationDecl *D) {
604 bool ShouldVisitBody = false;
605 switch (D->getSpecializationKind()) {
606 case TSK_Undeclared:
607 case TSK_ImplicitInstantiation:
608 // Nothing to visit
609 return false;
610
611 case TSK_ExplicitInstantiationDeclaration:
612 case TSK_ExplicitInstantiationDefinition:
613 break;
614
615 case TSK_ExplicitSpecialization:
616 ShouldVisitBody = true;
617 break;
618 }
619
620 // Visit the template arguments used in the specialization.
621 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
622 TypeLoc TL = SpecType->getTypeLoc();
623 if (TemplateSpecializationTypeLoc *TSTLoc
624 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
625 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
626 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
627 return true;
628 }
629 }
630
631 if (ShouldVisitBody && VisitCXXRecordDecl(D))
632 return true;
633
634 return false;
635}
636
Douglas Gregor74dbe642010-08-31 19:31:58 +0000637bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
638 ClassTemplatePartialSpecializationDecl *D) {
639 // FIXME: Visit the "outer" template parameter lists on the TagDecl
640 // before visiting these template parameters.
641 if (VisitTemplateParameters(D->getTemplateParameters()))
642 return true;
643
644 // Visit the partial specialization arguments.
645 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
646 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
647 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
648 return true;
649
650 return VisitCXXRecordDecl(D);
651}
652
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000653bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000654 // Visit the default argument.
655 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
656 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
657 if (Visit(DefArg->getTypeLoc()))
658 return true;
659
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000660 return false;
661}
662
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000663bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
664 if (Expr *Init = D->getInitExpr())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000665 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000666 return false;
667}
668
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000669bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
670 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
671 if (Visit(TSInfo->getTypeLoc()))
672 return true;
673
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000674 // Visit the nested-name-specifier, if present.
675 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
676 if (VisitNestedNameSpecifierLoc(QualifierLoc))
677 return true;
678
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000679 return false;
680}
681
Douglas Gregora67e03f2010-09-09 21:42:20 +0000682/// \brief Compare two base or member initializers based on their source order.
Sean Huntcbb67482011-01-08 20:30:50 +0000683static int CompareCXXCtorInitializers(const void* Xp, const void *Yp) {
684 CXXCtorInitializer const * const *X
685 = static_cast<CXXCtorInitializer const * const *>(Xp);
686 CXXCtorInitializer const * const *Y
687 = static_cast<CXXCtorInitializer const * const *>(Yp);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000688
689 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
690 return -1;
691 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
692 return 1;
693 else
694 return 0;
695}
696
Douglas Gregorb1373d02010-01-20 20:59:29 +0000697bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000698 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
699 // Visit the function declaration's syntactic components in the order
700 // written. This requires a bit of work.
Abramo Bagnara723df242010-12-14 22:11:44 +0000701 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
Douglas Gregor01829d32010-08-31 14:41:23 +0000702 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
703
704 // If we have a function declared directly (without the use of a typedef),
705 // visit just the return type. Otherwise, just visit the function's type
706 // now.
707 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
708 (!FTL && Visit(TL)))
709 return true;
710
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000711 // Visit the nested-name-specifier, if present.
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000712 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
713 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000714 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000715
716 // Visit the declaration name.
717 if (VisitDeclarationNameInfo(ND->getNameInfo()))
718 return true;
719
720 // FIXME: Visit explicitly-specified template arguments!
721
722 // Visit the function parameters, if we have a function type.
723 if (FTL && VisitFunctionTypeLoc(*FTL, true))
724 return true;
725
726 // FIXME: Attributes?
727 }
728
Sean Hunt10620eb2011-05-06 20:44:56 +0000729 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
Douglas Gregora67e03f2010-09-09 21:42:20 +0000730 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
731 // Find the initializers that were written in the source.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000732 SmallVector<CXXCtorInitializer *, 4> WrittenInits;
Douglas Gregora67e03f2010-09-09 21:42:20 +0000733 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
734 IEnd = Constructor->init_end();
735 I != IEnd; ++I) {
736 if (!(*I)->isWritten())
737 continue;
738
739 WrittenInits.push_back(*I);
740 }
741
742 // Sort the initializers in source order
743 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
Sean Huntcbb67482011-01-08 20:30:50 +0000744 &CompareCXXCtorInitializers);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000745
746 // Visit the initializers in source order
747 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
Sean Huntcbb67482011-01-08 20:30:50 +0000748 CXXCtorInitializer *Init = WrittenInits[I];
Francois Pichet00eb3f92010-12-04 09:14:42 +0000749 if (Init->isAnyMemberInitializer()) {
750 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
Douglas Gregora67e03f2010-09-09 21:42:20 +0000751 Init->getMemberLocation(), TU)))
752 return true;
Douglas Gregor76852c22011-11-01 01:16:03 +0000753 } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) {
754 if (Visit(TInfo->getTypeLoc()))
Douglas Gregora67e03f2010-09-09 21:42:20 +0000755 return true;
756 }
757
758 // Visit the initializer value.
759 if (Expr *Initializer = Init->getInit())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000760 if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
Douglas Gregora67e03f2010-09-09 21:42:20 +0000761 return true;
762 }
763 }
764
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000765 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
Douglas Gregora67e03f2010-09-09 21:42:20 +0000766 return true;
767 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000768
Douglas Gregorb1373d02010-01-20 20:59:29 +0000769 return false;
770}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000771
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000772bool CursorVisitor::VisitFieldDecl(FieldDecl *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 *BitWidth = D->getBitWidth())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000777 return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000778
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000779 return false;
780}
781
782bool CursorVisitor::VisitVarDecl(VarDecl *D) {
783 if (VisitDeclaratorDecl(D))
784 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000785
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000786 if (Expr *Init = D->getInit())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000787 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000788
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000789 return false;
790}
791
Douglas Gregor84b51d72010-09-01 20:16:53 +0000792bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
793 if (VisitDeclaratorDecl(D))
794 return true;
795
796 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
797 if (Expr *DefArg = D->getDefaultArgument())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000798 return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
Douglas Gregor84b51d72010-09-01 20:16:53 +0000799
800 return false;
801}
802
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000803bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
804 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
805 // before visiting these template parameters.
806 if (VisitTemplateParameters(D->getTemplateParameters()))
807 return true;
808
809 return VisitFunctionDecl(D->getTemplatedDecl());
810}
811
Douglas Gregor39d6f072010-08-31 19:02:00 +0000812bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
813 // FIXME: Visit the "outer" template parameter lists on the TagDecl
814 // before visiting these template parameters.
815 if (VisitTemplateParameters(D->getTemplateParameters()))
816 return true;
817
818 return VisitCXXRecordDecl(D->getTemplatedDecl());
819}
820
Douglas Gregor84b51d72010-09-01 20:16:53 +0000821bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
822 if (VisitTemplateParameters(D->getTemplateParameters()))
823 return true;
824
825 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
826 VisitTemplateArgumentLoc(D->getDefaultArgument()))
827 return true;
828
829 return false;
830}
831
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000832bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000833 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
834 if (Visit(TSInfo->getTypeLoc()))
835 return true;
836
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000837 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000838 PEnd = ND->param_end();
839 P != PEnd; ++P) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000840 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000841 return true;
842 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000843
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000844 if (ND->isThisDeclarationADefinition() &&
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000845 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000846 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000847
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000848 return false;
849}
850
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +0000851template <typename DeclIt>
852static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current,
853 SourceManager &SM, SourceLocation EndLoc,
854 SmallVectorImpl<Decl *> &Decls) {
855 DeclIt next = *DI_current;
856 while (++next != DE_current) {
857 Decl *D_next = *next;
858 if (!D_next)
859 break;
860 SourceLocation L = D_next->getLocStart();
861 if (!L.isValid())
862 break;
863 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
864 *DI_current = next;
865 Decls.push_back(D_next);
866 continue;
867 }
868 break;
869 }
870}
871
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000872namespace {
873 struct ContainerDeclsSort {
874 SourceManager &SM;
875 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
876 bool operator()(Decl *A, Decl *B) {
877 SourceLocation L_A = A->getLocStart();
878 SourceLocation L_B = B->getLocStart();
879 assert(L_A.isValid() && L_B.isValid());
880 return SM.isBeforeInTranslationUnit(L_A, L_B);
881 }
882 };
883}
884
Douglas Gregora59e3902010-01-21 23:27:09 +0000885bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000886 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
887 // an @implementation can lexically contain Decls that are not properly
888 // nested in the AST. When we identify such cases, we need to retrofit
889 // this nesting here.
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +0000890 if (!DI_current && !FileDI_current)
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000891 return VisitDeclContext(D);
892
893 // Scan the Decls that immediately come after the container
894 // in the current DeclContext. If any fall within the
895 // container's lexical region, stash them into a vector
896 // for later processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000897 SmallVector<Decl *, 24> DeclsInContainer;
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000898 SourceLocation EndLoc = D->getSourceRange().getEnd();
Ted Kremeneka60ed472010-11-16 08:15:36 +0000899 SourceManager &SM = AU->getSourceManager();
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000900 if (EndLoc.isValid()) {
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +0000901 if (DI_current) {
902 addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc,
903 DeclsInContainer);
904 } else {
905 addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc,
906 DeclsInContainer);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000907 }
908 }
909
910 // The common case.
911 if (DeclsInContainer.empty())
912 return VisitDeclContext(D);
913
914 // Get all the Decls in the DeclContext, and sort them with the
915 // additional ones we've collected. Then visit them.
916 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
917 I!=E; ++I) {
918 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000919 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
920 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000921 continue;
922 DeclsInContainer.push_back(subDecl);
923 }
924
925 // Now sort the Decls so that they appear in lexical order.
926 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
927 ContainerDeclsSort(SM));
928
929 // Now visit the decls.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000930 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000931 E = DeclsInContainer.end(); I != E; ++I) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000932 CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000933 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
934 if (!V.hasValue())
935 continue;
936 if (!V.getValue())
937 return false;
938 if (Visit(Cursor, true))
939 return true;
940 }
941 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000942}
943
Douglas Gregorb1373d02010-01-20 20:59:29 +0000944bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000945 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
946 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000947 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000948
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000949 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
950 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
951 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000952 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000953 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000954
Douglas Gregora59e3902010-01-21 23:27:09 +0000955 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000956}
957
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000958bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
959 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
960 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
961 E = PID->protocol_end(); I != E; ++I, ++PL)
962 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
963 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000964
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000965 return VisitObjCContainerDecl(PID);
966}
967
Ted Kremenek23173d72010-05-18 21:09:07 +0000968bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000969 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000970 return true;
971
Ted Kremenek23173d72010-05-18 21:09:07 +0000972 // FIXME: This implements a workaround with @property declarations also being
973 // installed in the DeclContext for the @interface. Eventually this code
974 // should be removed.
975 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
976 if (!CDecl || !CDecl->IsClassExtension())
977 return false;
978
979 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
980 if (!ID)
981 return false;
982
983 IdentifierInfo *PropertyId = PD->getIdentifier();
984 ObjCPropertyDecl *prevDecl =
985 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
986
987 if (!prevDecl)
988 return false;
989
990 // Visit synthesized methods since they will be skipped when visiting
991 // the @interface.
992 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000993 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000994 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
Ted Kremenek23173d72010-05-18 21:09:07 +0000995 return true;
996
997 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000998 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000999 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
Ted Kremenek23173d72010-05-18 21:09:07 +00001000 return true;
1001
1002 return false;
1003}
1004
Douglas Gregorb1373d02010-01-20 20:59:29 +00001005bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001006 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +00001007 if (D->getSuperClass() &&
1008 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001009 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001010 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001011 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001012
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001013 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1014 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1015 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001016 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001017 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001018
Douglas Gregora59e3902010-01-21 23:27:09 +00001019 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001020}
1021
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001022bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1023 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001024}
1025
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001026bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +00001027 // 'ID' could be null when dealing with invalid code.
1028 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1029 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1030 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001031
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001032 return VisitObjCImplDecl(D);
1033}
1034
1035bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1036#if 0
1037 // Issue callbacks for super class.
1038 // FIXME: No source location information!
1039 if (D->getSuperClass() &&
1040 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001041 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001042 TU)))
1043 return true;
1044#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001045
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001046 return VisitObjCImplDecl(D);
1047}
1048
1049bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1050 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1051 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1052 E = D->protocol_end();
1053 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001054 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001055 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001056
1057 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001058}
1059
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001060bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00001061 if (Visit(MakeCursorObjCClassRef(D->getForwardInterfaceDecl(),
1062 D->getForwardDecl()->getLocation(), TU)))
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001063 return true;
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001064 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001065}
1066
Douglas Gregora4ffd852010-11-17 01:03:52 +00001067bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1068 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1069 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1070
1071 return false;
1072}
1073
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001074bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1075 return VisitDeclContext(D);
1076}
1077
Douglas Gregor69319002010-08-31 23:48:11 +00001078bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001079 // Visit nested-name-specifier.
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00001080 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1081 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001082 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001083
1084 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1085 D->getTargetNameLoc(), TU));
1086}
1087
Douglas Gregor7e242562010-09-01 19:52:22 +00001088bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001089 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001090 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1091 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001092 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001093 }
Douglas Gregor7e242562010-09-01 19:52:22 +00001094
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001095 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1096 return true;
1097
Douglas Gregor7e242562010-09-01 19:52:22 +00001098 return VisitDeclarationNameInfo(D->getNameInfo());
1099}
1100
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001101bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001102 // Visit nested-name-specifier.
Douglas Gregordb992412011-02-25 16:33:46 +00001103 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1104 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001105 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001106
1107 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1108 D->getIdentLocation(), TU));
1109}
1110
Douglas Gregor7e242562010-09-01 19:52:22 +00001111bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001112 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001113 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1114 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001115 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001116 }
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001117
Douglas Gregor7e242562010-09-01 19:52:22 +00001118 return VisitDeclarationNameInfo(D->getNameInfo());
1119}
1120
1121bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1122 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001123 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001124 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1125 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001126 return true;
1127
Douglas Gregor7e242562010-09-01 19:52:22 +00001128 return false;
1129}
1130
Douglas Gregor01829d32010-08-31 14:41:23 +00001131bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1132 switch (Name.getName().getNameKind()) {
1133 case clang::DeclarationName::Identifier:
1134 case clang::DeclarationName::CXXLiteralOperatorName:
1135 case clang::DeclarationName::CXXOperatorName:
1136 case clang::DeclarationName::CXXUsingDirective:
1137 return false;
1138
1139 case clang::DeclarationName::CXXConstructorName:
1140 case clang::DeclarationName::CXXDestructorName:
1141 case clang::DeclarationName::CXXConversionFunctionName:
1142 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1143 return Visit(TSInfo->getTypeLoc());
1144 return false;
1145
1146 case clang::DeclarationName::ObjCZeroArgSelector:
1147 case clang::DeclarationName::ObjCOneArgSelector:
1148 case clang::DeclarationName::ObjCMultiArgSelector:
1149 // FIXME: Per-identifier location info?
1150 return false;
1151 }
1152
1153 return false;
1154}
1155
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001156bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1157 SourceRange Range) {
1158 // FIXME: This whole routine is a hack to work around the lack of proper
1159 // source information in nested-name-specifiers (PR5791). Since we do have
1160 // a beginning source location, we can visit the first component of the
1161 // nested-name-specifier, if it's a single-token component.
1162 if (!NNS)
1163 return false;
1164
1165 // Get the first component in the nested-name-specifier.
1166 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1167 NNS = Prefix;
1168
1169 switch (NNS->getKind()) {
1170 case NestedNameSpecifier::Namespace:
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001171 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1172 TU));
1173
Douglas Gregor14aba762011-02-24 02:36:08 +00001174 case NestedNameSpecifier::NamespaceAlias:
1175 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1176 Range.getBegin(), TU));
1177
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001178 case NestedNameSpecifier::TypeSpec: {
1179 // If the type has a form where we know that the beginning of the source
1180 // range matches up with a reference cursor. Visit the appropriate reference
1181 // cursor.
John McCallf4c73712011-01-19 06:33:43 +00001182 const Type *T = NNS->getAsType();
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001183 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1184 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1185 if (const TagType *Tag = dyn_cast<TagType>(T))
1186 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1187 if (const TemplateSpecializationType *TST
1188 = dyn_cast<TemplateSpecializationType>(T))
1189 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1190 break;
1191 }
1192
1193 case NestedNameSpecifier::TypeSpecWithTemplate:
1194 case NestedNameSpecifier::Global:
1195 case NestedNameSpecifier::Identifier:
1196 break;
1197 }
1198
1199 return false;
1200}
1201
Douglas Gregordc355712011-02-25 00:36:19 +00001202bool
1203CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001204 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
Douglas Gregordc355712011-02-25 00:36:19 +00001205 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1206 Qualifiers.push_back(Qualifier);
1207
1208 while (!Qualifiers.empty()) {
1209 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1210 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1211 switch (NNS->getKind()) {
1212 case NestedNameSpecifier::Namespace:
1213 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001214 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001215 TU)))
1216 return true;
1217
1218 break;
1219
1220 case NestedNameSpecifier::NamespaceAlias:
1221 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001222 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001223 TU)))
1224 return true;
1225
1226 break;
1227
1228 case NestedNameSpecifier::TypeSpec:
1229 case NestedNameSpecifier::TypeSpecWithTemplate:
1230 if (Visit(Q.getTypeLoc()))
1231 return true;
1232
1233 break;
1234
1235 case NestedNameSpecifier::Global:
1236 case NestedNameSpecifier::Identifier:
1237 break;
1238 }
1239 }
1240
1241 return false;
1242}
1243
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001244bool CursorVisitor::VisitTemplateParameters(
1245 const TemplateParameterList *Params) {
1246 if (!Params)
1247 return false;
1248
1249 for (TemplateParameterList::const_iterator P = Params->begin(),
1250 PEnd = Params->end();
1251 P != PEnd; ++P) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001252 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001253 return true;
1254 }
1255
1256 return false;
1257}
1258
Douglas Gregor0b36e612010-08-31 20:37:03 +00001259bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1260 switch (Name.getKind()) {
1261 case TemplateName::Template:
1262 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1263
1264 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001265 // Visit the overloaded template set.
1266 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1267 return true;
1268
Douglas Gregor0b36e612010-08-31 20:37:03 +00001269 return false;
1270
1271 case TemplateName::DependentTemplate:
1272 // FIXME: Visit nested-name-specifier.
1273 return false;
1274
1275 case TemplateName::QualifiedTemplate:
1276 // FIXME: Visit nested-name-specifier.
1277 return Visit(MakeCursorTemplateRef(
1278 Name.getAsQualifiedTemplateName()->getDecl(),
1279 Loc, TU));
John McCall14606042011-06-30 08:33:18 +00001280
1281 case TemplateName::SubstTemplateTemplateParm:
1282 return Visit(MakeCursorTemplateRef(
1283 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1284 Loc, TU));
Douglas Gregor1aee05d2011-01-15 06:45:20 +00001285
1286 case TemplateName::SubstTemplateTemplateParmPack:
1287 return Visit(MakeCursorTemplateRef(
1288 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1289 Loc, TU));
Douglas Gregor0b36e612010-08-31 20:37:03 +00001290 }
1291
1292 return false;
1293}
1294
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001295bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1296 switch (TAL.getArgument().getKind()) {
1297 case TemplateArgument::Null:
1298 case TemplateArgument::Integral:
Douglas Gregor87dd6972010-12-20 16:52:59 +00001299 case TemplateArgument::Pack:
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001300 return false;
1301
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001302 case TemplateArgument::Type:
1303 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1304 return Visit(TSInfo->getTypeLoc());
1305 return false;
1306
1307 case TemplateArgument::Declaration:
1308 if (Expr *E = TAL.getSourceDeclExpression())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001309 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001310 return false;
1311
1312 case TemplateArgument::Expression:
1313 if (Expr *E = TAL.getSourceExpression())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001314 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001315 return false;
1316
1317 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001318 case TemplateArgument::TemplateExpansion:
Douglas Gregorb6744ef2011-03-02 17:09:35 +00001319 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1320 return true;
1321
Douglas Gregora7fc9012011-01-05 18:58:31 +00001322 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
Douglas Gregor0b36e612010-08-31 20:37:03 +00001323 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001324 }
1325
1326 return false;
1327}
1328
Ted Kremeneka0536d82010-05-07 01:04:29 +00001329bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1330 return VisitDeclContext(D);
1331}
1332
Douglas Gregor01829d32010-08-31 14:41:23 +00001333bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1334 return Visit(TL.getUnqualifiedLoc());
1335}
1336
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001337bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00001338 ASTContext &Context = AU->getASTContext();
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001339
1340 // Some builtin types (such as Objective-C's "id", "sel", and
1341 // "Class") have associated declarations. Create cursors for those.
1342 QualType VisitType;
John McCalle0a22d02011-10-18 21:02:43 +00001343 switch (TL.getTypePtr()->getKind()) {
John McCall2dde35b2011-10-18 22:28:37 +00001344
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001345 case BuiltinType::Void:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001346 case BuiltinType::NullPtr:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001347 case BuiltinType::Dependent:
John McCall2dde35b2011-10-18 22:28:37 +00001348#define BUILTIN_TYPE(Id, SingletonId)
1349#define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1350#define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1351#define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
1352#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
1353#include "clang/AST/BuiltinTypes.def"
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001354 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001355
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001356 case BuiltinType::ObjCId:
1357 VisitType = Context.getObjCIdType();
1358 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001359
1360 case BuiltinType::ObjCClass:
1361 VisitType = Context.getObjCClassType();
1362 break;
1363
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001364 case BuiltinType::ObjCSel:
1365 VisitType = Context.getObjCSelType();
1366 break;
1367 }
1368
1369 if (!VisitType.isNull()) {
1370 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001371 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001372 TU));
1373 }
1374
1375 return false;
1376}
1377
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001378bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
Richard Smith162e1c12011-04-15 14:24:37 +00001379 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001380}
1381
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001382bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1383 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1384}
1385
1386bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
Argyrios Kyrtzidis6f155de2011-08-25 22:24:47 +00001387 if (TL.isDefinition())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001388 return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
Argyrios Kyrtzidis6f155de2011-08-25 22:24:47 +00001389
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001390 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1391}
1392
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001393bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Chandler Carruth960d13d2011-05-01 09:53:37 +00001394 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001395}
1396
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001397bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1398 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1399 return true;
1400
John McCallc12c5bb2010-05-15 11:32:37 +00001401 return false;
1402}
1403
1404bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1405 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1406 return true;
1407
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001408 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1409 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1410 TU)))
1411 return true;
1412 }
1413
1414 return false;
1415}
1416
1417bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001418 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001419}
1420
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001421bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1422 return Visit(TL.getInnerLoc());
1423}
1424
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001425bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1426 return Visit(TL.getPointeeLoc());
1427}
1428
1429bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1430 return Visit(TL.getPointeeLoc());
1431}
1432
1433bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1434 return Visit(TL.getPointeeLoc());
1435}
1436
1437bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001438 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001439}
1440
1441bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001442 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001443}
1444
Argyrios Kyrtzidis3422fbc2011-08-15 18:44:43 +00001445bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1446 return Visit(TL.getModifiedLoc());
1447}
1448
Douglas Gregor01829d32010-08-31 14:41:23 +00001449bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1450 bool SkipResultType) {
1451 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001452 return true;
1453
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001454 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001455 if (Decl *D = TL.getArg(I))
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001456 if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001457 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001458
1459 return false;
1460}
1461
1462bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1463 if (Visit(TL.getElementLoc()))
1464 return true;
1465
1466 if (Expr *Size = TL.getSizeExpr())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001467 return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001468
1469 return false;
1470}
1471
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001472bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1473 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001474 // Visit the template name.
1475 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1476 TL.getTemplateNameLoc()))
1477 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001478
1479 // Visit the template arguments.
1480 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1481 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1482 return true;
1483
1484 return false;
1485}
1486
Douglas Gregor2332c112010-01-21 20:48:56 +00001487bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1488 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1489}
1490
1491bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1492 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1493 return Visit(TSInfo->getTypeLoc());
1494
1495 return false;
1496}
1497
Sean Huntca63c202011-05-24 22:41:36 +00001498bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1499 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1500 return Visit(TSInfo->getTypeLoc());
1501
1502 return false;
1503}
1504
Douglas Gregor2494dd02011-03-01 01:34:45 +00001505bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
1506 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1507 return true;
1508
1509 return false;
1510}
1511
Douglas Gregor94fdffa2011-03-01 20:11:18 +00001512bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1513 DependentTemplateSpecializationTypeLoc TL) {
1514 // Visit the nested-name-specifier, if there is one.
1515 if (TL.getQualifierLoc() &&
1516 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1517 return true;
1518
1519 // Visit the template arguments.
1520 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1521 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1522 return true;
1523
1524 return false;
1525}
1526
Douglas Gregor9e876872011-03-01 18:12:44 +00001527bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1528 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1529 return true;
1530
1531 return Visit(TL.getNamedTypeLoc());
1532}
1533
Douglas Gregor7536dd52010-12-20 02:24:11 +00001534bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1535 return Visit(TL.getPatternLoc());
1536}
1537
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +00001538bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1539 if (Expr *E = TL.getUnderlyingExpr())
1540 return Visit(MakeCXCursor(E, StmtParent, TU));
1541
1542 return false;
1543}
1544
1545bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1546 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1547}
1548
Eli Friedmanb001de72011-10-06 23:00:33 +00001549bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1550 return Visit(TL.getValueLoc());
1551}
1552
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +00001553#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1554bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1555 return Visit##PARENT##Loc(TL); \
1556}
1557
1558DEFAULT_TYPELOC_IMPL(Complex, Type)
1559DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1560DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1561DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1562DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
1563DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1564DEFAULT_TYPELOC_IMPL(Vector, Type)
1565DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1566DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1567DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1568DEFAULT_TYPELOC_IMPL(Record, TagType)
1569DEFAULT_TYPELOC_IMPL(Enum, TagType)
1570DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1571DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1572DEFAULT_TYPELOC_IMPL(Auto, Type)
1573
Ted Kremenek3064ef92010-08-27 21:34:58 +00001574bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001575 // Visit the nested-name-specifier, if present.
1576 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1577 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1578 return true;
1579
John McCall5e1cdac2011-10-07 06:10:15 +00001580 if (D->isCompleteDefinition()) {
Ted Kremenek3064ef92010-08-27 21:34:58 +00001581 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1582 E = D->bases_end(); I != E; ++I) {
1583 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1584 return true;
1585 }
1586 }
1587
1588 return VisitTagDecl(D);
1589}
1590
Ted Kremenek09dfa372010-02-18 05:46:33 +00001591bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001592 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1593 i != e; ++i)
1594 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001595 return true;
1596
1597 return false;
1598}
1599
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001600//===----------------------------------------------------------------------===//
1601// Data-recursive visitor methods.
1602//===----------------------------------------------------------------------===//
1603
Ted Kremenek28a71942010-11-13 00:36:47 +00001604namespace {
Ted Kremenek035dc412010-11-13 00:36:50 +00001605#define DEF_JOB(NAME, DATA, KIND)\
1606class NAME : public VisitorJob {\
1607public:\
1608 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1609 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Ted Kremenekf64d8032010-11-18 00:02:32 +00001610 DATA *get() const { return static_cast<DATA*>(data[0]); }\
Ted Kremenek035dc412010-11-13 00:36:50 +00001611};
1612
1613DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1614DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001615DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001616DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001617DEF_JOB(ExplicitTemplateArgsVisit, ASTTemplateArgumentListInfo,
Ted Kremenek60608ec2010-11-17 00:50:47 +00001618 ExplicitTemplateArgsVisitKind)
Douglas Gregor94d96292011-01-19 20:34:17 +00001619DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001620#undef DEF_JOB
1621
1622class DeclVisit : public VisitorJob {
1623public:
1624 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1625 VisitorJob(parent, VisitorJob::DeclVisitKind,
1626 d, isFirst ? (void*) 1 : (void*) 0) {}
1627 static bool classof(const VisitorJob *VJ) {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001628 return VJ->getKind() == DeclVisitKind;
Ted Kremenek035dc412010-11-13 00:36:50 +00001629 }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001630 Decl *get() const { return static_cast<Decl*>(data[0]); }
1631 bool isFirst() const { return data[1] ? true : false; }
Ted Kremenek035dc412010-11-13 00:36:50 +00001632};
Ted Kremenek035dc412010-11-13 00:36:50 +00001633class TypeLocVisit : public VisitorJob {
1634public:
1635 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1636 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1637 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1638
1639 static bool classof(const VisitorJob *VJ) {
1640 return VJ->getKind() == TypeLocVisitKind;
1641 }
1642
Ted Kremenek82f3c502010-11-15 22:23:26 +00001643 TypeLoc get() const {
Ted Kremenekf64d8032010-11-18 00:02:32 +00001644 QualType T = QualType::getFromOpaquePtr(data[0]);
1645 return TypeLoc(T, data[1]);
Ted Kremenek035dc412010-11-13 00:36:50 +00001646 }
1647};
1648
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001649class LabelRefVisit : public VisitorJob {
1650public:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001651 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1652 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001653 labelLoc.getPtrEncoding()) {}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001654
1655 static bool classof(const VisitorJob *VJ) {
1656 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1657 }
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001658 LabelDecl *get() const { return static_cast<LabelDecl*>(data[0]); }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001659 SourceLocation getLoc() const {
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001660 return SourceLocation::getFromPtrEncoding(data[1]); }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001661};
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001662
1663class NestedNameSpecifierLocVisit : public VisitorJob {
1664public:
1665 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1666 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1667 Qualifier.getNestedNameSpecifier(),
1668 Qualifier.getOpaqueData()) { }
1669
1670 static bool classof(const VisitorJob *VJ) {
1671 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1672 }
1673
1674 NestedNameSpecifierLoc get() const {
1675 return NestedNameSpecifierLoc(static_cast<NestedNameSpecifier*>(data[0]),
1676 data[1]);
1677 }
1678};
1679
Ted Kremenekf64d8032010-11-18 00:02:32 +00001680class DeclarationNameInfoVisit : public VisitorJob {
1681public:
1682 DeclarationNameInfoVisit(Stmt *S, CXCursor parent)
1683 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
1684 static bool classof(const VisitorJob *VJ) {
1685 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1686 }
1687 DeclarationNameInfo get() const {
1688 Stmt *S = static_cast<Stmt*>(data[0]);
1689 switch (S->getStmtClass()) {
1690 default:
1691 llvm_unreachable("Unhandled Stmt");
Douglas Gregorba0513d2011-10-25 01:33:02 +00001692 case clang::Stmt::MSDependentExistsStmtClass:
1693 return cast<MSDependentExistsStmt>(S)->getNameInfo();
Ted Kremenekf64d8032010-11-18 00:02:32 +00001694 case Stmt::CXXDependentScopeMemberExprClass:
1695 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1696 case Stmt::DependentScopeDeclRefExprClass:
1697 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
1698 }
1699 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001700};
Ted Kremenekcdba6592010-11-18 00:42:18 +00001701class MemberRefVisit : public VisitorJob {
1702public:
1703 MemberRefVisit(FieldDecl *D, SourceLocation L, CXCursor parent)
1704 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001705 L.getPtrEncoding()) {}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001706 static bool classof(const VisitorJob *VJ) {
1707 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1708 }
1709 FieldDecl *get() const {
1710 return static_cast<FieldDecl*>(data[0]);
1711 }
1712 SourceLocation getLoc() const {
1713 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1714 }
1715};
Ted Kremenek28a71942010-11-13 00:36:47 +00001716class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1717 VisitorWorkList &WL;
1718 CXCursor Parent;
1719public:
1720 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1721 : WL(wl), Parent(parent) {}
1722
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001723 void VisitAddrLabelExpr(AddrLabelExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001724 void VisitBlockExpr(BlockExpr *B);
Ted Kremenek28a71942010-11-13 00:36:47 +00001725 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek083c7e22010-11-13 05:38:03 +00001726 void VisitCompoundStmt(CompoundStmt *S);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001727 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
Douglas Gregorba0513d2011-10-25 01:33:02 +00001728 void VisitMSDependentExistsStmt(MSDependentExistsStmt *S);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001729 void VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001730 void VisitCXXNewExpr(CXXNewExpr *E);
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001731 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001732 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001733 void VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001734 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001735 void VisitCXXTypeidExpr(CXXTypeidExpr *E);
Ted Kremenek55b933a2010-11-17 00:50:36 +00001736 void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001737 void VisitCXXUuidofExpr(CXXUuidofExpr *E);
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001738 void VisitDeclRefExpr(DeclRefExpr *D);
Ted Kremenek035dc412010-11-13 00:36:50 +00001739 void VisitDeclStmt(DeclStmt *S);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001740 void VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001741 void VisitDesignatedInitExpr(DesignatedInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001742 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1743 void VisitForStmt(ForStmt *FS);
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001744 void VisitGotoStmt(GotoStmt *GS);
Ted Kremenek28a71942010-11-13 00:36:47 +00001745 void VisitIfStmt(IfStmt *If);
1746 void VisitInitListExpr(InitListExpr *IE);
1747 void VisitMemberExpr(MemberExpr *M);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001748 void VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001749 void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001750 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1751 void VisitOverloadExpr(OverloadExpr *E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001752 void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001753 void VisitStmt(Stmt *S);
1754 void VisitSwitchStmt(SwitchStmt *S);
1755 void VisitWhileStmt(WhileStmt *W);
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001756 void VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Francois Pichet6ad6f282010-12-07 00:08:36 +00001757 void VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E);
John Wiegley21ff2e52011-04-28 00:16:57 +00001758 void VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E);
John Wiegley55262202011-04-25 06:54:41 +00001759 void VisitExpressionTraitExpr(ExpressionTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001760 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001761 void VisitVAArgExpr(VAArgExpr *E);
Douglas Gregor94d96292011-01-19 20:34:17 +00001762 void VisitSizeOfPackExpr(SizeOfPackExpr *E);
John McCall4b9c2d22011-11-06 09:01:30 +00001763 void VisitPseudoObjectExpr(PseudoObjectExpr *E);
1764 void VisitOpaqueValueExpr(OpaqueValueExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00001765
Ted Kremenek28a71942010-11-13 00:36:47 +00001766private:
Ted Kremenekf64d8032010-11-18 00:02:32 +00001767 void AddDeclarationNameInfo(Stmt *S);
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001768 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001769 void AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001770 void AddMemberRef(FieldDecl *D, SourceLocation L);
Ted Kremenek28a71942010-11-13 00:36:47 +00001771 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001772 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001773 void AddTypeLoc(TypeSourceInfo *TI);
1774 void EnqueueChildren(Stmt *S);
1775};
1776} // end anonyous namespace
1777
Ted Kremenekf64d8032010-11-18 00:02:32 +00001778void EnqueueVisitor::AddDeclarationNameInfo(Stmt *S) {
1779 // 'S' should always be non-null, since it comes from the
1780 // statement we are visiting.
1781 WL.push_back(DeclarationNameInfoVisit(S, Parent));
1782}
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001783
1784void
1785EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1786 if (Qualifier)
1787 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
1788}
1789
Ted Kremenek28a71942010-11-13 00:36:47 +00001790void EnqueueVisitor::AddStmt(Stmt *S) {
1791 if (S)
1792 WL.push_back(StmtVisit(S, Parent));
1793}
Ted Kremenek035dc412010-11-13 00:36:50 +00001794void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001795 if (D)
Ted Kremenek035dc412010-11-13 00:36:50 +00001796 WL.push_back(DeclVisit(D, Parent, isFirst));
Ted Kremenek28a71942010-11-13 00:36:47 +00001797}
Ted Kremenek60608ec2010-11-17 00:50:47 +00001798void EnqueueVisitor::
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001799 AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001800 if (A)
1801 WL.push_back(ExplicitTemplateArgsVisit(
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001802 const_cast<ASTTemplateArgumentListInfo*>(A), Parent));
Ted Kremenek60608ec2010-11-17 00:50:47 +00001803}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001804void EnqueueVisitor::AddMemberRef(FieldDecl *D, SourceLocation L) {
1805 if (D)
1806 WL.push_back(MemberRefVisit(D, L, Parent));
1807}
Ted Kremenek28a71942010-11-13 00:36:47 +00001808void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1809 if (TI)
1810 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1811 }
1812void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001813 unsigned size = WL.size();
John McCall7502c1d2011-02-13 04:07:26 +00001814 for (Stmt::child_range Child = S->children(); Child; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001815 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001816 }
1817 if (size == WL.size())
1818 return;
1819 // Now reverse the entries we just added. This will match the DFS
1820 // ordering performed by the worklist.
1821 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1822 std::reverse(I, E);
1823}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001824void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1825 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
1826}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001827void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1828 AddDecl(B->getBlockDecl());
1829}
Ted Kremenek28a71942010-11-13 00:36:47 +00001830void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1831 EnqueueChildren(E);
1832 AddTypeLoc(E->getTypeSourceInfo());
1833}
Ted Kremenek083c7e22010-11-13 05:38:03 +00001834void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1835 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1836 E = S->body_rend(); I != E; ++I) {
1837 AddStmt(*I);
1838 }
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001839}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001840void EnqueueVisitor::
Douglas Gregorba0513d2011-10-25 01:33:02 +00001841VisitMSDependentExistsStmt(MSDependentExistsStmt *S) {
1842 AddStmt(S->getSubStmt());
1843 AddDeclarationNameInfo(S);
1844 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
1845 AddNestedNameSpecifierLoc(QualifierLoc);
1846}
1847
1848void EnqueueVisitor::
Ted Kremenekf64d8032010-11-18 00:02:32 +00001849VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
1850 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1851 AddDeclarationNameInfo(E);
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001852 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1853 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001854 if (!E->isImplicitAccess())
1855 AddStmt(E->getBase());
1856}
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001857void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1858 // Enqueue the initializer or constructor arguments.
1859 for (unsigned I = E->getNumConstructorArgs(); I > 0; --I)
1860 AddStmt(E->getConstructorArg(I-1));
1861 // Enqueue the array size, if any.
1862 AddStmt(E->getArraySize());
1863 // Enqueue the allocated type.
1864 AddTypeLoc(E->getAllocatedTypeSourceInfo());
1865 // Enqueue the placement arguments.
1866 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1867 AddStmt(E->getPlacementArg(I-1));
1868}
Ted Kremenek28a71942010-11-13 00:36:47 +00001869void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
Ted Kremenek8b8d8c92010-11-13 05:55:56 +00001870 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1871 AddStmt(CE->getArg(I-1));
Ted Kremenek28a71942010-11-13 00:36:47 +00001872 AddStmt(CE->getCallee());
1873 AddStmt(CE->getArg(0));
1874}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001875void EnqueueVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1876 // Visit the name of the type being destroyed.
1877 AddTypeLoc(E->getDestroyedTypeInfo());
1878 // Visit the scope type that looks disturbingly like the nested-name-specifier
1879 // but isn't.
1880 AddTypeLoc(E->getScopeTypeInfo());
1881 // Visit the nested-name-specifier.
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001882 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1883 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001884 // Visit base expression.
1885 AddStmt(E->getBase());
1886}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001887void EnqueueVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1888 AddTypeLoc(E->getTypeSourceInfo());
1889}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001890void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1891 EnqueueChildren(E);
1892 AddTypeLoc(E->getTypeSourceInfo());
1893}
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001894void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1895 EnqueueChildren(E);
1896 if (E->isTypeOperand())
1897 AddTypeLoc(E->getTypeOperandSourceInfo());
1898}
Ted Kremenek55b933a2010-11-17 00:50:36 +00001899
1900void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
1901 *E) {
1902 EnqueueChildren(E);
1903 AddTypeLoc(E->getTypeSourceInfo());
1904}
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001905void EnqueueVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1906 EnqueueChildren(E);
1907 if (E->isTypeOperand())
1908 AddTypeLoc(E->getTypeOperandSourceInfo());
1909}
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001910void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001911 if (DR->hasExplicitTemplateArgs()) {
1912 AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
1913 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001914 WL.push_back(DeclRefExprParts(DR, Parent));
1915}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001916void EnqueueVisitor::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
1917 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1918 AddDeclarationNameInfo(E);
Douglas Gregor00cf3cc2011-02-25 20:49:16 +00001919 AddNestedNameSpecifierLoc(E->getQualifierLoc());
Ted Kremenekf64d8032010-11-18 00:02:32 +00001920}
Ted Kremenek035dc412010-11-13 00:36:50 +00001921void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1922 unsigned size = WL.size();
1923 bool isFirst = true;
1924 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1925 D != DEnd; ++D) {
1926 AddDecl(*D, isFirst);
1927 isFirst = false;
1928 }
1929 if (size == WL.size())
1930 return;
1931 // Now reverse the entries we just added. This will match the DFS
1932 // ordering performed by the worklist.
1933 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1934 std::reverse(I, E);
1935}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001936void EnqueueVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1937 AddStmt(E->getInit());
1938 typedef DesignatedInitExpr::Designator Designator;
1939 for (DesignatedInitExpr::reverse_designators_iterator
1940 D = E->designators_rbegin(), DEnd = E->designators_rend();
1941 D != DEnd; ++D) {
1942 if (D->isFieldDesignator()) {
1943 if (FieldDecl *Field = D->getField())
1944 AddMemberRef(Field, D->getFieldLoc());
1945 continue;
1946 }
1947 if (D->isArrayDesignator()) {
1948 AddStmt(E->getArrayIndex(*D));
1949 continue;
1950 }
1951 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1952 AddStmt(E->getArrayRangeEnd(*D));
1953 AddStmt(E->getArrayRangeStart(*D));
1954 }
1955}
Ted Kremenek28a71942010-11-13 00:36:47 +00001956void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1957 EnqueueChildren(E);
1958 AddTypeLoc(E->getTypeInfoAsWritten());
1959}
1960void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1961 AddStmt(FS->getBody());
1962 AddStmt(FS->getInc());
1963 AddStmt(FS->getCond());
1964 AddDecl(FS->getConditionVariable());
1965 AddStmt(FS->getInit());
1966}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001967void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) {
1968 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
1969}
Ted Kremenek28a71942010-11-13 00:36:47 +00001970void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
1971 AddStmt(If->getElse());
1972 AddStmt(If->getThen());
1973 AddStmt(If->getCond());
1974 AddDecl(If->getConditionVariable());
1975}
1976void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
1977 // We care about the syntactic form of the initializer list, only.
1978 if (InitListExpr *Syntactic = IE->getSyntacticForm())
1979 IE = Syntactic;
1980 EnqueueChildren(IE);
1981}
1982void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
Douglas Gregor89629a72010-11-17 17:15:08 +00001983 WL.push_back(MemberExprParts(M, Parent));
1984
1985 // If the base of the member access expression is an implicit 'this', don't
1986 // visit it.
1987 // FIXME: If we ever want to show these implicit accesses, this will be
1988 // unfortunate. However, clang_getCursor() relies on this behavior.
Douglas Gregor75e85042011-03-02 21:06:53 +00001989 if (!M->isImplicitAccess())
1990 AddStmt(M->getBase());
Ted Kremenek28a71942010-11-13 00:36:47 +00001991}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001992void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1993 AddTypeLoc(E->getEncodedTypeSourceInfo());
1994}
Ted Kremenek28a71942010-11-13 00:36:47 +00001995void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
1996 EnqueueChildren(M);
1997 AddTypeLoc(M->getClassReceiverTypeInfo());
1998}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001999void EnqueueVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
2000 // Visit the components of the offsetof expression.
2001 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
2002 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
2003 const OffsetOfNode &Node = E->getComponent(I-1);
2004 switch (Node.getKind()) {
2005 case OffsetOfNode::Array:
2006 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2007 break;
2008 case OffsetOfNode::Field:
Abramo Bagnara06dec892011-03-12 09:45:03 +00002009 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
Ted Kremenekcdba6592010-11-18 00:42:18 +00002010 break;
2011 case OffsetOfNode::Identifier:
2012 case OffsetOfNode::Base:
2013 continue;
2014 }
2015 }
2016 // Visit the type into which we're computing the offset.
2017 AddTypeLoc(E->getTypeSourceInfo());
2018}
Ted Kremenek28a71942010-11-13 00:36:47 +00002019void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00002020 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
Ted Kremenek60458782010-11-12 21:34:16 +00002021 WL.push_back(OverloadExprParts(E, Parent));
2022}
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002023void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
2024 UnaryExprOrTypeTraitExpr *E) {
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00002025 EnqueueChildren(E);
2026 if (E->isArgumentType())
2027 AddTypeLoc(E->getArgumentTypeInfo());
2028}
Ted Kremenek28a71942010-11-13 00:36:47 +00002029void EnqueueVisitor::VisitStmt(Stmt *S) {
2030 EnqueueChildren(S);
2031}
2032void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
2033 AddStmt(S->getBody());
2034 AddStmt(S->getCond());
2035 AddDecl(S->getConditionVariable());
2036}
Ted Kremenekfafa75a2010-11-17 00:50:39 +00002037
Ted Kremenek28a71942010-11-13 00:36:47 +00002038void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
2039 AddStmt(W->getBody());
2040 AddStmt(W->getCond());
2041 AddDecl(W->getConditionVariable());
2042}
John Wiegley21ff2e52011-04-28 00:16:57 +00002043
Ted Kremenek2939b6f2010-11-17 00:50:50 +00002044void EnqueueVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
2045 AddTypeLoc(E->getQueriedTypeSourceInfo());
2046}
Francois Pichet6ad6f282010-12-07 00:08:36 +00002047
2048void EnqueueVisitor::VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
Francois Pichet6ad6f282010-12-07 00:08:36 +00002049 AddTypeLoc(E->getRhsTypeSourceInfo());
Francois Pichet0a03a3f2010-12-08 09:11:05 +00002050 AddTypeLoc(E->getLhsTypeSourceInfo());
Francois Pichet6ad6f282010-12-07 00:08:36 +00002051}
2052
John Wiegley21ff2e52011-04-28 00:16:57 +00002053void EnqueueVisitor::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
2054 AddTypeLoc(E->getQueriedTypeSourceInfo());
2055}
2056
John Wiegley55262202011-04-25 06:54:41 +00002057void EnqueueVisitor::VisitExpressionTraitExpr(ExpressionTraitExpr *E) {
2058 EnqueueChildren(E);
2059}
2060
Ted Kremenek28a71942010-11-13 00:36:47 +00002061void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
2062 VisitOverloadExpr(U);
2063 if (!U->isImplicitAccess())
2064 AddStmt(U->getBase());
2065}
Ted Kremenek9d3bf792010-11-17 00:50:43 +00002066void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) {
2067 AddStmt(E->getSubExpr());
2068 AddTypeLoc(E->getWrittenTypeInfo());
2069}
Douglas Gregor94d96292011-01-19 20:34:17 +00002070void EnqueueVisitor::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
2071 WL.push_back(SizeOfPackExprParts(E, Parent));
2072}
John McCall4b9c2d22011-11-06 09:01:30 +00002073void EnqueueVisitor::VisitOpaqueValueExpr(OpaqueValueExpr *E) {
2074 // If the opaque value has a source expression, just transparently
2075 // visit that. This is useful for (e.g.) pseudo-object expressions.
2076 if (Expr *SourceExpr = E->getSourceExpr())
2077 return Visit(SourceExpr);
2078 AddStmt(E);
2079}
2080void EnqueueVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *E) {
2081 // Treat the expression like its syntactic form.
2082 Visit(E->getSyntacticForm());
2083}
Ted Kremenek60458782010-11-12 21:34:16 +00002084
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002085void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002086 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002087}
2088
2089bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2090 if (RegionOfInterest.isValid()) {
2091 SourceRange Range = getRawCursorExtent(C);
2092 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2093 return false;
2094 }
2095 return true;
2096}
2097
2098bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2099 while (!WL.empty()) {
2100 // Dequeue the worklist item.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002101 VisitorJob LI = WL.back();
2102 WL.pop_back();
2103
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002104 // Set the Parent field, then back to its old value once we're done.
2105 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2106
2107 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00002108 case VisitorJob::DeclVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002109 Decl *D = cast<DeclVisit>(&LI)->get();
Ted Kremenekf1107452010-11-12 18:26:56 +00002110 if (!D)
2111 continue;
2112
2113 // For now, perform default visitation for Decls.
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002114 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2115 cast<DeclVisit>(&LI)->isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00002116 return true;
2117
2118 continue;
2119 }
Ted Kremenek60608ec2010-11-17 00:50:47 +00002120 case VisitorJob::ExplicitTemplateArgsVisitKind: {
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00002121 const ASTTemplateArgumentListInfo *ArgList =
Ted Kremenek60608ec2010-11-17 00:50:47 +00002122 cast<ExplicitTemplateArgsVisit>(&LI)->get();
2123 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2124 *ArgEnd = Arg + ArgList->NumTemplateArgs;
2125 Arg != ArgEnd; ++Arg) {
2126 if (VisitTemplateArgumentLoc(*Arg))
2127 return true;
2128 }
2129 continue;
2130 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002131 case VisitorJob::TypeLocVisitKind: {
2132 // Perform default visitation for TypeLocs.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002133 if (Visit(cast<TypeLocVisit>(&LI)->get()))
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002134 return true;
2135 continue;
2136 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002137 case VisitorJob::LabelRefVisitKind: {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002138 LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Ted Kremeneke7455012011-02-23 04:54:51 +00002139 if (LabelStmt *stmt = LS->getStmt()) {
2140 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2141 TU))) {
2142 return true;
2143 }
2144 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002145 continue;
2146 }
Ted Kremenek47695c82011-08-18 22:25:21 +00002147
Douglas Gregorf3db29f2011-02-25 18:19:59 +00002148 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2149 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2150 if (VisitNestedNameSpecifierLoc(V->get()))
2151 return true;
2152 continue;
2153 }
2154
Ted Kremenekf64d8032010-11-18 00:02:32 +00002155 case VisitorJob::DeclarationNameInfoVisitKind: {
2156 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2157 ->get()))
2158 return true;
2159 continue;
2160 }
Ted Kremenekcdba6592010-11-18 00:42:18 +00002161 case VisitorJob::MemberRefVisitKind: {
2162 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2163 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2164 return true;
2165 continue;
2166 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002167 case VisitorJob::StmtVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002168 Stmt *S = cast<StmtVisit>(&LI)->get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00002169 if (!S)
2170 continue;
2171
Ted Kremenekf1107452010-11-12 18:26:56 +00002172 // Update the current cursor.
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002173 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
Ted Kremenekcdba6592010-11-18 00:42:18 +00002174 if (!IsInRegionOfInterest(Cursor))
2175 continue;
2176 switch (Visitor(Cursor, Parent, ClientData)) {
2177 case CXChildVisit_Break: return true;
2178 case CXChildVisit_Continue: break;
2179 case CXChildVisit_Recurse:
2180 EnqueueWorkList(WL, S);
Ted Kremenek82f3c502010-11-15 22:23:26 +00002181 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002182 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00002183 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002184 }
2185 case VisitorJob::MemberExprPartsKind: {
2186 // Handle the other pieces in the MemberExpr besides the base.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002187 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002188
2189 // Visit the nested-name-specifier
Douglas Gregor40d96a62011-02-28 21:54:11 +00002190 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
2191 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002192 return true;
2193
2194 // Visit the declaration name.
2195 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2196 return true;
2197
2198 // Visit the explicitly-specified template arguments, if any.
2199 if (M->hasExplicitTemplateArgs()) {
2200 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2201 *ArgEnd = Arg + M->getNumTemplateArgs();
2202 Arg != ArgEnd; ++Arg) {
2203 if (VisitTemplateArgumentLoc(*Arg))
2204 return true;
2205 }
2206 }
2207 continue;
2208 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002209 case VisitorJob::DeclRefExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002210 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002211 // Visit nested-name-specifier, if present.
Douglas Gregor40d96a62011-02-28 21:54:11 +00002212 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
2213 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002214 return true;
2215 // Visit declaration name.
2216 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2217 return true;
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002218 continue;
2219 }
Ted Kremenek60458782010-11-12 21:34:16 +00002220 case VisitorJob::OverloadExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002221 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Ted Kremenek60458782010-11-12 21:34:16 +00002222 // Visit the nested-name-specifier.
Douglas Gregor4c9be892011-02-28 20:01:57 +00002223 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
2224 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenek60458782010-11-12 21:34:16 +00002225 return true;
2226 // Visit the declaration name.
2227 if (VisitDeclarationNameInfo(O->getNameInfo()))
2228 return true;
2229 // Visit the overloaded declaration reference.
2230 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2231 return true;
Ted Kremenek60458782010-11-12 21:34:16 +00002232 continue;
2233 }
Douglas Gregor94d96292011-01-19 20:34:17 +00002234 case VisitorJob::SizeOfPackExprPartsKind: {
2235 SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
2236 NamedDecl *Pack = E->getPack();
2237 if (isa<TemplateTypeParmDecl>(Pack)) {
2238 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
2239 E->getPackLoc(), TU)))
2240 return true;
2241
2242 continue;
2243 }
2244
2245 if (isa<TemplateTemplateParmDecl>(Pack)) {
2246 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
2247 E->getPackLoc(), TU)))
2248 return true;
2249
2250 continue;
2251 }
2252
2253 // Non-type template parameter packs and function parameter packs are
2254 // treated like DeclRefExpr cursors.
2255 continue;
2256 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002257 }
2258 }
2259 return false;
2260}
2261
Ted Kremenekcdba6592010-11-18 00:42:18 +00002262bool CursorVisitor::Visit(Stmt *S) {
Ted Kremenekd1ded662010-11-15 23:31:32 +00002263 VisitorWorkList *WL = 0;
2264 if (!WorkListFreeList.empty()) {
2265 WL = WorkListFreeList.back();
2266 WL->clear();
2267 WorkListFreeList.pop_back();
2268 }
2269 else {
2270 WL = new VisitorWorkList();
2271 WorkListCache.push_back(WL);
2272 }
2273 EnqueueWorkList(*WL, S);
2274 bool result = RunVisitorWorkList(*WL);
2275 WorkListFreeList.push_back(WL);
2276 return result;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002277}
2278
Francois Pichet48a8d142011-07-25 22:00:44 +00002279namespace {
2280typedef llvm::SmallVector<SourceRange, 4> RefNamePieces;
2281RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
2282 const DeclarationNameInfo &NI,
2283 const SourceRange &QLoc,
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00002284 const ASTTemplateArgumentListInfo *TemplateArgs = 0){
Francois Pichet48a8d142011-07-25 22:00:44 +00002285 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
2286 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
2287 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
2288
2289 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
2290
2291 RefNamePieces Pieces;
2292
2293 if (WantQualifier && QLoc.isValid())
2294 Pieces.push_back(QLoc);
2295
2296 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
2297 Pieces.push_back(NI.getLoc());
2298
2299 if (WantTemplateArgs && TemplateArgs)
2300 Pieces.push_back(SourceRange(TemplateArgs->LAngleLoc,
2301 TemplateArgs->RAngleLoc));
2302
2303 if (Kind == DeclarationName::CXXOperatorName) {
2304 Pieces.push_back(SourceLocation::getFromRawEncoding(
2305 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
2306 Pieces.push_back(SourceLocation::getFromRawEncoding(
2307 NI.getInfo().CXXOperatorName.EndOpNameLoc));
2308 }
2309
2310 if (WantSinglePiece) {
2311 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
2312 Pieces.clear();
2313 Pieces.push_back(R);
2314 }
2315
2316 return Pieces;
2317}
2318}
2319
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002320//===----------------------------------------------------------------------===//
2321// Misc. API hooks.
2322//===----------------------------------------------------------------------===//
2323
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002324static llvm::sys::Mutex EnableMultithreadingMutex;
2325static bool EnabledMultithreading;
2326
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002327extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002328CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2329 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002330 // Disable pretty stack trace functionality, which will otherwise be a very
2331 // poor citizen of the world and set up all sorts of signal handlers.
2332 llvm::DisablePrettyStackTrace = true;
2333
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002334 // We use crash recovery to make some of our APIs more reliable, implicitly
2335 // enable it.
2336 llvm::CrashRecoveryContext::Enable();
2337
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002338 // Enable support for multithreading in LLVM.
2339 {
2340 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2341 if (!EnabledMultithreading) {
2342 llvm::llvm_start_multithreaded();
2343 EnabledMultithreading = true;
2344 }
2345 }
2346
Douglas Gregora030b7c2010-01-22 20:35:53 +00002347 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002348 if (excludeDeclarationsFromPCH)
2349 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002350 if (displayDiagnostics)
2351 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002352 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002353}
2354
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002355void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002356 if (CIdx)
2357 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002358}
2359
Ted Kremenekd2427dd2011-03-18 23:05:39 +00002360void clang_toggleCrashRecovery(unsigned isEnabled) {
2361 if (isEnabled)
2362 llvm::CrashRecoveryContext::Enable();
2363 else
2364 llvm::CrashRecoveryContext::Disable();
2365}
2366
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002367CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002368 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002369 if (!CIdx)
2370 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002371
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002372 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002373 FileSystemOptions FileSystemOpts;
2374 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002375
David Blaikied6471f72011-09-25 23:23:43 +00002376 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002377 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002378 CXXIdx->getOnlyLocalDecls(),
2379 0, 0, true);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002380 return MakeCXTranslationUnit(TU);
Steve Naroff600866c2009-08-27 19:51:58 +00002381}
2382
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002383unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002384 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregorb5af8432011-08-25 22:54:01 +00002385 CXTranslationUnit_CacheCompletionResults;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002386}
2387
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002388CXTranslationUnit
2389clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2390 const char *source_filename,
2391 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002392 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002393 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002394 struct CXUnsavedFile *unsaved_files) {
Douglas Gregordca8ee82011-05-06 16:33:08 +00002395 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord |
Chandler Carruthba7537f2011-07-14 09:02:10 +00002396 CXTranslationUnit_NestedMacroExpansions;
Douglas Gregor5a430212010-07-21 18:52:53 +00002397 return clang_parseTranslationUnit(CIdx, source_filename,
2398 command_line_args, num_command_line_args,
2399 unsaved_files, num_unsaved_files,
Douglas Gregordca8ee82011-05-06 16:33:08 +00002400 Options);
Douglas Gregor5a430212010-07-21 18:52:53 +00002401}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002402
2403struct ParseTranslationUnitInfo {
2404 CXIndex CIdx;
2405 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002406 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002407 int num_command_line_args;
2408 struct CXUnsavedFile *unsaved_files;
2409 unsigned num_unsaved_files;
2410 unsigned options;
2411 CXTranslationUnit result;
2412};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002413static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002414 ParseTranslationUnitInfo *PTUI =
2415 static_cast<ParseTranslationUnitInfo*>(UserData);
2416 CXIndex CIdx = PTUI->CIdx;
2417 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002418 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002419 int num_command_line_args = PTUI->num_command_line_args;
2420 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2421 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2422 unsigned options = PTUI->options;
2423 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002424
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002425 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002426 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002427
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002428 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2429
Douglas Gregor44c181a2010-07-23 00:33:23 +00002430 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregor467dc882011-08-25 22:30:56 +00002431 // FIXME: Add a flag for modules.
2432 TranslationUnitKind TUKind
2433 = (options & CXTranslationUnit_Incomplete)? TU_Prefix : TU_Complete;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002434 bool CacheCodeCompetionResults
2435 = options & CXTranslationUnit_CacheCompletionResults;
2436
Douglas Gregor5352ac02010-01-28 00:27:43 +00002437 // Configure the diagnostics.
2438 DiagnosticOptions DiagOpts;
David Blaikied6471f72011-09-25 23:23:43 +00002439 llvm::IntrusiveRefCntPtr<DiagnosticsEngine>
Ted Kremenek25a11e12011-03-22 01:15:24 +00002440 Diags(CompilerInstance::createDiagnostics(DiagOpts, num_command_line_args,
2441 command_line_args));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002442
Ted Kremenek25a11e12011-03-22 01:15:24 +00002443 // Recover resources if we crash before exiting this function.
David Blaikied6471f72011-09-25 23:23:43 +00002444 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
2445 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00002446 DiagCleanup(Diags.getPtr());
2447
2448 llvm::OwningPtr<std::vector<ASTUnit::RemappedFile> >
2449 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2450
2451 // Recover resources if we crash before exiting this function.
2452 llvm::CrashRecoveryContextCleanupRegistrar<
2453 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2454
Douglas Gregor4db64a42010-01-23 00:14:00 +00002455 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002456 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002457 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002458 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002459 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2460 Buffer));
Douglas Gregor4db64a42010-01-23 00:14:00 +00002461 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002462
Ted Kremenek25a11e12011-03-22 01:15:24 +00002463 llvm::OwningPtr<std::vector<const char *> >
2464 Args(new std::vector<const char*>());
2465
2466 // Recover resources if we crash before exiting this method.
2467 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
2468 ArgsCleanup(Args.get());
2469
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002470 // Since the Clang C library is primarily used by batch tools dealing with
2471 // (often very broken) source code, where spell-checking can have a
2472 // significant negative impact on performance (particularly when
2473 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002474 // Only do this if we haven't found a spell-checking-related argument.
2475 bool FoundSpellCheckingArgument = false;
2476 for (int I = 0; I != num_command_line_args; ++I) {
2477 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2478 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2479 FoundSpellCheckingArgument = true;
2480 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002481 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002482 }
2483 if (!FoundSpellCheckingArgument)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002484 Args->push_back("-fno-spell-checking");
Douglas Gregorb10daed2010-10-11 16:52:23 +00002485
Ted Kremenek25a11e12011-03-22 01:15:24 +00002486 Args->insert(Args->end(), command_line_args,
2487 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002488
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002489 // The 'source_filename' argument is optional. If the caller does not
2490 // specify it then it is assumed that the source file is specified
2491 // in the actual argument list.
2492 // Put the source file after command_line_args otherwise if '-x' flag is
2493 // present it will be unused.
2494 if (source_filename)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002495 Args->push_back(source_filename);
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002496
Douglas Gregor44c181a2010-07-23 00:33:23 +00002497 // Do we need the detailed preprocessing record?
Chandler Carruthba7537f2011-07-14 09:02:10 +00002498 bool NestedMacroExpansions = false;
Douglas Gregor44c181a2010-07-23 00:33:23 +00002499 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Ted Kremenek25a11e12011-03-22 01:15:24 +00002500 Args->push_back("-Xclang");
2501 Args->push_back("-detailed-preprocessing-record");
Chandler Carruthba7537f2011-07-14 09:02:10 +00002502 NestedMacroExpansions
2503 = (options & CXTranslationUnit_NestedMacroExpansions);
Douglas Gregor44c181a2010-07-23 00:33:23 +00002504 }
2505
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002506 unsigned NumErrors = Diags->getClient()->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002507 llvm::OwningPtr<ASTUnit> Unit(
Ted Kremenek4ee99262011-03-22 20:16:19 +00002508 ASTUnit::LoadFromCommandLine(Args->size() ? &(*Args)[0] : 0
2509 /* vector::data() not portable */,
2510 Args->size() ? (&(*Args)[0] + Args->size()) :0,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002511 Diags,
2512 CXXIdx->getClangResourcesPath(),
2513 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002514 /*CaptureDiagnostics=*/true,
Ted Kremenek4ee99262011-03-22 20:16:19 +00002515 RemappedFiles->size() ? &(*RemappedFiles)[0]:0,
Ted Kremenek25a11e12011-03-22 01:15:24 +00002516 RemappedFiles->size(),
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00002517 /*RemappedFilesKeepOriginalName=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002518 PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00002519 TUKind,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002520 CacheCodeCompetionResults,
Chandler Carruthba7537f2011-07-14 09:02:10 +00002521 NestedMacroExpansions));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002522
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002523 if (NumErrors != Diags->getClient()->getNumErrors()) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002524 // Make sure to check that 'Unit' is non-NULL.
2525 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2526 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2527 DEnd = Unit->stored_diag_end();
2528 D != DEnd; ++D) {
2529 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2530 CXString Msg = clang_formatDiagnostic(&Diag,
2531 clang_defaultDiagnosticDisplayOptions());
2532 fprintf(stderr, "%s\n", clang_getCString(Msg));
2533 clang_disposeString(Msg);
2534 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002535#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002536 // On Windows, force a flush, since there may be multiple copies of
2537 // stderr and stdout in the file system, all with different buffers
2538 // but writing to the same device.
2539 fflush(stderr);
2540#endif
2541 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002542 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002543
Ted Kremeneka60ed472010-11-16 08:15:36 +00002544 PTUI->result = MakeCXTranslationUnit(Unit.take());
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002545}
2546CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2547 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002548 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002549 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002550 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002551 unsigned num_unsaved_files,
2552 unsigned options) {
2553 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002554 num_command_line_args, unsaved_files,
2555 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002556 llvm::CrashRecoveryContext CRC;
2557
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002558 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002559 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2560 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2561 fprintf(stderr, " 'command_line_args' : [");
2562 for (int i = 0; i != num_command_line_args; ++i) {
2563 if (i)
2564 fprintf(stderr, ", ");
2565 fprintf(stderr, "'%s'", command_line_args[i]);
2566 }
2567 fprintf(stderr, "],\n");
2568 fprintf(stderr, " 'unsaved_files' : [");
2569 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2570 if (i)
2571 fprintf(stderr, ", ");
2572 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2573 unsaved_files[i].Length);
2574 }
2575 fprintf(stderr, "],\n");
2576 fprintf(stderr, " 'options' : %d,\n", options);
2577 fprintf(stderr, "}\n");
2578
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002579 return 0;
Douglas Gregor6df78732011-05-05 20:27:22 +00002580 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
2581 PrintLibclangResourceUsage(PTUI.result);
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002582 }
Douglas Gregor6df78732011-05-05 20:27:22 +00002583
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002584 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002585}
2586
Douglas Gregor19998442010-08-13 15:35:05 +00002587unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2588 return CXSaveTranslationUnit_None;
2589}
2590
2591int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2592 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002593 if (!TU)
Douglas Gregor39c411f2011-07-06 16:43:36 +00002594 return CXSaveError_InvalidTU;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002595
Douglas Gregor39c411f2011-07-06 16:43:36 +00002596 CXSaveError result = static_cast<ASTUnit *>(TU->TUData)->Save(FileName);
Douglas Gregor6df78732011-05-05 20:27:22 +00002597 if (getenv("LIBCLANG_RESOURCE_USAGE"))
2598 PrintLibclangResourceUsage(TU);
2599 return result;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002600}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002601
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002602void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002603 if (CTUnit) {
2604 // If the translation unit has been marked as unsafe to free, just discard
2605 // it.
Ted Kremeneka60ed472010-11-16 08:15:36 +00002606 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002607 return;
2608
Ted Kremeneka60ed472010-11-16 08:15:36 +00002609 delete static_cast<ASTUnit *>(CTUnit->TUData);
2610 disposeCXStringPool(CTUnit->StringPool);
Ted Kremenek15322172011-11-10 08:43:12 +00002611 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002612 delete CTUnit;
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002613 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002614}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002615
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002616unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2617 return CXReparse_None;
2618}
2619
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002620struct ReparseTranslationUnitInfo {
2621 CXTranslationUnit TU;
2622 unsigned num_unsaved_files;
2623 struct CXUnsavedFile *unsaved_files;
2624 unsigned options;
2625 int result;
2626};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002627
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002628static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002629 ReparseTranslationUnitInfo *RTUI =
2630 static_cast<ReparseTranslationUnitInfo*>(UserData);
2631 CXTranslationUnit TU = RTUI->TU;
Ted Kremenek15322172011-11-10 08:43:12 +00002632
2633 // Reset the associated diagnostics.
2634 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
2635 TU->Diagnostics = 0;
2636
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002637 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2638 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2639 unsigned options = RTUI->options;
2640 (void) options;
2641 RTUI->result = 1;
2642
Douglas Gregorabc563f2010-07-19 21:46:24 +00002643 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002644 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002645
Ted Kremeneka60ed472010-11-16 08:15:36 +00002646 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor593b0c12010-09-23 18:47:53 +00002647 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002648
Ted Kremenek25a11e12011-03-22 01:15:24 +00002649 llvm::OwningPtr<std::vector<ASTUnit::RemappedFile> >
2650 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2651
2652 // Recover resources if we crash before exiting this function.
2653 llvm::CrashRecoveryContextCleanupRegistrar<
2654 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2655
Douglas Gregorabc563f2010-07-19 21:46:24 +00002656 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002657 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002658 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002659 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002660 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2661 Buffer));
Douglas Gregorabc563f2010-07-19 21:46:24 +00002662 }
2663
Ted Kremenek4ee99262011-03-22 20:16:19 +00002664 if (!CXXUnit->Reparse(RemappedFiles->size() ? &(*RemappedFiles)[0] : 0,
2665 RemappedFiles->size()))
Douglas Gregor593b0c12010-09-23 18:47:53 +00002666 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002667}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002668
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002669int clang_reparseTranslationUnit(CXTranslationUnit TU,
2670 unsigned num_unsaved_files,
2671 struct CXUnsavedFile *unsaved_files,
2672 unsigned options) {
2673 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2674 options, 0 };
Argyrios Kyrtzidis8c4b47e2011-10-28 22:54:33 +00002675
Argyrios Kyrtzidise7de9b42011-10-29 19:32:39 +00002676 if (getenv("LIBCLANG_NOTHREADS")) {
Argyrios Kyrtzidis8c4b47e2011-10-28 22:54:33 +00002677 clang_reparseTranslationUnit_Impl(&RTUI);
2678 return RTUI.result;
2679 }
2680
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002681 llvm::CrashRecoveryContext CRC;
2682
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002683 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002684 fprintf(stderr, "libclang: crash detected during reparsing\n");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002685 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002686 return 1;
Douglas Gregor6df78732011-05-05 20:27:22 +00002687 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
2688 PrintLibclangResourceUsage(TU);
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002689
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002690 return RTUI.result;
2691}
2692
Douglas Gregordf95a132010-08-09 20:45:32 +00002693
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002694CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002695 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002696 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002697
Ted Kremeneka60ed472010-11-16 08:15:36 +00002698 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002699 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002700}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002701
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002702CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002703 CXCursor Result = { CXCursor_TranslationUnit, 0, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002704 return Result;
2705}
2706
Ted Kremenekfb480492010-01-13 21:46:36 +00002707} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002708
Ted Kremenekfb480492010-01-13 21:46:36 +00002709//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002710// CXFile Operations.
2711//===----------------------------------------------------------------------===//
2712
2713extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002714CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002715 if (!SFile)
Ted Kremeneka60ed472010-11-16 08:15:36 +00002716 return createCXString((const char*)NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002717
Steve Naroff88145032009-10-27 14:35:18 +00002718 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002719 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002720}
2721
2722time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002723 if (!SFile)
2724 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002725
Steve Naroff88145032009-10-27 14:35:18 +00002726 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2727 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002728}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002729
Douglas Gregorb9790342010-01-22 21:44:22 +00002730CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2731 if (!tu)
2732 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002733
Ted Kremeneka60ed472010-11-16 08:15:36 +00002734 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002735
Douglas Gregorb9790342010-01-22 21:44:22 +00002736 FileManager &FMgr = CXXUnit->getFileManager();
Chris Lattner39b49bc2010-11-23 08:35:12 +00002737 return const_cast<FileEntry *>(FMgr.getFile(file_name));
Douglas Gregorb9790342010-01-22 21:44:22 +00002738}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002739
Douglas Gregordd3e5542011-05-04 00:14:37 +00002740unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit tu, CXFile file) {
2741 if (!tu || !file)
2742 return 0;
2743
2744 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
2745 FileEntry *FEnt = static_cast<FileEntry *>(file);
2746 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
2747 .isFileMultipleIncludeGuarded(FEnt);
2748}
2749
Ted Kremenekfb480492010-01-13 21:46:36 +00002750} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002751
Ted Kremenekfb480492010-01-13 21:46:36 +00002752//===----------------------------------------------------------------------===//
2753// CXCursor Operations.
2754//===----------------------------------------------------------------------===//
2755
Ted Kremenekfb480492010-01-13 21:46:36 +00002756static Decl *getDeclFromExpr(Stmt *E) {
Argyrios Kyrtzidisc2954612011-09-12 22:17:26 +00002757 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Douglas Gregordb1314e2010-10-01 21:11:22 +00002758 return getDeclFromExpr(CE->getSubExpr());
2759
Ted Kremenekfb480492010-01-13 21:46:36 +00002760 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2761 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002762 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2763 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002764 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2765 return ME->getMemberDecl();
2766 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2767 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002768 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
John McCall12f78a62010-12-02 01:19:52 +00002769 return PRE->isExplicitProperty() ? PRE->getExplicitProperty() : 0;
John McCall4b9c2d22011-11-06 09:01:30 +00002770 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
2771 return getDeclFromExpr(POE->getSyntacticForm());
2772 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
2773 if (Expr *Src = OVE->getSourceExpr())
2774 return getDeclFromExpr(Src);
Douglas Gregordb1314e2010-10-01 21:11:22 +00002775
Ted Kremenekfb480492010-01-13 21:46:36 +00002776 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2777 return getDeclFromExpr(CE->getCallee());
Chris Lattner5f9e2722011-07-23 10:55:15 +00002778 if (CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Douglas Gregor93798e22010-11-05 21:11:19 +00002779 if (!CE->isElidable())
2780 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002781 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2782 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002783
Douglas Gregordb1314e2010-10-01 21:11:22 +00002784 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2785 return PE->getProtocol();
Douglas Gregorc7793c72011-01-15 01:15:58 +00002786 if (SubstNonTypeTemplateParmPackExpr *NTTP
2787 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
2788 return NTTP->getParameterPack();
Douglas Gregor94d96292011-01-19 20:34:17 +00002789 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2790 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
2791 isa<ParmVarDecl>(SizeOfPack->getPack()))
2792 return SizeOfPack->getPack();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002793
Ted Kremenekfb480492010-01-13 21:46:36 +00002794 return 0;
2795}
2796
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002797static SourceLocation getLocationFromExpr(Expr *E) {
Argyrios Kyrtzidisc2954612011-09-12 22:17:26 +00002798 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
2799 return getLocationFromExpr(CE->getSubExpr());
2800
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002801 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2802 return /*FIXME:*/Msg->getLeftLoc();
2803 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2804 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002805 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2806 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002807 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2808 return Member->getMemberLoc();
2809 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2810 return Ivar->getLocation();
Douglas Gregor94d96292011-01-19 20:34:17 +00002811 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2812 return SizeOfPack->getPackLoc();
2813
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002814 return E->getLocStart();
2815}
2816
Ted Kremenekfb480492010-01-13 21:46:36 +00002817extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002818
2819unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002820 CXCursorVisitor visitor,
2821 CXClientData client_data) {
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00002822 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
2823 /*VisitPreprocessorLast=*/false);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002824 return CursorVis.VisitChildren(parent);
2825}
2826
David Chisnall3387c652010-11-03 14:12:26 +00002827#ifndef __has_feature
2828#define __has_feature(x) 0
2829#endif
2830#if __has_feature(blocks)
2831typedef enum CXChildVisitResult
2832 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2833
2834static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2835 CXClientData client_data) {
2836 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2837 return block(cursor, parent);
2838}
2839#else
2840// If we are compiled with a compiler that doesn't have native blocks support,
2841// define and call the block manually, so the
2842typedef struct _CXChildVisitResult
2843{
2844 void *isa;
2845 int flags;
2846 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002847 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2848 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00002849} *CXCursorVisitorBlock;
2850
2851static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2852 CXClientData client_data) {
2853 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2854 return block->invoke(block, cursor, parent);
2855}
2856#endif
2857
2858
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002859unsigned clang_visitChildrenWithBlock(CXCursor parent,
2860 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00002861 return clang_visitChildren(parent, visitWithBlock, block);
2862}
2863
Douglas Gregor78205d42010-01-20 21:45:58 +00002864static CXString getDeclSpelling(Decl *D) {
2865 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
Douglas Gregore3c60a72010-11-17 00:13:31 +00002866 if (!ND) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002867 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00002868 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
2869 return createCXString(Property->getIdentifier()->getName());
2870
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002871 return createCXString("");
Douglas Gregore3c60a72010-11-17 00:13:31 +00002872 }
2873
Douglas Gregor78205d42010-01-20 21:45:58 +00002874 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002875 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002876
Douglas Gregor78205d42010-01-20 21:45:58 +00002877 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2878 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2879 // and returns different names. NamedDecl returns the class name and
2880 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002881 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002882
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002883 if (isa<UsingDirectiveDecl>(D))
2884 return createCXString("");
2885
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002886 llvm::SmallString<1024> S;
2887 llvm::raw_svector_ostream os(S);
2888 ND->printName(os);
2889
2890 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002891}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002892
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002893CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002894 if (clang_isTranslationUnit(C.kind))
Ted Kremeneka60ed472010-11-16 08:15:36 +00002895 return clang_getTranslationUnitSpelling(
2896 static_cast<CXTranslationUnit>(C.data[2]));
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002897
Steve Narofff334b4e2009-09-02 18:26:48 +00002898 if (clang_isReference(C.kind)) {
2899 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002900 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002901 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002902 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002903 }
2904 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002905 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002906 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002907 }
2908 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002909 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002910 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002911 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002912 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002913 case CXCursor_CXXBaseSpecifier: {
2914 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2915 return createCXString(B->getType().getAsString());
2916 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002917 case CXCursor_TypeRef: {
2918 TypeDecl *Type = getCursorTypeRef(C).first;
2919 assert(Type && "Missing type decl");
2920
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002921 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2922 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002923 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002924 case CXCursor_TemplateRef: {
2925 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002926 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002927
2928 return createCXString(Template->getNameAsString());
2929 }
Douglas Gregor69319002010-08-31 23:48:11 +00002930
2931 case CXCursor_NamespaceRef: {
2932 NamedDecl *NS = getCursorNamespaceRef(C).first;
2933 assert(NS && "Missing namespace decl");
2934
2935 return createCXString(NS->getNameAsString());
2936 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002937
Douglas Gregora67e03f2010-09-09 21:42:20 +00002938 case CXCursor_MemberRef: {
2939 FieldDecl *Field = getCursorMemberRef(C).first;
2940 assert(Field && "Missing member decl");
2941
2942 return createCXString(Field->getNameAsString());
2943 }
2944
Douglas Gregor36897b02010-09-10 00:22:18 +00002945 case CXCursor_LabelRef: {
2946 LabelStmt *Label = getCursorLabelRef(C).first;
2947 assert(Label && "Missing label");
2948
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002949 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00002950 }
2951
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002952 case CXCursor_OverloadedDeclRef: {
2953 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2954 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2955 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2956 return createCXString(ND->getNameAsString());
2957 return createCXString("");
2958 }
2959 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2960 return createCXString(E->getName().getAsString());
2961 OverloadedTemplateStorage *Ovl
2962 = Storage.get<OverloadedTemplateStorage*>();
2963 if (Ovl->size() == 0)
2964 return createCXString("");
2965 return createCXString((*Ovl->begin())->getNameAsString());
2966 }
2967
Daniel Dunbaracca7252009-11-30 20:42:49 +00002968 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002969 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002970 }
2971 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002972
2973 if (clang_isExpression(C.kind)) {
2974 Decl *D = getDeclFromExpr(getCursorExpr(C));
2975 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002976 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002977 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002978 }
2979
Douglas Gregor36897b02010-09-10 00:22:18 +00002980 if (clang_isStatement(C.kind)) {
2981 Stmt *S = getCursorStmt(C);
2982 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002983 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00002984
2985 return createCXString("");
2986 }
2987
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00002988 if (C.kind == CXCursor_MacroExpansion)
Chandler Carruth9e5bb852011-07-14 08:20:46 +00002989 return createCXString(getCursorMacroExpansion(C)->getName()
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002990 ->getNameStart());
2991
Douglas Gregor572feb22010-03-18 18:04:21 +00002992 if (C.kind == CXCursor_MacroDefinition)
2993 return createCXString(getCursorMacroDefinition(C)->getName()
2994 ->getNameStart());
2995
Douglas Gregorecdcb882010-10-20 22:00:55 +00002996 if (C.kind == CXCursor_InclusionDirective)
2997 return createCXString(getCursorInclusionDirective(C)->getFileName());
2998
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002999 if (clang_isDeclaration(C.kind))
3000 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00003001
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00003002 if (C.kind == CXCursor_AnnotateAttr) {
3003 AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
3004 return createCXString(AA->getAnnotation());
3005 }
3006
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003007 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00003008}
3009
Douglas Gregor358559d2010-10-02 22:49:11 +00003010CXString clang_getCursorDisplayName(CXCursor C) {
3011 if (!clang_isDeclaration(C.kind))
3012 return clang_getCursorSpelling(C);
3013
3014 Decl *D = getCursorDecl(C);
3015 if (!D)
3016 return createCXString("");
3017
Douglas Gregor30c42402011-09-27 22:38:19 +00003018 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
Douglas Gregor358559d2010-10-02 22:49:11 +00003019 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
3020 D = FunTmpl->getTemplatedDecl();
3021
3022 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
3023 llvm::SmallString<64> Str;
3024 llvm::raw_svector_ostream OS(Str);
3025 OS << Function->getNameAsString();
3026 if (Function->getPrimaryTemplate())
3027 OS << "<>";
3028 OS << "(";
3029 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
3030 if (I)
3031 OS << ", ";
3032 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
3033 }
3034
3035 if (Function->isVariadic()) {
3036 if (Function->getNumParams())
3037 OS << ", ";
3038 OS << "...";
3039 }
3040 OS << ")";
3041 return createCXString(OS.str());
3042 }
3043
3044 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
3045 llvm::SmallString<64> Str;
3046 llvm::raw_svector_ostream OS(Str);
3047 OS << ClassTemplate->getNameAsString();
3048 OS << "<";
3049 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
3050 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3051 if (I)
3052 OS << ", ";
3053
3054 NamedDecl *Param = Params->getParam(I);
3055 if (Param->getIdentifier()) {
3056 OS << Param->getIdentifier()->getName();
3057 continue;
3058 }
3059
3060 // There is no parameter name, which makes this tricky. Try to come up
3061 // with something useful that isn't too long.
3062 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3063 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
3064 else if (NonTypeTemplateParmDecl *NTTP
3065 = dyn_cast<NonTypeTemplateParmDecl>(Param))
3066 OS << NTTP->getType().getAsString(Policy);
3067 else
3068 OS << "template<...> class";
3069 }
3070
3071 OS << ">";
3072 return createCXString(OS.str());
3073 }
3074
3075 if (ClassTemplateSpecializationDecl *ClassSpec
3076 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
3077 // If the type was explicitly written, use that.
3078 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
3079 return createCXString(TSInfo->getType().getAsString(Policy));
3080
3081 llvm::SmallString<64> Str;
3082 llvm::raw_svector_ostream OS(Str);
3083 OS << ClassSpec->getNameAsString();
3084 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00003085 ClassSpec->getTemplateArgs().data(),
3086 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00003087 Policy);
3088 return createCXString(OS.str());
3089 }
3090
3091 return clang_getCursorSpelling(C);
3092}
3093
Ted Kremeneke68fff62010-02-17 00:41:32 +00003094CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00003095 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00003096 case CXCursor_FunctionDecl:
3097 return createCXString("FunctionDecl");
3098 case CXCursor_TypedefDecl:
3099 return createCXString("TypedefDecl");
3100 case CXCursor_EnumDecl:
3101 return createCXString("EnumDecl");
3102 case CXCursor_EnumConstantDecl:
3103 return createCXString("EnumConstantDecl");
3104 case CXCursor_StructDecl:
3105 return createCXString("StructDecl");
3106 case CXCursor_UnionDecl:
3107 return createCXString("UnionDecl");
3108 case CXCursor_ClassDecl:
3109 return createCXString("ClassDecl");
3110 case CXCursor_FieldDecl:
3111 return createCXString("FieldDecl");
3112 case CXCursor_VarDecl:
3113 return createCXString("VarDecl");
3114 case CXCursor_ParmDecl:
3115 return createCXString("ParmDecl");
3116 case CXCursor_ObjCInterfaceDecl:
3117 return createCXString("ObjCInterfaceDecl");
3118 case CXCursor_ObjCCategoryDecl:
3119 return createCXString("ObjCCategoryDecl");
3120 case CXCursor_ObjCProtocolDecl:
3121 return createCXString("ObjCProtocolDecl");
3122 case CXCursor_ObjCPropertyDecl:
3123 return createCXString("ObjCPropertyDecl");
3124 case CXCursor_ObjCIvarDecl:
3125 return createCXString("ObjCIvarDecl");
3126 case CXCursor_ObjCInstanceMethodDecl:
3127 return createCXString("ObjCInstanceMethodDecl");
3128 case CXCursor_ObjCClassMethodDecl:
3129 return createCXString("ObjCClassMethodDecl");
3130 case CXCursor_ObjCImplementationDecl:
3131 return createCXString("ObjCImplementationDecl");
3132 case CXCursor_ObjCCategoryImplDecl:
3133 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00003134 case CXCursor_CXXMethod:
3135 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003136 case CXCursor_UnexposedDecl:
3137 return createCXString("UnexposedDecl");
3138 case CXCursor_ObjCSuperClassRef:
3139 return createCXString("ObjCSuperClassRef");
3140 case CXCursor_ObjCProtocolRef:
3141 return createCXString("ObjCProtocolRef");
3142 case CXCursor_ObjCClassRef:
3143 return createCXString("ObjCClassRef");
3144 case CXCursor_TypeRef:
3145 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003146 case CXCursor_TemplateRef:
3147 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00003148 case CXCursor_NamespaceRef:
3149 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00003150 case CXCursor_MemberRef:
3151 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00003152 case CXCursor_LabelRef:
3153 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003154 case CXCursor_OverloadedDeclRef:
3155 return createCXString("OverloadedDeclRef");
Douglas Gregor42b29842011-10-05 19:00:14 +00003156 case CXCursor_IntegerLiteral:
3157 return createCXString("IntegerLiteral");
3158 case CXCursor_FloatingLiteral:
3159 return createCXString("FloatingLiteral");
3160 case CXCursor_ImaginaryLiteral:
3161 return createCXString("ImaginaryLiteral");
3162 case CXCursor_StringLiteral:
3163 return createCXString("StringLiteral");
3164 case CXCursor_CharacterLiteral:
3165 return createCXString("CharacterLiteral");
3166 case CXCursor_ParenExpr:
3167 return createCXString("ParenExpr");
3168 case CXCursor_UnaryOperator:
3169 return createCXString("UnaryOperator");
3170 case CXCursor_ArraySubscriptExpr:
3171 return createCXString("ArraySubscriptExpr");
3172 case CXCursor_BinaryOperator:
3173 return createCXString("BinaryOperator");
3174 case CXCursor_CompoundAssignOperator:
3175 return createCXString("CompoundAssignOperator");
3176 case CXCursor_ConditionalOperator:
3177 return createCXString("ConditionalOperator");
3178 case CXCursor_CStyleCastExpr:
3179 return createCXString("CStyleCastExpr");
3180 case CXCursor_CompoundLiteralExpr:
3181 return createCXString("CompoundLiteralExpr");
3182 case CXCursor_InitListExpr:
3183 return createCXString("InitListExpr");
3184 case CXCursor_AddrLabelExpr:
3185 return createCXString("AddrLabelExpr");
3186 case CXCursor_StmtExpr:
3187 return createCXString("StmtExpr");
3188 case CXCursor_GenericSelectionExpr:
3189 return createCXString("GenericSelectionExpr");
3190 case CXCursor_GNUNullExpr:
3191 return createCXString("GNUNullExpr");
3192 case CXCursor_CXXStaticCastExpr:
3193 return createCXString("CXXStaticCastExpr");
3194 case CXCursor_CXXDynamicCastExpr:
3195 return createCXString("CXXDynamicCastExpr");
3196 case CXCursor_CXXReinterpretCastExpr:
3197 return createCXString("CXXReinterpretCastExpr");
3198 case CXCursor_CXXConstCastExpr:
3199 return createCXString("CXXConstCastExpr");
3200 case CXCursor_CXXFunctionalCastExpr:
3201 return createCXString("CXXFunctionalCastExpr");
3202 case CXCursor_CXXTypeidExpr:
3203 return createCXString("CXXTypeidExpr");
3204 case CXCursor_CXXBoolLiteralExpr:
3205 return createCXString("CXXBoolLiteralExpr");
3206 case CXCursor_CXXNullPtrLiteralExpr:
3207 return createCXString("CXXNullPtrLiteralExpr");
3208 case CXCursor_CXXThisExpr:
3209 return createCXString("CXXThisExpr");
3210 case CXCursor_CXXThrowExpr:
3211 return createCXString("CXXThrowExpr");
3212 case CXCursor_CXXNewExpr:
3213 return createCXString("CXXNewExpr");
3214 case CXCursor_CXXDeleteExpr:
3215 return createCXString("CXXDeleteExpr");
3216 case CXCursor_UnaryExpr:
3217 return createCXString("UnaryExpr");
3218 case CXCursor_ObjCStringLiteral:
3219 return createCXString("ObjCStringLiteral");
3220 case CXCursor_ObjCEncodeExpr:
3221 return createCXString("ObjCEncodeExpr");
3222 case CXCursor_ObjCSelectorExpr:
3223 return createCXString("ObjCSelectorExpr");
3224 case CXCursor_ObjCProtocolExpr:
3225 return createCXString("ObjCProtocolExpr");
3226 case CXCursor_ObjCBridgedCastExpr:
3227 return createCXString("ObjCBridgedCastExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00003228 case CXCursor_BlockExpr:
3229 return createCXString("BlockExpr");
Douglas Gregor42b29842011-10-05 19:00:14 +00003230 case CXCursor_PackExpansionExpr:
3231 return createCXString("PackExpansionExpr");
3232 case CXCursor_SizeOfPackExpr:
3233 return createCXString("SizeOfPackExpr");
3234 case CXCursor_UnexposedExpr:
3235 return createCXString("UnexposedExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003236 case CXCursor_DeclRefExpr:
3237 return createCXString("DeclRefExpr");
3238 case CXCursor_MemberRefExpr:
3239 return createCXString("MemberRefExpr");
3240 case CXCursor_CallExpr:
3241 return createCXString("CallExpr");
3242 case CXCursor_ObjCMessageExpr:
3243 return createCXString("ObjCMessageExpr");
3244 case CXCursor_UnexposedStmt:
3245 return createCXString("UnexposedStmt");
Douglas Gregor42b29842011-10-05 19:00:14 +00003246 case CXCursor_DeclStmt:
3247 return createCXString("DeclStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00003248 case CXCursor_LabelStmt:
3249 return createCXString("LabelStmt");
Douglas Gregor42b29842011-10-05 19:00:14 +00003250 case CXCursor_CompoundStmt:
3251 return createCXString("CompoundStmt");
3252 case CXCursor_CaseStmt:
3253 return createCXString("CaseStmt");
3254 case CXCursor_DefaultStmt:
3255 return createCXString("DefaultStmt");
3256 case CXCursor_IfStmt:
3257 return createCXString("IfStmt");
3258 case CXCursor_SwitchStmt:
3259 return createCXString("SwitchStmt");
3260 case CXCursor_WhileStmt:
3261 return createCXString("WhileStmt");
3262 case CXCursor_DoStmt:
3263 return createCXString("DoStmt");
3264 case CXCursor_ForStmt:
3265 return createCXString("ForStmt");
3266 case CXCursor_GotoStmt:
3267 return createCXString("GotoStmt");
3268 case CXCursor_IndirectGotoStmt:
3269 return createCXString("IndirectGotoStmt");
3270 case CXCursor_ContinueStmt:
3271 return createCXString("ContinueStmt");
3272 case CXCursor_BreakStmt:
3273 return createCXString("BreakStmt");
3274 case CXCursor_ReturnStmt:
3275 return createCXString("ReturnStmt");
3276 case CXCursor_AsmStmt:
3277 return createCXString("AsmStmt");
3278 case CXCursor_ObjCAtTryStmt:
3279 return createCXString("ObjCAtTryStmt");
3280 case CXCursor_ObjCAtCatchStmt:
3281 return createCXString("ObjCAtCatchStmt");
3282 case CXCursor_ObjCAtFinallyStmt:
3283 return createCXString("ObjCAtFinallyStmt");
3284 case CXCursor_ObjCAtThrowStmt:
3285 return createCXString("ObjCAtThrowStmt");
3286 case CXCursor_ObjCAtSynchronizedStmt:
3287 return createCXString("ObjCAtSynchronizedStmt");
3288 case CXCursor_ObjCAutoreleasePoolStmt:
3289 return createCXString("ObjCAutoreleasePoolStmt");
3290 case CXCursor_ObjCForCollectionStmt:
3291 return createCXString("ObjCForCollectionStmt");
3292 case CXCursor_CXXCatchStmt:
3293 return createCXString("CXXCatchStmt");
3294 case CXCursor_CXXTryStmt:
3295 return createCXString("CXXTryStmt");
3296 case CXCursor_CXXForRangeStmt:
3297 return createCXString("CXXForRangeStmt");
3298 case CXCursor_SEHTryStmt:
3299 return createCXString("SEHTryStmt");
3300 case CXCursor_SEHExceptStmt:
3301 return createCXString("SEHExceptStmt");
3302 case CXCursor_SEHFinallyStmt:
3303 return createCXString("SEHFinallyStmt");
3304 case CXCursor_NullStmt:
3305 return createCXString("NullStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003306 case CXCursor_InvalidFile:
3307 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00003308 case CXCursor_InvalidCode:
3309 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003310 case CXCursor_NoDeclFound:
3311 return createCXString("NoDeclFound");
3312 case CXCursor_NotImplemented:
3313 return createCXString("NotImplemented");
3314 case CXCursor_TranslationUnit:
3315 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00003316 case CXCursor_UnexposedAttr:
3317 return createCXString("UnexposedAttr");
3318 case CXCursor_IBActionAttr:
3319 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003320 case CXCursor_IBOutletAttr:
3321 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003322 case CXCursor_IBOutletCollectionAttr:
3323 return createCXString("attribute(iboutletcollection)");
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00003324 case CXCursor_CXXFinalAttr:
3325 return createCXString("attribute(final)");
3326 case CXCursor_CXXOverrideAttr:
3327 return createCXString("attribute(override)");
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00003328 case CXCursor_AnnotateAttr:
3329 return createCXString("attribute(annotate)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003330 case CXCursor_PreprocessingDirective:
3331 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003332 case CXCursor_MacroDefinition:
3333 return createCXString("macro definition");
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003334 case CXCursor_MacroExpansion:
3335 return createCXString("macro expansion");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003336 case CXCursor_InclusionDirective:
3337 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003338 case CXCursor_Namespace:
3339 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003340 case CXCursor_LinkageSpec:
3341 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003342 case CXCursor_CXXBaseSpecifier:
3343 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003344 case CXCursor_Constructor:
3345 return createCXString("CXXConstructor");
3346 case CXCursor_Destructor:
3347 return createCXString("CXXDestructor");
3348 case CXCursor_ConversionFunction:
3349 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003350 case CXCursor_TemplateTypeParameter:
3351 return createCXString("TemplateTypeParameter");
3352 case CXCursor_NonTypeTemplateParameter:
3353 return createCXString("NonTypeTemplateParameter");
3354 case CXCursor_TemplateTemplateParameter:
3355 return createCXString("TemplateTemplateParameter");
3356 case CXCursor_FunctionTemplate:
3357 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003358 case CXCursor_ClassTemplate:
3359 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003360 case CXCursor_ClassTemplatePartialSpecialization:
3361 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003362 case CXCursor_NamespaceAlias:
3363 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003364 case CXCursor_UsingDirective:
3365 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003366 case CXCursor_UsingDeclaration:
3367 return createCXString("UsingDeclaration");
Richard Smith162e1c12011-04-15 14:24:37 +00003368 case CXCursor_TypeAliasDecl:
Douglas Gregor352697a2011-06-03 23:08:58 +00003369 return createCXString("TypeAliasDecl");
3370 case CXCursor_ObjCSynthesizeDecl:
3371 return createCXString("ObjCSynthesizeDecl");
3372 case CXCursor_ObjCDynamicDecl:
3373 return createCXString("ObjCDynamicDecl");
Argyrios Kyrtzidis2dfdb942011-09-30 17:58:23 +00003374 case CXCursor_CXXAccessSpecifier:
3375 return createCXString("CXXAccessSpecifier");
Steve Naroff89922f82009-08-31 00:59:03 +00003376 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003377
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003378 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneka60ed472010-11-16 08:15:36 +00003379 return createCXString((const char*) 0);
Steve Naroff600866c2009-08-27 19:51:58 +00003380}
Steve Naroff89922f82009-08-31 00:59:03 +00003381
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003382struct GetCursorData {
3383 SourceLocation TokenBeginLoc;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003384 bool PointsAtMacroArgExpansion;
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003385 CXCursor &BestCursor;
3386
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003387 GetCursorData(SourceManager &SM,
3388 SourceLocation tokenBegin, CXCursor &outputCursor)
3389 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
3390 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
3391 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003392};
3393
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003394static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3395 CXCursor parent,
3396 CXClientData client_data) {
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003397 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
3398 CXCursor *BestCursor = &Data->BestCursor;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003399
3400 // If we point inside a macro argument we should provide info of what the
3401 // token is so use the actual cursor, don't replace it with a macro expansion
3402 // cursor.
3403 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
3404 return CXChildVisit_Recurse;
Argyrios Kyrtzidis65ab9072011-09-26 19:05:37 +00003405
3406 if (clang_isDeclaration(cursor.kind)) {
3407 // Avoid having the implicit methods override the property decls.
3408 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(getCursorDecl(cursor)))
3409 if (MD->isImplicit())
3410 return CXChildVisit_Break;
3411 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003412
3413 if (clang_isExpression(cursor.kind) &&
3414 clang_isDeclaration(BestCursor->kind)) {
3415 Decl *D = getCursorDecl(*BestCursor);
3416
3417 // Avoid having the cursor of an expression replace the declaration cursor
3418 // when the expression source range overlaps the declaration range.
3419 // This can happen for C++ constructor expressions whose range generally
3420 // include the variable declaration, e.g.:
3421 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
3422 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
3423 D->getLocation() == Data->TokenBeginLoc)
3424 return CXChildVisit_Break;
3425 }
3426
Douglas Gregor93798e22010-11-05 21:11:19 +00003427 // If our current best cursor is the construction of a temporary object,
3428 // don't replace that cursor with a type reference, because we want
3429 // clang_getCursor() to point at the constructor.
3430 if (clang_isExpression(BestCursor->kind) &&
3431 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003432 cursor.kind == CXCursor_TypeRef) {
3433 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
3434 // as having the actual point on the type reference.
3435 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
Douglas Gregor93798e22010-11-05 21:11:19 +00003436 return CXChildVisit_Recurse;
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003437 }
Douglas Gregor93798e22010-11-05 21:11:19 +00003438
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003439 *BestCursor = cursor;
3440 return CXChildVisit_Recurse;
3441}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003442
Douglas Gregorb9790342010-01-22 21:44:22 +00003443CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3444 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003445 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003446
Ted Kremeneka60ed472010-11-16 08:15:36 +00003447 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003448 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3449
Ted Kremeneka297de22010-01-25 22:34:44 +00003450 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003451 CXCursor Result = cxcursor::getCursor(TU, SLoc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003452
Douglas Gregor40749ee2010-11-03 00:35:38 +00003453 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregor40749ee2010-11-03 00:35:38 +00003454 if (Logging) {
3455 CXFile SearchFile;
3456 unsigned SearchLine, SearchColumn;
3457 CXFile ResultFile;
3458 unsigned ResultLine, ResultColumn;
Douglas Gregor66537982010-11-17 17:14:07 +00003459 CXString SearchFileName, ResultFileName, KindSpelling, USR;
3460 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
Douglas Gregor40749ee2010-11-03 00:35:38 +00003461 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3462
Chandler Carruth20174222011-08-31 16:53:37 +00003463 clang_getExpansionLocation(Loc, &SearchFile, &SearchLine, &SearchColumn, 0);
3464 clang_getExpansionLocation(ResultLoc, &ResultFile, &ResultLine,
3465 &ResultColumn, 0);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003466 SearchFileName = clang_getFileName(SearchFile);
3467 ResultFileName = clang_getFileName(ResultFile);
3468 KindSpelling = clang_getCursorKindSpelling(Result.kind);
Douglas Gregor66537982010-11-17 17:14:07 +00003469 USR = clang_getCursorUSR(Result);
3470 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n",
Douglas Gregor40749ee2010-11-03 00:35:38 +00003471 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3472 clang_getCString(KindSpelling),
Douglas Gregor66537982010-11-17 17:14:07 +00003473 clang_getCString(ResultFileName), ResultLine, ResultColumn,
3474 clang_getCString(USR), IsDef);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003475 clang_disposeString(SearchFileName);
3476 clang_disposeString(ResultFileName);
3477 clang_disposeString(KindSpelling);
Douglas Gregor66537982010-11-17 17:14:07 +00003478 clang_disposeString(USR);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003479
3480 CXCursor Definition = clang_getCursorDefinition(Result);
3481 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
3482 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
3483 CXString DefinitionKindSpelling
3484 = clang_getCursorKindSpelling(Definition.kind);
3485 CXFile DefinitionFile;
3486 unsigned DefinitionLine, DefinitionColumn;
Chandler Carruth20174222011-08-31 16:53:37 +00003487 clang_getExpansionLocation(DefinitionLoc, &DefinitionFile,
3488 &DefinitionLine, &DefinitionColumn, 0);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003489 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
3490 fprintf(stderr, " -> %s(%s:%d:%d)\n",
3491 clang_getCString(DefinitionKindSpelling),
3492 clang_getCString(DefinitionFileName),
3493 DefinitionLine, DefinitionColumn);
3494 clang_disposeString(DefinitionFileName);
3495 clang_disposeString(DefinitionKindSpelling);
3496 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003497 }
3498
Ted Kremeneke68fff62010-02-17 00:41:32 +00003499 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003500}
3501
Ted Kremenek73885552009-11-17 19:28:59 +00003502CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003503 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003504}
3505
3506unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003507 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003508}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003509
Douglas Gregor9ce55842010-11-20 00:09:34 +00003510unsigned clang_hashCursor(CXCursor C) {
3511 unsigned Index = 0;
3512 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
3513 Index = 1;
3514
3515 return llvm::DenseMapInfo<std::pair<unsigned, void*> >::getHashValue(
3516 std::make_pair(C.kind, C.data[Index]));
3517}
3518
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003519unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003520 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3521}
3522
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003523unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003524 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3525}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003526
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003527unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003528 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3529}
3530
Douglas Gregor97b98722010-01-19 23:20:36 +00003531unsigned clang_isExpression(enum CXCursorKind K) {
3532 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3533}
3534
3535unsigned clang_isStatement(enum CXCursorKind K) {
3536 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3537}
3538
Douglas Gregor8be80e12011-07-06 03:00:34 +00003539unsigned clang_isAttribute(enum CXCursorKind K) {
3540 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
3541}
3542
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003543unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3544 return K == CXCursor_TranslationUnit;
3545}
3546
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003547unsigned clang_isPreprocessing(enum CXCursorKind K) {
3548 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3549}
3550
Ted Kremenekad6eff62010-03-08 21:17:29 +00003551unsigned clang_isUnexposed(enum CXCursorKind K) {
3552 switch (K) {
3553 case CXCursor_UnexposedDecl:
3554 case CXCursor_UnexposedExpr:
3555 case CXCursor_UnexposedStmt:
3556 case CXCursor_UnexposedAttr:
3557 return true;
3558 default:
3559 return false;
3560 }
3561}
3562
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003563CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003564 return C.kind;
3565}
3566
Douglas Gregor98258af2010-01-18 22:46:11 +00003567CXSourceLocation clang_getCursorLocation(CXCursor C) {
3568 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003569 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003570 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003571 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3572 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003573 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003574 }
3575
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003576 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003577 std::pair<ObjCProtocolDecl *, SourceLocation> P
3578 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003579 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003580 }
3581
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003582 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003583 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3584 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003585 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003586 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003587
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003588 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003589 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003590 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003591 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003592
3593 case CXCursor_TemplateRef: {
3594 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3595 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3596 }
3597
Douglas Gregor69319002010-08-31 23:48:11 +00003598 case CXCursor_NamespaceRef: {
3599 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3600 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3601 }
3602
Douglas Gregora67e03f2010-09-09 21:42:20 +00003603 case CXCursor_MemberRef: {
3604 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3605 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3606 }
3607
Ted Kremenek3064ef92010-08-27 21:34:58 +00003608 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003609 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3610 if (!BaseSpec)
3611 return clang_getNullLocation();
3612
3613 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3614 return cxloc::translateSourceLocation(getCursorContext(C),
3615 TSInfo->getTypeLoc().getBeginLoc());
3616
3617 return cxloc::translateSourceLocation(getCursorContext(C),
3618 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003619 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003620
Douglas Gregor36897b02010-09-10 00:22:18 +00003621 case CXCursor_LabelRef: {
3622 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3623 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3624 }
3625
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003626 case CXCursor_OverloadedDeclRef:
3627 return cxloc::translateSourceLocation(getCursorContext(C),
3628 getCursorOverloadedDeclRef(C).second);
3629
Douglas Gregorf46034a2010-01-18 23:41:10 +00003630 default:
3631 // FIXME: Need a way to enumerate all non-reference cases.
3632 llvm_unreachable("Missed a reference kind");
3633 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003634 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003635
3636 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003637 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003638 getLocationFromExpr(getCursorExpr(C)));
3639
Douglas Gregor36897b02010-09-10 00:22:18 +00003640 if (clang_isStatement(C.kind))
3641 return cxloc::translateSourceLocation(getCursorContext(C),
3642 getCursorStmt(C)->getLocStart());
3643
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003644 if (C.kind == CXCursor_PreprocessingDirective) {
3645 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3646 return cxloc::translateSourceLocation(getCursorContext(C), L);
3647 }
Douglas Gregor48072312010-03-18 15:23:44 +00003648
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003649 if (C.kind == CXCursor_MacroExpansion) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003650 SourceLocation L
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003651 = cxcursor::getCursorMacroExpansion(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003652 return cxloc::translateSourceLocation(getCursorContext(C), L);
3653 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003654
3655 if (C.kind == CXCursor_MacroDefinition) {
3656 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3657 return cxloc::translateSourceLocation(getCursorContext(C), L);
3658 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003659
3660 if (C.kind == CXCursor_InclusionDirective) {
3661 SourceLocation L
3662 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3663 return cxloc::translateSourceLocation(getCursorContext(C), L);
3664 }
3665
Ted Kremenek9a700d22010-05-12 06:16:13 +00003666 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003667 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003668
Douglas Gregorf46034a2010-01-18 23:41:10 +00003669 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003670 SourceLocation Loc = D->getLocation();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003671 // FIXME: Multiple variables declared in a single declaration
3672 // currently lack the information needed to correctly determine their
3673 // ranges when accounting for the type-specifier. We use context
3674 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3675 // and if so, whether it is the first decl.
3676 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3677 if (!cxcursor::isFirstInDeclGroup(C))
3678 Loc = VD->getLocation();
3679 }
3680
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003681 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003682}
Douglas Gregora7bde202010-01-19 00:34:46 +00003683
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003684} // end extern "C"
3685
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003686CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
3687 assert(TU);
3688
3689 // Guard against an invalid SourceLocation, or we may assert in one
3690 // of the following calls.
3691 if (SLoc.isInvalid())
3692 return clang_getNullCursor();
3693
3694 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
3695
3696 // Translate the given source location to make it point at the beginning of
3697 // the token under the cursor.
3698 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3699 CXXUnit->getASTContext().getLangOptions());
3700
3701 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3702 if (SLoc.isValid()) {
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003703 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003704 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
3705 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00003706 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003707 SourceLocation(SLoc));
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00003708 CursorVis.visitFileRegion();
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003709 }
3710
3711 return Result;
3712}
3713
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003714static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003715 if (clang_isReference(C.kind)) {
3716 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003717 case CXCursor_ObjCSuperClassRef:
3718 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003719
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003720 case CXCursor_ObjCProtocolRef:
3721 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003722
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003723 case CXCursor_ObjCClassRef:
3724 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003725
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003726 case CXCursor_TypeRef:
3727 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003728
3729 case CXCursor_TemplateRef:
3730 return getCursorTemplateRef(C).second;
3731
Douglas Gregor69319002010-08-31 23:48:11 +00003732 case CXCursor_NamespaceRef:
3733 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003734
3735 case CXCursor_MemberRef:
3736 return getCursorMemberRef(C).second;
3737
Ted Kremenek3064ef92010-08-27 21:34:58 +00003738 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003739 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003740
Douglas Gregor36897b02010-09-10 00:22:18 +00003741 case CXCursor_LabelRef:
3742 return getCursorLabelRef(C).second;
3743
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003744 case CXCursor_OverloadedDeclRef:
3745 return getCursorOverloadedDeclRef(C).second;
3746
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003747 default:
3748 // FIXME: Need a way to enumerate all non-reference cases.
3749 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003750 }
3751 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003752
3753 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003754 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003755
3756 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003757 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003758
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00003759 if (clang_isAttribute(C.kind))
3760 return getCursorAttr(C)->getRange();
3761
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003762 if (C.kind == CXCursor_PreprocessingDirective)
3763 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003764
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00003765 if (C.kind == CXCursor_MacroExpansion) {
3766 ASTUnit *TU = getCursorASTUnit(C);
3767 SourceRange Range = cxcursor::getCursorMacroExpansion(C)->getSourceRange();
3768 return TU->mapRangeFromPreamble(Range);
3769 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003770
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00003771 if (C.kind == CXCursor_MacroDefinition) {
3772 ASTUnit *TU = getCursorASTUnit(C);
3773 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
3774 return TU->mapRangeFromPreamble(Range);
3775 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003776
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00003777 if (C.kind == CXCursor_InclusionDirective) {
3778 ASTUnit *TU = getCursorASTUnit(C);
3779 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3780 return TU->mapRangeFromPreamble(Range);
3781 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003782
Ted Kremenek007a7c92010-11-01 23:26:51 +00003783 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3784 Decl *D = cxcursor::getCursorDecl(C);
3785 SourceRange R = D->getSourceRange();
3786 // FIXME: Multiple variables declared in a single declaration
3787 // currently lack the information needed to correctly determine their
3788 // ranges when accounting for the type-specifier. We use context
3789 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3790 // and if so, whether it is the first decl.
3791 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3792 if (!cxcursor::isFirstInDeclGroup(C))
3793 R.setBegin(VD->getLocation());
3794 }
3795 return R;
3796 }
Douglas Gregor66537982010-11-17 17:14:07 +00003797 return SourceRange();
3798}
3799
3800/// \brief Retrieves the "raw" cursor extent, which is then extended to include
3801/// the decl-specifier-seq for declarations.
3802static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
3803 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3804 Decl *D = cxcursor::getCursorDecl(C);
3805 SourceRange R = D->getSourceRange();
Douglas Gregor66537982010-11-17 17:14:07 +00003806
Douglas Gregor2494dd02011-03-01 01:34:45 +00003807 // Adjust the start of the location for declarations preceded by
3808 // declaration specifiers.
3809 SourceLocation StartLoc;
3810 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
3811 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
3812 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
3813 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
3814 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
3815 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
3816 }
3817
3818 if (StartLoc.isValid() && R.getBegin().isValid() &&
3819 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
3820 R.setBegin(StartLoc);
3821
3822 // FIXME: Multiple variables declared in a single declaration
3823 // currently lack the information needed to correctly determine their
3824 // ranges when accounting for the type-specifier. We use context
3825 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3826 // and if so, whether it is the first decl.
3827 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3828 if (!cxcursor::isFirstInDeclGroup(C))
3829 R.setBegin(VD->getLocation());
Douglas Gregor66537982010-11-17 17:14:07 +00003830 }
3831
3832 return R;
3833 }
3834
3835 return getRawCursorExtent(C);
3836}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003837
3838extern "C" {
3839
3840CXSourceRange clang_getCursorExtent(CXCursor C) {
3841 SourceRange R = getRawCursorExtent(C);
3842 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003843 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003844
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003845 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003846}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003847
3848CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003849 if (clang_isInvalid(C.kind))
3850 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003851
Ted Kremeneka60ed472010-11-16 08:15:36 +00003852 CXTranslationUnit tu = getCursorTU(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003853 if (clang_isDeclaration(C.kind)) {
3854 Decl *D = getCursorDecl(C);
3855 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003856 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003857 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003858 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003859 if (ObjCForwardProtocolDecl *Protocols
3860 = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003861 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), tu);
Chris Lattner5f9e2722011-07-23 10:55:15 +00003862 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00003863 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3864 return MakeCXCursor(Property, tu);
3865
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003866 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003867 }
3868
Douglas Gregor97b98722010-01-19 23:20:36 +00003869 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003870 Expr *E = getCursorExpr(C);
3871 Decl *D = getDeclFromExpr(E);
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003872 if (D) {
3873 CXCursor declCursor = MakeCXCursor(D, tu);
3874 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
3875 declCursor);
3876 return declCursor;
3877 }
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003878
3879 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003880 return MakeCursorOverloadedDeclRef(Ovl, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003881
Douglas Gregor97b98722010-01-19 23:20:36 +00003882 return clang_getNullCursor();
3883 }
3884
Douglas Gregor36897b02010-09-10 00:22:18 +00003885 if (clang_isStatement(C.kind)) {
3886 Stmt *S = getCursorStmt(C);
3887 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Ted Kremenek37c2e962011-03-15 23:47:49 +00003888 if (LabelDecl *label = Goto->getLabel())
3889 if (LabelStmt *labelS = label->getStmt())
3890 return MakeCXCursor(labelS, getCursorDecl(C), tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003891
3892 return clang_getNullCursor();
3893 }
3894
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003895 if (C.kind == CXCursor_MacroExpansion) {
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003896 if (MacroDefinition *Def = getCursorMacroExpansion(C)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003897 return MakeMacroDefinitionCursor(Def, tu);
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003898 }
3899
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003900 if (!clang_isReference(C.kind))
3901 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003902
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003903 switch (C.kind) {
3904 case CXCursor_ObjCSuperClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003905 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003906
3907 case CXCursor_ObjCProtocolRef: {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003908 return MakeCXCursor(getCursorObjCProtocolRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003909
3910 case CXCursor_ObjCClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003911 return MakeCXCursor(getCursorObjCClassRef(C).first, tu );
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003912
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003913 case CXCursor_TypeRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003914 return MakeCXCursor(getCursorTypeRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003915
3916 case CXCursor_TemplateRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003917 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003918
Douglas Gregor69319002010-08-31 23:48:11 +00003919 case CXCursor_NamespaceRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003920 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
Douglas Gregor69319002010-08-31 23:48:11 +00003921
Douglas Gregora67e03f2010-09-09 21:42:20 +00003922 case CXCursor_MemberRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003923 return MakeCXCursor(getCursorMemberRef(C).first, tu );
Douglas Gregora67e03f2010-09-09 21:42:20 +00003924
Ted Kremenek3064ef92010-08-27 21:34:58 +00003925 case CXCursor_CXXBaseSpecifier: {
3926 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3927 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003928 tu ));
Ted Kremenek3064ef92010-08-27 21:34:58 +00003929 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003930
Douglas Gregor36897b02010-09-10 00:22:18 +00003931 case CXCursor_LabelRef:
3932 // FIXME: We end up faking the "parent" declaration here because we
3933 // don't want to make CXCursor larger.
3934 return MakeCXCursor(getCursorLabelRef(C).first,
Ted Kremeneka60ed472010-11-16 08:15:36 +00003935 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
3936 .getTranslationUnitDecl(),
3937 tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003938
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003939 case CXCursor_OverloadedDeclRef:
3940 return C;
3941
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003942 default:
3943 // We would prefer to enumerate all non-reference cursor kinds here.
3944 llvm_unreachable("Unhandled reference cursor kind");
3945 break;
3946 }
3947 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003948
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003949 return clang_getNullCursor();
3950}
3951
Douglas Gregorb6998662010-01-19 19:34:47 +00003952CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003953 if (clang_isInvalid(C.kind))
3954 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003955
Ted Kremeneka60ed472010-11-16 08:15:36 +00003956 CXTranslationUnit TU = getCursorTU(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003957
Douglas Gregorb6998662010-01-19 19:34:47 +00003958 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003959 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003960 C = clang_getCursorReferenced(C);
3961 WasReference = true;
3962 }
3963
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003964 if (C.kind == CXCursor_MacroExpansion)
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003965 return clang_getCursorReferenced(C);
3966
Douglas Gregorb6998662010-01-19 19:34:47 +00003967 if (!clang_isDeclaration(C.kind))
3968 return clang_getNullCursor();
3969
3970 Decl *D = getCursorDecl(C);
3971 if (!D)
3972 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003973
Douglas Gregorb6998662010-01-19 19:34:47 +00003974 switch (D->getKind()) {
3975 // Declaration kinds that don't really separate the notions of
3976 // declaration and definition.
3977 case Decl::Namespace:
3978 case Decl::Typedef:
Richard Smith162e1c12011-04-15 14:24:37 +00003979 case Decl::TypeAlias:
Richard Smith3e4c6c42011-05-05 21:57:07 +00003980 case Decl::TypeAliasTemplate:
Douglas Gregorb6998662010-01-19 19:34:47 +00003981 case Decl::TemplateTypeParm:
3982 case Decl::EnumConstant:
3983 case Decl::Field:
Benjamin Kramerd9811462010-11-21 14:11:41 +00003984 case Decl::IndirectField:
Douglas Gregorb6998662010-01-19 19:34:47 +00003985 case Decl::ObjCIvar:
3986 case Decl::ObjCAtDefsField:
3987 case Decl::ImplicitParam:
3988 case Decl::ParmVar:
3989 case Decl::NonTypeTemplateParm:
3990 case Decl::TemplateTemplateParm:
3991 case Decl::ObjCCategoryImpl:
3992 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00003993 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00003994 case Decl::LinkageSpec:
3995 case Decl::ObjCPropertyImpl:
3996 case Decl::FileScopeAsm:
3997 case Decl::StaticAssert:
3998 case Decl::Block:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003999 case Decl::Label: // FIXME: Is this right??
Francois Pichetaf0f4d02011-08-14 03:52:19 +00004000 case Decl::ClassScopeFunctionSpecialization:
Douglas Gregorb6998662010-01-19 19:34:47 +00004001 return C;
4002
4003 // Declaration kinds that don't make any sense here, but are
4004 // nonetheless harmless.
4005 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00004006 break;
4007
4008 // Declaration kinds for which the definition is not resolvable.
4009 case Decl::UnresolvedUsingTypename:
4010 case Decl::UnresolvedUsingValue:
4011 break;
4012
4013 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00004014 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004015 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004016
4017 case Decl::NamespaceAlias:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004018 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004019
4020 case Decl::Enum:
4021 case Decl::Record:
4022 case Decl::CXXRecord:
4023 case Decl::ClassTemplateSpecialization:
4024 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00004025 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004026 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004027 return clang_getNullCursor();
4028
4029 case Decl::Function:
4030 case Decl::CXXMethod:
4031 case Decl::CXXConstructor:
4032 case Decl::CXXDestructor:
4033 case Decl::CXXConversion: {
4034 const FunctionDecl *Def = 0;
4035 if (cast<FunctionDecl>(D)->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004036 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004037 return clang_getNullCursor();
4038 }
4039
4040 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00004041 // Ask the variable if it has a definition.
4042 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004043 return MakeCXCursor(Def, TU);
Sebastian Redl31310a22010-02-01 20:16:42 +00004044 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00004045 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004046
Douglas Gregorb6998662010-01-19 19:34:47 +00004047 case Decl::FunctionTemplate: {
4048 const FunctionDecl *Def = 0;
4049 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004050 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004051 return clang_getNullCursor();
4052 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004053
Douglas Gregorb6998662010-01-19 19:34:47 +00004054 case Decl::ClassTemplate: {
4055 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00004056 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00004057 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004058 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004059 return clang_getNullCursor();
4060 }
4061
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004062 case Decl::Using:
4063 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004064 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004065
4066 case Decl::UsingShadow:
4067 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004068 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004069 TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004070
4071 case Decl::ObjCMethod: {
4072 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
4073 if (Method->isThisDeclarationADefinition())
4074 return C;
4075
4076 // Dig out the method definition in the associated
4077 // @implementation, if we have it.
4078 // FIXME: The ASTs should make finding the definition easier.
4079 if (ObjCInterfaceDecl *Class
4080 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
4081 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
4082 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
4083 Method->isInstanceMethod()))
4084 if (Def->isThisDeclarationADefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004085 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004086
4087 return clang_getNullCursor();
4088 }
4089
4090 case Decl::ObjCCategory:
4091 if (ObjCCategoryImplDecl *Impl
4092 = cast<ObjCCategoryDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004093 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004094 return clang_getNullCursor();
4095
4096 case Decl::ObjCProtocol:
4097 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
4098 return C;
4099 return clang_getNullCursor();
4100
4101 case Decl::ObjCInterface:
4102 // There are two notions of a "definition" for an Objective-C
4103 // class: the interface and its implementation. When we resolved a
4104 // reference to an Objective-C class, produce the @interface as
4105 // the definition; when we were provided with the interface,
4106 // produce the @implementation as the definition.
4107 if (WasReference) {
4108 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
4109 return C;
4110 } else if (ObjCImplementationDecl *Impl
4111 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004112 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004113 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004114
Douglas Gregorb6998662010-01-19 19:34:47 +00004115 case Decl::ObjCProperty:
4116 // FIXME: We don't really know where to find the
4117 // ObjCPropertyImplDecls that implement this property.
4118 return clang_getNullCursor();
4119
4120 case Decl::ObjCCompatibleAlias:
4121 if (ObjCInterfaceDecl *Class
4122 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
4123 if (!Class->isForwardDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004124 return MakeCXCursor(Class, TU);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004125
Douglas Gregorb6998662010-01-19 19:34:47 +00004126 return clang_getNullCursor();
4127
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004128 case Decl::ObjCForwardProtocol:
4129 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004130 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004131
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004132 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004133 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004134 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004135
4136 case Decl::Friend:
4137 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004138 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004139 return clang_getNullCursor();
4140
4141 case Decl::FriendTemplate:
4142 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004143 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004144 return clang_getNullCursor();
4145 }
4146
4147 return clang_getNullCursor();
4148}
4149
4150unsigned clang_isCursorDefinition(CXCursor C) {
4151 if (!clang_isDeclaration(C.kind))
4152 return 0;
4153
4154 return clang_getCursorDefinition(C) == C;
4155}
4156
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004157CXCursor clang_getCanonicalCursor(CXCursor C) {
4158 if (!clang_isDeclaration(C.kind))
4159 return C;
4160
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004161 if (Decl *D = getCursorDecl(C)) {
Argyrios Kyrtzidisdebb00f2011-07-15 22:37:58 +00004162 if (ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
4163 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
4164 return MakeCXCursor(CatD, getCursorTU(C));
4165
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004166 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
4167 if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
4168 return MakeCXCursor(IFD, getCursorTU(C));
4169
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004170 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004171 }
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004172
4173 return C;
4174}
4175
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004176unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004177 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004178 return 0;
4179
4180 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
4181 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
4182 return E->getNumDecls();
4183
4184 if (OverloadedTemplateStorage *S
4185 = Storage.dyn_cast<OverloadedTemplateStorage*>())
4186 return S->size();
4187
4188 Decl *D = Storage.get<Decl*>();
4189 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00004190 return Using->shadow_size();
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00004191 if (isa<ObjCClassDecl>(D))
4192 return 1;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004193 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
4194 return Protocols->protocol_size();
4195
4196 return 0;
4197}
4198
4199CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004200 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004201 return clang_getNullCursor();
4202
4203 if (index >= clang_getNumOverloadedDecls(cursor))
4204 return clang_getNullCursor();
4205
Ted Kremeneka60ed472010-11-16 08:15:36 +00004206 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004207 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
4208 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004209 return MakeCXCursor(E->decls_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004210
4211 if (OverloadedTemplateStorage *S
4212 = Storage.dyn_cast<OverloadedTemplateStorage*>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004213 return MakeCXCursor(S->begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004214
4215 Decl *D = Storage.get<Decl*>();
4216 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
4217 // FIXME: This is, unfortunately, linear time.
4218 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
4219 std::advance(Pos, index);
Ted Kremeneka60ed472010-11-16 08:15:36 +00004220 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004221 }
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004222 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00004223 return MakeCXCursor(Classes->getForwardInterfaceDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004224 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004225 return MakeCXCursor(Protocols->protocol_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004226
4227 return clang_getNullCursor();
4228}
4229
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00004230void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00004231 const char **startBuf,
4232 const char **endBuf,
4233 unsigned *startLine,
4234 unsigned *startColumn,
4235 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00004236 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00004237 assert(getCursorDecl(C) && "CXCursor has null decl");
4238 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00004239 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
4240 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004241
Steve Naroff4ade6d62009-09-23 17:52:52 +00004242 SourceManager &SM = FD->getASTContext().getSourceManager();
4243 *startBuf = SM.getCharacterData(Body->getLBracLoc());
4244 *endBuf = SM.getCharacterData(Body->getRBracLoc());
4245 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
4246 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
4247 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
4248 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
4249}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004250
Douglas Gregor430d7a12011-07-25 17:48:11 +00004251
4252CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
4253 unsigned PieceIndex) {
4254 RefNamePieces Pieces;
4255
4256 switch (C.kind) {
4257 case CXCursor_MemberRefExpr:
4258 if (MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
4259 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
4260 E->getQualifierLoc().getSourceRange());
4261 break;
4262
4263 case CXCursor_DeclRefExpr:
4264 if (DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C)))
4265 Pieces = buildPieces(NameFlags, false, E->getNameInfo(),
4266 E->getQualifierLoc().getSourceRange(),
4267 E->getExplicitTemplateArgsOpt());
4268 break;
4269
4270 case CXCursor_CallExpr:
4271 if (CXXOperatorCallExpr *OCE =
4272 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
4273 Expr *Callee = OCE->getCallee();
4274 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
4275 Callee = ICE->getSubExpr();
4276
4277 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
4278 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
4279 DRE->getQualifierLoc().getSourceRange());
4280 }
4281 break;
4282
4283 default:
4284 break;
4285 }
4286
4287 if (Pieces.empty()) {
4288 if (PieceIndex == 0)
4289 return clang_getCursorExtent(C);
4290 } else if (PieceIndex < Pieces.size()) {
4291 SourceRange R = Pieces[PieceIndex];
4292 if (R.isValid())
4293 return cxloc::translateSourceRange(getCursorContext(C), R);
4294 }
4295
4296 return clang_getNullRange();
4297}
4298
Douglas Gregor0a812cf2010-02-18 23:07:20 +00004299void clang_enableStackTraces(void) {
4300 llvm::sys::PrintStackTraceOnErrorSignal();
4301}
4302
Daniel Dunbar995aaf92010-11-04 01:26:29 +00004303void clang_executeOnThread(void (*fn)(void*), void *user_data,
4304 unsigned stack_size) {
4305 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
4306}
4307
Ted Kremenekfb480492010-01-13 21:46:36 +00004308} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00004309
Ted Kremenekfb480492010-01-13 21:46:36 +00004310//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004311// Token-based Operations.
4312//===----------------------------------------------------------------------===//
4313
4314/* CXToken layout:
4315 * int_data[0]: a CXTokenKind
4316 * int_data[1]: starting token location
4317 * int_data[2]: token length
4318 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004319 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004320 * otherwise unused.
4321 */
4322extern "C" {
4323
4324CXTokenKind clang_getTokenKind(CXToken CXTok) {
4325 return static_cast<CXTokenKind>(CXTok.int_data[0]);
4326}
4327
4328CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
4329 switch (clang_getTokenKind(CXTok)) {
4330 case CXToken_Identifier:
4331 case CXToken_Keyword:
4332 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004333 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
4334 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004335
4336 case CXToken_Literal: {
4337 // We have stashed the starting pointer in the ptr_data field. Use it.
4338 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Chris Lattner5f9e2722011-07-23 10:55:15 +00004339 return createCXString(StringRef(Text, 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 +00004342 case CXToken_Punctuation:
4343 case CXToken_Comment:
4344 break;
4345 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004346
4347 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004348 // deconstructing the source location.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004349 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004350 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004351 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004352
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004353 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
4354 std::pair<FileID, unsigned> LocInfo
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004355 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00004356 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004357 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004358 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
4359 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00004360 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004361
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004362 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004363}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004364
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004365CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004366 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004367 if (!CXXUnit)
4368 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004369
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004370 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
4371 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4372}
4373
4374CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004375 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor5352ac02010-01-28 00:27:43 +00004376 if (!CXXUnit)
4377 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004378
4379 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004380 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4381}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004382
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004383static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
4384 SmallVectorImpl<CXToken> &CXTokens) {
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004385 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4386 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004387 = SourceMgr.getDecomposedLoc(Range.getBegin());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004388 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004389 = SourceMgr.getDecomposedLoc(Range.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004390
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004391 // Cannot tokenize across files.
4392 if (BeginLocInfo.first != EndLocInfo.first)
4393 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004394
4395 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004396 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004397 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004398 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00004399 if (Invalid)
4400 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00004401
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004402 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4403 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004404 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004405 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004406
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004407 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004408 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004409 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00004410 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004411 do {
4412 // Lex the next token
4413 Lex.LexFromRawLexer(Tok);
4414 if (Tok.is(tok::eof))
4415 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004416
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004417 // Initialize the CXToken.
4418 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004419
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004420 // - Common fields
4421 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
4422 CXTok.int_data[2] = Tok.getLength();
4423 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004424
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004425 // - Kind-specific fields
4426 if (Tok.isLiteral()) {
4427 CXTok.int_data[0] = CXToken_Literal;
4428 CXTok.ptr_data = (void *)Tok.getLiteralData();
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004429 } else if (Tok.is(tok::raw_identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00004430 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004431 IdentifierInfo *II
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004432 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004433
David Chisnall096428b2010-10-13 21:44:48 +00004434 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004435 CXTok.int_data[0] = CXToken_Keyword;
4436 }
4437 else {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004438 CXTok.int_data[0] = Tok.is(tok::identifier)
4439 ? CXToken_Identifier
4440 : CXToken_Keyword;
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004441 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004442 CXTok.ptr_data = II;
4443 } else if (Tok.is(tok::comment)) {
4444 CXTok.int_data[0] = CXToken_Comment;
4445 CXTok.ptr_data = 0;
4446 } else {
4447 CXTok.int_data[0] = CXToken_Punctuation;
4448 CXTok.ptr_data = 0;
4449 }
4450 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00004451 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004452 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004453}
4454
4455void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
4456 CXToken **Tokens, unsigned *NumTokens) {
4457 if (Tokens)
4458 *Tokens = 0;
4459 if (NumTokens)
4460 *NumTokens = 0;
4461
4462 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4463 if (!CXXUnit || !Tokens || !NumTokens)
4464 return;
4465
4466 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4467
4468 SourceRange R = cxloc::translateCXSourceRange(Range);
4469 if (R.isInvalid())
4470 return;
4471
4472 SmallVector<CXToken, 32> CXTokens;
4473 getTokens(CXXUnit, R, CXTokens);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004474
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004475 if (CXTokens.empty())
4476 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004477
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004478 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
4479 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
4480 *NumTokens = CXTokens.size();
4481}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004482
Ted Kremenek6db61092010-05-05 00:55:15 +00004483void clang_disposeTokens(CXTranslationUnit TU,
4484 CXToken *Tokens, unsigned NumTokens) {
4485 free(Tokens);
4486}
4487
4488} // end: extern "C"
4489
4490//===----------------------------------------------------------------------===//
4491// Token annotation APIs.
4492//===----------------------------------------------------------------------===//
4493
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004494typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004495static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4496 CXCursor parent,
4497 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00004498namespace {
4499class AnnotateTokensWorker {
4500 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004501 CXToken *Tokens;
4502 CXCursor *Cursors;
4503 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004504 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00004505 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004506 CursorVisitor AnnotateVis;
4507 SourceManager &SrcMgr;
Douglas Gregorf5251602011-03-08 17:10:18 +00004508 bool HasContextSensitiveKeywords;
4509
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004510 bool MoreTokens() const { return TokIdx < NumTokens; }
4511 unsigned NextToken() const { return TokIdx; }
4512 void AdvanceToken() { ++TokIdx; }
4513 SourceLocation GetTokenLoc(unsigned tokI) {
4514 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4515 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004516 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004517 return Tokens[tokI].int_data[3] != 0;
4518 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004519 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004520 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[3]);
4521 }
4522
4523 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004524 void annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
4525 SourceRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004526
Ted Kremenek6db61092010-05-05 00:55:15 +00004527public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00004528 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004529 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004530 CXTranslationUnit tu, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00004531 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00004532 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004533 AnnotateVis(tu,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00004534 AnnotateTokensVisitor, this,
4535 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00004536 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00004537 RegionOfInterest),
Douglas Gregorf5251602011-03-08 17:10:18 +00004538 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()),
4539 HasContextSensitiveKeywords(false) { }
Ted Kremenek11949cb2010-05-05 00:55:17 +00004540
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004541 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00004542 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004543 void AnnotateTokens();
Douglas Gregorf5251602011-03-08 17:10:18 +00004544
4545 /// \brief Determine whether the annotator saw any cursors that have
4546 /// context-sensitive keywords.
4547 bool hasContextSensitiveKeywords() const {
4548 return HasContextSensitiveKeywords;
4549 }
Ted Kremenek6db61092010-05-05 00:55:15 +00004550};
4551}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004552
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004553void AnnotateTokensWorker::AnnotateTokens() {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004554 // Walk the AST within the region of interest, annotating tokens
4555 // along the way.
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004556 AnnotateVis.visitFileRegion();
Ted Kremenek11949cb2010-05-05 00:55:17 +00004557
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004558 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4559 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004560 if (Pos != Annotated.end() &&
4561 (clang_isInvalid(Cursors[I].kind) ||
4562 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004563 Cursors[I] = Pos->second;
4564 }
4565
4566 // Finish up annotating any tokens left.
4567 if (!MoreTokens())
4568 return;
4569
4570 const CXCursor &C = clang_getNullCursor();
4571 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004572 if (I < PreprocessingTokIdx && clang_isPreprocessing(Cursors[I].kind))
4573 continue;
4574
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004575 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4576 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004577 }
4578}
4579
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004580/// \brief It annotates and advances tokens with a cursor until the comparison
4581//// between the cursor location and the source range is the same as
4582/// \arg compResult.
4583///
4584/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
4585/// Pass RangeOverlap to annotate tokens inside a range.
4586void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
4587 RangeComparisonResult compResult,
4588 SourceRange range) {
4589 while (MoreTokens()) {
4590 const unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004591 if (isFunctionMacroToken(I))
4592 return annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004593
4594 SourceLocation TokLoc = GetTokenLoc(I);
4595 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4596 Cursors[I] = updateC;
4597 AdvanceToken();
4598 continue;
4599 }
4600 break;
4601 }
4602}
4603
4604/// \brief Special annotation handling for macro argument tokens.
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004605void AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
4606 CXCursor updateC,
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004607 RangeComparisonResult compResult,
4608 SourceRange range) {
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004609 assert(MoreTokens());
4610 assert(isFunctionMacroToken(NextToken()) &&
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004611 "Should be called only for macro arg tokens");
4612
4613 // This works differently than annotateAndAdvanceTokens; because expanded
4614 // macro arguments can have arbitrary translation-unit source order, we do not
4615 // advance the token index one by one until a token fails the range test.
4616 // We only advance once past all of the macro arg tokens if all of them
4617 // pass the range test. If one of them fails we keep the token index pointing
4618 // at the start of the macro arg tokens so that the failing token will be
4619 // annotated by a subsequent annotation try.
4620
4621 bool atLeastOneCompFail = false;
4622
4623 unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004624 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
4625 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004626 if (TokLoc.isFileID())
4627 continue; // not macro arg token, it's parens or comma.
4628 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4629 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
4630 Cursors[I] = updateC;
4631 } else
4632 atLeastOneCompFail = true;
4633 }
4634
4635 if (!atLeastOneCompFail)
4636 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
4637}
4638
Ted Kremenek6db61092010-05-05 00:55:15 +00004639enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004640AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004641 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004642 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004643 if (cursorRange.isInvalid())
4644 return CXChildVisit_Recurse;
Douglas Gregorf5251602011-03-08 17:10:18 +00004645
4646 if (!HasContextSensitiveKeywords) {
4647 // Objective-C properties can have context-sensitive keywords.
4648 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
4649 if (ObjCPropertyDecl *Property
4650 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
4651 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
4652 }
4653 // Objective-C methods can have context-sensitive keywords.
4654 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
4655 cursor.kind == CXCursor_ObjCClassMethodDecl) {
4656 if (ObjCMethodDecl *Method
4657 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
4658 if (Method->getObjCDeclQualifier())
4659 HasContextSensitiveKeywords = true;
4660 else {
4661 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
4662 PEnd = Method->param_end();
4663 P != PEnd; ++P) {
4664 if ((*P)->getObjCDeclQualifier()) {
4665 HasContextSensitiveKeywords = true;
4666 break;
4667 }
4668 }
4669 }
4670 }
4671 }
4672 // C++ methods can have context-sensitive keywords.
4673 else if (cursor.kind == CXCursor_CXXMethod) {
4674 if (CXXMethodDecl *Method
4675 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
4676 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
4677 HasContextSensitiveKeywords = true;
4678 }
4679 }
4680 // C++ classes can have context-sensitive keywords.
4681 else if (cursor.kind == CXCursor_StructDecl ||
4682 cursor.kind == CXCursor_ClassDecl ||
4683 cursor.kind == CXCursor_ClassTemplate ||
4684 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
4685 if (Decl *D = getCursorDecl(cursor))
4686 if (D->hasAttr<FinalAttr>())
4687 HasContextSensitiveKeywords = true;
4688 }
4689 }
4690
Douglas Gregor4419b672010-10-21 06:10:04 +00004691 if (clang_isPreprocessing(cursor.kind)) {
Chandler Carruthcea731a2011-07-14 16:07:57 +00004692 // For macro expansions, just note where the beginning of the macro
4693 // expansion occurs.
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004694 if (cursor.kind == CXCursor_MacroExpansion) {
Douglas Gregor4419b672010-10-21 06:10:04 +00004695 Annotated[Loc.int_data] = cursor;
4696 return CXChildVisit_Recurse;
4697 }
4698
Douglas Gregor4419b672010-10-21 06:10:04 +00004699 // Items in the preprocessing record are kept separate from items in
4700 // declarations, so we keep a separate token index.
4701 unsigned SavedTokIdx = TokIdx;
4702 TokIdx = PreprocessingTokIdx;
4703
4704 // Skip tokens up until we catch up to the beginning of the preprocessing
4705 // entry.
4706 while (MoreTokens()) {
4707 const unsigned I = NextToken();
4708 SourceLocation TokLoc = GetTokenLoc(I);
4709 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4710 case RangeBefore:
4711 AdvanceToken();
4712 continue;
4713 case RangeAfter:
4714 case RangeOverlap:
4715 break;
4716 }
4717 break;
4718 }
4719
4720 // Look at all of the tokens within this range.
4721 while (MoreTokens()) {
4722 const unsigned I = NextToken();
4723 SourceLocation TokLoc = GetTokenLoc(I);
4724 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4725 case RangeBefore:
David Blaikieb219cfc2011-09-23 05:06:16 +00004726 llvm_unreachable("Infeasible");
Douglas Gregor4419b672010-10-21 06:10:04 +00004727 case RangeAfter:
4728 break;
4729 case RangeOverlap:
4730 Cursors[I] = cursor;
4731 AdvanceToken();
4732 continue;
4733 }
4734 break;
4735 }
4736
4737 // Save the preprocessing token index; restore the non-preprocessing
4738 // token index.
4739 PreprocessingTokIdx = TokIdx;
4740 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004741 return CXChildVisit_Recurse;
4742 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004743
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004744 if (cursorRange.isInvalid())
4745 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004746
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004747 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4748
Ted Kremeneka333c662010-05-12 05:29:33 +00004749 // Adjust the annotated range based specific declarations.
4750 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4751 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004752 Decl *D = cxcursor::getCursorDecl(cursor);
Douglas Gregor2494dd02011-03-01 01:34:45 +00004753
4754 SourceLocation StartLoc;
Ted Kremenek23173d72010-05-18 21:09:07 +00004755 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00004756 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
4757 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
4758 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
4759 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
4760 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
Ted Kremeneka333c662010-05-12 05:29:33 +00004761 }
Douglas Gregor2494dd02011-03-01 01:34:45 +00004762
4763 if (StartLoc.isValid() && L.isValid() &&
4764 SrcMgr.isBeforeInTranslationUnit(StartLoc, L))
4765 cursorRange.setBegin(StartLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004766 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004767
Ted Kremenek3f404602010-08-14 01:14:06 +00004768 // If the location of the cursor occurs within a macro instantiation, record
4769 // the spelling location of the cursor in our annotation map. We can then
4770 // paper over the token labelings during a post-processing step to try and
4771 // get cursor mappings for tokens that are the *arguments* of a macro
4772 // instantiation.
4773 if (L.isMacroID()) {
4774 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4775 // Only invalidate the old annotation if it isn't part of a preprocessing
4776 // directive. Here we assume that the default construction of CXCursor
4777 // results in CXCursor.kind being an initialized value (i.e., 0). If
4778 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004779
Ted Kremenek3f404602010-08-14 01:14:06 +00004780 CXCursor &oldC = Annotated[rawEncoding];
4781 if (!clang_isPreprocessing(oldC.kind))
4782 oldC = cursor;
4783 }
4784
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004785 const enum CXCursorKind K = clang_getCursorKind(parent);
4786 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004787 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4788 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004789
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004790 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004791
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00004792 // Avoid having the cursor of an expression "overwrite" the annotation of the
4793 // variable declaration that it belongs to.
4794 // This can happen for C++ constructor expressions whose range generally
4795 // include the variable declaration, e.g.:
4796 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
4797 if (clang_isExpression(cursorK)) {
4798 Expr *E = getCursorExpr(cursor);
Argyrios Kyrtzidis8ccac3d2011-06-29 22:20:07 +00004799 if (Decl *D = getCursorParentDecl(cursor)) {
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00004800 const unsigned I = NextToken();
4801 if (E->getLocStart().isValid() && D->getLocation().isValid() &&
4802 E->getLocStart() == D->getLocation() &&
4803 E->getLocStart() == GetTokenLoc(I)) {
4804 Cursors[I] = updateC;
4805 AdvanceToken();
4806 }
4807 }
4808 }
4809
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004810 // Visit children to get their cursor information.
4811 const unsigned BeforeChildren = NextToken();
4812 VisitChildren(cursor);
4813 const unsigned AfterChildren = NextToken();
4814
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004815 // Scan the tokens that are at the end of the cursor, but are not captured
4816 // but the child cursors.
4817 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
Ted Kremenek6db61092010-05-05 00:55:15 +00004818
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004819 // Scan the tokens that are at the beginning of the cursor, but are not
4820 // capture by the child cursors.
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004821 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4822 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4823 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004824
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004825 Cursors[I] = cursor;
4826 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004827
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004828 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004829}
4830
Ted Kremenek6db61092010-05-05 00:55:15 +00004831static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4832 CXCursor parent,
4833 CXClientData client_data) {
4834 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4835}
4836
Ted Kremenek6628a612011-03-18 22:51:30 +00004837namespace {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004838
4839/// \brief Uses the macro expansions in the preprocessing record to find
4840/// and mark tokens that are macro arguments. This info is used by the
4841/// AnnotateTokensWorker.
4842class MarkMacroArgTokensVisitor {
4843 SourceManager &SM;
4844 CXToken *Tokens;
4845 unsigned NumTokens;
4846 unsigned CurIdx;
4847
4848public:
4849 MarkMacroArgTokensVisitor(SourceManager &SM,
4850 CXToken *tokens, unsigned numTokens)
4851 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
4852
4853 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
4854 if (cursor.kind != CXCursor_MacroExpansion)
4855 return CXChildVisit_Continue;
4856
4857 SourceRange macroRange = getCursorMacroExpansion(cursor)->getSourceRange();
4858 if (macroRange.getBegin() == macroRange.getEnd())
4859 return CXChildVisit_Continue; // it's not a function macro.
4860
4861 for (; CurIdx < NumTokens; ++CurIdx) {
4862 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
4863 macroRange.getBegin()))
4864 break;
4865 }
4866
4867 if (CurIdx == NumTokens)
4868 return CXChildVisit_Break;
4869
4870 for (; CurIdx < NumTokens; ++CurIdx) {
4871 SourceLocation tokLoc = getTokenLoc(CurIdx);
4872 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
4873 break;
4874
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004875 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004876 }
4877
4878 if (CurIdx == NumTokens)
4879 return CXChildVisit_Break;
4880
4881 return CXChildVisit_Continue;
4882 }
4883
4884private:
4885 SourceLocation getTokenLoc(unsigned tokI) {
4886 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4887 }
4888
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004889 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004890 // The third field is reserved and currently not used. Use it here
4891 // to mark macro arg expanded tokens with their expanded locations.
4892 Tokens[tokI].int_data[3] = loc.getRawEncoding();
4893 }
4894};
4895
4896} // end anonymous namespace
4897
4898static CXChildVisitResult
4899MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
4900 CXClientData client_data) {
4901 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
4902 parent);
4903}
4904
4905namespace {
Ted Kremenek6628a612011-03-18 22:51:30 +00004906 struct clang_annotateTokens_Data {
4907 CXTranslationUnit TU;
4908 ASTUnit *CXXUnit;
4909 CXToken *Tokens;
4910 unsigned NumTokens;
4911 CXCursor *Cursors;
4912 };
4913}
4914
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004915static void annotatePreprocessorTokens(CXTranslationUnit TU,
4916 SourceRange RegionOfInterest,
4917 AnnotateTokensData &Annotated) {
4918 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4919
4920 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4921 std::pair<FileID, unsigned> BeginLocInfo
4922 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4923 std::pair<FileID, unsigned> EndLocInfo
4924 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
4925
4926 if (BeginLocInfo.first != EndLocInfo.first)
4927 return;
4928
4929 StringRef Buffer;
4930 bool Invalid = false;
4931 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
4932 if (Buffer.empty() || Invalid)
4933 return;
4934
4935 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4936 CXXUnit->getASTContext().getLangOptions(),
4937 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
4938 Buffer.end());
4939 Lex.SetCommentRetentionState(true);
4940
4941 // Lex tokens in raw mode until we hit the end of the range, to avoid
4942 // entering #includes or expanding macros.
4943 while (true) {
4944 Token Tok;
4945 Lex.LexFromRawLexer(Tok);
4946
4947 reprocess:
4948 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4949 // We have found a preprocessing directive. Gobble it up so that we
4950 // don't see it while preprocessing these tokens later, but keep track
4951 // of all of the token locations inside this preprocessing directive so
4952 // that we can annotate them appropriately.
4953 //
4954 // FIXME: Some simple tests here could identify macro definitions and
4955 // #undefs, to provide specific cursor kinds for those.
4956 SmallVector<SourceLocation, 32> Locations;
4957 do {
4958 Locations.push_back(Tok.getLocation());
4959 Lex.LexFromRawLexer(Tok);
4960 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
4961
4962 using namespace cxcursor;
4963 CXCursor Cursor
4964 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4965 Locations.back()),
4966 TU);
4967 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4968 Annotated[Locations[I].getRawEncoding()] = Cursor;
4969 }
4970
4971 if (Tok.isAtStartOfLine())
4972 goto reprocess;
4973
4974 continue;
4975 }
4976
4977 if (Tok.is(tok::eof))
4978 break;
4979 }
4980}
4981
Ted Kremenekab979612010-11-11 08:05:23 +00004982// This gets run a separate thread to avoid stack blowout.
Ted Kremenek6628a612011-03-18 22:51:30 +00004983static void clang_annotateTokensImpl(void *UserData) {
4984 CXTranslationUnit TU = ((clang_annotateTokens_Data*)UserData)->TU;
4985 ASTUnit *CXXUnit = ((clang_annotateTokens_Data*)UserData)->CXXUnit;
4986 CXToken *Tokens = ((clang_annotateTokens_Data*)UserData)->Tokens;
4987 const unsigned NumTokens = ((clang_annotateTokens_Data*)UserData)->NumTokens;
4988 CXCursor *Cursors = ((clang_annotateTokens_Data*)UserData)->Cursors;
4989
4990 // Determine the region of interest, which contains all of the tokens.
4991 SourceRange RegionOfInterest;
4992 RegionOfInterest.setBegin(
4993 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
4994 RegionOfInterest.setEnd(
4995 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
4996 Tokens[NumTokens-1])));
4997
4998 // A mapping from the source locations found when re-lexing or traversing the
4999 // region of interest to the corresponding cursors.
5000 AnnotateTokensData Annotated;
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005001
Ted Kremenek6628a612011-03-18 22:51:30 +00005002 // Relex the tokens within the source range to look for preprocessing
5003 // directives.
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005004 annotatePreprocessorTokens(TU, RegionOfInterest, Annotated);
Ted Kremenek6628a612011-03-18 22:51:30 +00005005
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005006 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
5007 // Search and mark tokens that are macro argument expansions.
5008 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
5009 Tokens, NumTokens);
5010 CursorVisitor MacroArgMarker(TU,
5011 MarkMacroArgTokensVisitorDelegate, &Visitor,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00005012 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00005013 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00005014 RegionOfInterest);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005015 MacroArgMarker.visitPreprocessedEntitiesInRegion();
5016 }
5017
Ted Kremenek6628a612011-03-18 22:51:30 +00005018 // Annotate all of the source locations in the region of interest that map to
5019 // a specific cursor.
5020 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
5021 TU, RegionOfInterest);
5022
5023 // FIXME: We use a ridiculous stack size here because the data-recursion
5024 // algorithm uses a large stack frame than the non-data recursive version,
5025 // and AnnotationTokensWorker currently transforms the data-recursion
5026 // algorithm back into a traditional recursion by explicitly calling
5027 // VisitChildren(). We will need to remove this explicit recursive call.
5028 W.AnnotateTokens();
5029
5030 // If we ran into any entities that involve context-sensitive keywords,
5031 // take another pass through the tokens to mark them as such.
5032 if (W.hasContextSensitiveKeywords()) {
5033 for (unsigned I = 0; I != NumTokens; ++I) {
5034 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
5035 continue;
5036
5037 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
5038 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5039 if (ObjCPropertyDecl *Property
5040 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
5041 if (Property->getPropertyAttributesAsWritten() != 0 &&
5042 llvm::StringSwitch<bool>(II->getName())
5043 .Case("readonly", true)
5044 .Case("assign", true)
John McCallf85e1932011-06-15 23:02:42 +00005045 .Case("unsafe_unretained", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00005046 .Case("readwrite", true)
5047 .Case("retain", true)
5048 .Case("copy", true)
5049 .Case("nonatomic", true)
5050 .Case("atomic", true)
5051 .Case("getter", true)
5052 .Case("setter", true)
John McCallf85e1932011-06-15 23:02:42 +00005053 .Case("strong", true)
5054 .Case("weak", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00005055 .Default(false))
5056 Tokens[I].int_data[0] = CXToken_Keyword;
5057 }
5058 continue;
5059 }
5060
5061 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
5062 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
5063 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5064 if (llvm::StringSwitch<bool>(II->getName())
5065 .Case("in", true)
5066 .Case("out", true)
5067 .Case("inout", true)
5068 .Case("oneway", true)
5069 .Case("bycopy", true)
5070 .Case("byref", true)
5071 .Default(false))
5072 Tokens[I].int_data[0] = CXToken_Keyword;
5073 continue;
5074 }
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00005075
5076 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
5077 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
5078 Tokens[I].int_data[0] = CXToken_Keyword;
Ted Kremenek6628a612011-03-18 22:51:30 +00005079 continue;
5080 }
5081 }
5082 }
Ted Kremenekab979612010-11-11 08:05:23 +00005083}
5084
Ted Kremenek6db61092010-05-05 00:55:15 +00005085extern "C" {
5086
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005087void clang_annotateTokens(CXTranslationUnit TU,
5088 CXToken *Tokens, unsigned NumTokens,
5089 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005090
5091 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005092 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005093
Douglas Gregor4419b672010-10-21 06:10:04 +00005094 // Any token we don't specifically annotate will have a NULL cursor.
5095 CXCursor C = clang_getNullCursor();
5096 for (unsigned I = 0; I != NumTokens; ++I)
5097 Cursors[I] = C;
5098
Ted Kremeneka60ed472010-11-16 08:15:36 +00005099 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor4419b672010-10-21 06:10:04 +00005100 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005101 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005102
Douglas Gregorbdf60622010-03-05 21:16:25 +00005103 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenek6628a612011-03-18 22:51:30 +00005104
5105 clang_annotateTokens_Data data = { TU, CXXUnit, Tokens, NumTokens, Cursors };
Ted Kremenekab979612010-11-11 08:05:23 +00005106 llvm::CrashRecoveryContext CRC;
Ted Kremenek6628a612011-03-18 22:51:30 +00005107 if (!RunSafely(CRC, clang_annotateTokensImpl, &data,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005108 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00005109 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
5110 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005111}
Ted Kremenek6628a612011-03-18 22:51:30 +00005112
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005113} // end: extern "C"
5114
5115//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00005116// Operations for querying linkage of a cursor.
5117//===----------------------------------------------------------------------===//
5118
5119extern "C" {
5120CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00005121 if (!clang_isDeclaration(cursor.kind))
5122 return CXLinkage_Invalid;
5123
Ted Kremenek16b42592010-03-03 06:36:57 +00005124 Decl *D = cxcursor::getCursorDecl(cursor);
5125 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
5126 switch (ND->getLinkage()) {
5127 case NoLinkage: return CXLinkage_NoLinkage;
5128 case InternalLinkage: return CXLinkage_Internal;
5129 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
5130 case ExternalLinkage: return CXLinkage_External;
5131 };
5132
5133 return CXLinkage_Invalid;
5134}
5135} // end: extern "C"
5136
5137//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005138// Operations for querying language of a cursor.
5139//===----------------------------------------------------------------------===//
5140
5141static CXLanguageKind getDeclLanguage(const Decl *D) {
5142 switch (D->getKind()) {
5143 default:
5144 break;
5145 case Decl::ImplicitParam:
5146 case Decl::ObjCAtDefsField:
5147 case Decl::ObjCCategory:
5148 case Decl::ObjCCategoryImpl:
5149 case Decl::ObjCClass:
5150 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005151 case Decl::ObjCForwardProtocol:
5152 case Decl::ObjCImplementation:
5153 case Decl::ObjCInterface:
5154 case Decl::ObjCIvar:
5155 case Decl::ObjCMethod:
5156 case Decl::ObjCProperty:
5157 case Decl::ObjCPropertyImpl:
5158 case Decl::ObjCProtocol:
5159 return CXLanguage_ObjC;
5160 case Decl::CXXConstructor:
5161 case Decl::CXXConversion:
5162 case Decl::CXXDestructor:
5163 case Decl::CXXMethod:
5164 case Decl::CXXRecord:
5165 case Decl::ClassTemplate:
5166 case Decl::ClassTemplatePartialSpecialization:
5167 case Decl::ClassTemplateSpecialization:
5168 case Decl::Friend:
5169 case Decl::FriendTemplate:
5170 case Decl::FunctionTemplate:
5171 case Decl::LinkageSpec:
5172 case Decl::Namespace:
5173 case Decl::NamespaceAlias:
5174 case Decl::NonTypeTemplateParm:
5175 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005176 case Decl::TemplateTemplateParm:
5177 case Decl::TemplateTypeParm:
5178 case Decl::UnresolvedUsingTypename:
5179 case Decl::UnresolvedUsingValue:
5180 case Decl::Using:
5181 case Decl::UsingDirective:
5182 case Decl::UsingShadow:
5183 return CXLanguage_CPlusPlus;
5184 }
5185
5186 return CXLanguage_C;
5187}
5188
5189extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00005190
5191enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
5192 if (clang_isDeclaration(cursor.kind))
5193 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005194 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Douglas Gregor58ddb602010-08-23 23:00:57 +00005195 return CXAvailability_Available;
5196
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005197 switch (D->getAvailability()) {
5198 case AR_Available:
5199 case AR_NotYetIntroduced:
5200 return CXAvailability_Available;
5201
5202 case AR_Deprecated:
Douglas Gregor58ddb602010-08-23 23:00:57 +00005203 return CXAvailability_Deprecated;
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005204
5205 case AR_Unavailable:
5206 return CXAvailability_NotAvailable;
5207 }
Douglas Gregor58ddb602010-08-23 23:00:57 +00005208 }
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005209
Douglas Gregor58ddb602010-08-23 23:00:57 +00005210 return CXAvailability_Available;
5211}
5212
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005213CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
5214 if (clang_isDeclaration(cursor.kind))
5215 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
5216
5217 return CXLanguage_Invalid;
5218}
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005219
5220 /// \brief If the given cursor is the "templated" declaration
5221 /// descibing a class or function template, return the class or
5222 /// function template.
5223static Decl *maybeGetTemplateCursor(Decl *D) {
5224 if (!D)
5225 return 0;
5226
5227 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
5228 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
5229 return FunTmpl;
5230
5231 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
5232 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
5233 return ClassTmpl;
5234
5235 return D;
5236}
5237
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005238CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
5239 if (clang_isDeclaration(cursor.kind)) {
5240 if (Decl *D = getCursorDecl(cursor)) {
5241 DeclContext *DC = D->getDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005242 if (!DC)
5243 return clang_getNullCursor();
5244
5245 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5246 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005247 }
5248 }
5249
5250 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
5251 if (Decl *D = getCursorDecl(cursor))
Ted Kremeneka60ed472010-11-16 08:15:36 +00005252 return MakeCXCursor(D, getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005253 }
5254
5255 return clang_getNullCursor();
5256}
5257
5258CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
5259 if (clang_isDeclaration(cursor.kind)) {
5260 if (Decl *D = getCursorDecl(cursor)) {
5261 DeclContext *DC = D->getLexicalDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005262 if (!DC)
5263 return clang_getNullCursor();
5264
5265 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5266 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005267 }
5268 }
5269
5270 // FIXME: Note that we can't easily compute the lexical context of a
5271 // statement or expression, so we return nothing.
5272 return clang_getNullCursor();
5273}
5274
Douglas Gregor9f592342010-10-01 20:25:15 +00005275void clang_getOverriddenCursors(CXCursor cursor,
5276 CXCursor **overridden,
5277 unsigned *num_overridden) {
5278 if (overridden)
5279 *overridden = 0;
5280 if (num_overridden)
5281 *num_overridden = 0;
5282 if (!overridden || !num_overridden)
5283 return;
5284
Argyrios Kyrtzidisb11be042011-10-06 07:00:46 +00005285 SmallVector<CXCursor, 8> Overridden;
5286 cxcursor::getOverriddenCursors(cursor, Overridden);
Douglas Gregor9f592342010-10-01 20:25:15 +00005287
Ted Kremenek24077122011-11-14 23:51:37 +00005288 // Don't allocate memory if we have no overriden cursors.
5289 if (Overridden.size() == 0)
5290 return;
5291
Argyrios Kyrtzidisb11be042011-10-06 07:00:46 +00005292 *num_overridden = Overridden.size();
5293 *overridden = new CXCursor [Overridden.size()];
5294 std::copy(Overridden.begin(), Overridden.end(), *overridden);
Douglas Gregor9f592342010-10-01 20:25:15 +00005295}
5296
5297void clang_disposeOverriddenCursors(CXCursor *overridden) {
5298 delete [] overridden;
5299}
5300
Douglas Gregorecdcb882010-10-20 22:00:55 +00005301CXFile clang_getIncludedFile(CXCursor cursor) {
5302 if (cursor.kind != CXCursor_InclusionDirective)
5303 return 0;
5304
5305 InclusionDirective *ID = getCursorInclusionDirective(cursor);
5306 return (void *)ID->getFile();
5307}
5308
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005309} // end: extern "C"
5310
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005311
5312//===----------------------------------------------------------------------===//
5313// C++ AST instrospection.
5314//===----------------------------------------------------------------------===//
5315
5316extern "C" {
5317unsigned clang_CXXMethod_isStatic(CXCursor C) {
5318 if (!clang_isDeclaration(C.kind))
5319 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00005320
5321 CXXMethodDecl *Method = 0;
5322 Decl *D = cxcursor::getCursorDecl(C);
5323 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5324 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5325 else
5326 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5327 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00005328}
Ted Kremenekb12903e2010-05-18 22:32:15 +00005329
Douglas Gregor211924b2011-05-12 15:17:24 +00005330unsigned clang_CXXMethod_isVirtual(CXCursor C) {
5331 if (!clang_isDeclaration(C.kind))
5332 return 0;
5333
5334 CXXMethodDecl *Method = 0;
5335 Decl *D = cxcursor::getCursorDecl(C);
5336 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5337 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5338 else
5339 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5340 return (Method && Method->isVirtual()) ? 1 : 0;
5341}
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005342} // end: extern "C"
5343
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005344//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00005345// Attribute introspection.
5346//===----------------------------------------------------------------------===//
5347
5348extern "C" {
5349CXType clang_getIBOutletCollectionType(CXCursor C) {
5350 if (C.kind != CXCursor_IBOutletCollectionAttr)
Ted Kremeneka60ed472010-11-16 08:15:36 +00005351 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005352
5353 IBOutletCollectionAttr *A =
5354 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
5355
Argyrios Kyrtzidis18aa2ff2011-09-13 18:49:52 +00005356 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005357}
5358} // end: extern "C"
5359
5360//===----------------------------------------------------------------------===//
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005361// Inspecting memory usage.
5362//===----------------------------------------------------------------------===//
5363
Ted Kremenekf7870022011-04-20 16:41:07 +00005364typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005365
Ted Kremenekf7870022011-04-20 16:41:07 +00005366static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
5367 enum CXTUResourceUsageKind k,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005368 unsigned long amount) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005369 CXTUResourceUsageEntry entry = { k, amount };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005370 entries.push_back(entry);
5371}
5372
5373extern "C" {
5374
Ted Kremenekf7870022011-04-20 16:41:07 +00005375const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005376 const char *str = "";
5377 switch (kind) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005378 case CXTUResourceUsage_AST:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005379 str = "ASTContext: expressions, declarations, and types";
5380 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005381 case CXTUResourceUsage_Identifiers:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005382 str = "ASTContext: identifiers";
5383 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005384 case CXTUResourceUsage_Selectors:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005385 str = "ASTContext: selectors";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005386 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005387 case CXTUResourceUsage_GlobalCompletionResults:
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005388 str = "Code completion: cached global results";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005389 break;
Ted Kremenek457aaf02011-04-28 04:10:31 +00005390 case CXTUResourceUsage_SourceManagerContentCache:
5391 str = "SourceManager: content cache allocator";
5392 break;
Ted Kremenekba29bd22011-04-28 04:53:38 +00005393 case CXTUResourceUsage_AST_SideTables:
5394 str = "ASTContext: side tables";
5395 break;
Ted Kremenekf61b8312011-04-28 20:36:42 +00005396 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
5397 str = "SourceManager: malloc'ed memory buffers";
5398 break;
5399 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
5400 str = "SourceManager: mmap'ed memory buffers";
5401 break;
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005402 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
5403 str = "ExternalASTSource: malloc'ed memory buffers";
5404 break;
5405 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
5406 str = "ExternalASTSource: mmap'ed memory buffers";
5407 break;
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005408 case CXTUResourceUsage_Preprocessor:
5409 str = "Preprocessor: malloc'ed memory";
5410 break;
5411 case CXTUResourceUsage_PreprocessingRecord:
5412 str = "Preprocessor: PreprocessingRecord";
5413 break;
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005414 case CXTUResourceUsage_SourceManager_DataStructures:
5415 str = "SourceManager: data structures and tables";
5416 break;
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005417 case CXTUResourceUsage_Preprocessor_HeaderSearch:
5418 str = "Preprocessor: header search tables";
5419 break;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005420 }
5421 return str;
5422}
5423
Ted Kremenekf7870022011-04-20 16:41:07 +00005424CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005425 if (!TU) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005426 CXTUResourceUsage usage = { (void*) 0, 0, 0 };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005427 return usage;
5428 }
5429
5430 ASTUnit *astUnit = static_cast<ASTUnit*>(TU->TUData);
5431 llvm::OwningPtr<MemUsageEntries> entries(new MemUsageEntries());
5432 ASTContext &astContext = astUnit->getASTContext();
5433
5434 // How much memory is used by AST nodes and types?
Ted Kremenekf7870022011-04-20 16:41:07 +00005435 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005436 (unsigned long) astContext.getASTAllocatedMemory());
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005437
5438 // How much memory is used by identifiers?
Ted Kremenekf7870022011-04-20 16:41:07 +00005439 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005440 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
5441
5442 // How much memory is used for selectors?
Ted Kremenekf7870022011-04-20 16:41:07 +00005443 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005444 (unsigned long) astContext.Selectors.getTotalMemory());
5445
Ted Kremenekba29bd22011-04-28 04:53:38 +00005446 // How much memory is used by ASTContext's side tables?
5447 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
5448 (unsigned long) astContext.getSideTableAllocatedMemory());
5449
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005450 // How much memory is used for caching global code completion results?
5451 unsigned long completionBytes = 0;
5452 if (GlobalCodeCompletionAllocator *completionAllocator =
5453 astUnit->getCachedCompletionAllocator().getPtr()) {
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005454 completionBytes = completionAllocator->getTotalMemory();
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005455 }
Ted Kremenek457aaf02011-04-28 04:10:31 +00005456 createCXTUResourceUsageEntry(*entries,
5457 CXTUResourceUsage_GlobalCompletionResults,
5458 completionBytes);
5459
5460 // How much memory is being used by SourceManager's content cache?
5461 createCXTUResourceUsageEntry(*entries,
5462 CXTUResourceUsage_SourceManagerContentCache,
5463 (unsigned long) astContext.getSourceManager().getContentCacheSize());
Ted Kremenekf61b8312011-04-28 20:36:42 +00005464
5465 // How much memory is being used by the MemoryBuffer's in SourceManager?
5466 const SourceManager::MemoryBufferSizes &srcBufs =
5467 astUnit->getSourceManager().getMemoryBufferSizes();
5468
5469 createCXTUResourceUsageEntry(*entries,
5470 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
5471 (unsigned long) srcBufs.malloc_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005472 createCXTUResourceUsageEntry(*entries,
Ted Kremenekf61b8312011-04-28 20:36:42 +00005473 CXTUResourceUsage_SourceManager_Membuffer_MMap,
5474 (unsigned long) srcBufs.mmap_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005475 createCXTUResourceUsageEntry(*entries,
5476 CXTUResourceUsage_SourceManager_DataStructures,
5477 (unsigned long) astContext.getSourceManager()
5478 .getDataStructureSizes());
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005479
5480 // How much memory is being used by the ExternalASTSource?
5481 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
5482 const ExternalASTSource::MemoryBufferSizes &sizes =
5483 esrc->getMemoryBufferSizes();
5484
5485 createCXTUResourceUsageEntry(*entries,
5486 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
5487 (unsigned long) sizes.malloc_bytes);
5488 createCXTUResourceUsageEntry(*entries,
5489 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
5490 (unsigned long) sizes.mmap_bytes);
5491 }
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005492
5493 // How much memory is being used by the Preprocessor?
5494 Preprocessor &pp = astUnit->getPreprocessor();
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005495 createCXTUResourceUsageEntry(*entries,
5496 CXTUResourceUsage_Preprocessor,
Argyrios Kyrtzidisc5c5e922011-06-29 22:20:04 +00005497 pp.getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005498
5499 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
5500 createCXTUResourceUsageEntry(*entries,
5501 CXTUResourceUsage_PreprocessingRecord,
5502 pRec->getTotalMemory());
5503 }
5504
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005505 createCXTUResourceUsageEntry(*entries,
5506 CXTUResourceUsage_Preprocessor_HeaderSearch,
5507 pp.getHeaderSearchInfo().getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005508
Ted Kremenekf7870022011-04-20 16:41:07 +00005509 CXTUResourceUsage usage = { (void*) entries.get(),
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005510 (unsigned) entries->size(),
5511 entries->size() ? &(*entries)[0] : 0 };
5512 entries.take();
5513 return usage;
5514}
5515
Ted Kremenekf7870022011-04-20 16:41:07 +00005516void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005517 if (usage.data)
5518 delete (MemUsageEntries*) usage.data;
5519}
5520
5521} // end extern "C"
5522
Douglas Gregor6df78732011-05-05 20:27:22 +00005523void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
5524 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
5525 for (unsigned I = 0; I != Usage.numEntries; ++I)
5526 fprintf(stderr, " %s: %lu\n",
5527 clang_getTUResourceUsageName(Usage.entries[I].kind),
5528 Usage.entries[I].amount);
5529
5530 clang_disposeCXTUResourceUsage(Usage);
5531}
5532
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005533//===----------------------------------------------------------------------===//
Ted Kremenek04bb7162010-01-22 22:44:15 +00005534// Misc. utility functions.
5535//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00005536
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00005537/// Default to using an 8 MB stack size on "safety" threads.
5538static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005539
5540namespace clang {
5541
5542bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005543 void (*Fn)(void*), void *UserData,
5544 unsigned Size) {
5545 if (!Size)
5546 Size = GetSafetyThreadStackSize();
5547 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005548 return CRC.RunSafelyOnThread(Fn, UserData, Size);
5549 return CRC.RunSafely(Fn, UserData);
5550}
5551
5552unsigned GetSafetyThreadStackSize() {
5553 return SafetyStackThreadSize;
5554}
5555
5556void SetSafetyThreadStackSize(unsigned Value) {
5557 SafetyStackThreadSize = Value;
5558}
5559
5560}
5561
Ted Kremenek04bb7162010-01-22 22:44:15 +00005562extern "C" {
5563
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00005564CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00005565 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00005566}
5567
5568} // end: extern "C"
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005569