blob: e9a67dbfb5b77161ec5bb5e21bc914474aca668e [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
Argyrios Kyrtzidisb49e7282011-11-29 03:14:11 +0000229 if (!VisitDeclsOnly && !VisitPreprocessorLast)
230 if (visitPreprocessedEntitiesInRegion())
231 return; // visitation break.
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000232
233 visitDeclsFromFileRegion(File, Offset, Length);
234
Argyrios Kyrtzidisb49e7282011-11-29 03:14:11 +0000235 if (!VisitDeclsOnly && VisitPreprocessorLast)
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000236 visitPreprocessedEntitiesInRegion();
237}
238
Argyrios Kyrtzidise2079cf2011-11-16 08:58:54 +0000239static bool isInLexicalContext(Decl *D, DeclContext *DC) {
240 if (!DC)
241 return false;
242
243 for (DeclContext *DeclDC = D->getLexicalDeclContext();
244 DeclDC; DeclDC = DeclDC->getLexicalParent()) {
245 if (DeclDC == DC)
246 return true;
247 }
248 return false;
249}
250
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000251void CursorVisitor::visitDeclsFromFileRegion(FileID File,
252 unsigned Offset, unsigned Length) {
253 ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData);
254 SourceManager &SM = Unit->getSourceManager();
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000255 SourceRange Range = RegionOfInterest;
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000256
257 SmallVector<Decl *, 16> Decls;
258 Unit->findFileRegionDecls(File, Offset, Length, Decls);
259
260 // If we didn't find any file level decls for the file, try looking at the
261 // file that it was included from.
Argyrios Kyrtzidisc14a03d2011-11-23 20:27:36 +0000262 while (Decls.empty() || Decls.front()->isTopLevelDeclInObjCContainer()) {
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000263 bool Invalid = false;
264 const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid);
265 if (Invalid)
266 return;
267
268 SourceLocation Outer;
269 if (SLEntry.isFile())
270 Outer = SLEntry.getFile().getIncludeLoc();
271 else
272 Outer = SLEntry.getExpansion().getExpansionLocStart();
273 if (Outer.isInvalid())
274 return;
275
276 llvm::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer);
277 Length = 0;
278 Unit->findFileRegionDecls(File, Offset, Length, Decls);
279 }
280
281 assert(!Decls.empty());
282
283 bool VisitedAtLeastOnce = false;
Argyrios Kyrtzidise2079cf2011-11-16 08:58:54 +0000284 DeclContext *CurDC = 0;
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000285 SmallVector<Decl *, 16>::iterator DIt = Decls.begin();
286 for (SmallVector<Decl *, 16>::iterator DE = Decls.end(); DIt != DE; ++DIt) {
287 Decl *D = *DIt;
Argyrios Kyrtzidised8bef42011-11-28 22:38:07 +0000288 if (D->getSourceRange().isInvalid())
289 continue;
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000290
Argyrios Kyrtzidise2079cf2011-11-16 08:58:54 +0000291 if (isInLexicalContext(D, CurDC))
292 continue;
293
294 CurDC = dyn_cast<DeclContext>(D);
295
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000296 // We handle forward decls via ObjCClassDecl.
297 if (ObjCInterfaceDecl *InterD = dyn_cast<ObjCInterfaceDecl>(D)) {
298 if (InterD->isForwardDecl())
299 continue;
300 // An interface that started as a forward decl may have changed location
301 // because its @interface was parsed.
302 if (InterD->isInitiallyForwardDecl() &&
303 !SM.isInFileID(SM.getFileLoc(InterD->getLocation()), File))
304 continue;
305 }
306
Argyrios Kyrtzidise2079cf2011-11-16 08:58:54 +0000307 if (TagDecl *TD = dyn_cast<TagDecl>(D))
308 if (!TD->isFreeStanding())
309 continue;
310
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000311 RangeComparisonResult CompRes = RangeCompare(SM, D->getSourceRange(),Range);
312 if (CompRes == RangeBefore)
313 continue;
314 if (CompRes == RangeAfter)
315 break;
316
317 assert(CompRes == RangeOverlap);
318 VisitedAtLeastOnce = true;
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +0000319
320 if (isa<ObjCContainerDecl>(D)) {
321 FileDI_current = &DIt;
322 FileDE_current = DE;
323 } else {
324 FileDI_current = 0;
325 }
326
Argyrios Kyrtzidisba986172011-11-03 19:02:28 +0000327 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000328 break;
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000329 }
330
331 if (VisitedAtLeastOnce)
332 return;
333
334 // No Decls overlapped with the range. Move up the lexical context until there
335 // is a context that contains the range or we reach the translation unit
336 // level.
337 DeclContext *DC = DIt == Decls.begin() ? (*DIt)->getLexicalDeclContext()
338 : (*(DIt-1))->getLexicalDeclContext();
339
340 while (DC && !DC->isTranslationUnit()) {
341 Decl *D = cast<Decl>(DC);
342 SourceRange CurDeclRange = D->getSourceRange();
343 if (CurDeclRange.isInvalid())
344 break;
345
346 if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) {
Argyrios Kyrtzidisba986172011-11-03 19:02:28 +0000347 Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true);
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000348 break;
349 }
350
351 DC = D->getLexicalDeclContext();
352 }
353}
354
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000355bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
Argyrios Kyrtzidisb49e7282011-11-29 03:14:11 +0000356 if (!AU->getPreprocessor().getPreprocessingRecord())
357 return false;
358
Douglas Gregor788f5a12010-03-20 00:41:21 +0000359 PreprocessingRecord &PPRec
Ted Kremeneka60ed472010-11-16 08:15:36 +0000360 = *AU->getPreprocessor().getPreprocessingRecord();
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000361 SourceManager &SM = AU->getSourceManager();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000362
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000363 if (RegionOfInterest.isValid()) {
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +0000364 SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000365 SourceLocation B = MappedRange.getBegin();
366 SourceLocation E = MappedRange.getEnd();
367
368 if (AU->isInPreambleFileID(B)) {
369 if (SM.isLoadedSourceLocation(E))
370 return visitPreprocessedEntitiesInRange(SourceRange(B, E),
371 PPRec, *this);
372
373 // Beginning of range lies in the preamble but it also extends beyond
374 // it into the main file. Split the range into 2 parts, one covering
375 // the preamble and another covering the main file. This allows subsequent
376 // calls to visitPreprocessedEntitiesInRange to accept a source range that
377 // lies in the same FileID, allowing it to skip preprocessed entities that
378 // do not come from the same FileID.
379 bool breaked =
380 visitPreprocessedEntitiesInRange(
381 SourceRange(B, AU->getEndOfPreambleFileID()),
382 PPRec, *this);
383 if (breaked) return true;
384 return visitPreprocessedEntitiesInRange(
385 SourceRange(AU->getStartOfMainFileID(), E),
386 PPRec, *this);
387 }
388
389 return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this);
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000390 }
391
Douglas Gregor788f5a12010-03-20 00:41:21 +0000392 bool OnlyLocalDecls
Douglas Gregor32038bb2010-12-21 19:07:48 +0000393 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
394
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000395 if (OnlyLocalDecls)
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000396 return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(),
397 PPRec);
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000398
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000399 return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec);
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000400}
401
402template<typename InputIterator>
403bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000404 InputIterator Last,
405 PreprocessingRecord &PPRec,
406 FileID FID) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000407 for (; First != Last; ++First) {
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000408 if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID))
409 continue;
410
411 PreprocessedEntity *PPE = *First;
412 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000413 if (Visit(MakeMacroExpansionCursor(ME, TU)))
414 return true;
415
416 continue;
417 }
418
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000419 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(PPE)) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000420 if (Visit(MakeMacroDefinitionCursor(MD, TU)))
421 return true;
422
423 continue;
424 }
425
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000426 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000427 if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
428 return true;
429
430 continue;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000431 }
432 }
433
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000434 return false;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000435}
436
Douglas Gregorb1373d02010-01-20 20:59:29 +0000437/// \brief Visit the children of the given cursor.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000438///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000439/// \returns true if the visitation should be aborted, false if it
440/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000441bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregorc314aa42011-03-02 19:17:03 +0000442 if (clang_isReference(Cursor.kind) &&
443 Cursor.kind != CXCursor_CXXBaseSpecifier) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000444 // By definition, references have no children.
445 return false;
446 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000447
448 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000449 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000450 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000451
Douglas Gregorb1373d02010-01-20 20:59:29 +0000452 if (clang_isDeclaration(Cursor.kind)) {
453 Decl *D = getCursorDecl(Cursor);
Douglas Gregor06d9b1a2011-04-14 21:41:34 +0000454 if (!D)
455 return false;
456
Ted Kremenek539311e2010-02-18 18:47:01 +0000457 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000458 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000459
Douglas Gregor06d9b1a2011-04-14 21:41:34 +0000460 if (clang_isStatement(Cursor.kind)) {
461 if (Stmt *S = getCursorStmt(Cursor))
462 return Visit(S);
463
464 return false;
465 }
466
467 if (clang_isExpression(Cursor.kind)) {
468 if (Expr *E = getCursorExpr(Cursor))
469 return Visit(E);
470
471 return false;
472 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000473
Douglas Gregorb1373d02010-01-20 20:59:29 +0000474 if (clang_isTranslationUnit(Cursor.kind)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000475 CXTranslationUnit tu = getCursorTU(Cursor);
476 ASTUnit *CXXUnit = static_cast<ASTUnit*>(tu->TUData);
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000477
478 int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
479 for (unsigned I = 0; I != 2; ++I) {
480 if (VisitOrder[I]) {
481 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
482 RegionOfInterest.isInvalid()) {
483 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
484 TLEnd = CXXUnit->top_level_end();
485 TL != TLEnd; ++TL) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000486 if (Visit(MakeCXCursor(*TL, tu, RegionOfInterest), true))
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000487 return true;
488 }
489 } else if (VisitDeclContext(
490 CXXUnit->getASTContext().getTranslationUnitDecl()))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000491 return true;
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000492 continue;
Douglas Gregor7b691f332010-01-20 21:13:59 +0000493 }
Bob Wilson3178cb62010-03-19 03:57:57 +0000494
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000495 // Walk the preprocessing record.
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000496 if (CXXUnit->getPreprocessor().getPreprocessingRecord())
497 visitPreprocessedEntitiesInRegion();
Douglas Gregor0396f462010-03-19 05:22:59 +0000498 }
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000499
Douglas Gregor7b691f332010-01-20 21:13:59 +0000500 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000501 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000502
Douglas Gregorc314aa42011-03-02 19:17:03 +0000503 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
504 if (CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
505 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
506 return Visit(BaseTSInfo->getTypeLoc());
507 }
508 }
509 }
Argyrios Kyrtzidis221d5a52011-09-13 18:49:56 +0000510
511 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
512 IBOutletCollectionAttr *A =
513 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
514 if (const ObjCInterfaceType *InterT = A->getInterface()->getAs<ObjCInterfaceType>())
515 return Visit(cxcursor::MakeCursorObjCClassRef(InterT->getInterface(),
516 A->getInterfaceLoc(), TU));
517 }
518
Douglas Gregorb1373d02010-01-20 20:59:29 +0000519 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000520 return false;
521}
522
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000523bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
Douglas Gregor13c8ccb2011-04-22 23:49:24 +0000524 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
525 if (Visit(TSInfo->getTypeLoc()))
526 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000527
Ted Kremenek664cffd2010-07-22 11:30:19 +0000528 if (Stmt *Body = B->getBody())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000529 return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest));
Ted Kremenek664cffd2010-07-22 11:30:19 +0000530
531 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000532}
533
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000534llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
535 if (RegionOfInterest.isValid()) {
Douglas Gregor66537982010-11-17 17:14:07 +0000536 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000537 if (Range.isInvalid())
538 return llvm::Optional<bool>();
Douglas Gregor66537982010-11-17 17:14:07 +0000539
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000540 switch (CompareRegionOfInterest(Range)) {
541 case RangeBefore:
542 // This declaration comes before the region of interest; skip it.
543 return llvm::Optional<bool>();
544
545 case RangeAfter:
546 // This declaration comes after the region of interest; we're done.
547 return false;
548
549 case RangeOverlap:
550 // This declaration overlaps the region of interest; visit it.
551 break;
552 }
553 }
554 return true;
555}
556
557bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
558 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
559
560 // FIXME: Eventually remove. This part of a hack to support proper
561 // iteration over all Decls contained lexically within an ObjC container.
562 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
563 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
564
565 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000566 Decl *D = *I;
567 if (D->getLexicalDeclContext() != DC)
568 continue;
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000569 CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000570 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
571 if (!V.hasValue())
572 continue;
573 if (!V.getValue())
574 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000575 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000576 return true;
577 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000578 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000579}
580
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000581bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
582 llvm_unreachable("Translation units are visited directly by Visit()");
583 return false;
584}
585
Richard Smith162e1c12011-04-15 14:24:37 +0000586bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
587 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
588 return Visit(TSInfo->getTypeLoc());
589
590 return false;
591}
592
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000593bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
594 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
595 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000596
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000597 return false;
598}
599
600bool CursorVisitor::VisitTagDecl(TagDecl *D) {
601 return VisitDeclContext(D);
602}
603
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000604bool CursorVisitor::VisitClassTemplateSpecializationDecl(
605 ClassTemplateSpecializationDecl *D) {
606 bool ShouldVisitBody = false;
607 switch (D->getSpecializationKind()) {
608 case TSK_Undeclared:
609 case TSK_ImplicitInstantiation:
610 // Nothing to visit
611 return false;
612
613 case TSK_ExplicitInstantiationDeclaration:
614 case TSK_ExplicitInstantiationDefinition:
615 break;
616
617 case TSK_ExplicitSpecialization:
618 ShouldVisitBody = true;
619 break;
620 }
621
622 // Visit the template arguments used in the specialization.
623 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
624 TypeLoc TL = SpecType->getTypeLoc();
625 if (TemplateSpecializationTypeLoc *TSTLoc
626 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
627 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
628 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
629 return true;
630 }
631 }
632
633 if (ShouldVisitBody && VisitCXXRecordDecl(D))
634 return true;
635
636 return false;
637}
638
Douglas Gregor74dbe642010-08-31 19:31:58 +0000639bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
640 ClassTemplatePartialSpecializationDecl *D) {
641 // FIXME: Visit the "outer" template parameter lists on the TagDecl
642 // before visiting these template parameters.
643 if (VisitTemplateParameters(D->getTemplateParameters()))
644 return true;
645
646 // Visit the partial specialization arguments.
647 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
648 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
649 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
650 return true;
651
652 return VisitCXXRecordDecl(D);
653}
654
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000655bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000656 // Visit the default argument.
657 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
658 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
659 if (Visit(DefArg->getTypeLoc()))
660 return true;
661
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000662 return false;
663}
664
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000665bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
666 if (Expr *Init = D->getInitExpr())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000667 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000668 return false;
669}
670
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000671bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
672 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
673 if (Visit(TSInfo->getTypeLoc()))
674 return true;
675
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000676 // Visit the nested-name-specifier, if present.
677 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
678 if (VisitNestedNameSpecifierLoc(QualifierLoc))
679 return true;
680
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000681 return false;
682}
683
Douglas Gregora67e03f2010-09-09 21:42:20 +0000684/// \brief Compare two base or member initializers based on their source order.
Sean Huntcbb67482011-01-08 20:30:50 +0000685static int CompareCXXCtorInitializers(const void* Xp, const void *Yp) {
686 CXXCtorInitializer const * const *X
687 = static_cast<CXXCtorInitializer const * const *>(Xp);
688 CXXCtorInitializer const * const *Y
689 = static_cast<CXXCtorInitializer const * const *>(Yp);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000690
691 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
692 return -1;
693 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
694 return 1;
695 else
696 return 0;
697}
698
Douglas Gregorb1373d02010-01-20 20:59:29 +0000699bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000700 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
701 // Visit the function declaration's syntactic components in the order
702 // written. This requires a bit of work.
Abramo Bagnara723df242010-12-14 22:11:44 +0000703 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
Douglas Gregor01829d32010-08-31 14:41:23 +0000704 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
705
706 // If we have a function declared directly (without the use of a typedef),
707 // visit just the return type. Otherwise, just visit the function's type
708 // now.
709 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
710 (!FTL && Visit(TL)))
711 return true;
712
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000713 // Visit the nested-name-specifier, if present.
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000714 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
715 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000716 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000717
718 // Visit the declaration name.
719 if (VisitDeclarationNameInfo(ND->getNameInfo()))
720 return true;
721
722 // FIXME: Visit explicitly-specified template arguments!
723
724 // Visit the function parameters, if we have a function type.
725 if (FTL && VisitFunctionTypeLoc(*FTL, true))
726 return true;
727
728 // FIXME: Attributes?
729 }
730
Sean Hunt10620eb2011-05-06 20:44:56 +0000731 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
Douglas Gregora67e03f2010-09-09 21:42:20 +0000732 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
733 // Find the initializers that were written in the source.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000734 SmallVector<CXXCtorInitializer *, 4> WrittenInits;
Douglas Gregora67e03f2010-09-09 21:42:20 +0000735 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
736 IEnd = Constructor->init_end();
737 I != IEnd; ++I) {
738 if (!(*I)->isWritten())
739 continue;
740
741 WrittenInits.push_back(*I);
742 }
743
744 // Sort the initializers in source order
745 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
Sean Huntcbb67482011-01-08 20:30:50 +0000746 &CompareCXXCtorInitializers);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000747
748 // Visit the initializers in source order
749 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
Sean Huntcbb67482011-01-08 20:30:50 +0000750 CXXCtorInitializer *Init = WrittenInits[I];
Francois Pichet00eb3f92010-12-04 09:14:42 +0000751 if (Init->isAnyMemberInitializer()) {
752 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
Douglas Gregora67e03f2010-09-09 21:42:20 +0000753 Init->getMemberLocation(), TU)))
754 return true;
Douglas Gregor76852c22011-11-01 01:16:03 +0000755 } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) {
756 if (Visit(TInfo->getTypeLoc()))
Douglas Gregora67e03f2010-09-09 21:42:20 +0000757 return true;
758 }
759
760 // Visit the initializer value.
761 if (Expr *Initializer = Init->getInit())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000762 if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
Douglas Gregora67e03f2010-09-09 21:42:20 +0000763 return true;
764 }
765 }
766
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000767 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
Douglas Gregora67e03f2010-09-09 21:42:20 +0000768 return true;
769 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000770
Douglas Gregorb1373d02010-01-20 20:59:29 +0000771 return false;
772}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000773
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000774bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
775 if (VisitDeclaratorDecl(D))
776 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000777
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000778 if (Expr *BitWidth = D->getBitWidth())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000779 return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000780
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000781 return false;
782}
783
784bool CursorVisitor::VisitVarDecl(VarDecl *D) {
785 if (VisitDeclaratorDecl(D))
786 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000787
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000788 if (Expr *Init = D->getInit())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000789 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000790
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000791 return false;
792}
793
Douglas Gregor84b51d72010-09-01 20:16:53 +0000794bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
795 if (VisitDeclaratorDecl(D))
796 return true;
797
798 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
799 if (Expr *DefArg = D->getDefaultArgument())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000800 return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
Douglas Gregor84b51d72010-09-01 20:16:53 +0000801
802 return false;
803}
804
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000805bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
806 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
807 // before visiting these template parameters.
808 if (VisitTemplateParameters(D->getTemplateParameters()))
809 return true;
810
811 return VisitFunctionDecl(D->getTemplatedDecl());
812}
813
Douglas Gregor39d6f072010-08-31 19:02:00 +0000814bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
815 // FIXME: Visit the "outer" template parameter lists on the TagDecl
816 // before visiting these template parameters.
817 if (VisitTemplateParameters(D->getTemplateParameters()))
818 return true;
819
820 return VisitCXXRecordDecl(D->getTemplatedDecl());
821}
822
Douglas Gregor84b51d72010-09-01 20:16:53 +0000823bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
824 if (VisitTemplateParameters(D->getTemplateParameters()))
825 return true;
826
827 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
828 VisitTemplateArgumentLoc(D->getDefaultArgument()))
829 return true;
830
831 return false;
832}
833
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000834bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000835 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
836 if (Visit(TSInfo->getTypeLoc()))
837 return true;
838
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000839 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000840 PEnd = ND->param_end();
841 P != PEnd; ++P) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000842 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000843 return true;
844 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000845
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000846 if (ND->isThisDeclarationADefinition() &&
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000847 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000848 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000849
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000850 return false;
851}
852
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +0000853template <typename DeclIt>
854static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current,
855 SourceManager &SM, SourceLocation EndLoc,
856 SmallVectorImpl<Decl *> &Decls) {
857 DeclIt next = *DI_current;
858 while (++next != DE_current) {
859 Decl *D_next = *next;
860 if (!D_next)
861 break;
862 SourceLocation L = D_next->getLocStart();
863 if (!L.isValid())
864 break;
865 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
866 *DI_current = next;
867 Decls.push_back(D_next);
868 continue;
869 }
870 break;
871 }
872}
873
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000874namespace {
875 struct ContainerDeclsSort {
876 SourceManager &SM;
877 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
878 bool operator()(Decl *A, Decl *B) {
879 SourceLocation L_A = A->getLocStart();
880 SourceLocation L_B = B->getLocStart();
881 assert(L_A.isValid() && L_B.isValid());
882 return SM.isBeforeInTranslationUnit(L_A, L_B);
883 }
884 };
885}
886
Douglas Gregora59e3902010-01-21 23:27:09 +0000887bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000888 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
889 // an @implementation can lexically contain Decls that are not properly
890 // nested in the AST. When we identify such cases, we need to retrofit
891 // this nesting here.
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +0000892 if (!DI_current && !FileDI_current)
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000893 return VisitDeclContext(D);
894
895 // Scan the Decls that immediately come after the container
896 // in the current DeclContext. If any fall within the
897 // container's lexical region, stash them into a vector
898 // for later processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000899 SmallVector<Decl *, 24> DeclsInContainer;
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000900 SourceLocation EndLoc = D->getSourceRange().getEnd();
Ted Kremeneka60ed472010-11-16 08:15:36 +0000901 SourceManager &SM = AU->getSourceManager();
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000902 if (EndLoc.isValid()) {
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +0000903 if (DI_current) {
904 addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc,
905 DeclsInContainer);
906 } else {
907 addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc,
908 DeclsInContainer);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000909 }
910 }
911
912 // The common case.
913 if (DeclsInContainer.empty())
914 return VisitDeclContext(D);
915
916 // Get all the Decls in the DeclContext, and sort them with the
917 // additional ones we've collected. Then visit them.
918 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
919 I!=E; ++I) {
920 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000921 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
922 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000923 continue;
924 DeclsInContainer.push_back(subDecl);
925 }
926
927 // Now sort the Decls so that they appear in lexical order.
928 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
929 ContainerDeclsSort(SM));
930
931 // Now visit the decls.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000932 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000933 E = DeclsInContainer.end(); I != E; ++I) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000934 CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000935 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
936 if (!V.hasValue())
937 continue;
938 if (!V.getValue())
939 return false;
940 if (Visit(Cursor, true))
941 return true;
942 }
943 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000944}
945
Douglas Gregorb1373d02010-01-20 20:59:29 +0000946bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000947 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
948 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000949 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000950
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000951 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
952 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
953 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000954 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000955 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000956
Douglas Gregora59e3902010-01-21 23:27:09 +0000957 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000958}
959
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000960bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
961 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
962 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
963 E = PID->protocol_end(); I != E; ++I, ++PL)
964 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
965 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000966
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000967 return VisitObjCContainerDecl(PID);
968}
969
Ted Kremenek23173d72010-05-18 21:09:07 +0000970bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000971 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000972 return true;
973
Ted Kremenek23173d72010-05-18 21:09:07 +0000974 // FIXME: This implements a workaround with @property declarations also being
975 // installed in the DeclContext for the @interface. Eventually this code
976 // should be removed.
977 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
978 if (!CDecl || !CDecl->IsClassExtension())
979 return false;
980
981 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
982 if (!ID)
983 return false;
984
985 IdentifierInfo *PropertyId = PD->getIdentifier();
986 ObjCPropertyDecl *prevDecl =
987 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
988
989 if (!prevDecl)
990 return false;
991
992 // Visit synthesized methods since they will be skipped when visiting
993 // the @interface.
994 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000995 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000996 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
Ted Kremenek23173d72010-05-18 21:09:07 +0000997 return true;
998
999 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +00001000 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001001 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
Ted Kremenek23173d72010-05-18 21:09:07 +00001002 return true;
1003
1004 return false;
1005}
1006
Douglas Gregorb1373d02010-01-20 20:59:29 +00001007bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001008 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +00001009 if (D->getSuperClass() &&
1010 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001011 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001012 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001013 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001014
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001015 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1016 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1017 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001018 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001019 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001020
Douglas Gregora59e3902010-01-21 23:27:09 +00001021 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001022}
1023
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001024bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1025 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001026}
1027
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001028bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +00001029 // 'ID' could be null when dealing with invalid code.
1030 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1031 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1032 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001033
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001034 return VisitObjCImplDecl(D);
1035}
1036
1037bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1038#if 0
1039 // Issue callbacks for super class.
1040 // FIXME: No source location information!
1041 if (D->getSuperClass() &&
1042 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001043 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001044 TU)))
1045 return true;
1046#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001047
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001048 return VisitObjCImplDecl(D);
1049}
1050
1051bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1052 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1053 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1054 E = D->protocol_end();
1055 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001056 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001057 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001058
1059 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001060}
1061
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001062bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00001063 if (Visit(MakeCursorObjCClassRef(D->getForwardInterfaceDecl(),
1064 D->getForwardDecl()->getLocation(), TU)))
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001065 return true;
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001066 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001067}
1068
Douglas Gregora4ffd852010-11-17 01:03:52 +00001069bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1070 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1071 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1072
1073 return false;
1074}
1075
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001076bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1077 return VisitDeclContext(D);
1078}
1079
Douglas Gregor69319002010-08-31 23:48:11 +00001080bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001081 // Visit nested-name-specifier.
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00001082 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1083 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001084 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001085
1086 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1087 D->getTargetNameLoc(), TU));
1088}
1089
Douglas Gregor7e242562010-09-01 19:52:22 +00001090bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001091 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001092 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1093 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001094 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001095 }
Douglas Gregor7e242562010-09-01 19:52:22 +00001096
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001097 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1098 return true;
1099
Douglas Gregor7e242562010-09-01 19:52:22 +00001100 return VisitDeclarationNameInfo(D->getNameInfo());
1101}
1102
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001103bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001104 // Visit nested-name-specifier.
Douglas Gregordb992412011-02-25 16:33:46 +00001105 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1106 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001107 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001108
1109 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1110 D->getIdentLocation(), TU));
1111}
1112
Douglas Gregor7e242562010-09-01 19:52:22 +00001113bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001114 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001115 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1116 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001117 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001118 }
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001119
Douglas Gregor7e242562010-09-01 19:52:22 +00001120 return VisitDeclarationNameInfo(D->getNameInfo());
1121}
1122
1123bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1124 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001125 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001126 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1127 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001128 return true;
1129
Douglas Gregor7e242562010-09-01 19:52:22 +00001130 return false;
1131}
1132
Douglas Gregor01829d32010-08-31 14:41:23 +00001133bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1134 switch (Name.getName().getNameKind()) {
1135 case clang::DeclarationName::Identifier:
1136 case clang::DeclarationName::CXXLiteralOperatorName:
1137 case clang::DeclarationName::CXXOperatorName:
1138 case clang::DeclarationName::CXXUsingDirective:
1139 return false;
1140
1141 case clang::DeclarationName::CXXConstructorName:
1142 case clang::DeclarationName::CXXDestructorName:
1143 case clang::DeclarationName::CXXConversionFunctionName:
1144 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1145 return Visit(TSInfo->getTypeLoc());
1146 return false;
1147
1148 case clang::DeclarationName::ObjCZeroArgSelector:
1149 case clang::DeclarationName::ObjCOneArgSelector:
1150 case clang::DeclarationName::ObjCMultiArgSelector:
1151 // FIXME: Per-identifier location info?
1152 return false;
1153 }
1154
1155 return false;
1156}
1157
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001158bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1159 SourceRange Range) {
1160 // FIXME: This whole routine is a hack to work around the lack of proper
1161 // source information in nested-name-specifiers (PR5791). Since we do have
1162 // a beginning source location, we can visit the first component of the
1163 // nested-name-specifier, if it's a single-token component.
1164 if (!NNS)
1165 return false;
1166
1167 // Get the first component in the nested-name-specifier.
1168 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1169 NNS = Prefix;
1170
1171 switch (NNS->getKind()) {
1172 case NestedNameSpecifier::Namespace:
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001173 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1174 TU));
1175
Douglas Gregor14aba762011-02-24 02:36:08 +00001176 case NestedNameSpecifier::NamespaceAlias:
1177 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1178 Range.getBegin(), TU));
1179
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001180 case NestedNameSpecifier::TypeSpec: {
1181 // If the type has a form where we know that the beginning of the source
1182 // range matches up with a reference cursor. Visit the appropriate reference
1183 // cursor.
John McCallf4c73712011-01-19 06:33:43 +00001184 const Type *T = NNS->getAsType();
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001185 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1186 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1187 if (const TagType *Tag = dyn_cast<TagType>(T))
1188 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1189 if (const TemplateSpecializationType *TST
1190 = dyn_cast<TemplateSpecializationType>(T))
1191 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1192 break;
1193 }
1194
1195 case NestedNameSpecifier::TypeSpecWithTemplate:
1196 case NestedNameSpecifier::Global:
1197 case NestedNameSpecifier::Identifier:
1198 break;
1199 }
1200
1201 return false;
1202}
1203
Douglas Gregordc355712011-02-25 00:36:19 +00001204bool
1205CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001206 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
Douglas Gregordc355712011-02-25 00:36:19 +00001207 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1208 Qualifiers.push_back(Qualifier);
1209
1210 while (!Qualifiers.empty()) {
1211 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1212 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1213 switch (NNS->getKind()) {
1214 case NestedNameSpecifier::Namespace:
1215 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001216 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001217 TU)))
1218 return true;
1219
1220 break;
1221
1222 case NestedNameSpecifier::NamespaceAlias:
1223 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001224 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001225 TU)))
1226 return true;
1227
1228 break;
1229
1230 case NestedNameSpecifier::TypeSpec:
1231 case NestedNameSpecifier::TypeSpecWithTemplate:
1232 if (Visit(Q.getTypeLoc()))
1233 return true;
1234
1235 break;
1236
1237 case NestedNameSpecifier::Global:
1238 case NestedNameSpecifier::Identifier:
1239 break;
1240 }
1241 }
1242
1243 return false;
1244}
1245
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001246bool CursorVisitor::VisitTemplateParameters(
1247 const TemplateParameterList *Params) {
1248 if (!Params)
1249 return false;
1250
1251 for (TemplateParameterList::const_iterator P = Params->begin(),
1252 PEnd = Params->end();
1253 P != PEnd; ++P) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001254 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001255 return true;
1256 }
1257
1258 return false;
1259}
1260
Douglas Gregor0b36e612010-08-31 20:37:03 +00001261bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1262 switch (Name.getKind()) {
1263 case TemplateName::Template:
1264 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1265
1266 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001267 // Visit the overloaded template set.
1268 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1269 return true;
1270
Douglas Gregor0b36e612010-08-31 20:37:03 +00001271 return false;
1272
1273 case TemplateName::DependentTemplate:
1274 // FIXME: Visit nested-name-specifier.
1275 return false;
1276
1277 case TemplateName::QualifiedTemplate:
1278 // FIXME: Visit nested-name-specifier.
1279 return Visit(MakeCursorTemplateRef(
1280 Name.getAsQualifiedTemplateName()->getDecl(),
1281 Loc, TU));
John McCall14606042011-06-30 08:33:18 +00001282
1283 case TemplateName::SubstTemplateTemplateParm:
1284 return Visit(MakeCursorTemplateRef(
1285 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1286 Loc, TU));
Douglas Gregor1aee05d2011-01-15 06:45:20 +00001287
1288 case TemplateName::SubstTemplateTemplateParmPack:
1289 return Visit(MakeCursorTemplateRef(
1290 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1291 Loc, TU));
Douglas Gregor0b36e612010-08-31 20:37:03 +00001292 }
1293
1294 return false;
1295}
1296
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001297bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1298 switch (TAL.getArgument().getKind()) {
1299 case TemplateArgument::Null:
1300 case TemplateArgument::Integral:
Douglas Gregor87dd6972010-12-20 16:52:59 +00001301 case TemplateArgument::Pack:
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001302 return false;
1303
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001304 case TemplateArgument::Type:
1305 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1306 return Visit(TSInfo->getTypeLoc());
1307 return false;
1308
1309 case TemplateArgument::Declaration:
1310 if (Expr *E = TAL.getSourceDeclExpression())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001311 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001312 return false;
1313
1314 case TemplateArgument::Expression:
1315 if (Expr *E = TAL.getSourceExpression())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001316 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001317 return false;
1318
1319 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001320 case TemplateArgument::TemplateExpansion:
Douglas Gregorb6744ef2011-03-02 17:09:35 +00001321 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1322 return true;
1323
Douglas Gregora7fc9012011-01-05 18:58:31 +00001324 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
Douglas Gregor0b36e612010-08-31 20:37:03 +00001325 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001326 }
1327
1328 return false;
1329}
1330
Ted Kremeneka0536d82010-05-07 01:04:29 +00001331bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1332 return VisitDeclContext(D);
1333}
1334
Douglas Gregor01829d32010-08-31 14:41:23 +00001335bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1336 return Visit(TL.getUnqualifiedLoc());
1337}
1338
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001339bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00001340 ASTContext &Context = AU->getASTContext();
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001341
1342 // Some builtin types (such as Objective-C's "id", "sel", and
1343 // "Class") have associated declarations. Create cursors for those.
1344 QualType VisitType;
John McCalle0a22d02011-10-18 21:02:43 +00001345 switch (TL.getTypePtr()->getKind()) {
John McCall2dde35b2011-10-18 22:28:37 +00001346
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001347 case BuiltinType::Void:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001348 case BuiltinType::NullPtr:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001349 case BuiltinType::Dependent:
John McCall2dde35b2011-10-18 22:28:37 +00001350#define BUILTIN_TYPE(Id, SingletonId)
1351#define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1352#define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1353#define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
1354#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
1355#include "clang/AST/BuiltinTypes.def"
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001356 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001357
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001358 case BuiltinType::ObjCId:
1359 VisitType = Context.getObjCIdType();
1360 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001361
1362 case BuiltinType::ObjCClass:
1363 VisitType = Context.getObjCClassType();
1364 break;
1365
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001366 case BuiltinType::ObjCSel:
1367 VisitType = Context.getObjCSelType();
1368 break;
1369 }
1370
1371 if (!VisitType.isNull()) {
1372 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001373 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001374 TU));
1375 }
1376
1377 return false;
1378}
1379
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001380bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
Richard Smith162e1c12011-04-15 14:24:37 +00001381 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001382}
1383
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001384bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1385 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1386}
1387
1388bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
Argyrios Kyrtzidis6f155de2011-08-25 22:24:47 +00001389 if (TL.isDefinition())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001390 return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
Argyrios Kyrtzidis6f155de2011-08-25 22:24:47 +00001391
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001392 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1393}
1394
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001395bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Chandler Carruth960d13d2011-05-01 09:53:37 +00001396 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001397}
1398
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001399bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1400 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1401 return true;
1402
John McCallc12c5bb2010-05-15 11:32:37 +00001403 return false;
1404}
1405
1406bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1407 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1408 return true;
1409
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001410 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1411 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1412 TU)))
1413 return true;
1414 }
1415
1416 return false;
1417}
1418
1419bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001420 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001421}
1422
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001423bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1424 return Visit(TL.getInnerLoc());
1425}
1426
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001427bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1428 return Visit(TL.getPointeeLoc());
1429}
1430
1431bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1432 return Visit(TL.getPointeeLoc());
1433}
1434
1435bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1436 return Visit(TL.getPointeeLoc());
1437}
1438
1439bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001440 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001441}
1442
1443bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001444 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001445}
1446
Argyrios Kyrtzidis3422fbc2011-08-15 18:44:43 +00001447bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1448 return Visit(TL.getModifiedLoc());
1449}
1450
Douglas Gregor01829d32010-08-31 14:41:23 +00001451bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1452 bool SkipResultType) {
1453 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001454 return true;
1455
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001456 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001457 if (Decl *D = TL.getArg(I))
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001458 if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001459 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001460
1461 return false;
1462}
1463
1464bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1465 if (Visit(TL.getElementLoc()))
1466 return true;
1467
1468 if (Expr *Size = TL.getSizeExpr())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001469 return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001470
1471 return false;
1472}
1473
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001474bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1475 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001476 // Visit the template name.
1477 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1478 TL.getTemplateNameLoc()))
1479 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001480
1481 // Visit the template arguments.
1482 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1483 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1484 return true;
1485
1486 return false;
1487}
1488
Douglas Gregor2332c112010-01-21 20:48:56 +00001489bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1490 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1491}
1492
1493bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1494 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1495 return Visit(TSInfo->getTypeLoc());
1496
1497 return false;
1498}
1499
Sean Huntca63c202011-05-24 22:41:36 +00001500bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1501 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1502 return Visit(TSInfo->getTypeLoc());
1503
1504 return false;
1505}
1506
Douglas Gregor2494dd02011-03-01 01:34:45 +00001507bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
1508 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1509 return true;
1510
1511 return false;
1512}
1513
Douglas Gregor94fdffa2011-03-01 20:11:18 +00001514bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1515 DependentTemplateSpecializationTypeLoc TL) {
1516 // Visit the nested-name-specifier, if there is one.
1517 if (TL.getQualifierLoc() &&
1518 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1519 return true;
1520
1521 // Visit the template arguments.
1522 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1523 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1524 return true;
1525
1526 return false;
1527}
1528
Douglas Gregor9e876872011-03-01 18:12:44 +00001529bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1530 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1531 return true;
1532
1533 return Visit(TL.getNamedTypeLoc());
1534}
1535
Douglas Gregor7536dd52010-12-20 02:24:11 +00001536bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1537 return Visit(TL.getPatternLoc());
1538}
1539
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +00001540bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1541 if (Expr *E = TL.getUnderlyingExpr())
1542 return Visit(MakeCXCursor(E, StmtParent, TU));
1543
1544 return false;
1545}
1546
1547bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1548 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1549}
1550
Eli Friedmanb001de72011-10-06 23:00:33 +00001551bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1552 return Visit(TL.getValueLoc());
1553}
1554
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +00001555#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1556bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1557 return Visit##PARENT##Loc(TL); \
1558}
1559
1560DEFAULT_TYPELOC_IMPL(Complex, Type)
1561DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1562DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1563DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1564DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
1565DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1566DEFAULT_TYPELOC_IMPL(Vector, Type)
1567DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1568DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1569DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1570DEFAULT_TYPELOC_IMPL(Record, TagType)
1571DEFAULT_TYPELOC_IMPL(Enum, TagType)
1572DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1573DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1574DEFAULT_TYPELOC_IMPL(Auto, Type)
1575
Ted Kremenek3064ef92010-08-27 21:34:58 +00001576bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001577 // Visit the nested-name-specifier, if present.
1578 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1579 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1580 return true;
1581
John McCall5e1cdac2011-10-07 06:10:15 +00001582 if (D->isCompleteDefinition()) {
Ted Kremenek3064ef92010-08-27 21:34:58 +00001583 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1584 E = D->bases_end(); I != E; ++I) {
1585 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1586 return true;
1587 }
1588 }
1589
1590 return VisitTagDecl(D);
1591}
1592
Ted Kremenek09dfa372010-02-18 05:46:33 +00001593bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001594 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1595 i != e; ++i)
1596 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001597 return true;
1598
1599 return false;
1600}
1601
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001602//===----------------------------------------------------------------------===//
1603// Data-recursive visitor methods.
1604//===----------------------------------------------------------------------===//
1605
Ted Kremenek28a71942010-11-13 00:36:47 +00001606namespace {
Ted Kremenek035dc412010-11-13 00:36:50 +00001607#define DEF_JOB(NAME, DATA, KIND)\
1608class NAME : public VisitorJob {\
1609public:\
1610 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1611 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Ted Kremenekf64d8032010-11-18 00:02:32 +00001612 DATA *get() const { return static_cast<DATA*>(data[0]); }\
Ted Kremenek035dc412010-11-13 00:36:50 +00001613};
1614
1615DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1616DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001617DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001618DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001619DEF_JOB(ExplicitTemplateArgsVisit, ASTTemplateArgumentListInfo,
Ted Kremenek60608ec2010-11-17 00:50:47 +00001620 ExplicitTemplateArgsVisitKind)
Douglas Gregor94d96292011-01-19 20:34:17 +00001621DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001622#undef DEF_JOB
1623
1624class DeclVisit : public VisitorJob {
1625public:
1626 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1627 VisitorJob(parent, VisitorJob::DeclVisitKind,
1628 d, isFirst ? (void*) 1 : (void*) 0) {}
1629 static bool classof(const VisitorJob *VJ) {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001630 return VJ->getKind() == DeclVisitKind;
Ted Kremenek035dc412010-11-13 00:36:50 +00001631 }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001632 Decl *get() const { return static_cast<Decl*>(data[0]); }
1633 bool isFirst() const { return data[1] ? true : false; }
Ted Kremenek035dc412010-11-13 00:36:50 +00001634};
Ted Kremenek035dc412010-11-13 00:36:50 +00001635class TypeLocVisit : public VisitorJob {
1636public:
1637 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1638 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1639 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1640
1641 static bool classof(const VisitorJob *VJ) {
1642 return VJ->getKind() == TypeLocVisitKind;
1643 }
1644
Ted Kremenek82f3c502010-11-15 22:23:26 +00001645 TypeLoc get() const {
Ted Kremenekf64d8032010-11-18 00:02:32 +00001646 QualType T = QualType::getFromOpaquePtr(data[0]);
1647 return TypeLoc(T, data[1]);
Ted Kremenek035dc412010-11-13 00:36:50 +00001648 }
1649};
1650
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001651class LabelRefVisit : public VisitorJob {
1652public:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001653 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1654 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001655 labelLoc.getPtrEncoding()) {}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001656
1657 static bool classof(const VisitorJob *VJ) {
1658 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1659 }
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001660 LabelDecl *get() const { return static_cast<LabelDecl*>(data[0]); }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001661 SourceLocation getLoc() const {
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001662 return SourceLocation::getFromPtrEncoding(data[1]); }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001663};
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001664
1665class NestedNameSpecifierLocVisit : public VisitorJob {
1666public:
1667 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1668 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1669 Qualifier.getNestedNameSpecifier(),
1670 Qualifier.getOpaqueData()) { }
1671
1672 static bool classof(const VisitorJob *VJ) {
1673 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1674 }
1675
1676 NestedNameSpecifierLoc get() const {
1677 return NestedNameSpecifierLoc(static_cast<NestedNameSpecifier*>(data[0]),
1678 data[1]);
1679 }
1680};
1681
Ted Kremenekf64d8032010-11-18 00:02:32 +00001682class DeclarationNameInfoVisit : public VisitorJob {
1683public:
1684 DeclarationNameInfoVisit(Stmt *S, CXCursor parent)
1685 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
1686 static bool classof(const VisitorJob *VJ) {
1687 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1688 }
1689 DeclarationNameInfo get() const {
1690 Stmt *S = static_cast<Stmt*>(data[0]);
1691 switch (S->getStmtClass()) {
1692 default:
1693 llvm_unreachable("Unhandled Stmt");
Douglas Gregorba0513d2011-10-25 01:33:02 +00001694 case clang::Stmt::MSDependentExistsStmtClass:
1695 return cast<MSDependentExistsStmt>(S)->getNameInfo();
Ted Kremenekf64d8032010-11-18 00:02:32 +00001696 case Stmt::CXXDependentScopeMemberExprClass:
1697 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1698 case Stmt::DependentScopeDeclRefExprClass:
1699 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
1700 }
1701 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001702};
Ted Kremenekcdba6592010-11-18 00:42:18 +00001703class MemberRefVisit : public VisitorJob {
1704public:
1705 MemberRefVisit(FieldDecl *D, SourceLocation L, CXCursor parent)
1706 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001707 L.getPtrEncoding()) {}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001708 static bool classof(const VisitorJob *VJ) {
1709 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1710 }
1711 FieldDecl *get() const {
1712 return static_cast<FieldDecl*>(data[0]);
1713 }
1714 SourceLocation getLoc() const {
1715 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1716 }
1717};
Ted Kremenek28a71942010-11-13 00:36:47 +00001718class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1719 VisitorWorkList &WL;
1720 CXCursor Parent;
1721public:
1722 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1723 : WL(wl), Parent(parent) {}
1724
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001725 void VisitAddrLabelExpr(AddrLabelExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001726 void VisitBlockExpr(BlockExpr *B);
Ted Kremenek28a71942010-11-13 00:36:47 +00001727 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek083c7e22010-11-13 05:38:03 +00001728 void VisitCompoundStmt(CompoundStmt *S);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001729 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
Douglas Gregorba0513d2011-10-25 01:33:02 +00001730 void VisitMSDependentExistsStmt(MSDependentExistsStmt *S);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001731 void VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001732 void VisitCXXNewExpr(CXXNewExpr *E);
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001733 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001734 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001735 void VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001736 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001737 void VisitCXXTypeidExpr(CXXTypeidExpr *E);
Ted Kremenek55b933a2010-11-17 00:50:36 +00001738 void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001739 void VisitCXXUuidofExpr(CXXUuidofExpr *E);
Argyrios Kyrtzidisdcbb2fb2011-12-03 03:49:44 +00001740 void VisitCXXCatchStmt(CXXCatchStmt *S);
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001741 void VisitDeclRefExpr(DeclRefExpr *D);
Ted Kremenek035dc412010-11-13 00:36:50 +00001742 void VisitDeclStmt(DeclStmt *S);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001743 void VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001744 void VisitDesignatedInitExpr(DesignatedInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001745 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1746 void VisitForStmt(ForStmt *FS);
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001747 void VisitGotoStmt(GotoStmt *GS);
Ted Kremenek28a71942010-11-13 00:36:47 +00001748 void VisitIfStmt(IfStmt *If);
1749 void VisitInitListExpr(InitListExpr *IE);
1750 void VisitMemberExpr(MemberExpr *M);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001751 void VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001752 void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001753 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1754 void VisitOverloadExpr(OverloadExpr *E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001755 void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001756 void VisitStmt(Stmt *S);
1757 void VisitSwitchStmt(SwitchStmt *S);
1758 void VisitWhileStmt(WhileStmt *W);
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001759 void VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Francois Pichet6ad6f282010-12-07 00:08:36 +00001760 void VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E);
John Wiegley21ff2e52011-04-28 00:16:57 +00001761 void VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E);
John Wiegley55262202011-04-25 06:54:41 +00001762 void VisitExpressionTraitExpr(ExpressionTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001763 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001764 void VisitVAArgExpr(VAArgExpr *E);
Douglas Gregor94d96292011-01-19 20:34:17 +00001765 void VisitSizeOfPackExpr(SizeOfPackExpr *E);
John McCall4b9c2d22011-11-06 09:01:30 +00001766 void VisitPseudoObjectExpr(PseudoObjectExpr *E);
1767 void VisitOpaqueValueExpr(OpaqueValueExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00001768
Ted Kremenek28a71942010-11-13 00:36:47 +00001769private:
Ted Kremenekf64d8032010-11-18 00:02:32 +00001770 void AddDeclarationNameInfo(Stmt *S);
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001771 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001772 void AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001773 void AddMemberRef(FieldDecl *D, SourceLocation L);
Ted Kremenek28a71942010-11-13 00:36:47 +00001774 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001775 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001776 void AddTypeLoc(TypeSourceInfo *TI);
1777 void EnqueueChildren(Stmt *S);
1778};
1779} // end anonyous namespace
1780
Ted Kremenekf64d8032010-11-18 00:02:32 +00001781void EnqueueVisitor::AddDeclarationNameInfo(Stmt *S) {
1782 // 'S' should always be non-null, since it comes from the
1783 // statement we are visiting.
1784 WL.push_back(DeclarationNameInfoVisit(S, Parent));
1785}
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001786
1787void
1788EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1789 if (Qualifier)
1790 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
1791}
1792
Ted Kremenek28a71942010-11-13 00:36:47 +00001793void EnqueueVisitor::AddStmt(Stmt *S) {
1794 if (S)
1795 WL.push_back(StmtVisit(S, Parent));
1796}
Ted Kremenek035dc412010-11-13 00:36:50 +00001797void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001798 if (D)
Ted Kremenek035dc412010-11-13 00:36:50 +00001799 WL.push_back(DeclVisit(D, Parent, isFirst));
Ted Kremenek28a71942010-11-13 00:36:47 +00001800}
Ted Kremenek60608ec2010-11-17 00:50:47 +00001801void EnqueueVisitor::
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001802 AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001803 if (A)
1804 WL.push_back(ExplicitTemplateArgsVisit(
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001805 const_cast<ASTTemplateArgumentListInfo*>(A), Parent));
Ted Kremenek60608ec2010-11-17 00:50:47 +00001806}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001807void EnqueueVisitor::AddMemberRef(FieldDecl *D, SourceLocation L) {
1808 if (D)
1809 WL.push_back(MemberRefVisit(D, L, Parent));
1810}
Ted Kremenek28a71942010-11-13 00:36:47 +00001811void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1812 if (TI)
1813 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1814 }
1815void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001816 unsigned size = WL.size();
John McCall7502c1d2011-02-13 04:07:26 +00001817 for (Stmt::child_range Child = S->children(); Child; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001818 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001819 }
1820 if (size == WL.size())
1821 return;
1822 // Now reverse the entries we just added. This will match the DFS
1823 // ordering performed by the worklist.
1824 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1825 std::reverse(I, E);
1826}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001827void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1828 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
1829}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001830void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1831 AddDecl(B->getBlockDecl());
1832}
Ted Kremenek28a71942010-11-13 00:36:47 +00001833void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1834 EnqueueChildren(E);
1835 AddTypeLoc(E->getTypeSourceInfo());
1836}
Ted Kremenek083c7e22010-11-13 05:38:03 +00001837void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1838 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1839 E = S->body_rend(); I != E; ++I) {
1840 AddStmt(*I);
1841 }
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001842}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001843void EnqueueVisitor::
Douglas Gregorba0513d2011-10-25 01:33:02 +00001844VisitMSDependentExistsStmt(MSDependentExistsStmt *S) {
1845 AddStmt(S->getSubStmt());
1846 AddDeclarationNameInfo(S);
1847 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
1848 AddNestedNameSpecifierLoc(QualifierLoc);
1849}
1850
1851void EnqueueVisitor::
Ted Kremenekf64d8032010-11-18 00:02:32 +00001852VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
1853 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1854 AddDeclarationNameInfo(E);
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001855 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1856 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001857 if (!E->isImplicitAccess())
1858 AddStmt(E->getBase());
1859}
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001860void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1861 // Enqueue the initializer or constructor arguments.
1862 for (unsigned I = E->getNumConstructorArgs(); I > 0; --I)
1863 AddStmt(E->getConstructorArg(I-1));
1864 // Enqueue the array size, if any.
1865 AddStmt(E->getArraySize());
1866 // Enqueue the allocated type.
1867 AddTypeLoc(E->getAllocatedTypeSourceInfo());
1868 // Enqueue the placement arguments.
1869 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1870 AddStmt(E->getPlacementArg(I-1));
1871}
Ted Kremenek28a71942010-11-13 00:36:47 +00001872void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
Ted Kremenek8b8d8c92010-11-13 05:55:56 +00001873 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1874 AddStmt(CE->getArg(I-1));
Ted Kremenek28a71942010-11-13 00:36:47 +00001875 AddStmt(CE->getCallee());
1876 AddStmt(CE->getArg(0));
1877}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001878void EnqueueVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1879 // Visit the name of the type being destroyed.
1880 AddTypeLoc(E->getDestroyedTypeInfo());
1881 // Visit the scope type that looks disturbingly like the nested-name-specifier
1882 // but isn't.
1883 AddTypeLoc(E->getScopeTypeInfo());
1884 // Visit the nested-name-specifier.
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001885 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1886 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001887 // Visit base expression.
1888 AddStmt(E->getBase());
1889}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001890void EnqueueVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1891 AddTypeLoc(E->getTypeSourceInfo());
1892}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001893void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1894 EnqueueChildren(E);
1895 AddTypeLoc(E->getTypeSourceInfo());
1896}
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001897void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1898 EnqueueChildren(E);
1899 if (E->isTypeOperand())
1900 AddTypeLoc(E->getTypeOperandSourceInfo());
1901}
Ted Kremenek55b933a2010-11-17 00:50:36 +00001902
1903void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
1904 *E) {
1905 EnqueueChildren(E);
1906 AddTypeLoc(E->getTypeSourceInfo());
1907}
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001908void EnqueueVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1909 EnqueueChildren(E);
1910 if (E->isTypeOperand())
1911 AddTypeLoc(E->getTypeOperandSourceInfo());
1912}
Argyrios Kyrtzidisdcbb2fb2011-12-03 03:49:44 +00001913
1914void EnqueueVisitor::VisitCXXCatchStmt(CXXCatchStmt *S) {
1915 EnqueueChildren(S);
1916 AddDecl(S->getExceptionDecl());
1917}
1918
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001919void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001920 if (DR->hasExplicitTemplateArgs()) {
1921 AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
1922 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001923 WL.push_back(DeclRefExprParts(DR, Parent));
1924}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001925void EnqueueVisitor::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
1926 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1927 AddDeclarationNameInfo(E);
Douglas Gregor00cf3cc2011-02-25 20:49:16 +00001928 AddNestedNameSpecifierLoc(E->getQualifierLoc());
Ted Kremenekf64d8032010-11-18 00:02:32 +00001929}
Ted Kremenek035dc412010-11-13 00:36:50 +00001930void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1931 unsigned size = WL.size();
1932 bool isFirst = true;
1933 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1934 D != DEnd; ++D) {
1935 AddDecl(*D, isFirst);
1936 isFirst = false;
1937 }
1938 if (size == WL.size())
1939 return;
1940 // Now reverse the entries we just added. This will match the DFS
1941 // ordering performed by the worklist.
1942 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1943 std::reverse(I, E);
1944}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001945void EnqueueVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1946 AddStmt(E->getInit());
1947 typedef DesignatedInitExpr::Designator Designator;
1948 for (DesignatedInitExpr::reverse_designators_iterator
1949 D = E->designators_rbegin(), DEnd = E->designators_rend();
1950 D != DEnd; ++D) {
1951 if (D->isFieldDesignator()) {
1952 if (FieldDecl *Field = D->getField())
1953 AddMemberRef(Field, D->getFieldLoc());
1954 continue;
1955 }
1956 if (D->isArrayDesignator()) {
1957 AddStmt(E->getArrayIndex(*D));
1958 continue;
1959 }
1960 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1961 AddStmt(E->getArrayRangeEnd(*D));
1962 AddStmt(E->getArrayRangeStart(*D));
1963 }
1964}
Ted Kremenek28a71942010-11-13 00:36:47 +00001965void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1966 EnqueueChildren(E);
1967 AddTypeLoc(E->getTypeInfoAsWritten());
1968}
1969void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1970 AddStmt(FS->getBody());
1971 AddStmt(FS->getInc());
1972 AddStmt(FS->getCond());
1973 AddDecl(FS->getConditionVariable());
1974 AddStmt(FS->getInit());
1975}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001976void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) {
1977 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
1978}
Ted Kremenek28a71942010-11-13 00:36:47 +00001979void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
1980 AddStmt(If->getElse());
1981 AddStmt(If->getThen());
1982 AddStmt(If->getCond());
1983 AddDecl(If->getConditionVariable());
1984}
1985void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
1986 // We care about the syntactic form of the initializer list, only.
1987 if (InitListExpr *Syntactic = IE->getSyntacticForm())
1988 IE = Syntactic;
1989 EnqueueChildren(IE);
1990}
1991void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
Douglas Gregor89629a72010-11-17 17:15:08 +00001992 WL.push_back(MemberExprParts(M, Parent));
1993
1994 // If the base of the member access expression is an implicit 'this', don't
1995 // visit it.
1996 // FIXME: If we ever want to show these implicit accesses, this will be
1997 // unfortunate. However, clang_getCursor() relies on this behavior.
Douglas Gregor75e85042011-03-02 21:06:53 +00001998 if (!M->isImplicitAccess())
1999 AddStmt(M->getBase());
Ted Kremenek28a71942010-11-13 00:36:47 +00002000}
Ted Kremenek73d15c42010-11-13 01:09:29 +00002001void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
2002 AddTypeLoc(E->getEncodedTypeSourceInfo());
2003}
Ted Kremenek28a71942010-11-13 00:36:47 +00002004void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
2005 EnqueueChildren(M);
2006 AddTypeLoc(M->getClassReceiverTypeInfo());
2007}
Ted Kremenekcdba6592010-11-18 00:42:18 +00002008void EnqueueVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
2009 // Visit the components of the offsetof expression.
2010 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
2011 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
2012 const OffsetOfNode &Node = E->getComponent(I-1);
2013 switch (Node.getKind()) {
2014 case OffsetOfNode::Array:
2015 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2016 break;
2017 case OffsetOfNode::Field:
Abramo Bagnara06dec892011-03-12 09:45:03 +00002018 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
Ted Kremenekcdba6592010-11-18 00:42:18 +00002019 break;
2020 case OffsetOfNode::Identifier:
2021 case OffsetOfNode::Base:
2022 continue;
2023 }
2024 }
2025 // Visit the type into which we're computing the offset.
2026 AddTypeLoc(E->getTypeSourceInfo());
2027}
Ted Kremenek28a71942010-11-13 00:36:47 +00002028void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00002029 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
Ted Kremenek60458782010-11-12 21:34:16 +00002030 WL.push_back(OverloadExprParts(E, Parent));
2031}
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002032void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
2033 UnaryExprOrTypeTraitExpr *E) {
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00002034 EnqueueChildren(E);
2035 if (E->isArgumentType())
2036 AddTypeLoc(E->getArgumentTypeInfo());
2037}
Ted Kremenek28a71942010-11-13 00:36:47 +00002038void EnqueueVisitor::VisitStmt(Stmt *S) {
2039 EnqueueChildren(S);
2040}
2041void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
2042 AddStmt(S->getBody());
2043 AddStmt(S->getCond());
2044 AddDecl(S->getConditionVariable());
2045}
Ted Kremenekfafa75a2010-11-17 00:50:39 +00002046
Ted Kremenek28a71942010-11-13 00:36:47 +00002047void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
2048 AddStmt(W->getBody());
2049 AddStmt(W->getCond());
2050 AddDecl(W->getConditionVariable());
2051}
John Wiegley21ff2e52011-04-28 00:16:57 +00002052
Ted Kremenek2939b6f2010-11-17 00:50:50 +00002053void EnqueueVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
2054 AddTypeLoc(E->getQueriedTypeSourceInfo());
2055}
Francois Pichet6ad6f282010-12-07 00:08:36 +00002056
2057void EnqueueVisitor::VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
Francois Pichet6ad6f282010-12-07 00:08:36 +00002058 AddTypeLoc(E->getRhsTypeSourceInfo());
Francois Pichet0a03a3f2010-12-08 09:11:05 +00002059 AddTypeLoc(E->getLhsTypeSourceInfo());
Francois Pichet6ad6f282010-12-07 00:08:36 +00002060}
2061
John Wiegley21ff2e52011-04-28 00:16:57 +00002062void EnqueueVisitor::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
2063 AddTypeLoc(E->getQueriedTypeSourceInfo());
2064}
2065
John Wiegley55262202011-04-25 06:54:41 +00002066void EnqueueVisitor::VisitExpressionTraitExpr(ExpressionTraitExpr *E) {
2067 EnqueueChildren(E);
2068}
2069
Ted Kremenek28a71942010-11-13 00:36:47 +00002070void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
2071 VisitOverloadExpr(U);
2072 if (!U->isImplicitAccess())
2073 AddStmt(U->getBase());
2074}
Ted Kremenek9d3bf792010-11-17 00:50:43 +00002075void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) {
2076 AddStmt(E->getSubExpr());
2077 AddTypeLoc(E->getWrittenTypeInfo());
2078}
Douglas Gregor94d96292011-01-19 20:34:17 +00002079void EnqueueVisitor::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
2080 WL.push_back(SizeOfPackExprParts(E, Parent));
2081}
John McCall4b9c2d22011-11-06 09:01:30 +00002082void EnqueueVisitor::VisitOpaqueValueExpr(OpaqueValueExpr *E) {
2083 // If the opaque value has a source expression, just transparently
2084 // visit that. This is useful for (e.g.) pseudo-object expressions.
2085 if (Expr *SourceExpr = E->getSourceExpr())
2086 return Visit(SourceExpr);
John McCall4b9c2d22011-11-06 09:01:30 +00002087}
2088void EnqueueVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *E) {
2089 // Treat the expression like its syntactic form.
2090 Visit(E->getSyntacticForm());
2091}
Ted Kremenek60458782010-11-12 21:34:16 +00002092
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002093void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002094 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002095}
2096
2097bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2098 if (RegionOfInterest.isValid()) {
2099 SourceRange Range = getRawCursorExtent(C);
2100 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2101 return false;
2102 }
2103 return true;
2104}
2105
2106bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2107 while (!WL.empty()) {
2108 // Dequeue the worklist item.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002109 VisitorJob LI = WL.back();
2110 WL.pop_back();
2111
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002112 // Set the Parent field, then back to its old value once we're done.
2113 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2114
2115 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00002116 case VisitorJob::DeclVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002117 Decl *D = cast<DeclVisit>(&LI)->get();
Ted Kremenekf1107452010-11-12 18:26:56 +00002118 if (!D)
2119 continue;
2120
2121 // For now, perform default visitation for Decls.
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002122 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2123 cast<DeclVisit>(&LI)->isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00002124 return true;
2125
2126 continue;
2127 }
Ted Kremenek60608ec2010-11-17 00:50:47 +00002128 case VisitorJob::ExplicitTemplateArgsVisitKind: {
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00002129 const ASTTemplateArgumentListInfo *ArgList =
Ted Kremenek60608ec2010-11-17 00:50:47 +00002130 cast<ExplicitTemplateArgsVisit>(&LI)->get();
2131 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2132 *ArgEnd = Arg + ArgList->NumTemplateArgs;
2133 Arg != ArgEnd; ++Arg) {
2134 if (VisitTemplateArgumentLoc(*Arg))
2135 return true;
2136 }
2137 continue;
2138 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002139 case VisitorJob::TypeLocVisitKind: {
2140 // Perform default visitation for TypeLocs.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002141 if (Visit(cast<TypeLocVisit>(&LI)->get()))
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002142 return true;
2143 continue;
2144 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002145 case VisitorJob::LabelRefVisitKind: {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002146 LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Ted Kremeneke7455012011-02-23 04:54:51 +00002147 if (LabelStmt *stmt = LS->getStmt()) {
2148 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2149 TU))) {
2150 return true;
2151 }
2152 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002153 continue;
2154 }
Ted Kremenek47695c82011-08-18 22:25:21 +00002155
Douglas Gregorf3db29f2011-02-25 18:19:59 +00002156 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2157 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2158 if (VisitNestedNameSpecifierLoc(V->get()))
2159 return true;
2160 continue;
2161 }
2162
Ted Kremenekf64d8032010-11-18 00:02:32 +00002163 case VisitorJob::DeclarationNameInfoVisitKind: {
2164 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2165 ->get()))
2166 return true;
2167 continue;
2168 }
Ted Kremenekcdba6592010-11-18 00:42:18 +00002169 case VisitorJob::MemberRefVisitKind: {
2170 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2171 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2172 return true;
2173 continue;
2174 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002175 case VisitorJob::StmtVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002176 Stmt *S = cast<StmtVisit>(&LI)->get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00002177 if (!S)
2178 continue;
2179
Ted Kremenekf1107452010-11-12 18:26:56 +00002180 // Update the current cursor.
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002181 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
Ted Kremenekcdba6592010-11-18 00:42:18 +00002182 if (!IsInRegionOfInterest(Cursor))
2183 continue;
2184 switch (Visitor(Cursor, Parent, ClientData)) {
2185 case CXChildVisit_Break: return true;
2186 case CXChildVisit_Continue: break;
2187 case CXChildVisit_Recurse:
2188 EnqueueWorkList(WL, S);
Ted Kremenek82f3c502010-11-15 22:23:26 +00002189 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002190 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00002191 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002192 }
2193 case VisitorJob::MemberExprPartsKind: {
2194 // Handle the other pieces in the MemberExpr besides the base.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002195 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002196
2197 // Visit the nested-name-specifier
Douglas Gregor40d96a62011-02-28 21:54:11 +00002198 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
2199 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002200 return true;
2201
2202 // Visit the declaration name.
2203 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2204 return true;
2205
2206 // Visit the explicitly-specified template arguments, if any.
2207 if (M->hasExplicitTemplateArgs()) {
2208 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2209 *ArgEnd = Arg + M->getNumTemplateArgs();
2210 Arg != ArgEnd; ++Arg) {
2211 if (VisitTemplateArgumentLoc(*Arg))
2212 return true;
2213 }
2214 }
2215 continue;
2216 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002217 case VisitorJob::DeclRefExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002218 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002219 // Visit nested-name-specifier, if present.
Douglas Gregor40d96a62011-02-28 21:54:11 +00002220 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
2221 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002222 return true;
2223 // Visit declaration name.
2224 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2225 return true;
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002226 continue;
2227 }
Ted Kremenek60458782010-11-12 21:34:16 +00002228 case VisitorJob::OverloadExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002229 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Ted Kremenek60458782010-11-12 21:34:16 +00002230 // Visit the nested-name-specifier.
Douglas Gregor4c9be892011-02-28 20:01:57 +00002231 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
2232 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenek60458782010-11-12 21:34:16 +00002233 return true;
2234 // Visit the declaration name.
2235 if (VisitDeclarationNameInfo(O->getNameInfo()))
2236 return true;
2237 // Visit the overloaded declaration reference.
2238 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2239 return true;
Ted Kremenek60458782010-11-12 21:34:16 +00002240 continue;
2241 }
Douglas Gregor94d96292011-01-19 20:34:17 +00002242 case VisitorJob::SizeOfPackExprPartsKind: {
2243 SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
2244 NamedDecl *Pack = E->getPack();
2245 if (isa<TemplateTypeParmDecl>(Pack)) {
2246 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
2247 E->getPackLoc(), TU)))
2248 return true;
2249
2250 continue;
2251 }
2252
2253 if (isa<TemplateTemplateParmDecl>(Pack)) {
2254 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
2255 E->getPackLoc(), TU)))
2256 return true;
2257
2258 continue;
2259 }
2260
2261 // Non-type template parameter packs and function parameter packs are
2262 // treated like DeclRefExpr cursors.
2263 continue;
2264 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002265 }
2266 }
2267 return false;
2268}
2269
Ted Kremenekcdba6592010-11-18 00:42:18 +00002270bool CursorVisitor::Visit(Stmt *S) {
Ted Kremenekd1ded662010-11-15 23:31:32 +00002271 VisitorWorkList *WL = 0;
2272 if (!WorkListFreeList.empty()) {
2273 WL = WorkListFreeList.back();
2274 WL->clear();
2275 WorkListFreeList.pop_back();
2276 }
2277 else {
2278 WL = new VisitorWorkList();
2279 WorkListCache.push_back(WL);
2280 }
2281 EnqueueWorkList(*WL, S);
2282 bool result = RunVisitorWorkList(*WL);
2283 WorkListFreeList.push_back(WL);
2284 return result;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002285}
2286
Francois Pichet48a8d142011-07-25 22:00:44 +00002287namespace {
2288typedef llvm::SmallVector<SourceRange, 4> RefNamePieces;
2289RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
2290 const DeclarationNameInfo &NI,
2291 const SourceRange &QLoc,
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00002292 const ASTTemplateArgumentListInfo *TemplateArgs = 0){
Francois Pichet48a8d142011-07-25 22:00:44 +00002293 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
2294 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
2295 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
2296
2297 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
2298
2299 RefNamePieces Pieces;
2300
2301 if (WantQualifier && QLoc.isValid())
2302 Pieces.push_back(QLoc);
2303
2304 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
2305 Pieces.push_back(NI.getLoc());
2306
2307 if (WantTemplateArgs && TemplateArgs)
2308 Pieces.push_back(SourceRange(TemplateArgs->LAngleLoc,
2309 TemplateArgs->RAngleLoc));
2310
2311 if (Kind == DeclarationName::CXXOperatorName) {
2312 Pieces.push_back(SourceLocation::getFromRawEncoding(
2313 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
2314 Pieces.push_back(SourceLocation::getFromRawEncoding(
2315 NI.getInfo().CXXOperatorName.EndOpNameLoc));
2316 }
2317
2318 if (WantSinglePiece) {
2319 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
2320 Pieces.clear();
2321 Pieces.push_back(R);
2322 }
2323
2324 return Pieces;
2325}
2326}
2327
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002328//===----------------------------------------------------------------------===//
2329// Misc. API hooks.
2330//===----------------------------------------------------------------------===//
2331
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002332static llvm::sys::Mutex EnableMultithreadingMutex;
2333static bool EnabledMultithreading;
2334
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002335extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002336CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2337 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002338 // Disable pretty stack trace functionality, which will otherwise be a very
2339 // poor citizen of the world and set up all sorts of signal handlers.
2340 llvm::DisablePrettyStackTrace = true;
2341
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002342 // We use crash recovery to make some of our APIs more reliable, implicitly
2343 // enable it.
2344 llvm::CrashRecoveryContext::Enable();
2345
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002346 // Enable support for multithreading in LLVM.
2347 {
2348 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2349 if (!EnabledMultithreading) {
2350 llvm::llvm_start_multithreaded();
2351 EnabledMultithreading = true;
2352 }
2353 }
2354
Douglas Gregora030b7c2010-01-22 20:35:53 +00002355 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002356 if (excludeDeclarationsFromPCH)
2357 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002358 if (displayDiagnostics)
2359 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002360 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002361}
2362
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002363void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002364 if (CIdx)
2365 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002366}
2367
Ted Kremenekd2427dd2011-03-18 23:05:39 +00002368void clang_toggleCrashRecovery(unsigned isEnabled) {
2369 if (isEnabled)
2370 llvm::CrashRecoveryContext::Enable();
2371 else
2372 llvm::CrashRecoveryContext::Disable();
2373}
2374
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002375CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002376 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002377 if (!CIdx)
2378 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002379
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002380 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002381 FileSystemOptions FileSystemOpts;
2382 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002383
David Blaikied6471f72011-09-25 23:23:43 +00002384 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002385 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002386 CXXIdx->getOnlyLocalDecls(),
2387 0, 0, true);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002388 return MakeCXTranslationUnit(TU);
Steve Naroff600866c2009-08-27 19:51:58 +00002389}
2390
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002391unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002392 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregorb5af8432011-08-25 22:54:01 +00002393 CXTranslationUnit_CacheCompletionResults;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002394}
2395
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002396CXTranslationUnit
2397clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2398 const char *source_filename,
2399 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002400 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002401 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002402 struct CXUnsavedFile *unsaved_files) {
Douglas Gregordca8ee82011-05-06 16:33:08 +00002403 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord |
Chandler Carruthba7537f2011-07-14 09:02:10 +00002404 CXTranslationUnit_NestedMacroExpansions;
Douglas Gregor5a430212010-07-21 18:52:53 +00002405 return clang_parseTranslationUnit(CIdx, source_filename,
2406 command_line_args, num_command_line_args,
2407 unsaved_files, num_unsaved_files,
Douglas Gregordca8ee82011-05-06 16:33:08 +00002408 Options);
Douglas Gregor5a430212010-07-21 18:52:53 +00002409}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002410
2411struct ParseTranslationUnitInfo {
2412 CXIndex CIdx;
2413 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002414 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002415 int num_command_line_args;
2416 struct CXUnsavedFile *unsaved_files;
2417 unsigned num_unsaved_files;
2418 unsigned options;
2419 CXTranslationUnit result;
2420};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002421static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002422 ParseTranslationUnitInfo *PTUI =
2423 static_cast<ParseTranslationUnitInfo*>(UserData);
2424 CXIndex CIdx = PTUI->CIdx;
2425 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002426 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002427 int num_command_line_args = PTUI->num_command_line_args;
2428 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2429 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2430 unsigned options = PTUI->options;
2431 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002432
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002433 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002434 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002435
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002436 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2437
Douglas Gregor44c181a2010-07-23 00:33:23 +00002438 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregor467dc882011-08-25 22:30:56 +00002439 // FIXME: Add a flag for modules.
2440 TranslationUnitKind TUKind
2441 = (options & CXTranslationUnit_Incomplete)? TU_Prefix : TU_Complete;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002442 bool CacheCodeCompetionResults
2443 = options & CXTranslationUnit_CacheCompletionResults;
2444
Douglas Gregor5352ac02010-01-28 00:27:43 +00002445 // Configure the diagnostics.
2446 DiagnosticOptions DiagOpts;
David Blaikied6471f72011-09-25 23:23:43 +00002447 llvm::IntrusiveRefCntPtr<DiagnosticsEngine>
Ted Kremenek25a11e12011-03-22 01:15:24 +00002448 Diags(CompilerInstance::createDiagnostics(DiagOpts, num_command_line_args,
2449 command_line_args));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002450
Ted Kremenek25a11e12011-03-22 01:15:24 +00002451 // Recover resources if we crash before exiting this function.
David Blaikied6471f72011-09-25 23:23:43 +00002452 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
2453 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00002454 DiagCleanup(Diags.getPtr());
2455
2456 llvm::OwningPtr<std::vector<ASTUnit::RemappedFile> >
2457 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2458
2459 // Recover resources if we crash before exiting this function.
2460 llvm::CrashRecoveryContextCleanupRegistrar<
2461 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2462
Douglas Gregor4db64a42010-01-23 00:14:00 +00002463 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002464 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002465 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002466 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002467 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2468 Buffer));
Douglas Gregor4db64a42010-01-23 00:14:00 +00002469 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002470
Ted Kremenek25a11e12011-03-22 01:15:24 +00002471 llvm::OwningPtr<std::vector<const char *> >
2472 Args(new std::vector<const char*>());
2473
2474 // Recover resources if we crash before exiting this method.
2475 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
2476 ArgsCleanup(Args.get());
2477
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002478 // Since the Clang C library is primarily used by batch tools dealing with
2479 // (often very broken) source code, where spell-checking can have a
2480 // significant negative impact on performance (particularly when
2481 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002482 // Only do this if we haven't found a spell-checking-related argument.
2483 bool FoundSpellCheckingArgument = false;
2484 for (int I = 0; I != num_command_line_args; ++I) {
2485 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2486 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2487 FoundSpellCheckingArgument = true;
2488 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002489 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002490 }
2491 if (!FoundSpellCheckingArgument)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002492 Args->push_back("-fno-spell-checking");
Douglas Gregorb10daed2010-10-11 16:52:23 +00002493
Ted Kremenek25a11e12011-03-22 01:15:24 +00002494 Args->insert(Args->end(), command_line_args,
2495 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002496
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002497 // The 'source_filename' argument is optional. If the caller does not
2498 // specify it then it is assumed that the source file is specified
2499 // in the actual argument list.
2500 // Put the source file after command_line_args otherwise if '-x' flag is
2501 // present it will be unused.
2502 if (source_filename)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002503 Args->push_back(source_filename);
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002504
Douglas Gregor44c181a2010-07-23 00:33:23 +00002505 // Do we need the detailed preprocessing record?
Chandler Carruthba7537f2011-07-14 09:02:10 +00002506 bool NestedMacroExpansions = false;
Douglas Gregor44c181a2010-07-23 00:33:23 +00002507 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Ted Kremenek25a11e12011-03-22 01:15:24 +00002508 Args->push_back("-Xclang");
2509 Args->push_back("-detailed-preprocessing-record");
Chandler Carruthba7537f2011-07-14 09:02:10 +00002510 NestedMacroExpansions
2511 = (options & CXTranslationUnit_NestedMacroExpansions);
Douglas Gregor44c181a2010-07-23 00:33:23 +00002512 }
2513
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002514 unsigned NumErrors = Diags->getClient()->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002515 llvm::OwningPtr<ASTUnit> Unit(
Ted Kremenek4ee99262011-03-22 20:16:19 +00002516 ASTUnit::LoadFromCommandLine(Args->size() ? &(*Args)[0] : 0
2517 /* vector::data() not portable */,
2518 Args->size() ? (&(*Args)[0] + Args->size()) :0,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002519 Diags,
2520 CXXIdx->getClangResourcesPath(),
2521 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002522 /*CaptureDiagnostics=*/true,
Ted Kremenek4ee99262011-03-22 20:16:19 +00002523 RemappedFiles->size() ? &(*RemappedFiles)[0]:0,
Ted Kremenek25a11e12011-03-22 01:15:24 +00002524 RemappedFiles->size(),
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00002525 /*RemappedFilesKeepOriginalName=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002526 PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00002527 TUKind,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002528 CacheCodeCompetionResults,
Chandler Carruthba7537f2011-07-14 09:02:10 +00002529 NestedMacroExpansions));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002530
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002531 if (NumErrors != Diags->getClient()->getNumErrors()) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002532 // Make sure to check that 'Unit' is non-NULL.
2533 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2534 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2535 DEnd = Unit->stored_diag_end();
2536 D != DEnd; ++D) {
2537 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2538 CXString Msg = clang_formatDiagnostic(&Diag,
2539 clang_defaultDiagnosticDisplayOptions());
2540 fprintf(stderr, "%s\n", clang_getCString(Msg));
2541 clang_disposeString(Msg);
2542 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002543#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002544 // On Windows, force a flush, since there may be multiple copies of
2545 // stderr and stdout in the file system, all with different buffers
2546 // but writing to the same device.
2547 fflush(stderr);
2548#endif
2549 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002550 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002551
Ted Kremeneka60ed472010-11-16 08:15:36 +00002552 PTUI->result = MakeCXTranslationUnit(Unit.take());
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002553}
2554CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2555 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002556 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002557 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002558 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002559 unsigned num_unsaved_files,
2560 unsigned options) {
2561 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002562 num_command_line_args, unsaved_files,
2563 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002564 llvm::CrashRecoveryContext CRC;
2565
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002566 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002567 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2568 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2569 fprintf(stderr, " 'command_line_args' : [");
2570 for (int i = 0; i != num_command_line_args; ++i) {
2571 if (i)
2572 fprintf(stderr, ", ");
2573 fprintf(stderr, "'%s'", command_line_args[i]);
2574 }
2575 fprintf(stderr, "],\n");
2576 fprintf(stderr, " 'unsaved_files' : [");
2577 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2578 if (i)
2579 fprintf(stderr, ", ");
2580 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2581 unsaved_files[i].Length);
2582 }
2583 fprintf(stderr, "],\n");
2584 fprintf(stderr, " 'options' : %d,\n", options);
2585 fprintf(stderr, "}\n");
2586
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002587 return 0;
Douglas Gregor6df78732011-05-05 20:27:22 +00002588 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
2589 PrintLibclangResourceUsage(PTUI.result);
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002590 }
Douglas Gregor6df78732011-05-05 20:27:22 +00002591
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002592 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002593}
2594
Douglas Gregor19998442010-08-13 15:35:05 +00002595unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2596 return CXSaveTranslationUnit_None;
2597}
2598
2599int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2600 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002601 if (!TU)
Douglas Gregor39c411f2011-07-06 16:43:36 +00002602 return CXSaveError_InvalidTU;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002603
Douglas Gregor39c411f2011-07-06 16:43:36 +00002604 CXSaveError result = static_cast<ASTUnit *>(TU->TUData)->Save(FileName);
Douglas Gregor6df78732011-05-05 20:27:22 +00002605 if (getenv("LIBCLANG_RESOURCE_USAGE"))
2606 PrintLibclangResourceUsage(TU);
2607 return result;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002608}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002609
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002610void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002611 if (CTUnit) {
2612 // If the translation unit has been marked as unsafe to free, just discard
2613 // it.
Ted Kremeneka60ed472010-11-16 08:15:36 +00002614 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002615 return;
2616
Ted Kremeneka60ed472010-11-16 08:15:36 +00002617 delete static_cast<ASTUnit *>(CTUnit->TUData);
2618 disposeCXStringPool(CTUnit->StringPool);
Ted Kremenek15322172011-11-10 08:43:12 +00002619 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002620 delete CTUnit;
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002621 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002622}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002623
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002624unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2625 return CXReparse_None;
2626}
2627
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002628struct ReparseTranslationUnitInfo {
2629 CXTranslationUnit TU;
2630 unsigned num_unsaved_files;
2631 struct CXUnsavedFile *unsaved_files;
2632 unsigned options;
2633 int result;
2634};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002635
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002636static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002637 ReparseTranslationUnitInfo *RTUI =
2638 static_cast<ReparseTranslationUnitInfo*>(UserData);
2639 CXTranslationUnit TU = RTUI->TU;
Ted Kremenek15322172011-11-10 08:43:12 +00002640
2641 // Reset the associated diagnostics.
2642 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
2643 TU->Diagnostics = 0;
2644
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002645 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2646 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2647 unsigned options = RTUI->options;
2648 (void) options;
2649 RTUI->result = 1;
2650
Douglas Gregorabc563f2010-07-19 21:46:24 +00002651 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002652 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002653
Ted Kremeneka60ed472010-11-16 08:15:36 +00002654 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor593b0c12010-09-23 18:47:53 +00002655 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002656
Ted Kremenek25a11e12011-03-22 01:15:24 +00002657 llvm::OwningPtr<std::vector<ASTUnit::RemappedFile> >
2658 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2659
2660 // Recover resources if we crash before exiting this function.
2661 llvm::CrashRecoveryContextCleanupRegistrar<
2662 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2663
Douglas Gregorabc563f2010-07-19 21:46:24 +00002664 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002665 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002666 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002667 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002668 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2669 Buffer));
Douglas Gregorabc563f2010-07-19 21:46:24 +00002670 }
2671
Ted Kremenek4ee99262011-03-22 20:16:19 +00002672 if (!CXXUnit->Reparse(RemappedFiles->size() ? &(*RemappedFiles)[0] : 0,
2673 RemappedFiles->size()))
Douglas Gregor593b0c12010-09-23 18:47:53 +00002674 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002675}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002676
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002677int clang_reparseTranslationUnit(CXTranslationUnit TU,
2678 unsigned num_unsaved_files,
2679 struct CXUnsavedFile *unsaved_files,
2680 unsigned options) {
2681 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2682 options, 0 };
Argyrios Kyrtzidis8c4b47e2011-10-28 22:54:33 +00002683
Argyrios Kyrtzidise7de9b42011-10-29 19:32:39 +00002684 if (getenv("LIBCLANG_NOTHREADS")) {
Argyrios Kyrtzidis8c4b47e2011-10-28 22:54:33 +00002685 clang_reparseTranslationUnit_Impl(&RTUI);
2686 return RTUI.result;
2687 }
2688
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002689 llvm::CrashRecoveryContext CRC;
2690
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002691 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002692 fprintf(stderr, "libclang: crash detected during reparsing\n");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002693 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002694 return 1;
Douglas Gregor6df78732011-05-05 20:27:22 +00002695 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
2696 PrintLibclangResourceUsage(TU);
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002697
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002698 return RTUI.result;
2699}
2700
Douglas Gregordf95a132010-08-09 20:45:32 +00002701
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002702CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002703 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002704 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002705
Ted Kremeneka60ed472010-11-16 08:15:36 +00002706 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002707 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002708}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002709
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002710CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002711 CXCursor Result = { CXCursor_TranslationUnit, 0, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002712 return Result;
2713}
2714
Ted Kremenekfb480492010-01-13 21:46:36 +00002715} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002716
Ted Kremenekfb480492010-01-13 21:46:36 +00002717//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002718// CXFile Operations.
2719//===----------------------------------------------------------------------===//
2720
2721extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002722CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002723 if (!SFile)
Ted Kremeneka60ed472010-11-16 08:15:36 +00002724 return createCXString((const char*)NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002725
Steve Naroff88145032009-10-27 14:35:18 +00002726 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002727 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002728}
2729
2730time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002731 if (!SFile)
2732 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002733
Steve Naroff88145032009-10-27 14:35:18 +00002734 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2735 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002736}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002737
Douglas Gregorb9790342010-01-22 21:44:22 +00002738CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2739 if (!tu)
2740 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002741
Ted Kremeneka60ed472010-11-16 08:15:36 +00002742 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002743
Douglas Gregorb9790342010-01-22 21:44:22 +00002744 FileManager &FMgr = CXXUnit->getFileManager();
Chris Lattner39b49bc2010-11-23 08:35:12 +00002745 return const_cast<FileEntry *>(FMgr.getFile(file_name));
Douglas Gregorb9790342010-01-22 21:44:22 +00002746}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002747
Douglas Gregordd3e5542011-05-04 00:14:37 +00002748unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit tu, CXFile file) {
2749 if (!tu || !file)
2750 return 0;
2751
2752 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
2753 FileEntry *FEnt = static_cast<FileEntry *>(file);
2754 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
2755 .isFileMultipleIncludeGuarded(FEnt);
2756}
2757
Ted Kremenekfb480492010-01-13 21:46:36 +00002758} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002759
Ted Kremenekfb480492010-01-13 21:46:36 +00002760//===----------------------------------------------------------------------===//
2761// CXCursor Operations.
2762//===----------------------------------------------------------------------===//
2763
Ted Kremenekfb480492010-01-13 21:46:36 +00002764static Decl *getDeclFromExpr(Stmt *E) {
Argyrios Kyrtzidisc2954612011-09-12 22:17:26 +00002765 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Douglas Gregordb1314e2010-10-01 21:11:22 +00002766 return getDeclFromExpr(CE->getSubExpr());
2767
Ted Kremenekfb480492010-01-13 21:46:36 +00002768 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2769 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002770 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2771 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002772 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2773 return ME->getMemberDecl();
2774 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2775 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002776 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
John McCall12f78a62010-12-02 01:19:52 +00002777 return PRE->isExplicitProperty() ? PRE->getExplicitProperty() : 0;
John McCall4b9c2d22011-11-06 09:01:30 +00002778 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
2779 return getDeclFromExpr(POE->getSyntacticForm());
2780 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
2781 if (Expr *Src = OVE->getSourceExpr())
2782 return getDeclFromExpr(Src);
Douglas Gregordb1314e2010-10-01 21:11:22 +00002783
Ted Kremenekfb480492010-01-13 21:46:36 +00002784 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2785 return getDeclFromExpr(CE->getCallee());
Chris Lattner5f9e2722011-07-23 10:55:15 +00002786 if (CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Douglas Gregor93798e22010-11-05 21:11:19 +00002787 if (!CE->isElidable())
2788 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002789 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2790 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002791
Douglas Gregordb1314e2010-10-01 21:11:22 +00002792 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2793 return PE->getProtocol();
Douglas Gregorc7793c72011-01-15 01:15:58 +00002794 if (SubstNonTypeTemplateParmPackExpr *NTTP
2795 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
2796 return NTTP->getParameterPack();
Douglas Gregor94d96292011-01-19 20:34:17 +00002797 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2798 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
2799 isa<ParmVarDecl>(SizeOfPack->getPack()))
2800 return SizeOfPack->getPack();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002801
Ted Kremenekfb480492010-01-13 21:46:36 +00002802 return 0;
2803}
2804
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002805static SourceLocation getLocationFromExpr(Expr *E) {
Argyrios Kyrtzidisc2954612011-09-12 22:17:26 +00002806 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
2807 return getLocationFromExpr(CE->getSubExpr());
2808
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002809 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2810 return /*FIXME:*/Msg->getLeftLoc();
2811 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2812 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002813 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2814 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002815 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2816 return Member->getMemberLoc();
2817 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2818 return Ivar->getLocation();
Douglas Gregor94d96292011-01-19 20:34:17 +00002819 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2820 return SizeOfPack->getPackLoc();
2821
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002822 return E->getLocStart();
2823}
2824
Ted Kremenekfb480492010-01-13 21:46:36 +00002825extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002826
2827unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002828 CXCursorVisitor visitor,
2829 CXClientData client_data) {
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00002830 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
2831 /*VisitPreprocessorLast=*/false);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002832 return CursorVis.VisitChildren(parent);
2833}
2834
David Chisnall3387c652010-11-03 14:12:26 +00002835#ifndef __has_feature
2836#define __has_feature(x) 0
2837#endif
2838#if __has_feature(blocks)
2839typedef enum CXChildVisitResult
2840 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2841
2842static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2843 CXClientData client_data) {
2844 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2845 return block(cursor, parent);
2846}
2847#else
2848// If we are compiled with a compiler that doesn't have native blocks support,
2849// define and call the block manually, so the
2850typedef struct _CXChildVisitResult
2851{
2852 void *isa;
2853 int flags;
2854 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002855 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2856 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00002857} *CXCursorVisitorBlock;
2858
2859static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2860 CXClientData client_data) {
2861 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2862 return block->invoke(block, cursor, parent);
2863}
2864#endif
2865
2866
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002867unsigned clang_visitChildrenWithBlock(CXCursor parent,
2868 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00002869 return clang_visitChildren(parent, visitWithBlock, block);
2870}
2871
Douglas Gregor78205d42010-01-20 21:45:58 +00002872static CXString getDeclSpelling(Decl *D) {
2873 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
Douglas Gregore3c60a72010-11-17 00:13:31 +00002874 if (!ND) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002875 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00002876 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
2877 return createCXString(Property->getIdentifier()->getName());
2878
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002879 return createCXString("");
Douglas Gregore3c60a72010-11-17 00:13:31 +00002880 }
2881
Douglas Gregor78205d42010-01-20 21:45:58 +00002882 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002883 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002884
Douglas Gregor78205d42010-01-20 21:45:58 +00002885 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2886 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2887 // and returns different names. NamedDecl returns the class name and
2888 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002889 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002890
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002891 if (isa<UsingDirectiveDecl>(D))
2892 return createCXString("");
2893
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002894 llvm::SmallString<1024> S;
2895 llvm::raw_svector_ostream os(S);
2896 ND->printName(os);
2897
2898 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002899}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002900
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002901CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002902 if (clang_isTranslationUnit(C.kind))
Ted Kremeneka60ed472010-11-16 08:15:36 +00002903 return clang_getTranslationUnitSpelling(
2904 static_cast<CXTranslationUnit>(C.data[2]));
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002905
Steve Narofff334b4e2009-09-02 18:26:48 +00002906 if (clang_isReference(C.kind)) {
2907 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002908 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002909 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002910 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002911 }
2912 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002913 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002914 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002915 }
2916 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002917 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002918 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002919 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002920 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002921 case CXCursor_CXXBaseSpecifier: {
2922 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2923 return createCXString(B->getType().getAsString());
2924 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002925 case CXCursor_TypeRef: {
2926 TypeDecl *Type = getCursorTypeRef(C).first;
2927 assert(Type && "Missing type decl");
2928
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002929 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2930 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002931 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002932 case CXCursor_TemplateRef: {
2933 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002934 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002935
2936 return createCXString(Template->getNameAsString());
2937 }
Douglas Gregor69319002010-08-31 23:48:11 +00002938
2939 case CXCursor_NamespaceRef: {
2940 NamedDecl *NS = getCursorNamespaceRef(C).first;
2941 assert(NS && "Missing namespace decl");
2942
2943 return createCXString(NS->getNameAsString());
2944 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002945
Douglas Gregora67e03f2010-09-09 21:42:20 +00002946 case CXCursor_MemberRef: {
2947 FieldDecl *Field = getCursorMemberRef(C).first;
2948 assert(Field && "Missing member decl");
2949
2950 return createCXString(Field->getNameAsString());
2951 }
2952
Douglas Gregor36897b02010-09-10 00:22:18 +00002953 case CXCursor_LabelRef: {
2954 LabelStmt *Label = getCursorLabelRef(C).first;
2955 assert(Label && "Missing label");
2956
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002957 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00002958 }
2959
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002960 case CXCursor_OverloadedDeclRef: {
2961 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2962 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2963 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2964 return createCXString(ND->getNameAsString());
2965 return createCXString("");
2966 }
2967 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2968 return createCXString(E->getName().getAsString());
2969 OverloadedTemplateStorage *Ovl
2970 = Storage.get<OverloadedTemplateStorage*>();
2971 if (Ovl->size() == 0)
2972 return createCXString("");
2973 return createCXString((*Ovl->begin())->getNameAsString());
2974 }
2975
Daniel Dunbaracca7252009-11-30 20:42:49 +00002976 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002977 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002978 }
2979 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002980
2981 if (clang_isExpression(C.kind)) {
2982 Decl *D = getDeclFromExpr(getCursorExpr(C));
2983 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002984 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002985 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002986 }
2987
Douglas Gregor36897b02010-09-10 00:22:18 +00002988 if (clang_isStatement(C.kind)) {
2989 Stmt *S = getCursorStmt(C);
2990 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002991 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00002992
2993 return createCXString("");
2994 }
2995
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00002996 if (C.kind == CXCursor_MacroExpansion)
Chandler Carruth9e5bb852011-07-14 08:20:46 +00002997 return createCXString(getCursorMacroExpansion(C)->getName()
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002998 ->getNameStart());
2999
Douglas Gregor572feb22010-03-18 18:04:21 +00003000 if (C.kind == CXCursor_MacroDefinition)
3001 return createCXString(getCursorMacroDefinition(C)->getName()
3002 ->getNameStart());
3003
Douglas Gregorecdcb882010-10-20 22:00:55 +00003004 if (C.kind == CXCursor_InclusionDirective)
3005 return createCXString(getCursorInclusionDirective(C)->getFileName());
3006
Douglas Gregor60cbfac2010-01-25 16:56:17 +00003007 if (clang_isDeclaration(C.kind))
3008 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00003009
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00003010 if (C.kind == CXCursor_AnnotateAttr) {
3011 AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
3012 return createCXString(AA->getAnnotation());
3013 }
3014
Argyrios Kyrtzidis84b79642011-12-06 22:05:01 +00003015 if (C.kind == CXCursor_AsmLabelAttr) {
3016 AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
3017 return createCXString(AA->getLabel());
3018 }
3019
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003020 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00003021}
3022
Douglas Gregor358559d2010-10-02 22:49:11 +00003023CXString clang_getCursorDisplayName(CXCursor C) {
3024 if (!clang_isDeclaration(C.kind))
3025 return clang_getCursorSpelling(C);
3026
3027 Decl *D = getCursorDecl(C);
3028 if (!D)
3029 return createCXString("");
3030
Douglas Gregor30c42402011-09-27 22:38:19 +00003031 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
Douglas Gregor358559d2010-10-02 22:49:11 +00003032 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
3033 D = FunTmpl->getTemplatedDecl();
3034
3035 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
3036 llvm::SmallString<64> Str;
3037 llvm::raw_svector_ostream OS(Str);
3038 OS << Function->getNameAsString();
3039 if (Function->getPrimaryTemplate())
3040 OS << "<>";
3041 OS << "(";
3042 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
3043 if (I)
3044 OS << ", ";
3045 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
3046 }
3047
3048 if (Function->isVariadic()) {
3049 if (Function->getNumParams())
3050 OS << ", ";
3051 OS << "...";
3052 }
3053 OS << ")";
3054 return createCXString(OS.str());
3055 }
3056
3057 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
3058 llvm::SmallString<64> Str;
3059 llvm::raw_svector_ostream OS(Str);
3060 OS << ClassTemplate->getNameAsString();
3061 OS << "<";
3062 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
3063 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3064 if (I)
3065 OS << ", ";
3066
3067 NamedDecl *Param = Params->getParam(I);
3068 if (Param->getIdentifier()) {
3069 OS << Param->getIdentifier()->getName();
3070 continue;
3071 }
3072
3073 // There is no parameter name, which makes this tricky. Try to come up
3074 // with something useful that isn't too long.
3075 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3076 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
3077 else if (NonTypeTemplateParmDecl *NTTP
3078 = dyn_cast<NonTypeTemplateParmDecl>(Param))
3079 OS << NTTP->getType().getAsString(Policy);
3080 else
3081 OS << "template<...> class";
3082 }
3083
3084 OS << ">";
3085 return createCXString(OS.str());
3086 }
3087
3088 if (ClassTemplateSpecializationDecl *ClassSpec
3089 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
3090 // If the type was explicitly written, use that.
3091 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
3092 return createCXString(TSInfo->getType().getAsString(Policy));
3093
3094 llvm::SmallString<64> Str;
3095 llvm::raw_svector_ostream OS(Str);
3096 OS << ClassSpec->getNameAsString();
3097 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00003098 ClassSpec->getTemplateArgs().data(),
3099 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00003100 Policy);
3101 return createCXString(OS.str());
3102 }
3103
3104 return clang_getCursorSpelling(C);
3105}
3106
Ted Kremeneke68fff62010-02-17 00:41:32 +00003107CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00003108 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00003109 case CXCursor_FunctionDecl:
3110 return createCXString("FunctionDecl");
3111 case CXCursor_TypedefDecl:
3112 return createCXString("TypedefDecl");
3113 case CXCursor_EnumDecl:
3114 return createCXString("EnumDecl");
3115 case CXCursor_EnumConstantDecl:
3116 return createCXString("EnumConstantDecl");
3117 case CXCursor_StructDecl:
3118 return createCXString("StructDecl");
3119 case CXCursor_UnionDecl:
3120 return createCXString("UnionDecl");
3121 case CXCursor_ClassDecl:
3122 return createCXString("ClassDecl");
3123 case CXCursor_FieldDecl:
3124 return createCXString("FieldDecl");
3125 case CXCursor_VarDecl:
3126 return createCXString("VarDecl");
3127 case CXCursor_ParmDecl:
3128 return createCXString("ParmDecl");
3129 case CXCursor_ObjCInterfaceDecl:
3130 return createCXString("ObjCInterfaceDecl");
3131 case CXCursor_ObjCCategoryDecl:
3132 return createCXString("ObjCCategoryDecl");
3133 case CXCursor_ObjCProtocolDecl:
3134 return createCXString("ObjCProtocolDecl");
3135 case CXCursor_ObjCPropertyDecl:
3136 return createCXString("ObjCPropertyDecl");
3137 case CXCursor_ObjCIvarDecl:
3138 return createCXString("ObjCIvarDecl");
3139 case CXCursor_ObjCInstanceMethodDecl:
3140 return createCXString("ObjCInstanceMethodDecl");
3141 case CXCursor_ObjCClassMethodDecl:
3142 return createCXString("ObjCClassMethodDecl");
3143 case CXCursor_ObjCImplementationDecl:
3144 return createCXString("ObjCImplementationDecl");
3145 case CXCursor_ObjCCategoryImplDecl:
3146 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00003147 case CXCursor_CXXMethod:
3148 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003149 case CXCursor_UnexposedDecl:
3150 return createCXString("UnexposedDecl");
3151 case CXCursor_ObjCSuperClassRef:
3152 return createCXString("ObjCSuperClassRef");
3153 case CXCursor_ObjCProtocolRef:
3154 return createCXString("ObjCProtocolRef");
3155 case CXCursor_ObjCClassRef:
3156 return createCXString("ObjCClassRef");
3157 case CXCursor_TypeRef:
3158 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003159 case CXCursor_TemplateRef:
3160 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00003161 case CXCursor_NamespaceRef:
3162 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00003163 case CXCursor_MemberRef:
3164 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00003165 case CXCursor_LabelRef:
3166 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003167 case CXCursor_OverloadedDeclRef:
3168 return createCXString("OverloadedDeclRef");
Douglas Gregor42b29842011-10-05 19:00:14 +00003169 case CXCursor_IntegerLiteral:
3170 return createCXString("IntegerLiteral");
3171 case CXCursor_FloatingLiteral:
3172 return createCXString("FloatingLiteral");
3173 case CXCursor_ImaginaryLiteral:
3174 return createCXString("ImaginaryLiteral");
3175 case CXCursor_StringLiteral:
3176 return createCXString("StringLiteral");
3177 case CXCursor_CharacterLiteral:
3178 return createCXString("CharacterLiteral");
3179 case CXCursor_ParenExpr:
3180 return createCXString("ParenExpr");
3181 case CXCursor_UnaryOperator:
3182 return createCXString("UnaryOperator");
3183 case CXCursor_ArraySubscriptExpr:
3184 return createCXString("ArraySubscriptExpr");
3185 case CXCursor_BinaryOperator:
3186 return createCXString("BinaryOperator");
3187 case CXCursor_CompoundAssignOperator:
3188 return createCXString("CompoundAssignOperator");
3189 case CXCursor_ConditionalOperator:
3190 return createCXString("ConditionalOperator");
3191 case CXCursor_CStyleCastExpr:
3192 return createCXString("CStyleCastExpr");
3193 case CXCursor_CompoundLiteralExpr:
3194 return createCXString("CompoundLiteralExpr");
3195 case CXCursor_InitListExpr:
3196 return createCXString("InitListExpr");
3197 case CXCursor_AddrLabelExpr:
3198 return createCXString("AddrLabelExpr");
3199 case CXCursor_StmtExpr:
3200 return createCXString("StmtExpr");
3201 case CXCursor_GenericSelectionExpr:
3202 return createCXString("GenericSelectionExpr");
3203 case CXCursor_GNUNullExpr:
3204 return createCXString("GNUNullExpr");
3205 case CXCursor_CXXStaticCastExpr:
3206 return createCXString("CXXStaticCastExpr");
3207 case CXCursor_CXXDynamicCastExpr:
3208 return createCXString("CXXDynamicCastExpr");
3209 case CXCursor_CXXReinterpretCastExpr:
3210 return createCXString("CXXReinterpretCastExpr");
3211 case CXCursor_CXXConstCastExpr:
3212 return createCXString("CXXConstCastExpr");
3213 case CXCursor_CXXFunctionalCastExpr:
3214 return createCXString("CXXFunctionalCastExpr");
3215 case CXCursor_CXXTypeidExpr:
3216 return createCXString("CXXTypeidExpr");
3217 case CXCursor_CXXBoolLiteralExpr:
3218 return createCXString("CXXBoolLiteralExpr");
3219 case CXCursor_CXXNullPtrLiteralExpr:
3220 return createCXString("CXXNullPtrLiteralExpr");
3221 case CXCursor_CXXThisExpr:
3222 return createCXString("CXXThisExpr");
3223 case CXCursor_CXXThrowExpr:
3224 return createCXString("CXXThrowExpr");
3225 case CXCursor_CXXNewExpr:
3226 return createCXString("CXXNewExpr");
3227 case CXCursor_CXXDeleteExpr:
3228 return createCXString("CXXDeleteExpr");
3229 case CXCursor_UnaryExpr:
3230 return createCXString("UnaryExpr");
3231 case CXCursor_ObjCStringLiteral:
3232 return createCXString("ObjCStringLiteral");
3233 case CXCursor_ObjCEncodeExpr:
3234 return createCXString("ObjCEncodeExpr");
3235 case CXCursor_ObjCSelectorExpr:
3236 return createCXString("ObjCSelectorExpr");
3237 case CXCursor_ObjCProtocolExpr:
3238 return createCXString("ObjCProtocolExpr");
3239 case CXCursor_ObjCBridgedCastExpr:
3240 return createCXString("ObjCBridgedCastExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00003241 case CXCursor_BlockExpr:
3242 return createCXString("BlockExpr");
Douglas Gregor42b29842011-10-05 19:00:14 +00003243 case CXCursor_PackExpansionExpr:
3244 return createCXString("PackExpansionExpr");
3245 case CXCursor_SizeOfPackExpr:
3246 return createCXString("SizeOfPackExpr");
3247 case CXCursor_UnexposedExpr:
3248 return createCXString("UnexposedExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003249 case CXCursor_DeclRefExpr:
3250 return createCXString("DeclRefExpr");
3251 case CXCursor_MemberRefExpr:
3252 return createCXString("MemberRefExpr");
3253 case CXCursor_CallExpr:
3254 return createCXString("CallExpr");
3255 case CXCursor_ObjCMessageExpr:
3256 return createCXString("ObjCMessageExpr");
3257 case CXCursor_UnexposedStmt:
3258 return createCXString("UnexposedStmt");
Douglas Gregor42b29842011-10-05 19:00:14 +00003259 case CXCursor_DeclStmt:
3260 return createCXString("DeclStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00003261 case CXCursor_LabelStmt:
3262 return createCXString("LabelStmt");
Douglas Gregor42b29842011-10-05 19:00:14 +00003263 case CXCursor_CompoundStmt:
3264 return createCXString("CompoundStmt");
3265 case CXCursor_CaseStmt:
3266 return createCXString("CaseStmt");
3267 case CXCursor_DefaultStmt:
3268 return createCXString("DefaultStmt");
3269 case CXCursor_IfStmt:
3270 return createCXString("IfStmt");
3271 case CXCursor_SwitchStmt:
3272 return createCXString("SwitchStmt");
3273 case CXCursor_WhileStmt:
3274 return createCXString("WhileStmt");
3275 case CXCursor_DoStmt:
3276 return createCXString("DoStmt");
3277 case CXCursor_ForStmt:
3278 return createCXString("ForStmt");
3279 case CXCursor_GotoStmt:
3280 return createCXString("GotoStmt");
3281 case CXCursor_IndirectGotoStmt:
3282 return createCXString("IndirectGotoStmt");
3283 case CXCursor_ContinueStmt:
3284 return createCXString("ContinueStmt");
3285 case CXCursor_BreakStmt:
3286 return createCXString("BreakStmt");
3287 case CXCursor_ReturnStmt:
3288 return createCXString("ReturnStmt");
3289 case CXCursor_AsmStmt:
3290 return createCXString("AsmStmt");
3291 case CXCursor_ObjCAtTryStmt:
3292 return createCXString("ObjCAtTryStmt");
3293 case CXCursor_ObjCAtCatchStmt:
3294 return createCXString("ObjCAtCatchStmt");
3295 case CXCursor_ObjCAtFinallyStmt:
3296 return createCXString("ObjCAtFinallyStmt");
3297 case CXCursor_ObjCAtThrowStmt:
3298 return createCXString("ObjCAtThrowStmt");
3299 case CXCursor_ObjCAtSynchronizedStmt:
3300 return createCXString("ObjCAtSynchronizedStmt");
3301 case CXCursor_ObjCAutoreleasePoolStmt:
3302 return createCXString("ObjCAutoreleasePoolStmt");
3303 case CXCursor_ObjCForCollectionStmt:
3304 return createCXString("ObjCForCollectionStmt");
3305 case CXCursor_CXXCatchStmt:
3306 return createCXString("CXXCatchStmt");
3307 case CXCursor_CXXTryStmt:
3308 return createCXString("CXXTryStmt");
3309 case CXCursor_CXXForRangeStmt:
3310 return createCXString("CXXForRangeStmt");
3311 case CXCursor_SEHTryStmt:
3312 return createCXString("SEHTryStmt");
3313 case CXCursor_SEHExceptStmt:
3314 return createCXString("SEHExceptStmt");
3315 case CXCursor_SEHFinallyStmt:
3316 return createCXString("SEHFinallyStmt");
3317 case CXCursor_NullStmt:
3318 return createCXString("NullStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003319 case CXCursor_InvalidFile:
3320 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00003321 case CXCursor_InvalidCode:
3322 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003323 case CXCursor_NoDeclFound:
3324 return createCXString("NoDeclFound");
3325 case CXCursor_NotImplemented:
3326 return createCXString("NotImplemented");
3327 case CXCursor_TranslationUnit:
3328 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00003329 case CXCursor_UnexposedAttr:
3330 return createCXString("UnexposedAttr");
3331 case CXCursor_IBActionAttr:
3332 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003333 case CXCursor_IBOutletAttr:
3334 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003335 case CXCursor_IBOutletCollectionAttr:
3336 return createCXString("attribute(iboutletcollection)");
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00003337 case CXCursor_CXXFinalAttr:
3338 return createCXString("attribute(final)");
3339 case CXCursor_CXXOverrideAttr:
3340 return createCXString("attribute(override)");
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00003341 case CXCursor_AnnotateAttr:
3342 return createCXString("attribute(annotate)");
Argyrios Kyrtzidis84b79642011-12-06 22:05:01 +00003343 case CXCursor_AsmLabelAttr:
3344 return createCXString("asm label");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003345 case CXCursor_PreprocessingDirective:
3346 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003347 case CXCursor_MacroDefinition:
3348 return createCXString("macro definition");
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003349 case CXCursor_MacroExpansion:
3350 return createCXString("macro expansion");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003351 case CXCursor_InclusionDirective:
3352 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003353 case CXCursor_Namespace:
3354 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003355 case CXCursor_LinkageSpec:
3356 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003357 case CXCursor_CXXBaseSpecifier:
3358 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003359 case CXCursor_Constructor:
3360 return createCXString("CXXConstructor");
3361 case CXCursor_Destructor:
3362 return createCXString("CXXDestructor");
3363 case CXCursor_ConversionFunction:
3364 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003365 case CXCursor_TemplateTypeParameter:
3366 return createCXString("TemplateTypeParameter");
3367 case CXCursor_NonTypeTemplateParameter:
3368 return createCXString("NonTypeTemplateParameter");
3369 case CXCursor_TemplateTemplateParameter:
3370 return createCXString("TemplateTemplateParameter");
3371 case CXCursor_FunctionTemplate:
3372 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003373 case CXCursor_ClassTemplate:
3374 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003375 case CXCursor_ClassTemplatePartialSpecialization:
3376 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003377 case CXCursor_NamespaceAlias:
3378 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003379 case CXCursor_UsingDirective:
3380 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003381 case CXCursor_UsingDeclaration:
3382 return createCXString("UsingDeclaration");
Richard Smith162e1c12011-04-15 14:24:37 +00003383 case CXCursor_TypeAliasDecl:
Douglas Gregor352697a2011-06-03 23:08:58 +00003384 return createCXString("TypeAliasDecl");
3385 case CXCursor_ObjCSynthesizeDecl:
3386 return createCXString("ObjCSynthesizeDecl");
3387 case CXCursor_ObjCDynamicDecl:
3388 return createCXString("ObjCDynamicDecl");
Argyrios Kyrtzidis2dfdb942011-09-30 17:58:23 +00003389 case CXCursor_CXXAccessSpecifier:
3390 return createCXString("CXXAccessSpecifier");
Steve Naroff89922f82009-08-31 00:59:03 +00003391 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003392
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003393 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneka60ed472010-11-16 08:15:36 +00003394 return createCXString((const char*) 0);
Steve Naroff600866c2009-08-27 19:51:58 +00003395}
Steve Naroff89922f82009-08-31 00:59:03 +00003396
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003397struct GetCursorData {
3398 SourceLocation TokenBeginLoc;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003399 bool PointsAtMacroArgExpansion;
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003400 CXCursor &BestCursor;
3401
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003402 GetCursorData(SourceManager &SM,
3403 SourceLocation tokenBegin, CXCursor &outputCursor)
3404 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
3405 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
3406 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003407};
3408
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003409static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3410 CXCursor parent,
3411 CXClientData client_data) {
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003412 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
3413 CXCursor *BestCursor = &Data->BestCursor;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003414
3415 // If we point inside a macro argument we should provide info of what the
3416 // token is so use the actual cursor, don't replace it with a macro expansion
3417 // cursor.
3418 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
3419 return CXChildVisit_Recurse;
Argyrios Kyrtzidis65ab9072011-09-26 19:05:37 +00003420
3421 if (clang_isDeclaration(cursor.kind)) {
3422 // Avoid having the implicit methods override the property decls.
3423 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(getCursorDecl(cursor)))
3424 if (MD->isImplicit())
3425 return CXChildVisit_Break;
3426 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003427
3428 if (clang_isExpression(cursor.kind) &&
3429 clang_isDeclaration(BestCursor->kind)) {
3430 Decl *D = getCursorDecl(*BestCursor);
3431
3432 // Avoid having the cursor of an expression replace the declaration cursor
3433 // when the expression source range overlaps the declaration range.
3434 // This can happen for C++ constructor expressions whose range generally
3435 // include the variable declaration, e.g.:
3436 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
3437 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
3438 D->getLocation() == Data->TokenBeginLoc)
3439 return CXChildVisit_Break;
3440 }
3441
Douglas Gregor93798e22010-11-05 21:11:19 +00003442 // If our current best cursor is the construction of a temporary object,
3443 // don't replace that cursor with a type reference, because we want
3444 // clang_getCursor() to point at the constructor.
3445 if (clang_isExpression(BestCursor->kind) &&
3446 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003447 cursor.kind == CXCursor_TypeRef) {
3448 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
3449 // as having the actual point on the type reference.
3450 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
Douglas Gregor93798e22010-11-05 21:11:19 +00003451 return CXChildVisit_Recurse;
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003452 }
Douglas Gregor93798e22010-11-05 21:11:19 +00003453
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003454 *BestCursor = cursor;
3455 return CXChildVisit_Recurse;
3456}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003457
Douglas Gregorb9790342010-01-22 21:44:22 +00003458CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3459 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003460 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003461
Ted Kremeneka60ed472010-11-16 08:15:36 +00003462 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003463 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3464
Ted Kremeneka297de22010-01-25 22:34:44 +00003465 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003466 CXCursor Result = cxcursor::getCursor(TU, SLoc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003467
Douglas Gregor40749ee2010-11-03 00:35:38 +00003468 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregor40749ee2010-11-03 00:35:38 +00003469 if (Logging) {
3470 CXFile SearchFile;
3471 unsigned SearchLine, SearchColumn;
3472 CXFile ResultFile;
3473 unsigned ResultLine, ResultColumn;
Douglas Gregor66537982010-11-17 17:14:07 +00003474 CXString SearchFileName, ResultFileName, KindSpelling, USR;
3475 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
Douglas Gregor40749ee2010-11-03 00:35:38 +00003476 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3477
Chandler Carruth20174222011-08-31 16:53:37 +00003478 clang_getExpansionLocation(Loc, &SearchFile, &SearchLine, &SearchColumn, 0);
3479 clang_getExpansionLocation(ResultLoc, &ResultFile, &ResultLine,
3480 &ResultColumn, 0);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003481 SearchFileName = clang_getFileName(SearchFile);
3482 ResultFileName = clang_getFileName(ResultFile);
3483 KindSpelling = clang_getCursorKindSpelling(Result.kind);
Douglas Gregor66537982010-11-17 17:14:07 +00003484 USR = clang_getCursorUSR(Result);
3485 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n",
Douglas Gregor40749ee2010-11-03 00:35:38 +00003486 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3487 clang_getCString(KindSpelling),
Douglas Gregor66537982010-11-17 17:14:07 +00003488 clang_getCString(ResultFileName), ResultLine, ResultColumn,
3489 clang_getCString(USR), IsDef);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003490 clang_disposeString(SearchFileName);
3491 clang_disposeString(ResultFileName);
3492 clang_disposeString(KindSpelling);
Douglas Gregor66537982010-11-17 17:14:07 +00003493 clang_disposeString(USR);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003494
3495 CXCursor Definition = clang_getCursorDefinition(Result);
3496 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
3497 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
3498 CXString DefinitionKindSpelling
3499 = clang_getCursorKindSpelling(Definition.kind);
3500 CXFile DefinitionFile;
3501 unsigned DefinitionLine, DefinitionColumn;
Chandler Carruth20174222011-08-31 16:53:37 +00003502 clang_getExpansionLocation(DefinitionLoc, &DefinitionFile,
3503 &DefinitionLine, &DefinitionColumn, 0);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003504 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
3505 fprintf(stderr, " -> %s(%s:%d:%d)\n",
3506 clang_getCString(DefinitionKindSpelling),
3507 clang_getCString(DefinitionFileName),
3508 DefinitionLine, DefinitionColumn);
3509 clang_disposeString(DefinitionFileName);
3510 clang_disposeString(DefinitionKindSpelling);
3511 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003512 }
3513
Ted Kremeneke68fff62010-02-17 00:41:32 +00003514 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003515}
3516
Ted Kremenek73885552009-11-17 19:28:59 +00003517CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003518 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003519}
3520
3521unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003522 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003523}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003524
Douglas Gregor9ce55842010-11-20 00:09:34 +00003525unsigned clang_hashCursor(CXCursor C) {
3526 unsigned Index = 0;
3527 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
3528 Index = 1;
3529
3530 return llvm::DenseMapInfo<std::pair<unsigned, void*> >::getHashValue(
3531 std::make_pair(C.kind, C.data[Index]));
3532}
3533
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003534unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003535 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3536}
3537
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003538unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003539 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3540}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003541
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003542unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003543 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3544}
3545
Douglas Gregor97b98722010-01-19 23:20:36 +00003546unsigned clang_isExpression(enum CXCursorKind K) {
3547 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3548}
3549
3550unsigned clang_isStatement(enum CXCursorKind K) {
3551 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3552}
3553
Douglas Gregor8be80e12011-07-06 03:00:34 +00003554unsigned clang_isAttribute(enum CXCursorKind K) {
3555 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
3556}
3557
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003558unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3559 return K == CXCursor_TranslationUnit;
3560}
3561
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003562unsigned clang_isPreprocessing(enum CXCursorKind K) {
3563 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3564}
3565
Ted Kremenekad6eff62010-03-08 21:17:29 +00003566unsigned clang_isUnexposed(enum CXCursorKind K) {
3567 switch (K) {
3568 case CXCursor_UnexposedDecl:
3569 case CXCursor_UnexposedExpr:
3570 case CXCursor_UnexposedStmt:
3571 case CXCursor_UnexposedAttr:
3572 return true;
3573 default:
3574 return false;
3575 }
3576}
3577
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003578CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003579 return C.kind;
3580}
3581
Douglas Gregor98258af2010-01-18 22:46:11 +00003582CXSourceLocation clang_getCursorLocation(CXCursor C) {
3583 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003584 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003585 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003586 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3587 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003588 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003589 }
3590
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003591 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003592 std::pair<ObjCProtocolDecl *, SourceLocation> P
3593 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003594 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003595 }
3596
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003597 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003598 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3599 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003600 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003601 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003602
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003603 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003604 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003605 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003606 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003607
3608 case CXCursor_TemplateRef: {
3609 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3610 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3611 }
3612
Douglas Gregor69319002010-08-31 23:48:11 +00003613 case CXCursor_NamespaceRef: {
3614 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3615 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3616 }
3617
Douglas Gregora67e03f2010-09-09 21:42:20 +00003618 case CXCursor_MemberRef: {
3619 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3620 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3621 }
3622
Ted Kremenek3064ef92010-08-27 21:34:58 +00003623 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003624 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3625 if (!BaseSpec)
3626 return clang_getNullLocation();
3627
3628 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3629 return cxloc::translateSourceLocation(getCursorContext(C),
3630 TSInfo->getTypeLoc().getBeginLoc());
3631
3632 return cxloc::translateSourceLocation(getCursorContext(C),
3633 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003634 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003635
Douglas Gregor36897b02010-09-10 00:22:18 +00003636 case CXCursor_LabelRef: {
3637 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3638 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3639 }
3640
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003641 case CXCursor_OverloadedDeclRef:
3642 return cxloc::translateSourceLocation(getCursorContext(C),
3643 getCursorOverloadedDeclRef(C).second);
3644
Douglas Gregorf46034a2010-01-18 23:41:10 +00003645 default:
3646 // FIXME: Need a way to enumerate all non-reference cases.
3647 llvm_unreachable("Missed a reference kind");
3648 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003649 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003650
3651 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003652 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003653 getLocationFromExpr(getCursorExpr(C)));
3654
Douglas Gregor36897b02010-09-10 00:22:18 +00003655 if (clang_isStatement(C.kind))
3656 return cxloc::translateSourceLocation(getCursorContext(C),
3657 getCursorStmt(C)->getLocStart());
3658
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003659 if (C.kind == CXCursor_PreprocessingDirective) {
3660 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3661 return cxloc::translateSourceLocation(getCursorContext(C), L);
3662 }
Douglas Gregor48072312010-03-18 15:23:44 +00003663
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003664 if (C.kind == CXCursor_MacroExpansion) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003665 SourceLocation L
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003666 = cxcursor::getCursorMacroExpansion(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003667 return cxloc::translateSourceLocation(getCursorContext(C), L);
3668 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003669
3670 if (C.kind == CXCursor_MacroDefinition) {
3671 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3672 return cxloc::translateSourceLocation(getCursorContext(C), L);
3673 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003674
3675 if (C.kind == CXCursor_InclusionDirective) {
3676 SourceLocation L
3677 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3678 return cxloc::translateSourceLocation(getCursorContext(C), L);
3679 }
3680
Ted Kremenek9a700d22010-05-12 06:16:13 +00003681 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003682 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003683
Douglas Gregorf46034a2010-01-18 23:41:10 +00003684 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003685 SourceLocation Loc = D->getLocation();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003686 // FIXME: Multiple variables declared in a single declaration
3687 // currently lack the information needed to correctly determine their
3688 // ranges when accounting for the type-specifier. We use context
3689 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3690 // and if so, whether it is the first decl.
3691 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3692 if (!cxcursor::isFirstInDeclGroup(C))
3693 Loc = VD->getLocation();
3694 }
3695
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003696 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003697}
Douglas Gregora7bde202010-01-19 00:34:46 +00003698
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003699} // end extern "C"
3700
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003701CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
3702 assert(TU);
3703
3704 // Guard against an invalid SourceLocation, or we may assert in one
3705 // of the following calls.
3706 if (SLoc.isInvalid())
3707 return clang_getNullCursor();
3708
3709 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
3710
3711 // Translate the given source location to make it point at the beginning of
3712 // the token under the cursor.
3713 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3714 CXXUnit->getASTContext().getLangOptions());
3715
3716 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3717 if (SLoc.isValid()) {
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003718 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003719 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
3720 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00003721 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003722 SourceLocation(SLoc));
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00003723 CursorVis.visitFileRegion();
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003724 }
3725
3726 return Result;
3727}
3728
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003729static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003730 if (clang_isReference(C.kind)) {
3731 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003732 case CXCursor_ObjCSuperClassRef:
3733 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003734
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003735 case CXCursor_ObjCProtocolRef:
3736 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003737
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003738 case CXCursor_ObjCClassRef:
3739 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003740
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003741 case CXCursor_TypeRef:
3742 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003743
3744 case CXCursor_TemplateRef:
3745 return getCursorTemplateRef(C).second;
3746
Douglas Gregor69319002010-08-31 23:48:11 +00003747 case CXCursor_NamespaceRef:
3748 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003749
3750 case CXCursor_MemberRef:
3751 return getCursorMemberRef(C).second;
3752
Ted Kremenek3064ef92010-08-27 21:34:58 +00003753 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003754 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003755
Douglas Gregor36897b02010-09-10 00:22:18 +00003756 case CXCursor_LabelRef:
3757 return getCursorLabelRef(C).second;
3758
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003759 case CXCursor_OverloadedDeclRef:
3760 return getCursorOverloadedDeclRef(C).second;
3761
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003762 default:
3763 // FIXME: Need a way to enumerate all non-reference cases.
3764 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003765 }
3766 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003767
3768 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003769 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003770
3771 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003772 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003773
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00003774 if (clang_isAttribute(C.kind))
3775 return getCursorAttr(C)->getRange();
3776
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003777 if (C.kind == CXCursor_PreprocessingDirective)
3778 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003779
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00003780 if (C.kind == CXCursor_MacroExpansion) {
3781 ASTUnit *TU = getCursorASTUnit(C);
3782 SourceRange Range = cxcursor::getCursorMacroExpansion(C)->getSourceRange();
3783 return TU->mapRangeFromPreamble(Range);
3784 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003785
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00003786 if (C.kind == CXCursor_MacroDefinition) {
3787 ASTUnit *TU = getCursorASTUnit(C);
3788 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
3789 return TU->mapRangeFromPreamble(Range);
3790 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003791
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00003792 if (C.kind == CXCursor_InclusionDirective) {
3793 ASTUnit *TU = getCursorASTUnit(C);
3794 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3795 return TU->mapRangeFromPreamble(Range);
3796 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003797
Ted Kremenek007a7c92010-11-01 23:26:51 +00003798 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3799 Decl *D = cxcursor::getCursorDecl(C);
3800 SourceRange R = D->getSourceRange();
3801 // FIXME: Multiple variables declared in a single declaration
3802 // currently lack the information needed to correctly determine their
3803 // ranges when accounting for the type-specifier. We use context
3804 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3805 // and if so, whether it is the first decl.
3806 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3807 if (!cxcursor::isFirstInDeclGroup(C))
3808 R.setBegin(VD->getLocation());
3809 }
3810 return R;
3811 }
Douglas Gregor66537982010-11-17 17:14:07 +00003812 return SourceRange();
3813}
3814
3815/// \brief Retrieves the "raw" cursor extent, which is then extended to include
3816/// the decl-specifier-seq for declarations.
3817static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
3818 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3819 Decl *D = cxcursor::getCursorDecl(C);
3820 SourceRange R = D->getSourceRange();
Douglas Gregor66537982010-11-17 17:14:07 +00003821
Douglas Gregor2494dd02011-03-01 01:34:45 +00003822 // Adjust the start of the location for declarations preceded by
3823 // declaration specifiers.
3824 SourceLocation StartLoc;
3825 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
3826 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
3827 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
3828 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
3829 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
3830 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
3831 }
3832
3833 if (StartLoc.isValid() && R.getBegin().isValid() &&
3834 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
3835 R.setBegin(StartLoc);
3836
3837 // FIXME: Multiple variables declared in a single declaration
3838 // currently lack the information needed to correctly determine their
3839 // ranges when accounting for the type-specifier. We use context
3840 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3841 // and if so, whether it is the first decl.
3842 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3843 if (!cxcursor::isFirstInDeclGroup(C))
3844 R.setBegin(VD->getLocation());
Douglas Gregor66537982010-11-17 17:14:07 +00003845 }
3846
3847 return R;
3848 }
3849
3850 return getRawCursorExtent(C);
3851}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003852
3853extern "C" {
3854
3855CXSourceRange clang_getCursorExtent(CXCursor C) {
3856 SourceRange R = getRawCursorExtent(C);
3857 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003858 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003859
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003860 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003861}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003862
3863CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003864 if (clang_isInvalid(C.kind))
3865 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003866
Ted Kremeneka60ed472010-11-16 08:15:36 +00003867 CXTranslationUnit tu = getCursorTU(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003868 if (clang_isDeclaration(C.kind)) {
3869 Decl *D = getCursorDecl(C);
3870 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003871 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003872 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003873 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003874 if (ObjCForwardProtocolDecl *Protocols
3875 = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003876 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), tu);
Chris Lattner5f9e2722011-07-23 10:55:15 +00003877 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00003878 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3879 return MakeCXCursor(Property, tu);
3880
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003881 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003882 }
3883
Douglas Gregor97b98722010-01-19 23:20:36 +00003884 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003885 Expr *E = getCursorExpr(C);
3886 Decl *D = getDeclFromExpr(E);
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003887 if (D) {
3888 CXCursor declCursor = MakeCXCursor(D, tu);
3889 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
3890 declCursor);
3891 return declCursor;
3892 }
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003893
3894 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003895 return MakeCursorOverloadedDeclRef(Ovl, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003896
Douglas Gregor97b98722010-01-19 23:20:36 +00003897 return clang_getNullCursor();
3898 }
3899
Douglas Gregor36897b02010-09-10 00:22:18 +00003900 if (clang_isStatement(C.kind)) {
3901 Stmt *S = getCursorStmt(C);
3902 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Ted Kremenek37c2e962011-03-15 23:47:49 +00003903 if (LabelDecl *label = Goto->getLabel())
3904 if (LabelStmt *labelS = label->getStmt())
3905 return MakeCXCursor(labelS, getCursorDecl(C), tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003906
3907 return clang_getNullCursor();
3908 }
3909
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003910 if (C.kind == CXCursor_MacroExpansion) {
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003911 if (MacroDefinition *Def = getCursorMacroExpansion(C)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003912 return MakeMacroDefinitionCursor(Def, tu);
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003913 }
3914
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003915 if (!clang_isReference(C.kind))
3916 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003917
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003918 switch (C.kind) {
3919 case CXCursor_ObjCSuperClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003920 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003921
3922 case CXCursor_ObjCProtocolRef: {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003923 return MakeCXCursor(getCursorObjCProtocolRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003924
3925 case CXCursor_ObjCClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003926 return MakeCXCursor(getCursorObjCClassRef(C).first, tu );
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003927
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003928 case CXCursor_TypeRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003929 return MakeCXCursor(getCursorTypeRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003930
3931 case CXCursor_TemplateRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003932 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003933
Douglas Gregor69319002010-08-31 23:48:11 +00003934 case CXCursor_NamespaceRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003935 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
Douglas Gregor69319002010-08-31 23:48:11 +00003936
Douglas Gregora67e03f2010-09-09 21:42:20 +00003937 case CXCursor_MemberRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003938 return MakeCXCursor(getCursorMemberRef(C).first, tu );
Douglas Gregora67e03f2010-09-09 21:42:20 +00003939
Ted Kremenek3064ef92010-08-27 21:34:58 +00003940 case CXCursor_CXXBaseSpecifier: {
3941 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3942 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003943 tu ));
Ted Kremenek3064ef92010-08-27 21:34:58 +00003944 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003945
Douglas Gregor36897b02010-09-10 00:22:18 +00003946 case CXCursor_LabelRef:
3947 // FIXME: We end up faking the "parent" declaration here because we
3948 // don't want to make CXCursor larger.
3949 return MakeCXCursor(getCursorLabelRef(C).first,
Ted Kremeneka60ed472010-11-16 08:15:36 +00003950 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
3951 .getTranslationUnitDecl(),
3952 tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003953
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003954 case CXCursor_OverloadedDeclRef:
3955 return C;
3956
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003957 default:
3958 // We would prefer to enumerate all non-reference cursor kinds here.
3959 llvm_unreachable("Unhandled reference cursor kind");
3960 break;
3961 }
3962 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003963
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003964 return clang_getNullCursor();
3965}
3966
Douglas Gregorb6998662010-01-19 19:34:47 +00003967CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003968 if (clang_isInvalid(C.kind))
3969 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003970
Ted Kremeneka60ed472010-11-16 08:15:36 +00003971 CXTranslationUnit TU = getCursorTU(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003972
Douglas Gregorb6998662010-01-19 19:34:47 +00003973 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003974 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003975 C = clang_getCursorReferenced(C);
3976 WasReference = true;
3977 }
3978
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003979 if (C.kind == CXCursor_MacroExpansion)
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003980 return clang_getCursorReferenced(C);
3981
Douglas Gregorb6998662010-01-19 19:34:47 +00003982 if (!clang_isDeclaration(C.kind))
3983 return clang_getNullCursor();
3984
3985 Decl *D = getCursorDecl(C);
3986 if (!D)
3987 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003988
Douglas Gregorb6998662010-01-19 19:34:47 +00003989 switch (D->getKind()) {
3990 // Declaration kinds that don't really separate the notions of
3991 // declaration and definition.
3992 case Decl::Namespace:
3993 case Decl::Typedef:
Richard Smith162e1c12011-04-15 14:24:37 +00003994 case Decl::TypeAlias:
Richard Smith3e4c6c42011-05-05 21:57:07 +00003995 case Decl::TypeAliasTemplate:
Douglas Gregorb6998662010-01-19 19:34:47 +00003996 case Decl::TemplateTypeParm:
3997 case Decl::EnumConstant:
3998 case Decl::Field:
Benjamin Kramerd9811462010-11-21 14:11:41 +00003999 case Decl::IndirectField:
Douglas Gregorb6998662010-01-19 19:34:47 +00004000 case Decl::ObjCIvar:
4001 case Decl::ObjCAtDefsField:
4002 case Decl::ImplicitParam:
4003 case Decl::ParmVar:
4004 case Decl::NonTypeTemplateParm:
4005 case Decl::TemplateTemplateParm:
4006 case Decl::ObjCCategoryImpl:
4007 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00004008 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00004009 case Decl::LinkageSpec:
4010 case Decl::ObjCPropertyImpl:
4011 case Decl::FileScopeAsm:
4012 case Decl::StaticAssert:
4013 case Decl::Block:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00004014 case Decl::Label: // FIXME: Is this right??
Francois Pichetaf0f4d02011-08-14 03:52:19 +00004015 case Decl::ClassScopeFunctionSpecialization:
Douglas Gregor15de72c2011-12-02 23:23:56 +00004016 case Decl::Import:
Douglas Gregorb6998662010-01-19 19:34:47 +00004017 return C;
4018
4019 // Declaration kinds that don't make any sense here, but are
4020 // nonetheless harmless.
4021 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00004022 break;
4023
4024 // Declaration kinds for which the definition is not resolvable.
4025 case Decl::UnresolvedUsingTypename:
4026 case Decl::UnresolvedUsingValue:
4027 break;
4028
4029 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00004030 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004031 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004032
4033 case Decl::NamespaceAlias:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004034 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004035
4036 case Decl::Enum:
4037 case Decl::Record:
4038 case Decl::CXXRecord:
4039 case Decl::ClassTemplateSpecialization:
4040 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00004041 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004042 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004043 return clang_getNullCursor();
4044
4045 case Decl::Function:
4046 case Decl::CXXMethod:
4047 case Decl::CXXConstructor:
4048 case Decl::CXXDestructor:
4049 case Decl::CXXConversion: {
4050 const FunctionDecl *Def = 0;
4051 if (cast<FunctionDecl>(D)->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004052 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004053 return clang_getNullCursor();
4054 }
4055
4056 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00004057 // Ask the variable if it has a definition.
4058 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004059 return MakeCXCursor(Def, TU);
Sebastian Redl31310a22010-02-01 20:16:42 +00004060 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00004061 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004062
Douglas Gregorb6998662010-01-19 19:34:47 +00004063 case Decl::FunctionTemplate: {
4064 const FunctionDecl *Def = 0;
4065 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004066 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004067 return clang_getNullCursor();
4068 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004069
Douglas Gregorb6998662010-01-19 19:34:47 +00004070 case Decl::ClassTemplate: {
4071 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00004072 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00004073 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004074 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004075 return clang_getNullCursor();
4076 }
4077
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004078 case Decl::Using:
4079 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004080 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004081
4082 case Decl::UsingShadow:
4083 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004084 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004085 TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004086
4087 case Decl::ObjCMethod: {
4088 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
4089 if (Method->isThisDeclarationADefinition())
4090 return C;
4091
4092 // Dig out the method definition in the associated
4093 // @implementation, if we have it.
4094 // FIXME: The ASTs should make finding the definition easier.
4095 if (ObjCInterfaceDecl *Class
4096 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
4097 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
4098 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
4099 Method->isInstanceMethod()))
4100 if (Def->isThisDeclarationADefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004101 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004102
4103 return clang_getNullCursor();
4104 }
4105
4106 case Decl::ObjCCategory:
4107 if (ObjCCategoryImplDecl *Impl
4108 = cast<ObjCCategoryDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004109 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004110 return clang_getNullCursor();
4111
4112 case Decl::ObjCProtocol:
4113 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
4114 return C;
4115 return clang_getNullCursor();
4116
4117 case Decl::ObjCInterface:
4118 // There are two notions of a "definition" for an Objective-C
4119 // class: the interface and its implementation. When we resolved a
4120 // reference to an Objective-C class, produce the @interface as
4121 // the definition; when we were provided with the interface,
4122 // produce the @implementation as the definition.
4123 if (WasReference) {
4124 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
4125 return C;
4126 } else if (ObjCImplementationDecl *Impl
4127 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004128 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004129 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004130
Douglas Gregorb6998662010-01-19 19:34:47 +00004131 case Decl::ObjCProperty:
4132 // FIXME: We don't really know where to find the
4133 // ObjCPropertyImplDecls that implement this property.
4134 return clang_getNullCursor();
4135
4136 case Decl::ObjCCompatibleAlias:
4137 if (ObjCInterfaceDecl *Class
4138 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
4139 if (!Class->isForwardDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004140 return MakeCXCursor(Class, TU);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004141
Douglas Gregorb6998662010-01-19 19:34:47 +00004142 return clang_getNullCursor();
4143
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004144 case Decl::ObjCForwardProtocol:
4145 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004146 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004147
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004148 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004149 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004150 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004151
4152 case Decl::Friend:
4153 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004154 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004155 return clang_getNullCursor();
4156
4157 case Decl::FriendTemplate:
4158 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004159 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004160 return clang_getNullCursor();
4161 }
4162
4163 return clang_getNullCursor();
4164}
4165
4166unsigned clang_isCursorDefinition(CXCursor C) {
4167 if (!clang_isDeclaration(C.kind))
4168 return 0;
4169
4170 return clang_getCursorDefinition(C) == C;
4171}
4172
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004173CXCursor clang_getCanonicalCursor(CXCursor C) {
4174 if (!clang_isDeclaration(C.kind))
4175 return C;
4176
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004177 if (Decl *D = getCursorDecl(C)) {
Argyrios Kyrtzidisdebb00f2011-07-15 22:37:58 +00004178 if (ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
4179 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
4180 return MakeCXCursor(CatD, getCursorTU(C));
4181
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004182 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
4183 if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
4184 return MakeCXCursor(IFD, getCursorTU(C));
4185
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004186 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004187 }
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004188
4189 return C;
4190}
4191
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004192unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004193 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004194 return 0;
4195
4196 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
4197 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
4198 return E->getNumDecls();
4199
4200 if (OverloadedTemplateStorage *S
4201 = Storage.dyn_cast<OverloadedTemplateStorage*>())
4202 return S->size();
4203
4204 Decl *D = Storage.get<Decl*>();
4205 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00004206 return Using->shadow_size();
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00004207 if (isa<ObjCClassDecl>(D))
4208 return 1;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004209 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
4210 return Protocols->protocol_size();
4211
4212 return 0;
4213}
4214
4215CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004216 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004217 return clang_getNullCursor();
4218
4219 if (index >= clang_getNumOverloadedDecls(cursor))
4220 return clang_getNullCursor();
4221
Ted Kremeneka60ed472010-11-16 08:15:36 +00004222 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004223 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
4224 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004225 return MakeCXCursor(E->decls_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004226
4227 if (OverloadedTemplateStorage *S
4228 = Storage.dyn_cast<OverloadedTemplateStorage*>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004229 return MakeCXCursor(S->begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004230
4231 Decl *D = Storage.get<Decl*>();
4232 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
4233 // FIXME: This is, unfortunately, linear time.
4234 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
4235 std::advance(Pos, index);
Ted Kremeneka60ed472010-11-16 08:15:36 +00004236 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004237 }
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004238 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00004239 return MakeCXCursor(Classes->getForwardInterfaceDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004240 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004241 return MakeCXCursor(Protocols->protocol_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004242
4243 return clang_getNullCursor();
4244}
4245
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00004246void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00004247 const char **startBuf,
4248 const char **endBuf,
4249 unsigned *startLine,
4250 unsigned *startColumn,
4251 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00004252 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00004253 assert(getCursorDecl(C) && "CXCursor has null decl");
4254 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00004255 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
4256 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004257
Steve Naroff4ade6d62009-09-23 17:52:52 +00004258 SourceManager &SM = FD->getASTContext().getSourceManager();
4259 *startBuf = SM.getCharacterData(Body->getLBracLoc());
4260 *endBuf = SM.getCharacterData(Body->getRBracLoc());
4261 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
4262 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
4263 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
4264 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
4265}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004266
Douglas Gregor430d7a12011-07-25 17:48:11 +00004267
4268CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
4269 unsigned PieceIndex) {
4270 RefNamePieces Pieces;
4271
4272 switch (C.kind) {
4273 case CXCursor_MemberRefExpr:
4274 if (MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
4275 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
4276 E->getQualifierLoc().getSourceRange());
4277 break;
4278
4279 case CXCursor_DeclRefExpr:
4280 if (DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C)))
4281 Pieces = buildPieces(NameFlags, false, E->getNameInfo(),
4282 E->getQualifierLoc().getSourceRange(),
4283 E->getExplicitTemplateArgsOpt());
4284 break;
4285
4286 case CXCursor_CallExpr:
4287 if (CXXOperatorCallExpr *OCE =
4288 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
4289 Expr *Callee = OCE->getCallee();
4290 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
4291 Callee = ICE->getSubExpr();
4292
4293 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
4294 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
4295 DRE->getQualifierLoc().getSourceRange());
4296 }
4297 break;
4298
4299 default:
4300 break;
4301 }
4302
4303 if (Pieces.empty()) {
4304 if (PieceIndex == 0)
4305 return clang_getCursorExtent(C);
4306 } else if (PieceIndex < Pieces.size()) {
4307 SourceRange R = Pieces[PieceIndex];
4308 if (R.isValid())
4309 return cxloc::translateSourceRange(getCursorContext(C), R);
4310 }
4311
4312 return clang_getNullRange();
4313}
4314
Douglas Gregor0a812cf2010-02-18 23:07:20 +00004315void clang_enableStackTraces(void) {
4316 llvm::sys::PrintStackTraceOnErrorSignal();
4317}
4318
Daniel Dunbar995aaf92010-11-04 01:26:29 +00004319void clang_executeOnThread(void (*fn)(void*), void *user_data,
4320 unsigned stack_size) {
4321 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
4322}
4323
Ted Kremenekfb480492010-01-13 21:46:36 +00004324} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00004325
Ted Kremenekfb480492010-01-13 21:46:36 +00004326//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004327// Token-based Operations.
4328//===----------------------------------------------------------------------===//
4329
4330/* CXToken layout:
4331 * int_data[0]: a CXTokenKind
4332 * int_data[1]: starting token location
4333 * int_data[2]: token length
4334 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004335 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004336 * otherwise unused.
4337 */
4338extern "C" {
4339
4340CXTokenKind clang_getTokenKind(CXToken CXTok) {
4341 return static_cast<CXTokenKind>(CXTok.int_data[0]);
4342}
4343
4344CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
4345 switch (clang_getTokenKind(CXTok)) {
4346 case CXToken_Identifier:
4347 case CXToken_Keyword:
4348 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004349 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
4350 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004351
4352 case CXToken_Literal: {
4353 // We have stashed the starting pointer in the ptr_data field. Use it.
4354 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Chris Lattner5f9e2722011-07-23 10:55:15 +00004355 return createCXString(StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004356 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004357
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004358 case CXToken_Punctuation:
4359 case CXToken_Comment:
4360 break;
4361 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004362
4363 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004364 // deconstructing the source location.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004365 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004366 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004367 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004368
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004369 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
4370 std::pair<FileID, unsigned> LocInfo
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004371 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00004372 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004373 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004374 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
4375 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00004376 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004377
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004378 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004379}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004380
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004381CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004382 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004383 if (!CXXUnit)
4384 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004385
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004386 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
4387 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4388}
4389
4390CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004391 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor5352ac02010-01-28 00:27:43 +00004392 if (!CXXUnit)
4393 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004394
4395 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004396 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4397}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004398
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004399static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
4400 SmallVectorImpl<CXToken> &CXTokens) {
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004401 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4402 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004403 = SourceMgr.getDecomposedLoc(Range.getBegin());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004404 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004405 = SourceMgr.getDecomposedLoc(Range.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004406
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004407 // Cannot tokenize across files.
4408 if (BeginLocInfo.first != EndLocInfo.first)
4409 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004410
4411 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004412 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004413 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004414 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00004415 if (Invalid)
4416 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00004417
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004418 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4419 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004420 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004421 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004422
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004423 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004424 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004425 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00004426 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004427 do {
4428 // Lex the next token
4429 Lex.LexFromRawLexer(Tok);
4430 if (Tok.is(tok::eof))
4431 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004432
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004433 // Initialize the CXToken.
4434 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004435
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004436 // - Common fields
4437 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
4438 CXTok.int_data[2] = Tok.getLength();
4439 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004440
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004441 // - Kind-specific fields
4442 if (Tok.isLiteral()) {
4443 CXTok.int_data[0] = CXToken_Literal;
4444 CXTok.ptr_data = (void *)Tok.getLiteralData();
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004445 } else if (Tok.is(tok::raw_identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00004446 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004447 IdentifierInfo *II
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004448 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004449
David Chisnall096428b2010-10-13 21:44:48 +00004450 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004451 CXTok.int_data[0] = CXToken_Keyword;
4452 }
4453 else {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004454 CXTok.int_data[0] = Tok.is(tok::identifier)
4455 ? CXToken_Identifier
4456 : CXToken_Keyword;
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004457 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004458 CXTok.ptr_data = II;
4459 } else if (Tok.is(tok::comment)) {
4460 CXTok.int_data[0] = CXToken_Comment;
4461 CXTok.ptr_data = 0;
4462 } else {
4463 CXTok.int_data[0] = CXToken_Punctuation;
4464 CXTok.ptr_data = 0;
4465 }
4466 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00004467 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004468 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004469}
4470
4471void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
4472 CXToken **Tokens, unsigned *NumTokens) {
4473 if (Tokens)
4474 *Tokens = 0;
4475 if (NumTokens)
4476 *NumTokens = 0;
4477
4478 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4479 if (!CXXUnit || !Tokens || !NumTokens)
4480 return;
4481
4482 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4483
4484 SourceRange R = cxloc::translateCXSourceRange(Range);
4485 if (R.isInvalid())
4486 return;
4487
4488 SmallVector<CXToken, 32> CXTokens;
4489 getTokens(CXXUnit, R, CXTokens);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004490
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004491 if (CXTokens.empty())
4492 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004493
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004494 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
4495 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
4496 *NumTokens = CXTokens.size();
4497}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004498
Ted Kremenek6db61092010-05-05 00:55:15 +00004499void clang_disposeTokens(CXTranslationUnit TU,
4500 CXToken *Tokens, unsigned NumTokens) {
4501 free(Tokens);
4502}
4503
4504} // end: extern "C"
4505
4506//===----------------------------------------------------------------------===//
4507// Token annotation APIs.
4508//===----------------------------------------------------------------------===//
4509
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004510typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004511static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4512 CXCursor parent,
4513 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00004514namespace {
4515class AnnotateTokensWorker {
4516 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004517 CXToken *Tokens;
4518 CXCursor *Cursors;
4519 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004520 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00004521 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004522 CursorVisitor AnnotateVis;
4523 SourceManager &SrcMgr;
Douglas Gregorf5251602011-03-08 17:10:18 +00004524 bool HasContextSensitiveKeywords;
4525
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004526 bool MoreTokens() const { return TokIdx < NumTokens; }
4527 unsigned NextToken() const { return TokIdx; }
4528 void AdvanceToken() { ++TokIdx; }
4529 SourceLocation GetTokenLoc(unsigned tokI) {
4530 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4531 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004532 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004533 return Tokens[tokI].int_data[3] != 0;
4534 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004535 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004536 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[3]);
4537 }
4538
4539 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004540 void annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
4541 SourceRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004542
Ted Kremenek6db61092010-05-05 00:55:15 +00004543public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00004544 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004545 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004546 CXTranslationUnit tu, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00004547 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00004548 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004549 AnnotateVis(tu,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00004550 AnnotateTokensVisitor, this,
4551 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00004552 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00004553 RegionOfInterest),
Douglas Gregorf5251602011-03-08 17:10:18 +00004554 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()),
4555 HasContextSensitiveKeywords(false) { }
Ted Kremenek11949cb2010-05-05 00:55:17 +00004556
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004557 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00004558 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004559 void AnnotateTokens();
Douglas Gregorf5251602011-03-08 17:10:18 +00004560
4561 /// \brief Determine whether the annotator saw any cursors that have
4562 /// context-sensitive keywords.
4563 bool hasContextSensitiveKeywords() const {
4564 return HasContextSensitiveKeywords;
4565 }
Ted Kremenek6db61092010-05-05 00:55:15 +00004566};
4567}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004568
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004569void AnnotateTokensWorker::AnnotateTokens() {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004570 // Walk the AST within the region of interest, annotating tokens
4571 // along the way.
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004572 AnnotateVis.visitFileRegion();
Ted Kremenek11949cb2010-05-05 00:55:17 +00004573
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004574 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4575 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004576 if (Pos != Annotated.end() &&
4577 (clang_isInvalid(Cursors[I].kind) ||
4578 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004579 Cursors[I] = Pos->second;
4580 }
4581
4582 // Finish up annotating any tokens left.
4583 if (!MoreTokens())
4584 return;
4585
4586 const CXCursor &C = clang_getNullCursor();
4587 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004588 if (I < PreprocessingTokIdx && clang_isPreprocessing(Cursors[I].kind))
4589 continue;
4590
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004591 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4592 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004593 }
4594}
4595
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004596/// \brief It annotates and advances tokens with a cursor until the comparison
4597//// between the cursor location and the source range is the same as
4598/// \arg compResult.
4599///
4600/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
4601/// Pass RangeOverlap to annotate tokens inside a range.
4602void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
4603 RangeComparisonResult compResult,
4604 SourceRange range) {
4605 while (MoreTokens()) {
4606 const unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004607 if (isFunctionMacroToken(I))
4608 return annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004609
4610 SourceLocation TokLoc = GetTokenLoc(I);
4611 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4612 Cursors[I] = updateC;
4613 AdvanceToken();
4614 continue;
4615 }
4616 break;
4617 }
4618}
4619
4620/// \brief Special annotation handling for macro argument tokens.
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004621void AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
4622 CXCursor updateC,
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004623 RangeComparisonResult compResult,
4624 SourceRange range) {
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004625 assert(MoreTokens());
4626 assert(isFunctionMacroToken(NextToken()) &&
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004627 "Should be called only for macro arg tokens");
4628
4629 // This works differently than annotateAndAdvanceTokens; because expanded
4630 // macro arguments can have arbitrary translation-unit source order, we do not
4631 // advance the token index one by one until a token fails the range test.
4632 // We only advance once past all of the macro arg tokens if all of them
4633 // pass the range test. If one of them fails we keep the token index pointing
4634 // at the start of the macro arg tokens so that the failing token will be
4635 // annotated by a subsequent annotation try.
4636
4637 bool atLeastOneCompFail = false;
4638
4639 unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004640 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
4641 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004642 if (TokLoc.isFileID())
4643 continue; // not macro arg token, it's parens or comma.
4644 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4645 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
4646 Cursors[I] = updateC;
4647 } else
4648 atLeastOneCompFail = true;
4649 }
4650
4651 if (!atLeastOneCompFail)
4652 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
4653}
4654
Ted Kremenek6db61092010-05-05 00:55:15 +00004655enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004656AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004657 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004658 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004659 if (cursorRange.isInvalid())
4660 return CXChildVisit_Recurse;
Douglas Gregorf5251602011-03-08 17:10:18 +00004661
4662 if (!HasContextSensitiveKeywords) {
4663 // Objective-C properties can have context-sensitive keywords.
4664 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
4665 if (ObjCPropertyDecl *Property
4666 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
4667 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
4668 }
4669 // Objective-C methods can have context-sensitive keywords.
4670 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
4671 cursor.kind == CXCursor_ObjCClassMethodDecl) {
4672 if (ObjCMethodDecl *Method
4673 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
4674 if (Method->getObjCDeclQualifier())
4675 HasContextSensitiveKeywords = true;
4676 else {
4677 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
4678 PEnd = Method->param_end();
4679 P != PEnd; ++P) {
4680 if ((*P)->getObjCDeclQualifier()) {
4681 HasContextSensitiveKeywords = true;
4682 break;
4683 }
4684 }
4685 }
4686 }
4687 }
4688 // C++ methods can have context-sensitive keywords.
4689 else if (cursor.kind == CXCursor_CXXMethod) {
4690 if (CXXMethodDecl *Method
4691 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
4692 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
4693 HasContextSensitiveKeywords = true;
4694 }
4695 }
4696 // C++ classes can have context-sensitive keywords.
4697 else if (cursor.kind == CXCursor_StructDecl ||
4698 cursor.kind == CXCursor_ClassDecl ||
4699 cursor.kind == CXCursor_ClassTemplate ||
4700 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
4701 if (Decl *D = getCursorDecl(cursor))
4702 if (D->hasAttr<FinalAttr>())
4703 HasContextSensitiveKeywords = true;
4704 }
4705 }
4706
Douglas Gregor4419b672010-10-21 06:10:04 +00004707 if (clang_isPreprocessing(cursor.kind)) {
Chandler Carruthcea731a2011-07-14 16:07:57 +00004708 // For macro expansions, just note where the beginning of the macro
4709 // expansion occurs.
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004710 if (cursor.kind == CXCursor_MacroExpansion) {
Douglas Gregor4419b672010-10-21 06:10:04 +00004711 Annotated[Loc.int_data] = cursor;
4712 return CXChildVisit_Recurse;
4713 }
4714
Douglas Gregor4419b672010-10-21 06:10:04 +00004715 // Items in the preprocessing record are kept separate from items in
4716 // declarations, so we keep a separate token index.
4717 unsigned SavedTokIdx = TokIdx;
4718 TokIdx = PreprocessingTokIdx;
4719
4720 // Skip tokens up until we catch up to the beginning of the preprocessing
4721 // entry.
4722 while (MoreTokens()) {
4723 const unsigned I = NextToken();
4724 SourceLocation TokLoc = GetTokenLoc(I);
4725 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4726 case RangeBefore:
4727 AdvanceToken();
4728 continue;
4729 case RangeAfter:
4730 case RangeOverlap:
4731 break;
4732 }
4733 break;
4734 }
4735
4736 // Look at all of the tokens within this range.
4737 while (MoreTokens()) {
4738 const unsigned I = NextToken();
4739 SourceLocation TokLoc = GetTokenLoc(I);
4740 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4741 case RangeBefore:
David Blaikieb219cfc2011-09-23 05:06:16 +00004742 llvm_unreachable("Infeasible");
Douglas Gregor4419b672010-10-21 06:10:04 +00004743 case RangeAfter:
4744 break;
4745 case RangeOverlap:
4746 Cursors[I] = cursor;
4747 AdvanceToken();
4748 continue;
4749 }
4750 break;
4751 }
4752
4753 // Save the preprocessing token index; restore the non-preprocessing
4754 // token index.
4755 PreprocessingTokIdx = TokIdx;
4756 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004757 return CXChildVisit_Recurse;
4758 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004759
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004760 if (cursorRange.isInvalid())
4761 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004762
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004763 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4764
Ted Kremeneka333c662010-05-12 05:29:33 +00004765 // Adjust the annotated range based specific declarations.
4766 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4767 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004768 Decl *D = cxcursor::getCursorDecl(cursor);
Douglas Gregor2494dd02011-03-01 01:34:45 +00004769
4770 SourceLocation StartLoc;
Ted Kremenek23173d72010-05-18 21:09:07 +00004771 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00004772 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
4773 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
4774 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
4775 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
4776 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
Ted Kremeneka333c662010-05-12 05:29:33 +00004777 }
Douglas Gregor2494dd02011-03-01 01:34:45 +00004778
4779 if (StartLoc.isValid() && L.isValid() &&
4780 SrcMgr.isBeforeInTranslationUnit(StartLoc, L))
4781 cursorRange.setBegin(StartLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004782 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004783
Ted Kremenek3f404602010-08-14 01:14:06 +00004784 // If the location of the cursor occurs within a macro instantiation, record
4785 // the spelling location of the cursor in our annotation map. We can then
4786 // paper over the token labelings during a post-processing step to try and
4787 // get cursor mappings for tokens that are the *arguments* of a macro
4788 // instantiation.
4789 if (L.isMacroID()) {
4790 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4791 // Only invalidate the old annotation if it isn't part of a preprocessing
4792 // directive. Here we assume that the default construction of CXCursor
4793 // results in CXCursor.kind being an initialized value (i.e., 0). If
4794 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004795
Ted Kremenek3f404602010-08-14 01:14:06 +00004796 CXCursor &oldC = Annotated[rawEncoding];
4797 if (!clang_isPreprocessing(oldC.kind))
4798 oldC = cursor;
4799 }
4800
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004801 const enum CXCursorKind K = clang_getCursorKind(parent);
4802 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004803 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4804 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004805
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004806 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004807
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00004808 // Avoid having the cursor of an expression "overwrite" the annotation of the
4809 // variable declaration that it belongs to.
4810 // This can happen for C++ constructor expressions whose range generally
4811 // include the variable declaration, e.g.:
4812 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
4813 if (clang_isExpression(cursorK)) {
4814 Expr *E = getCursorExpr(cursor);
Argyrios Kyrtzidis8ccac3d2011-06-29 22:20:07 +00004815 if (Decl *D = getCursorParentDecl(cursor)) {
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00004816 const unsigned I = NextToken();
4817 if (E->getLocStart().isValid() && D->getLocation().isValid() &&
4818 E->getLocStart() == D->getLocation() &&
4819 E->getLocStart() == GetTokenLoc(I)) {
4820 Cursors[I] = updateC;
4821 AdvanceToken();
4822 }
4823 }
4824 }
4825
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004826 // Visit children to get their cursor information.
4827 const unsigned BeforeChildren = NextToken();
4828 VisitChildren(cursor);
4829 const unsigned AfterChildren = NextToken();
4830
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004831 // Scan the tokens that are at the end of the cursor, but are not captured
4832 // but the child cursors.
4833 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
Ted Kremenek6db61092010-05-05 00:55:15 +00004834
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004835 // Scan the tokens that are at the beginning of the cursor, but are not
4836 // capture by the child cursors.
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004837 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4838 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4839 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004840
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004841 Cursors[I] = cursor;
4842 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004843
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004844 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004845}
4846
Ted Kremenek6db61092010-05-05 00:55:15 +00004847static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4848 CXCursor parent,
4849 CXClientData client_data) {
4850 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4851}
4852
Ted Kremenek6628a612011-03-18 22:51:30 +00004853namespace {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004854
4855/// \brief Uses the macro expansions in the preprocessing record to find
4856/// and mark tokens that are macro arguments. This info is used by the
4857/// AnnotateTokensWorker.
4858class MarkMacroArgTokensVisitor {
4859 SourceManager &SM;
4860 CXToken *Tokens;
4861 unsigned NumTokens;
4862 unsigned CurIdx;
4863
4864public:
4865 MarkMacroArgTokensVisitor(SourceManager &SM,
4866 CXToken *tokens, unsigned numTokens)
4867 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
4868
4869 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
4870 if (cursor.kind != CXCursor_MacroExpansion)
4871 return CXChildVisit_Continue;
4872
4873 SourceRange macroRange = getCursorMacroExpansion(cursor)->getSourceRange();
4874 if (macroRange.getBegin() == macroRange.getEnd())
4875 return CXChildVisit_Continue; // it's not a function macro.
4876
4877 for (; CurIdx < NumTokens; ++CurIdx) {
4878 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
4879 macroRange.getBegin()))
4880 break;
4881 }
4882
4883 if (CurIdx == NumTokens)
4884 return CXChildVisit_Break;
4885
4886 for (; CurIdx < NumTokens; ++CurIdx) {
4887 SourceLocation tokLoc = getTokenLoc(CurIdx);
4888 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
4889 break;
4890
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004891 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004892 }
4893
4894 if (CurIdx == NumTokens)
4895 return CXChildVisit_Break;
4896
4897 return CXChildVisit_Continue;
4898 }
4899
4900private:
4901 SourceLocation getTokenLoc(unsigned tokI) {
4902 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4903 }
4904
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004905 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004906 // The third field is reserved and currently not used. Use it here
4907 // to mark macro arg expanded tokens with their expanded locations.
4908 Tokens[tokI].int_data[3] = loc.getRawEncoding();
4909 }
4910};
4911
4912} // end anonymous namespace
4913
4914static CXChildVisitResult
4915MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
4916 CXClientData client_data) {
4917 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
4918 parent);
4919}
4920
4921namespace {
Ted Kremenek6628a612011-03-18 22:51:30 +00004922 struct clang_annotateTokens_Data {
4923 CXTranslationUnit TU;
4924 ASTUnit *CXXUnit;
4925 CXToken *Tokens;
4926 unsigned NumTokens;
4927 CXCursor *Cursors;
4928 };
4929}
4930
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004931static void annotatePreprocessorTokens(CXTranslationUnit TU,
4932 SourceRange RegionOfInterest,
4933 AnnotateTokensData &Annotated) {
4934 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4935
4936 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4937 std::pair<FileID, unsigned> BeginLocInfo
4938 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4939 std::pair<FileID, unsigned> EndLocInfo
4940 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
4941
4942 if (BeginLocInfo.first != EndLocInfo.first)
4943 return;
4944
4945 StringRef Buffer;
4946 bool Invalid = false;
4947 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
4948 if (Buffer.empty() || Invalid)
4949 return;
4950
4951 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4952 CXXUnit->getASTContext().getLangOptions(),
4953 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
4954 Buffer.end());
4955 Lex.SetCommentRetentionState(true);
4956
4957 // Lex tokens in raw mode until we hit the end of the range, to avoid
4958 // entering #includes or expanding macros.
4959 while (true) {
4960 Token Tok;
4961 Lex.LexFromRawLexer(Tok);
4962
4963 reprocess:
4964 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4965 // We have found a preprocessing directive. Gobble it up so that we
4966 // don't see it while preprocessing these tokens later, but keep track
4967 // of all of the token locations inside this preprocessing directive so
4968 // that we can annotate them appropriately.
4969 //
4970 // FIXME: Some simple tests here could identify macro definitions and
4971 // #undefs, to provide specific cursor kinds for those.
4972 SmallVector<SourceLocation, 32> Locations;
4973 do {
4974 Locations.push_back(Tok.getLocation());
4975 Lex.LexFromRawLexer(Tok);
4976 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
4977
4978 using namespace cxcursor;
4979 CXCursor Cursor
4980 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4981 Locations.back()),
4982 TU);
4983 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4984 Annotated[Locations[I].getRawEncoding()] = Cursor;
4985 }
4986
4987 if (Tok.isAtStartOfLine())
4988 goto reprocess;
4989
4990 continue;
4991 }
4992
4993 if (Tok.is(tok::eof))
4994 break;
4995 }
4996}
4997
Ted Kremenekab979612010-11-11 08:05:23 +00004998// This gets run a separate thread to avoid stack blowout.
Ted Kremenek6628a612011-03-18 22:51:30 +00004999static void clang_annotateTokensImpl(void *UserData) {
5000 CXTranslationUnit TU = ((clang_annotateTokens_Data*)UserData)->TU;
5001 ASTUnit *CXXUnit = ((clang_annotateTokens_Data*)UserData)->CXXUnit;
5002 CXToken *Tokens = ((clang_annotateTokens_Data*)UserData)->Tokens;
5003 const unsigned NumTokens = ((clang_annotateTokens_Data*)UserData)->NumTokens;
5004 CXCursor *Cursors = ((clang_annotateTokens_Data*)UserData)->Cursors;
5005
5006 // Determine the region of interest, which contains all of the tokens.
5007 SourceRange RegionOfInterest;
5008 RegionOfInterest.setBegin(
5009 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
5010 RegionOfInterest.setEnd(
5011 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
5012 Tokens[NumTokens-1])));
5013
5014 // A mapping from the source locations found when re-lexing or traversing the
5015 // region of interest to the corresponding cursors.
5016 AnnotateTokensData Annotated;
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005017
Ted Kremenek6628a612011-03-18 22:51:30 +00005018 // Relex the tokens within the source range to look for preprocessing
5019 // directives.
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005020 annotatePreprocessorTokens(TU, RegionOfInterest, Annotated);
Ted Kremenek6628a612011-03-18 22:51:30 +00005021
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005022 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
5023 // Search and mark tokens that are macro argument expansions.
5024 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
5025 Tokens, NumTokens);
5026 CursorVisitor MacroArgMarker(TU,
5027 MarkMacroArgTokensVisitorDelegate, &Visitor,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00005028 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00005029 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00005030 RegionOfInterest);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005031 MacroArgMarker.visitPreprocessedEntitiesInRegion();
5032 }
5033
Ted Kremenek6628a612011-03-18 22:51:30 +00005034 // Annotate all of the source locations in the region of interest that map to
5035 // a specific cursor.
5036 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
5037 TU, RegionOfInterest);
5038
5039 // FIXME: We use a ridiculous stack size here because the data-recursion
5040 // algorithm uses a large stack frame than the non-data recursive version,
5041 // and AnnotationTokensWorker currently transforms the data-recursion
5042 // algorithm back into a traditional recursion by explicitly calling
5043 // VisitChildren(). We will need to remove this explicit recursive call.
5044 W.AnnotateTokens();
5045
5046 // If we ran into any entities that involve context-sensitive keywords,
5047 // take another pass through the tokens to mark them as such.
5048 if (W.hasContextSensitiveKeywords()) {
5049 for (unsigned I = 0; I != NumTokens; ++I) {
5050 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
5051 continue;
5052
5053 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
5054 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5055 if (ObjCPropertyDecl *Property
5056 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
5057 if (Property->getPropertyAttributesAsWritten() != 0 &&
5058 llvm::StringSwitch<bool>(II->getName())
5059 .Case("readonly", true)
5060 .Case("assign", true)
John McCallf85e1932011-06-15 23:02:42 +00005061 .Case("unsafe_unretained", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00005062 .Case("readwrite", true)
5063 .Case("retain", true)
5064 .Case("copy", true)
5065 .Case("nonatomic", true)
5066 .Case("atomic", true)
5067 .Case("getter", true)
5068 .Case("setter", true)
John McCallf85e1932011-06-15 23:02:42 +00005069 .Case("strong", true)
5070 .Case("weak", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00005071 .Default(false))
5072 Tokens[I].int_data[0] = CXToken_Keyword;
5073 }
5074 continue;
5075 }
5076
5077 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
5078 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
5079 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5080 if (llvm::StringSwitch<bool>(II->getName())
5081 .Case("in", true)
5082 .Case("out", true)
5083 .Case("inout", true)
5084 .Case("oneway", true)
5085 .Case("bycopy", true)
5086 .Case("byref", true)
5087 .Default(false))
5088 Tokens[I].int_data[0] = CXToken_Keyword;
5089 continue;
5090 }
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00005091
5092 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
5093 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
5094 Tokens[I].int_data[0] = CXToken_Keyword;
Ted Kremenek6628a612011-03-18 22:51:30 +00005095 continue;
5096 }
5097 }
5098 }
Ted Kremenekab979612010-11-11 08:05:23 +00005099}
5100
Ted Kremenek6db61092010-05-05 00:55:15 +00005101extern "C" {
5102
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005103void clang_annotateTokens(CXTranslationUnit TU,
5104 CXToken *Tokens, unsigned NumTokens,
5105 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005106
5107 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005108 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005109
Douglas Gregor4419b672010-10-21 06:10:04 +00005110 // Any token we don't specifically annotate will have a NULL cursor.
5111 CXCursor C = clang_getNullCursor();
5112 for (unsigned I = 0; I != NumTokens; ++I)
5113 Cursors[I] = C;
5114
Ted Kremeneka60ed472010-11-16 08:15:36 +00005115 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor4419b672010-10-21 06:10:04 +00005116 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005117 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005118
Douglas Gregorbdf60622010-03-05 21:16:25 +00005119 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenek6628a612011-03-18 22:51:30 +00005120
5121 clang_annotateTokens_Data data = { TU, CXXUnit, Tokens, NumTokens, Cursors };
Ted Kremenekab979612010-11-11 08:05:23 +00005122 llvm::CrashRecoveryContext CRC;
Ted Kremenek6628a612011-03-18 22:51:30 +00005123 if (!RunSafely(CRC, clang_annotateTokensImpl, &data,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005124 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00005125 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
5126 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005127}
Ted Kremenek6628a612011-03-18 22:51:30 +00005128
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005129} // end: extern "C"
5130
5131//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00005132// Operations for querying linkage of a cursor.
5133//===----------------------------------------------------------------------===//
5134
5135extern "C" {
5136CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00005137 if (!clang_isDeclaration(cursor.kind))
5138 return CXLinkage_Invalid;
5139
Ted Kremenek16b42592010-03-03 06:36:57 +00005140 Decl *D = cxcursor::getCursorDecl(cursor);
5141 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
5142 switch (ND->getLinkage()) {
5143 case NoLinkage: return CXLinkage_NoLinkage;
5144 case InternalLinkage: return CXLinkage_Internal;
5145 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
5146 case ExternalLinkage: return CXLinkage_External;
5147 };
5148
5149 return CXLinkage_Invalid;
5150}
5151} // end: extern "C"
5152
5153//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005154// Operations for querying language of a cursor.
5155//===----------------------------------------------------------------------===//
5156
5157static CXLanguageKind getDeclLanguage(const Decl *D) {
5158 switch (D->getKind()) {
5159 default:
5160 break;
5161 case Decl::ImplicitParam:
5162 case Decl::ObjCAtDefsField:
5163 case Decl::ObjCCategory:
5164 case Decl::ObjCCategoryImpl:
5165 case Decl::ObjCClass:
5166 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005167 case Decl::ObjCForwardProtocol:
5168 case Decl::ObjCImplementation:
5169 case Decl::ObjCInterface:
5170 case Decl::ObjCIvar:
5171 case Decl::ObjCMethod:
5172 case Decl::ObjCProperty:
5173 case Decl::ObjCPropertyImpl:
5174 case Decl::ObjCProtocol:
5175 return CXLanguage_ObjC;
5176 case Decl::CXXConstructor:
5177 case Decl::CXXConversion:
5178 case Decl::CXXDestructor:
5179 case Decl::CXXMethod:
5180 case Decl::CXXRecord:
5181 case Decl::ClassTemplate:
5182 case Decl::ClassTemplatePartialSpecialization:
5183 case Decl::ClassTemplateSpecialization:
5184 case Decl::Friend:
5185 case Decl::FriendTemplate:
5186 case Decl::FunctionTemplate:
5187 case Decl::LinkageSpec:
5188 case Decl::Namespace:
5189 case Decl::NamespaceAlias:
5190 case Decl::NonTypeTemplateParm:
5191 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005192 case Decl::TemplateTemplateParm:
5193 case Decl::TemplateTypeParm:
5194 case Decl::UnresolvedUsingTypename:
5195 case Decl::UnresolvedUsingValue:
5196 case Decl::Using:
5197 case Decl::UsingDirective:
5198 case Decl::UsingShadow:
5199 return CXLanguage_CPlusPlus;
5200 }
5201
5202 return CXLanguage_C;
5203}
5204
5205extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00005206
5207enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
5208 if (clang_isDeclaration(cursor.kind))
5209 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005210 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Douglas Gregor58ddb602010-08-23 23:00:57 +00005211 return CXAvailability_Available;
5212
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005213 switch (D->getAvailability()) {
5214 case AR_Available:
5215 case AR_NotYetIntroduced:
5216 return CXAvailability_Available;
5217
5218 case AR_Deprecated:
Douglas Gregor58ddb602010-08-23 23:00:57 +00005219 return CXAvailability_Deprecated;
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005220
5221 case AR_Unavailable:
5222 return CXAvailability_NotAvailable;
5223 }
Douglas Gregor58ddb602010-08-23 23:00:57 +00005224 }
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005225
Douglas Gregor58ddb602010-08-23 23:00:57 +00005226 return CXAvailability_Available;
5227}
5228
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005229CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
5230 if (clang_isDeclaration(cursor.kind))
5231 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
5232
5233 return CXLanguage_Invalid;
5234}
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005235
5236 /// \brief If the given cursor is the "templated" declaration
5237 /// descibing a class or function template, return the class or
5238 /// function template.
5239static Decl *maybeGetTemplateCursor(Decl *D) {
5240 if (!D)
5241 return 0;
5242
5243 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
5244 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
5245 return FunTmpl;
5246
5247 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
5248 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
5249 return ClassTmpl;
5250
5251 return D;
5252}
5253
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005254CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
5255 if (clang_isDeclaration(cursor.kind)) {
5256 if (Decl *D = getCursorDecl(cursor)) {
5257 DeclContext *DC = D->getDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005258 if (!DC)
5259 return clang_getNullCursor();
5260
5261 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5262 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005263 }
5264 }
5265
5266 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
5267 if (Decl *D = getCursorDecl(cursor))
Ted Kremeneka60ed472010-11-16 08:15:36 +00005268 return MakeCXCursor(D, getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005269 }
5270
5271 return clang_getNullCursor();
5272}
5273
5274CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
5275 if (clang_isDeclaration(cursor.kind)) {
5276 if (Decl *D = getCursorDecl(cursor)) {
5277 DeclContext *DC = D->getLexicalDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005278 if (!DC)
5279 return clang_getNullCursor();
5280
5281 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5282 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005283 }
5284 }
5285
5286 // FIXME: Note that we can't easily compute the lexical context of a
5287 // statement or expression, so we return nothing.
5288 return clang_getNullCursor();
5289}
5290
Douglas Gregor9f592342010-10-01 20:25:15 +00005291void clang_getOverriddenCursors(CXCursor cursor,
5292 CXCursor **overridden,
5293 unsigned *num_overridden) {
5294 if (overridden)
5295 *overridden = 0;
5296 if (num_overridden)
5297 *num_overridden = 0;
5298 if (!overridden || !num_overridden)
5299 return;
5300
Argyrios Kyrtzidisb11be042011-10-06 07:00:46 +00005301 SmallVector<CXCursor, 8> Overridden;
5302 cxcursor::getOverriddenCursors(cursor, Overridden);
Douglas Gregor9f592342010-10-01 20:25:15 +00005303
Ted Kremenek24077122011-11-14 23:51:37 +00005304 // Don't allocate memory if we have no overriden cursors.
5305 if (Overridden.size() == 0)
5306 return;
5307
Argyrios Kyrtzidisb11be042011-10-06 07:00:46 +00005308 *num_overridden = Overridden.size();
5309 *overridden = new CXCursor [Overridden.size()];
5310 std::copy(Overridden.begin(), Overridden.end(), *overridden);
Douglas Gregor9f592342010-10-01 20:25:15 +00005311}
5312
5313void clang_disposeOverriddenCursors(CXCursor *overridden) {
5314 delete [] overridden;
5315}
5316
Douglas Gregorecdcb882010-10-20 22:00:55 +00005317CXFile clang_getIncludedFile(CXCursor cursor) {
5318 if (cursor.kind != CXCursor_InclusionDirective)
5319 return 0;
5320
5321 InclusionDirective *ID = getCursorInclusionDirective(cursor);
5322 return (void *)ID->getFile();
5323}
5324
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005325} // end: extern "C"
5326
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005327
5328//===----------------------------------------------------------------------===//
5329// C++ AST instrospection.
5330//===----------------------------------------------------------------------===//
5331
5332extern "C" {
5333unsigned clang_CXXMethod_isStatic(CXCursor C) {
5334 if (!clang_isDeclaration(C.kind))
5335 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00005336
5337 CXXMethodDecl *Method = 0;
5338 Decl *D = cxcursor::getCursorDecl(C);
5339 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5340 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5341 else
5342 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5343 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00005344}
Ted Kremenekb12903e2010-05-18 22:32:15 +00005345
Douglas Gregor211924b2011-05-12 15:17:24 +00005346unsigned clang_CXXMethod_isVirtual(CXCursor C) {
5347 if (!clang_isDeclaration(C.kind))
5348 return 0;
5349
5350 CXXMethodDecl *Method = 0;
5351 Decl *D = cxcursor::getCursorDecl(C);
5352 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5353 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5354 else
5355 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5356 return (Method && Method->isVirtual()) ? 1 : 0;
5357}
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005358} // end: extern "C"
5359
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005360//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00005361// Attribute introspection.
5362//===----------------------------------------------------------------------===//
5363
5364extern "C" {
5365CXType clang_getIBOutletCollectionType(CXCursor C) {
5366 if (C.kind != CXCursor_IBOutletCollectionAttr)
Ted Kremeneka60ed472010-11-16 08:15:36 +00005367 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005368
5369 IBOutletCollectionAttr *A =
5370 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
5371
Argyrios Kyrtzidis18aa2ff2011-09-13 18:49:52 +00005372 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005373}
5374} // end: extern "C"
5375
5376//===----------------------------------------------------------------------===//
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005377// Inspecting memory usage.
5378//===----------------------------------------------------------------------===//
5379
Ted Kremenekf7870022011-04-20 16:41:07 +00005380typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005381
Ted Kremenekf7870022011-04-20 16:41:07 +00005382static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
5383 enum CXTUResourceUsageKind k,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005384 unsigned long amount) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005385 CXTUResourceUsageEntry entry = { k, amount };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005386 entries.push_back(entry);
5387}
5388
5389extern "C" {
5390
Ted Kremenekf7870022011-04-20 16:41:07 +00005391const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005392 const char *str = "";
5393 switch (kind) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005394 case CXTUResourceUsage_AST:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005395 str = "ASTContext: expressions, declarations, and types";
5396 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005397 case CXTUResourceUsage_Identifiers:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005398 str = "ASTContext: identifiers";
5399 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005400 case CXTUResourceUsage_Selectors:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005401 str = "ASTContext: selectors";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005402 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005403 case CXTUResourceUsage_GlobalCompletionResults:
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005404 str = "Code completion: cached global results";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005405 break;
Ted Kremenek457aaf02011-04-28 04:10:31 +00005406 case CXTUResourceUsage_SourceManagerContentCache:
5407 str = "SourceManager: content cache allocator";
5408 break;
Ted Kremenekba29bd22011-04-28 04:53:38 +00005409 case CXTUResourceUsage_AST_SideTables:
5410 str = "ASTContext: side tables";
5411 break;
Ted Kremenekf61b8312011-04-28 20:36:42 +00005412 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
5413 str = "SourceManager: malloc'ed memory buffers";
5414 break;
5415 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
5416 str = "SourceManager: mmap'ed memory buffers";
5417 break;
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005418 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
5419 str = "ExternalASTSource: malloc'ed memory buffers";
5420 break;
5421 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
5422 str = "ExternalASTSource: mmap'ed memory buffers";
5423 break;
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005424 case CXTUResourceUsage_Preprocessor:
5425 str = "Preprocessor: malloc'ed memory";
5426 break;
5427 case CXTUResourceUsage_PreprocessingRecord:
5428 str = "Preprocessor: PreprocessingRecord";
5429 break;
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005430 case CXTUResourceUsage_SourceManager_DataStructures:
5431 str = "SourceManager: data structures and tables";
5432 break;
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005433 case CXTUResourceUsage_Preprocessor_HeaderSearch:
5434 str = "Preprocessor: header search tables";
5435 break;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005436 }
5437 return str;
5438}
5439
Ted Kremenekf7870022011-04-20 16:41:07 +00005440CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005441 if (!TU) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005442 CXTUResourceUsage usage = { (void*) 0, 0, 0 };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005443 return usage;
5444 }
5445
5446 ASTUnit *astUnit = static_cast<ASTUnit*>(TU->TUData);
5447 llvm::OwningPtr<MemUsageEntries> entries(new MemUsageEntries());
5448 ASTContext &astContext = astUnit->getASTContext();
5449
5450 // How much memory is used by AST nodes and types?
Ted Kremenekf7870022011-04-20 16:41:07 +00005451 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005452 (unsigned long) astContext.getASTAllocatedMemory());
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005453
5454 // How much memory is used by identifiers?
Ted Kremenekf7870022011-04-20 16:41:07 +00005455 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005456 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
5457
5458 // How much memory is used for selectors?
Ted Kremenekf7870022011-04-20 16:41:07 +00005459 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005460 (unsigned long) astContext.Selectors.getTotalMemory());
5461
Ted Kremenekba29bd22011-04-28 04:53:38 +00005462 // How much memory is used by ASTContext's side tables?
5463 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
5464 (unsigned long) astContext.getSideTableAllocatedMemory());
5465
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005466 // How much memory is used for caching global code completion results?
5467 unsigned long completionBytes = 0;
5468 if (GlobalCodeCompletionAllocator *completionAllocator =
5469 astUnit->getCachedCompletionAllocator().getPtr()) {
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005470 completionBytes = completionAllocator->getTotalMemory();
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005471 }
Ted Kremenek457aaf02011-04-28 04:10:31 +00005472 createCXTUResourceUsageEntry(*entries,
5473 CXTUResourceUsage_GlobalCompletionResults,
5474 completionBytes);
5475
5476 // How much memory is being used by SourceManager's content cache?
5477 createCXTUResourceUsageEntry(*entries,
5478 CXTUResourceUsage_SourceManagerContentCache,
5479 (unsigned long) astContext.getSourceManager().getContentCacheSize());
Ted Kremenekf61b8312011-04-28 20:36:42 +00005480
5481 // How much memory is being used by the MemoryBuffer's in SourceManager?
5482 const SourceManager::MemoryBufferSizes &srcBufs =
5483 astUnit->getSourceManager().getMemoryBufferSizes();
5484
5485 createCXTUResourceUsageEntry(*entries,
5486 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
5487 (unsigned long) srcBufs.malloc_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005488 createCXTUResourceUsageEntry(*entries,
Ted Kremenekf61b8312011-04-28 20:36:42 +00005489 CXTUResourceUsage_SourceManager_Membuffer_MMap,
5490 (unsigned long) srcBufs.mmap_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005491 createCXTUResourceUsageEntry(*entries,
5492 CXTUResourceUsage_SourceManager_DataStructures,
5493 (unsigned long) astContext.getSourceManager()
5494 .getDataStructureSizes());
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005495
5496 // How much memory is being used by the ExternalASTSource?
5497 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
5498 const ExternalASTSource::MemoryBufferSizes &sizes =
5499 esrc->getMemoryBufferSizes();
5500
5501 createCXTUResourceUsageEntry(*entries,
5502 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
5503 (unsigned long) sizes.malloc_bytes);
5504 createCXTUResourceUsageEntry(*entries,
5505 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
5506 (unsigned long) sizes.mmap_bytes);
5507 }
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005508
5509 // How much memory is being used by the Preprocessor?
5510 Preprocessor &pp = astUnit->getPreprocessor();
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005511 createCXTUResourceUsageEntry(*entries,
5512 CXTUResourceUsage_Preprocessor,
Argyrios Kyrtzidisc5c5e922011-06-29 22:20:04 +00005513 pp.getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005514
5515 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
5516 createCXTUResourceUsageEntry(*entries,
5517 CXTUResourceUsage_PreprocessingRecord,
5518 pRec->getTotalMemory());
5519 }
5520
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005521 createCXTUResourceUsageEntry(*entries,
5522 CXTUResourceUsage_Preprocessor_HeaderSearch,
5523 pp.getHeaderSearchInfo().getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005524
Ted Kremenekf7870022011-04-20 16:41:07 +00005525 CXTUResourceUsage usage = { (void*) entries.get(),
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005526 (unsigned) entries->size(),
5527 entries->size() ? &(*entries)[0] : 0 };
5528 entries.take();
5529 return usage;
5530}
5531
Ted Kremenekf7870022011-04-20 16:41:07 +00005532void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005533 if (usage.data)
5534 delete (MemUsageEntries*) usage.data;
5535}
5536
5537} // end extern "C"
5538
Douglas Gregor6df78732011-05-05 20:27:22 +00005539void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
5540 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
5541 for (unsigned I = 0; I != Usage.numEntries; ++I)
5542 fprintf(stderr, " %s: %lu\n",
5543 clang_getTUResourceUsageName(Usage.entries[I].kind),
5544 Usage.entries[I].amount);
5545
5546 clang_disposeCXTUResourceUsage(Usage);
5547}
5548
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005549//===----------------------------------------------------------------------===//
Ted Kremenek04bb7162010-01-22 22:44:15 +00005550// Misc. utility functions.
5551//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00005552
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00005553/// Default to using an 8 MB stack size on "safety" threads.
5554static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005555
5556namespace clang {
5557
5558bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005559 void (*Fn)(void*), void *UserData,
5560 unsigned Size) {
5561 if (!Size)
5562 Size = GetSafetyThreadStackSize();
5563 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005564 return CRC.RunSafelyOnThread(Fn, UserData, Size);
5565 return CRC.RunSafely(Fn, UserData);
5566}
5567
5568unsigned GetSafetyThreadStackSize() {
5569 return SafetyStackThreadSize;
5570}
5571
5572void SetSafetyThreadStackSize(unsigned Value) {
5573 SafetyStackThreadSize = Value;
5574}
5575
5576}
5577
Ted Kremenek04bb7162010-01-22 22:44:15 +00005578extern "C" {
5579
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00005580CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00005581 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00005582}
5583
5584} // end: extern "C"
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005585