blob: a189042f56449b3e3bd54bd1b1f8d4f7f0840cc2 [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);
2087 AddStmt(E);
2088}
2089void EnqueueVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *E) {
2090 // Treat the expression like its syntactic form.
2091 Visit(E->getSyntacticForm());
2092}
Ted Kremenek60458782010-11-12 21:34:16 +00002093
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002094void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002095 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002096}
2097
2098bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2099 if (RegionOfInterest.isValid()) {
2100 SourceRange Range = getRawCursorExtent(C);
2101 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2102 return false;
2103 }
2104 return true;
2105}
2106
2107bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2108 while (!WL.empty()) {
2109 // Dequeue the worklist item.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002110 VisitorJob LI = WL.back();
2111 WL.pop_back();
2112
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002113 // Set the Parent field, then back to its old value once we're done.
2114 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2115
2116 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00002117 case VisitorJob::DeclVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002118 Decl *D = cast<DeclVisit>(&LI)->get();
Ted Kremenekf1107452010-11-12 18:26:56 +00002119 if (!D)
2120 continue;
2121
2122 // For now, perform default visitation for Decls.
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002123 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2124 cast<DeclVisit>(&LI)->isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00002125 return true;
2126
2127 continue;
2128 }
Ted Kremenek60608ec2010-11-17 00:50:47 +00002129 case VisitorJob::ExplicitTemplateArgsVisitKind: {
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00002130 const ASTTemplateArgumentListInfo *ArgList =
Ted Kremenek60608ec2010-11-17 00:50:47 +00002131 cast<ExplicitTemplateArgsVisit>(&LI)->get();
2132 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2133 *ArgEnd = Arg + ArgList->NumTemplateArgs;
2134 Arg != ArgEnd; ++Arg) {
2135 if (VisitTemplateArgumentLoc(*Arg))
2136 return true;
2137 }
2138 continue;
2139 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002140 case VisitorJob::TypeLocVisitKind: {
2141 // Perform default visitation for TypeLocs.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002142 if (Visit(cast<TypeLocVisit>(&LI)->get()))
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002143 return true;
2144 continue;
2145 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002146 case VisitorJob::LabelRefVisitKind: {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002147 LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Ted Kremeneke7455012011-02-23 04:54:51 +00002148 if (LabelStmt *stmt = LS->getStmt()) {
2149 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2150 TU))) {
2151 return true;
2152 }
2153 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002154 continue;
2155 }
Ted Kremenek47695c82011-08-18 22:25:21 +00002156
Douglas Gregorf3db29f2011-02-25 18:19:59 +00002157 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2158 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2159 if (VisitNestedNameSpecifierLoc(V->get()))
2160 return true;
2161 continue;
2162 }
2163
Ted Kremenekf64d8032010-11-18 00:02:32 +00002164 case VisitorJob::DeclarationNameInfoVisitKind: {
2165 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2166 ->get()))
2167 return true;
2168 continue;
2169 }
Ted Kremenekcdba6592010-11-18 00:42:18 +00002170 case VisitorJob::MemberRefVisitKind: {
2171 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2172 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2173 return true;
2174 continue;
2175 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002176 case VisitorJob::StmtVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002177 Stmt *S = cast<StmtVisit>(&LI)->get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00002178 if (!S)
2179 continue;
2180
Ted Kremenekf1107452010-11-12 18:26:56 +00002181 // Update the current cursor.
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002182 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
Ted Kremenekcdba6592010-11-18 00:42:18 +00002183 if (!IsInRegionOfInterest(Cursor))
2184 continue;
2185 switch (Visitor(Cursor, Parent, ClientData)) {
2186 case CXChildVisit_Break: return true;
2187 case CXChildVisit_Continue: break;
2188 case CXChildVisit_Recurse:
2189 EnqueueWorkList(WL, S);
Ted Kremenek82f3c502010-11-15 22:23:26 +00002190 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002191 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00002192 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002193 }
2194 case VisitorJob::MemberExprPartsKind: {
2195 // Handle the other pieces in the MemberExpr besides the base.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002196 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002197
2198 // Visit the nested-name-specifier
Douglas Gregor40d96a62011-02-28 21:54:11 +00002199 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
2200 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002201 return true;
2202
2203 // Visit the declaration name.
2204 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2205 return true;
2206
2207 // Visit the explicitly-specified template arguments, if any.
2208 if (M->hasExplicitTemplateArgs()) {
2209 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2210 *ArgEnd = Arg + M->getNumTemplateArgs();
2211 Arg != ArgEnd; ++Arg) {
2212 if (VisitTemplateArgumentLoc(*Arg))
2213 return true;
2214 }
2215 }
2216 continue;
2217 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002218 case VisitorJob::DeclRefExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002219 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002220 // Visit nested-name-specifier, if present.
Douglas Gregor40d96a62011-02-28 21:54:11 +00002221 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
2222 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002223 return true;
2224 // Visit declaration name.
2225 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2226 return true;
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002227 continue;
2228 }
Ted Kremenek60458782010-11-12 21:34:16 +00002229 case VisitorJob::OverloadExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002230 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Ted Kremenek60458782010-11-12 21:34:16 +00002231 // Visit the nested-name-specifier.
Douglas Gregor4c9be892011-02-28 20:01:57 +00002232 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
2233 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenek60458782010-11-12 21:34:16 +00002234 return true;
2235 // Visit the declaration name.
2236 if (VisitDeclarationNameInfo(O->getNameInfo()))
2237 return true;
2238 // Visit the overloaded declaration reference.
2239 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2240 return true;
Ted Kremenek60458782010-11-12 21:34:16 +00002241 continue;
2242 }
Douglas Gregor94d96292011-01-19 20:34:17 +00002243 case VisitorJob::SizeOfPackExprPartsKind: {
2244 SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
2245 NamedDecl *Pack = E->getPack();
2246 if (isa<TemplateTypeParmDecl>(Pack)) {
2247 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
2248 E->getPackLoc(), TU)))
2249 return true;
2250
2251 continue;
2252 }
2253
2254 if (isa<TemplateTemplateParmDecl>(Pack)) {
2255 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
2256 E->getPackLoc(), TU)))
2257 return true;
2258
2259 continue;
2260 }
2261
2262 // Non-type template parameter packs and function parameter packs are
2263 // treated like DeclRefExpr cursors.
2264 continue;
2265 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002266 }
2267 }
2268 return false;
2269}
2270
Ted Kremenekcdba6592010-11-18 00:42:18 +00002271bool CursorVisitor::Visit(Stmt *S) {
Ted Kremenekd1ded662010-11-15 23:31:32 +00002272 VisitorWorkList *WL = 0;
2273 if (!WorkListFreeList.empty()) {
2274 WL = WorkListFreeList.back();
2275 WL->clear();
2276 WorkListFreeList.pop_back();
2277 }
2278 else {
2279 WL = new VisitorWorkList();
2280 WorkListCache.push_back(WL);
2281 }
2282 EnqueueWorkList(*WL, S);
2283 bool result = RunVisitorWorkList(*WL);
2284 WorkListFreeList.push_back(WL);
2285 return result;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002286}
2287
Francois Pichet48a8d142011-07-25 22:00:44 +00002288namespace {
2289typedef llvm::SmallVector<SourceRange, 4> RefNamePieces;
2290RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
2291 const DeclarationNameInfo &NI,
2292 const SourceRange &QLoc,
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00002293 const ASTTemplateArgumentListInfo *TemplateArgs = 0){
Francois Pichet48a8d142011-07-25 22:00:44 +00002294 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
2295 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
2296 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
2297
2298 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
2299
2300 RefNamePieces Pieces;
2301
2302 if (WantQualifier && QLoc.isValid())
2303 Pieces.push_back(QLoc);
2304
2305 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
2306 Pieces.push_back(NI.getLoc());
2307
2308 if (WantTemplateArgs && TemplateArgs)
2309 Pieces.push_back(SourceRange(TemplateArgs->LAngleLoc,
2310 TemplateArgs->RAngleLoc));
2311
2312 if (Kind == DeclarationName::CXXOperatorName) {
2313 Pieces.push_back(SourceLocation::getFromRawEncoding(
2314 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
2315 Pieces.push_back(SourceLocation::getFromRawEncoding(
2316 NI.getInfo().CXXOperatorName.EndOpNameLoc));
2317 }
2318
2319 if (WantSinglePiece) {
2320 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
2321 Pieces.clear();
2322 Pieces.push_back(R);
2323 }
2324
2325 return Pieces;
2326}
2327}
2328
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002329//===----------------------------------------------------------------------===//
2330// Misc. API hooks.
2331//===----------------------------------------------------------------------===//
2332
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002333static llvm::sys::Mutex EnableMultithreadingMutex;
2334static bool EnabledMultithreading;
2335
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002336extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002337CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2338 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002339 // Disable pretty stack trace functionality, which will otherwise be a very
2340 // poor citizen of the world and set up all sorts of signal handlers.
2341 llvm::DisablePrettyStackTrace = true;
2342
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002343 // We use crash recovery to make some of our APIs more reliable, implicitly
2344 // enable it.
2345 llvm::CrashRecoveryContext::Enable();
2346
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002347 // Enable support for multithreading in LLVM.
2348 {
2349 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2350 if (!EnabledMultithreading) {
2351 llvm::llvm_start_multithreaded();
2352 EnabledMultithreading = true;
2353 }
2354 }
2355
Douglas Gregora030b7c2010-01-22 20:35:53 +00002356 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002357 if (excludeDeclarationsFromPCH)
2358 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002359 if (displayDiagnostics)
2360 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002361 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002362}
2363
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002364void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002365 if (CIdx)
2366 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002367}
2368
Ted Kremenekd2427dd2011-03-18 23:05:39 +00002369void clang_toggleCrashRecovery(unsigned isEnabled) {
2370 if (isEnabled)
2371 llvm::CrashRecoveryContext::Enable();
2372 else
2373 llvm::CrashRecoveryContext::Disable();
2374}
2375
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002376CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002377 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002378 if (!CIdx)
2379 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002380
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002381 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002382 FileSystemOptions FileSystemOpts;
2383 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002384
David Blaikied6471f72011-09-25 23:23:43 +00002385 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002386 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002387 CXXIdx->getOnlyLocalDecls(),
2388 0, 0, true);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002389 return MakeCXTranslationUnit(TU);
Steve Naroff600866c2009-08-27 19:51:58 +00002390}
2391
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002392unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002393 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregorb5af8432011-08-25 22:54:01 +00002394 CXTranslationUnit_CacheCompletionResults;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002395}
2396
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002397CXTranslationUnit
2398clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2399 const char *source_filename,
2400 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002401 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002402 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002403 struct CXUnsavedFile *unsaved_files) {
Douglas Gregordca8ee82011-05-06 16:33:08 +00002404 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord |
Chandler Carruthba7537f2011-07-14 09:02:10 +00002405 CXTranslationUnit_NestedMacroExpansions;
Douglas Gregor5a430212010-07-21 18:52:53 +00002406 return clang_parseTranslationUnit(CIdx, source_filename,
2407 command_line_args, num_command_line_args,
2408 unsaved_files, num_unsaved_files,
Douglas Gregordca8ee82011-05-06 16:33:08 +00002409 Options);
Douglas Gregor5a430212010-07-21 18:52:53 +00002410}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002411
2412struct ParseTranslationUnitInfo {
2413 CXIndex CIdx;
2414 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002415 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002416 int num_command_line_args;
2417 struct CXUnsavedFile *unsaved_files;
2418 unsigned num_unsaved_files;
2419 unsigned options;
2420 CXTranslationUnit result;
2421};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002422static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002423 ParseTranslationUnitInfo *PTUI =
2424 static_cast<ParseTranslationUnitInfo*>(UserData);
2425 CXIndex CIdx = PTUI->CIdx;
2426 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002427 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002428 int num_command_line_args = PTUI->num_command_line_args;
2429 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2430 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2431 unsigned options = PTUI->options;
2432 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002433
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002434 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002435 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002436
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002437 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2438
Douglas Gregor44c181a2010-07-23 00:33:23 +00002439 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregor467dc882011-08-25 22:30:56 +00002440 // FIXME: Add a flag for modules.
2441 TranslationUnitKind TUKind
2442 = (options & CXTranslationUnit_Incomplete)? TU_Prefix : TU_Complete;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002443 bool CacheCodeCompetionResults
2444 = options & CXTranslationUnit_CacheCompletionResults;
2445
Douglas Gregor5352ac02010-01-28 00:27:43 +00002446 // Configure the diagnostics.
2447 DiagnosticOptions DiagOpts;
David Blaikied6471f72011-09-25 23:23:43 +00002448 llvm::IntrusiveRefCntPtr<DiagnosticsEngine>
Ted Kremenek25a11e12011-03-22 01:15:24 +00002449 Diags(CompilerInstance::createDiagnostics(DiagOpts, num_command_line_args,
2450 command_line_args));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002451
Ted Kremenek25a11e12011-03-22 01:15:24 +00002452 // Recover resources if we crash before exiting this function.
David Blaikied6471f72011-09-25 23:23:43 +00002453 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
2454 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00002455 DiagCleanup(Diags.getPtr());
2456
2457 llvm::OwningPtr<std::vector<ASTUnit::RemappedFile> >
2458 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2459
2460 // Recover resources if we crash before exiting this function.
2461 llvm::CrashRecoveryContextCleanupRegistrar<
2462 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2463
Douglas Gregor4db64a42010-01-23 00:14:00 +00002464 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002465 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002466 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002467 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002468 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2469 Buffer));
Douglas Gregor4db64a42010-01-23 00:14:00 +00002470 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002471
Ted Kremenek25a11e12011-03-22 01:15:24 +00002472 llvm::OwningPtr<std::vector<const char *> >
2473 Args(new std::vector<const char*>());
2474
2475 // Recover resources if we crash before exiting this method.
2476 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
2477 ArgsCleanup(Args.get());
2478
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002479 // Since the Clang C library is primarily used by batch tools dealing with
2480 // (often very broken) source code, where spell-checking can have a
2481 // significant negative impact on performance (particularly when
2482 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002483 // Only do this if we haven't found a spell-checking-related argument.
2484 bool FoundSpellCheckingArgument = false;
2485 for (int I = 0; I != num_command_line_args; ++I) {
2486 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2487 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2488 FoundSpellCheckingArgument = true;
2489 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002490 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002491 }
2492 if (!FoundSpellCheckingArgument)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002493 Args->push_back("-fno-spell-checking");
Douglas Gregorb10daed2010-10-11 16:52:23 +00002494
Ted Kremenek25a11e12011-03-22 01:15:24 +00002495 Args->insert(Args->end(), command_line_args,
2496 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002497
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002498 // The 'source_filename' argument is optional. If the caller does not
2499 // specify it then it is assumed that the source file is specified
2500 // in the actual argument list.
2501 // Put the source file after command_line_args otherwise if '-x' flag is
2502 // present it will be unused.
2503 if (source_filename)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002504 Args->push_back(source_filename);
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002505
Douglas Gregor44c181a2010-07-23 00:33:23 +00002506 // Do we need the detailed preprocessing record?
Chandler Carruthba7537f2011-07-14 09:02:10 +00002507 bool NestedMacroExpansions = false;
Douglas Gregor44c181a2010-07-23 00:33:23 +00002508 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Ted Kremenek25a11e12011-03-22 01:15:24 +00002509 Args->push_back("-Xclang");
2510 Args->push_back("-detailed-preprocessing-record");
Chandler Carruthba7537f2011-07-14 09:02:10 +00002511 NestedMacroExpansions
2512 = (options & CXTranslationUnit_NestedMacroExpansions);
Douglas Gregor44c181a2010-07-23 00:33:23 +00002513 }
2514
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002515 unsigned NumErrors = Diags->getClient()->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002516 llvm::OwningPtr<ASTUnit> Unit(
Ted Kremenek4ee99262011-03-22 20:16:19 +00002517 ASTUnit::LoadFromCommandLine(Args->size() ? &(*Args)[0] : 0
2518 /* vector::data() not portable */,
2519 Args->size() ? (&(*Args)[0] + Args->size()) :0,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002520 Diags,
2521 CXXIdx->getClangResourcesPath(),
2522 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002523 /*CaptureDiagnostics=*/true,
Ted Kremenek4ee99262011-03-22 20:16:19 +00002524 RemappedFiles->size() ? &(*RemappedFiles)[0]:0,
Ted Kremenek25a11e12011-03-22 01:15:24 +00002525 RemappedFiles->size(),
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00002526 /*RemappedFilesKeepOriginalName=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002527 PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00002528 TUKind,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002529 CacheCodeCompetionResults,
Chandler Carruthba7537f2011-07-14 09:02:10 +00002530 NestedMacroExpansions));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002531
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002532 if (NumErrors != Diags->getClient()->getNumErrors()) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002533 // Make sure to check that 'Unit' is non-NULL.
2534 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2535 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2536 DEnd = Unit->stored_diag_end();
2537 D != DEnd; ++D) {
2538 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2539 CXString Msg = clang_formatDiagnostic(&Diag,
2540 clang_defaultDiagnosticDisplayOptions());
2541 fprintf(stderr, "%s\n", clang_getCString(Msg));
2542 clang_disposeString(Msg);
2543 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002544#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002545 // On Windows, force a flush, since there may be multiple copies of
2546 // stderr and stdout in the file system, all with different buffers
2547 // but writing to the same device.
2548 fflush(stderr);
2549#endif
2550 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002551 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002552
Ted Kremeneka60ed472010-11-16 08:15:36 +00002553 PTUI->result = MakeCXTranslationUnit(Unit.take());
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002554}
2555CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2556 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002557 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002558 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002559 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002560 unsigned num_unsaved_files,
2561 unsigned options) {
2562 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002563 num_command_line_args, unsaved_files,
2564 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002565 llvm::CrashRecoveryContext CRC;
2566
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002567 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002568 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2569 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2570 fprintf(stderr, " 'command_line_args' : [");
2571 for (int i = 0; i != num_command_line_args; ++i) {
2572 if (i)
2573 fprintf(stderr, ", ");
2574 fprintf(stderr, "'%s'", command_line_args[i]);
2575 }
2576 fprintf(stderr, "],\n");
2577 fprintf(stderr, " 'unsaved_files' : [");
2578 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2579 if (i)
2580 fprintf(stderr, ", ");
2581 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2582 unsaved_files[i].Length);
2583 }
2584 fprintf(stderr, "],\n");
2585 fprintf(stderr, " 'options' : %d,\n", options);
2586 fprintf(stderr, "}\n");
2587
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002588 return 0;
Douglas Gregor6df78732011-05-05 20:27:22 +00002589 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
2590 PrintLibclangResourceUsage(PTUI.result);
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002591 }
Douglas Gregor6df78732011-05-05 20:27:22 +00002592
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002593 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002594}
2595
Douglas Gregor19998442010-08-13 15:35:05 +00002596unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2597 return CXSaveTranslationUnit_None;
2598}
2599
2600int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2601 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002602 if (!TU)
Douglas Gregor39c411f2011-07-06 16:43:36 +00002603 return CXSaveError_InvalidTU;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002604
Douglas Gregor39c411f2011-07-06 16:43:36 +00002605 CXSaveError result = static_cast<ASTUnit *>(TU->TUData)->Save(FileName);
Douglas Gregor6df78732011-05-05 20:27:22 +00002606 if (getenv("LIBCLANG_RESOURCE_USAGE"))
2607 PrintLibclangResourceUsage(TU);
2608 return result;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002609}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002610
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002611void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002612 if (CTUnit) {
2613 // If the translation unit has been marked as unsafe to free, just discard
2614 // it.
Ted Kremeneka60ed472010-11-16 08:15:36 +00002615 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002616 return;
2617
Ted Kremeneka60ed472010-11-16 08:15:36 +00002618 delete static_cast<ASTUnit *>(CTUnit->TUData);
2619 disposeCXStringPool(CTUnit->StringPool);
Ted Kremenek15322172011-11-10 08:43:12 +00002620 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002621 delete CTUnit;
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002622 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002623}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002624
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002625unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2626 return CXReparse_None;
2627}
2628
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002629struct ReparseTranslationUnitInfo {
2630 CXTranslationUnit TU;
2631 unsigned num_unsaved_files;
2632 struct CXUnsavedFile *unsaved_files;
2633 unsigned options;
2634 int result;
2635};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002636
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002637static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002638 ReparseTranslationUnitInfo *RTUI =
2639 static_cast<ReparseTranslationUnitInfo*>(UserData);
2640 CXTranslationUnit TU = RTUI->TU;
Ted Kremenek15322172011-11-10 08:43:12 +00002641
2642 // Reset the associated diagnostics.
2643 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
2644 TU->Diagnostics = 0;
2645
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002646 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2647 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2648 unsigned options = RTUI->options;
2649 (void) options;
2650 RTUI->result = 1;
2651
Douglas Gregorabc563f2010-07-19 21:46:24 +00002652 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002653 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002654
Ted Kremeneka60ed472010-11-16 08:15:36 +00002655 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor593b0c12010-09-23 18:47:53 +00002656 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002657
Ted Kremenek25a11e12011-03-22 01:15:24 +00002658 llvm::OwningPtr<std::vector<ASTUnit::RemappedFile> >
2659 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2660
2661 // Recover resources if we crash before exiting this function.
2662 llvm::CrashRecoveryContextCleanupRegistrar<
2663 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2664
Douglas Gregorabc563f2010-07-19 21:46:24 +00002665 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002666 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002667 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002668 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002669 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2670 Buffer));
Douglas Gregorabc563f2010-07-19 21:46:24 +00002671 }
2672
Ted Kremenek4ee99262011-03-22 20:16:19 +00002673 if (!CXXUnit->Reparse(RemappedFiles->size() ? &(*RemappedFiles)[0] : 0,
2674 RemappedFiles->size()))
Douglas Gregor593b0c12010-09-23 18:47:53 +00002675 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002676}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002677
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002678int clang_reparseTranslationUnit(CXTranslationUnit TU,
2679 unsigned num_unsaved_files,
2680 struct CXUnsavedFile *unsaved_files,
2681 unsigned options) {
2682 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2683 options, 0 };
Argyrios Kyrtzidis8c4b47e2011-10-28 22:54:33 +00002684
Argyrios Kyrtzidise7de9b42011-10-29 19:32:39 +00002685 if (getenv("LIBCLANG_NOTHREADS")) {
Argyrios Kyrtzidis8c4b47e2011-10-28 22:54:33 +00002686 clang_reparseTranslationUnit_Impl(&RTUI);
2687 return RTUI.result;
2688 }
2689
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002690 llvm::CrashRecoveryContext CRC;
2691
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002692 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002693 fprintf(stderr, "libclang: crash detected during reparsing\n");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002694 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002695 return 1;
Douglas Gregor6df78732011-05-05 20:27:22 +00002696 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
2697 PrintLibclangResourceUsage(TU);
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002698
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002699 return RTUI.result;
2700}
2701
Douglas Gregordf95a132010-08-09 20:45:32 +00002702
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002703CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002704 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002705 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002706
Ted Kremeneka60ed472010-11-16 08:15:36 +00002707 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002708 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002709}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002710
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002711CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002712 CXCursor Result = { CXCursor_TranslationUnit, 0, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002713 return Result;
2714}
2715
Ted Kremenekfb480492010-01-13 21:46:36 +00002716} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002717
Ted Kremenekfb480492010-01-13 21:46:36 +00002718//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002719// CXFile Operations.
2720//===----------------------------------------------------------------------===//
2721
2722extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002723CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002724 if (!SFile)
Ted Kremeneka60ed472010-11-16 08:15:36 +00002725 return createCXString((const char*)NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002726
Steve Naroff88145032009-10-27 14:35:18 +00002727 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002728 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002729}
2730
2731time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002732 if (!SFile)
2733 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002734
Steve Naroff88145032009-10-27 14:35:18 +00002735 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2736 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002737}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002738
Douglas Gregorb9790342010-01-22 21:44:22 +00002739CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2740 if (!tu)
2741 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002742
Ted Kremeneka60ed472010-11-16 08:15:36 +00002743 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002744
Douglas Gregorb9790342010-01-22 21:44:22 +00002745 FileManager &FMgr = CXXUnit->getFileManager();
Chris Lattner39b49bc2010-11-23 08:35:12 +00002746 return const_cast<FileEntry *>(FMgr.getFile(file_name));
Douglas Gregorb9790342010-01-22 21:44:22 +00002747}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002748
Douglas Gregordd3e5542011-05-04 00:14:37 +00002749unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit tu, CXFile file) {
2750 if (!tu || !file)
2751 return 0;
2752
2753 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
2754 FileEntry *FEnt = static_cast<FileEntry *>(file);
2755 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
2756 .isFileMultipleIncludeGuarded(FEnt);
2757}
2758
Ted Kremenekfb480492010-01-13 21:46:36 +00002759} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002760
Ted Kremenekfb480492010-01-13 21:46:36 +00002761//===----------------------------------------------------------------------===//
2762// CXCursor Operations.
2763//===----------------------------------------------------------------------===//
2764
Ted Kremenekfb480492010-01-13 21:46:36 +00002765static Decl *getDeclFromExpr(Stmt *E) {
Argyrios Kyrtzidisc2954612011-09-12 22:17:26 +00002766 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Douglas Gregordb1314e2010-10-01 21:11:22 +00002767 return getDeclFromExpr(CE->getSubExpr());
2768
Ted Kremenekfb480492010-01-13 21:46:36 +00002769 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2770 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002771 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2772 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002773 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2774 return ME->getMemberDecl();
2775 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2776 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002777 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
John McCall12f78a62010-12-02 01:19:52 +00002778 return PRE->isExplicitProperty() ? PRE->getExplicitProperty() : 0;
John McCall4b9c2d22011-11-06 09:01:30 +00002779 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
2780 return getDeclFromExpr(POE->getSyntacticForm());
2781 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
2782 if (Expr *Src = OVE->getSourceExpr())
2783 return getDeclFromExpr(Src);
Douglas Gregordb1314e2010-10-01 21:11:22 +00002784
Ted Kremenekfb480492010-01-13 21:46:36 +00002785 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2786 return getDeclFromExpr(CE->getCallee());
Chris Lattner5f9e2722011-07-23 10:55:15 +00002787 if (CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Douglas Gregor93798e22010-11-05 21:11:19 +00002788 if (!CE->isElidable())
2789 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002790 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2791 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002792
Douglas Gregordb1314e2010-10-01 21:11:22 +00002793 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2794 return PE->getProtocol();
Douglas Gregorc7793c72011-01-15 01:15:58 +00002795 if (SubstNonTypeTemplateParmPackExpr *NTTP
2796 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
2797 return NTTP->getParameterPack();
Douglas Gregor94d96292011-01-19 20:34:17 +00002798 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2799 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
2800 isa<ParmVarDecl>(SizeOfPack->getPack()))
2801 return SizeOfPack->getPack();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002802
Ted Kremenekfb480492010-01-13 21:46:36 +00002803 return 0;
2804}
2805
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002806static SourceLocation getLocationFromExpr(Expr *E) {
Argyrios Kyrtzidisc2954612011-09-12 22:17:26 +00002807 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
2808 return getLocationFromExpr(CE->getSubExpr());
2809
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002810 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2811 return /*FIXME:*/Msg->getLeftLoc();
2812 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2813 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002814 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2815 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002816 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2817 return Member->getMemberLoc();
2818 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2819 return Ivar->getLocation();
Douglas Gregor94d96292011-01-19 20:34:17 +00002820 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2821 return SizeOfPack->getPackLoc();
2822
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002823 return E->getLocStart();
2824}
2825
Ted Kremenekfb480492010-01-13 21:46:36 +00002826extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002827
2828unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002829 CXCursorVisitor visitor,
2830 CXClientData client_data) {
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00002831 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
2832 /*VisitPreprocessorLast=*/false);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002833 return CursorVis.VisitChildren(parent);
2834}
2835
David Chisnall3387c652010-11-03 14:12:26 +00002836#ifndef __has_feature
2837#define __has_feature(x) 0
2838#endif
2839#if __has_feature(blocks)
2840typedef enum CXChildVisitResult
2841 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2842
2843static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2844 CXClientData client_data) {
2845 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2846 return block(cursor, parent);
2847}
2848#else
2849// If we are compiled with a compiler that doesn't have native blocks support,
2850// define and call the block manually, so the
2851typedef struct _CXChildVisitResult
2852{
2853 void *isa;
2854 int flags;
2855 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002856 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2857 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00002858} *CXCursorVisitorBlock;
2859
2860static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2861 CXClientData client_data) {
2862 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2863 return block->invoke(block, cursor, parent);
2864}
2865#endif
2866
2867
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002868unsigned clang_visitChildrenWithBlock(CXCursor parent,
2869 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00002870 return clang_visitChildren(parent, visitWithBlock, block);
2871}
2872
Douglas Gregor78205d42010-01-20 21:45:58 +00002873static CXString getDeclSpelling(Decl *D) {
2874 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
Douglas Gregore3c60a72010-11-17 00:13:31 +00002875 if (!ND) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002876 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00002877 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
2878 return createCXString(Property->getIdentifier()->getName());
2879
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002880 return createCXString("");
Douglas Gregore3c60a72010-11-17 00:13:31 +00002881 }
2882
Douglas Gregor78205d42010-01-20 21:45:58 +00002883 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002884 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002885
Douglas Gregor78205d42010-01-20 21:45:58 +00002886 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2887 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2888 // and returns different names. NamedDecl returns the class name and
2889 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002890 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002891
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002892 if (isa<UsingDirectiveDecl>(D))
2893 return createCXString("");
2894
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002895 llvm::SmallString<1024> S;
2896 llvm::raw_svector_ostream os(S);
2897 ND->printName(os);
2898
2899 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002900}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002901
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002902CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002903 if (clang_isTranslationUnit(C.kind))
Ted Kremeneka60ed472010-11-16 08:15:36 +00002904 return clang_getTranslationUnitSpelling(
2905 static_cast<CXTranslationUnit>(C.data[2]));
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002906
Steve Narofff334b4e2009-09-02 18:26:48 +00002907 if (clang_isReference(C.kind)) {
2908 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002909 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002910 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002911 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002912 }
2913 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002914 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002915 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002916 }
2917 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002918 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002919 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002920 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002921 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002922 case CXCursor_CXXBaseSpecifier: {
2923 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2924 return createCXString(B->getType().getAsString());
2925 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002926 case CXCursor_TypeRef: {
2927 TypeDecl *Type = getCursorTypeRef(C).first;
2928 assert(Type && "Missing type decl");
2929
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002930 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2931 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002932 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002933 case CXCursor_TemplateRef: {
2934 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002935 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002936
2937 return createCXString(Template->getNameAsString());
2938 }
Douglas Gregor69319002010-08-31 23:48:11 +00002939
2940 case CXCursor_NamespaceRef: {
2941 NamedDecl *NS = getCursorNamespaceRef(C).first;
2942 assert(NS && "Missing namespace decl");
2943
2944 return createCXString(NS->getNameAsString());
2945 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002946
Douglas Gregora67e03f2010-09-09 21:42:20 +00002947 case CXCursor_MemberRef: {
2948 FieldDecl *Field = getCursorMemberRef(C).first;
2949 assert(Field && "Missing member decl");
2950
2951 return createCXString(Field->getNameAsString());
2952 }
2953
Douglas Gregor36897b02010-09-10 00:22:18 +00002954 case CXCursor_LabelRef: {
2955 LabelStmt *Label = getCursorLabelRef(C).first;
2956 assert(Label && "Missing label");
2957
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002958 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00002959 }
2960
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002961 case CXCursor_OverloadedDeclRef: {
2962 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2963 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2964 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2965 return createCXString(ND->getNameAsString());
2966 return createCXString("");
2967 }
2968 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2969 return createCXString(E->getName().getAsString());
2970 OverloadedTemplateStorage *Ovl
2971 = Storage.get<OverloadedTemplateStorage*>();
2972 if (Ovl->size() == 0)
2973 return createCXString("");
2974 return createCXString((*Ovl->begin())->getNameAsString());
2975 }
2976
Daniel Dunbaracca7252009-11-30 20:42:49 +00002977 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002978 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002979 }
2980 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002981
2982 if (clang_isExpression(C.kind)) {
2983 Decl *D = getDeclFromExpr(getCursorExpr(C));
2984 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002985 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002986 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002987 }
2988
Douglas Gregor36897b02010-09-10 00:22:18 +00002989 if (clang_isStatement(C.kind)) {
2990 Stmt *S = getCursorStmt(C);
2991 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002992 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00002993
2994 return createCXString("");
2995 }
2996
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00002997 if (C.kind == CXCursor_MacroExpansion)
Chandler Carruth9e5bb852011-07-14 08:20:46 +00002998 return createCXString(getCursorMacroExpansion(C)->getName()
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002999 ->getNameStart());
3000
Douglas Gregor572feb22010-03-18 18:04:21 +00003001 if (C.kind == CXCursor_MacroDefinition)
3002 return createCXString(getCursorMacroDefinition(C)->getName()
3003 ->getNameStart());
3004
Douglas Gregorecdcb882010-10-20 22:00:55 +00003005 if (C.kind == CXCursor_InclusionDirective)
3006 return createCXString(getCursorInclusionDirective(C)->getFileName());
3007
Douglas Gregor60cbfac2010-01-25 16:56:17 +00003008 if (clang_isDeclaration(C.kind))
3009 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00003010
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00003011 if (C.kind == CXCursor_AnnotateAttr) {
3012 AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
3013 return createCXString(AA->getAnnotation());
3014 }
3015
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003016 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00003017}
3018
Douglas Gregor358559d2010-10-02 22:49:11 +00003019CXString clang_getCursorDisplayName(CXCursor C) {
3020 if (!clang_isDeclaration(C.kind))
3021 return clang_getCursorSpelling(C);
3022
3023 Decl *D = getCursorDecl(C);
3024 if (!D)
3025 return createCXString("");
3026
Douglas Gregor30c42402011-09-27 22:38:19 +00003027 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
Douglas Gregor358559d2010-10-02 22:49:11 +00003028 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
3029 D = FunTmpl->getTemplatedDecl();
3030
3031 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
3032 llvm::SmallString<64> Str;
3033 llvm::raw_svector_ostream OS(Str);
3034 OS << Function->getNameAsString();
3035 if (Function->getPrimaryTemplate())
3036 OS << "<>";
3037 OS << "(";
3038 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
3039 if (I)
3040 OS << ", ";
3041 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
3042 }
3043
3044 if (Function->isVariadic()) {
3045 if (Function->getNumParams())
3046 OS << ", ";
3047 OS << "...";
3048 }
3049 OS << ")";
3050 return createCXString(OS.str());
3051 }
3052
3053 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
3054 llvm::SmallString<64> Str;
3055 llvm::raw_svector_ostream OS(Str);
3056 OS << ClassTemplate->getNameAsString();
3057 OS << "<";
3058 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
3059 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3060 if (I)
3061 OS << ", ";
3062
3063 NamedDecl *Param = Params->getParam(I);
3064 if (Param->getIdentifier()) {
3065 OS << Param->getIdentifier()->getName();
3066 continue;
3067 }
3068
3069 // There is no parameter name, which makes this tricky. Try to come up
3070 // with something useful that isn't too long.
3071 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3072 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
3073 else if (NonTypeTemplateParmDecl *NTTP
3074 = dyn_cast<NonTypeTemplateParmDecl>(Param))
3075 OS << NTTP->getType().getAsString(Policy);
3076 else
3077 OS << "template<...> class";
3078 }
3079
3080 OS << ">";
3081 return createCXString(OS.str());
3082 }
3083
3084 if (ClassTemplateSpecializationDecl *ClassSpec
3085 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
3086 // If the type was explicitly written, use that.
3087 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
3088 return createCXString(TSInfo->getType().getAsString(Policy));
3089
3090 llvm::SmallString<64> Str;
3091 llvm::raw_svector_ostream OS(Str);
3092 OS << ClassSpec->getNameAsString();
3093 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00003094 ClassSpec->getTemplateArgs().data(),
3095 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00003096 Policy);
3097 return createCXString(OS.str());
3098 }
3099
3100 return clang_getCursorSpelling(C);
3101}
3102
Ted Kremeneke68fff62010-02-17 00:41:32 +00003103CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00003104 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00003105 case CXCursor_FunctionDecl:
3106 return createCXString("FunctionDecl");
3107 case CXCursor_TypedefDecl:
3108 return createCXString("TypedefDecl");
3109 case CXCursor_EnumDecl:
3110 return createCXString("EnumDecl");
3111 case CXCursor_EnumConstantDecl:
3112 return createCXString("EnumConstantDecl");
3113 case CXCursor_StructDecl:
3114 return createCXString("StructDecl");
3115 case CXCursor_UnionDecl:
3116 return createCXString("UnionDecl");
3117 case CXCursor_ClassDecl:
3118 return createCXString("ClassDecl");
3119 case CXCursor_FieldDecl:
3120 return createCXString("FieldDecl");
3121 case CXCursor_VarDecl:
3122 return createCXString("VarDecl");
3123 case CXCursor_ParmDecl:
3124 return createCXString("ParmDecl");
3125 case CXCursor_ObjCInterfaceDecl:
3126 return createCXString("ObjCInterfaceDecl");
3127 case CXCursor_ObjCCategoryDecl:
3128 return createCXString("ObjCCategoryDecl");
3129 case CXCursor_ObjCProtocolDecl:
3130 return createCXString("ObjCProtocolDecl");
3131 case CXCursor_ObjCPropertyDecl:
3132 return createCXString("ObjCPropertyDecl");
3133 case CXCursor_ObjCIvarDecl:
3134 return createCXString("ObjCIvarDecl");
3135 case CXCursor_ObjCInstanceMethodDecl:
3136 return createCXString("ObjCInstanceMethodDecl");
3137 case CXCursor_ObjCClassMethodDecl:
3138 return createCXString("ObjCClassMethodDecl");
3139 case CXCursor_ObjCImplementationDecl:
3140 return createCXString("ObjCImplementationDecl");
3141 case CXCursor_ObjCCategoryImplDecl:
3142 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00003143 case CXCursor_CXXMethod:
3144 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003145 case CXCursor_UnexposedDecl:
3146 return createCXString("UnexposedDecl");
3147 case CXCursor_ObjCSuperClassRef:
3148 return createCXString("ObjCSuperClassRef");
3149 case CXCursor_ObjCProtocolRef:
3150 return createCXString("ObjCProtocolRef");
3151 case CXCursor_ObjCClassRef:
3152 return createCXString("ObjCClassRef");
3153 case CXCursor_TypeRef:
3154 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003155 case CXCursor_TemplateRef:
3156 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00003157 case CXCursor_NamespaceRef:
3158 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00003159 case CXCursor_MemberRef:
3160 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00003161 case CXCursor_LabelRef:
3162 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003163 case CXCursor_OverloadedDeclRef:
3164 return createCXString("OverloadedDeclRef");
Douglas Gregor42b29842011-10-05 19:00:14 +00003165 case CXCursor_IntegerLiteral:
3166 return createCXString("IntegerLiteral");
3167 case CXCursor_FloatingLiteral:
3168 return createCXString("FloatingLiteral");
3169 case CXCursor_ImaginaryLiteral:
3170 return createCXString("ImaginaryLiteral");
3171 case CXCursor_StringLiteral:
3172 return createCXString("StringLiteral");
3173 case CXCursor_CharacterLiteral:
3174 return createCXString("CharacterLiteral");
3175 case CXCursor_ParenExpr:
3176 return createCXString("ParenExpr");
3177 case CXCursor_UnaryOperator:
3178 return createCXString("UnaryOperator");
3179 case CXCursor_ArraySubscriptExpr:
3180 return createCXString("ArraySubscriptExpr");
3181 case CXCursor_BinaryOperator:
3182 return createCXString("BinaryOperator");
3183 case CXCursor_CompoundAssignOperator:
3184 return createCXString("CompoundAssignOperator");
3185 case CXCursor_ConditionalOperator:
3186 return createCXString("ConditionalOperator");
3187 case CXCursor_CStyleCastExpr:
3188 return createCXString("CStyleCastExpr");
3189 case CXCursor_CompoundLiteralExpr:
3190 return createCXString("CompoundLiteralExpr");
3191 case CXCursor_InitListExpr:
3192 return createCXString("InitListExpr");
3193 case CXCursor_AddrLabelExpr:
3194 return createCXString("AddrLabelExpr");
3195 case CXCursor_StmtExpr:
3196 return createCXString("StmtExpr");
3197 case CXCursor_GenericSelectionExpr:
3198 return createCXString("GenericSelectionExpr");
3199 case CXCursor_GNUNullExpr:
3200 return createCXString("GNUNullExpr");
3201 case CXCursor_CXXStaticCastExpr:
3202 return createCXString("CXXStaticCastExpr");
3203 case CXCursor_CXXDynamicCastExpr:
3204 return createCXString("CXXDynamicCastExpr");
3205 case CXCursor_CXXReinterpretCastExpr:
3206 return createCXString("CXXReinterpretCastExpr");
3207 case CXCursor_CXXConstCastExpr:
3208 return createCXString("CXXConstCastExpr");
3209 case CXCursor_CXXFunctionalCastExpr:
3210 return createCXString("CXXFunctionalCastExpr");
3211 case CXCursor_CXXTypeidExpr:
3212 return createCXString("CXXTypeidExpr");
3213 case CXCursor_CXXBoolLiteralExpr:
3214 return createCXString("CXXBoolLiteralExpr");
3215 case CXCursor_CXXNullPtrLiteralExpr:
3216 return createCXString("CXXNullPtrLiteralExpr");
3217 case CXCursor_CXXThisExpr:
3218 return createCXString("CXXThisExpr");
3219 case CXCursor_CXXThrowExpr:
3220 return createCXString("CXXThrowExpr");
3221 case CXCursor_CXXNewExpr:
3222 return createCXString("CXXNewExpr");
3223 case CXCursor_CXXDeleteExpr:
3224 return createCXString("CXXDeleteExpr");
3225 case CXCursor_UnaryExpr:
3226 return createCXString("UnaryExpr");
3227 case CXCursor_ObjCStringLiteral:
3228 return createCXString("ObjCStringLiteral");
3229 case CXCursor_ObjCEncodeExpr:
3230 return createCXString("ObjCEncodeExpr");
3231 case CXCursor_ObjCSelectorExpr:
3232 return createCXString("ObjCSelectorExpr");
3233 case CXCursor_ObjCProtocolExpr:
3234 return createCXString("ObjCProtocolExpr");
3235 case CXCursor_ObjCBridgedCastExpr:
3236 return createCXString("ObjCBridgedCastExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00003237 case CXCursor_BlockExpr:
3238 return createCXString("BlockExpr");
Douglas Gregor42b29842011-10-05 19:00:14 +00003239 case CXCursor_PackExpansionExpr:
3240 return createCXString("PackExpansionExpr");
3241 case CXCursor_SizeOfPackExpr:
3242 return createCXString("SizeOfPackExpr");
3243 case CXCursor_UnexposedExpr:
3244 return createCXString("UnexposedExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003245 case CXCursor_DeclRefExpr:
3246 return createCXString("DeclRefExpr");
3247 case CXCursor_MemberRefExpr:
3248 return createCXString("MemberRefExpr");
3249 case CXCursor_CallExpr:
3250 return createCXString("CallExpr");
3251 case CXCursor_ObjCMessageExpr:
3252 return createCXString("ObjCMessageExpr");
3253 case CXCursor_UnexposedStmt:
3254 return createCXString("UnexposedStmt");
Douglas Gregor42b29842011-10-05 19:00:14 +00003255 case CXCursor_DeclStmt:
3256 return createCXString("DeclStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00003257 case CXCursor_LabelStmt:
3258 return createCXString("LabelStmt");
Douglas Gregor42b29842011-10-05 19:00:14 +00003259 case CXCursor_CompoundStmt:
3260 return createCXString("CompoundStmt");
3261 case CXCursor_CaseStmt:
3262 return createCXString("CaseStmt");
3263 case CXCursor_DefaultStmt:
3264 return createCXString("DefaultStmt");
3265 case CXCursor_IfStmt:
3266 return createCXString("IfStmt");
3267 case CXCursor_SwitchStmt:
3268 return createCXString("SwitchStmt");
3269 case CXCursor_WhileStmt:
3270 return createCXString("WhileStmt");
3271 case CXCursor_DoStmt:
3272 return createCXString("DoStmt");
3273 case CXCursor_ForStmt:
3274 return createCXString("ForStmt");
3275 case CXCursor_GotoStmt:
3276 return createCXString("GotoStmt");
3277 case CXCursor_IndirectGotoStmt:
3278 return createCXString("IndirectGotoStmt");
3279 case CXCursor_ContinueStmt:
3280 return createCXString("ContinueStmt");
3281 case CXCursor_BreakStmt:
3282 return createCXString("BreakStmt");
3283 case CXCursor_ReturnStmt:
3284 return createCXString("ReturnStmt");
3285 case CXCursor_AsmStmt:
3286 return createCXString("AsmStmt");
3287 case CXCursor_ObjCAtTryStmt:
3288 return createCXString("ObjCAtTryStmt");
3289 case CXCursor_ObjCAtCatchStmt:
3290 return createCXString("ObjCAtCatchStmt");
3291 case CXCursor_ObjCAtFinallyStmt:
3292 return createCXString("ObjCAtFinallyStmt");
3293 case CXCursor_ObjCAtThrowStmt:
3294 return createCXString("ObjCAtThrowStmt");
3295 case CXCursor_ObjCAtSynchronizedStmt:
3296 return createCXString("ObjCAtSynchronizedStmt");
3297 case CXCursor_ObjCAutoreleasePoolStmt:
3298 return createCXString("ObjCAutoreleasePoolStmt");
3299 case CXCursor_ObjCForCollectionStmt:
3300 return createCXString("ObjCForCollectionStmt");
3301 case CXCursor_CXXCatchStmt:
3302 return createCXString("CXXCatchStmt");
3303 case CXCursor_CXXTryStmt:
3304 return createCXString("CXXTryStmt");
3305 case CXCursor_CXXForRangeStmt:
3306 return createCXString("CXXForRangeStmt");
3307 case CXCursor_SEHTryStmt:
3308 return createCXString("SEHTryStmt");
3309 case CXCursor_SEHExceptStmt:
3310 return createCXString("SEHExceptStmt");
3311 case CXCursor_SEHFinallyStmt:
3312 return createCXString("SEHFinallyStmt");
3313 case CXCursor_NullStmt:
3314 return createCXString("NullStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003315 case CXCursor_InvalidFile:
3316 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00003317 case CXCursor_InvalidCode:
3318 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003319 case CXCursor_NoDeclFound:
3320 return createCXString("NoDeclFound");
3321 case CXCursor_NotImplemented:
3322 return createCXString("NotImplemented");
3323 case CXCursor_TranslationUnit:
3324 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00003325 case CXCursor_UnexposedAttr:
3326 return createCXString("UnexposedAttr");
3327 case CXCursor_IBActionAttr:
3328 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003329 case CXCursor_IBOutletAttr:
3330 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003331 case CXCursor_IBOutletCollectionAttr:
3332 return createCXString("attribute(iboutletcollection)");
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00003333 case CXCursor_CXXFinalAttr:
3334 return createCXString("attribute(final)");
3335 case CXCursor_CXXOverrideAttr:
3336 return createCXString("attribute(override)");
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00003337 case CXCursor_AnnotateAttr:
3338 return createCXString("attribute(annotate)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003339 case CXCursor_PreprocessingDirective:
3340 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003341 case CXCursor_MacroDefinition:
3342 return createCXString("macro definition");
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003343 case CXCursor_MacroExpansion:
3344 return createCXString("macro expansion");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003345 case CXCursor_InclusionDirective:
3346 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003347 case CXCursor_Namespace:
3348 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003349 case CXCursor_LinkageSpec:
3350 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003351 case CXCursor_CXXBaseSpecifier:
3352 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003353 case CXCursor_Constructor:
3354 return createCXString("CXXConstructor");
3355 case CXCursor_Destructor:
3356 return createCXString("CXXDestructor");
3357 case CXCursor_ConversionFunction:
3358 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003359 case CXCursor_TemplateTypeParameter:
3360 return createCXString("TemplateTypeParameter");
3361 case CXCursor_NonTypeTemplateParameter:
3362 return createCXString("NonTypeTemplateParameter");
3363 case CXCursor_TemplateTemplateParameter:
3364 return createCXString("TemplateTemplateParameter");
3365 case CXCursor_FunctionTemplate:
3366 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003367 case CXCursor_ClassTemplate:
3368 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003369 case CXCursor_ClassTemplatePartialSpecialization:
3370 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003371 case CXCursor_NamespaceAlias:
3372 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003373 case CXCursor_UsingDirective:
3374 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003375 case CXCursor_UsingDeclaration:
3376 return createCXString("UsingDeclaration");
Richard Smith162e1c12011-04-15 14:24:37 +00003377 case CXCursor_TypeAliasDecl:
Douglas Gregor352697a2011-06-03 23:08:58 +00003378 return createCXString("TypeAliasDecl");
3379 case CXCursor_ObjCSynthesizeDecl:
3380 return createCXString("ObjCSynthesizeDecl");
3381 case CXCursor_ObjCDynamicDecl:
3382 return createCXString("ObjCDynamicDecl");
Argyrios Kyrtzidis2dfdb942011-09-30 17:58:23 +00003383 case CXCursor_CXXAccessSpecifier:
3384 return createCXString("CXXAccessSpecifier");
Steve Naroff89922f82009-08-31 00:59:03 +00003385 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003386
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003387 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneka60ed472010-11-16 08:15:36 +00003388 return createCXString((const char*) 0);
Steve Naroff600866c2009-08-27 19:51:58 +00003389}
Steve Naroff89922f82009-08-31 00:59:03 +00003390
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003391struct GetCursorData {
3392 SourceLocation TokenBeginLoc;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003393 bool PointsAtMacroArgExpansion;
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003394 CXCursor &BestCursor;
3395
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003396 GetCursorData(SourceManager &SM,
3397 SourceLocation tokenBegin, CXCursor &outputCursor)
3398 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
3399 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
3400 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003401};
3402
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003403static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3404 CXCursor parent,
3405 CXClientData client_data) {
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003406 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
3407 CXCursor *BestCursor = &Data->BestCursor;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003408
3409 // If we point inside a macro argument we should provide info of what the
3410 // token is so use the actual cursor, don't replace it with a macro expansion
3411 // cursor.
3412 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
3413 return CXChildVisit_Recurse;
Argyrios Kyrtzidis65ab9072011-09-26 19:05:37 +00003414
3415 if (clang_isDeclaration(cursor.kind)) {
3416 // Avoid having the implicit methods override the property decls.
3417 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(getCursorDecl(cursor)))
3418 if (MD->isImplicit())
3419 return CXChildVisit_Break;
3420 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003421
3422 if (clang_isExpression(cursor.kind) &&
3423 clang_isDeclaration(BestCursor->kind)) {
3424 Decl *D = getCursorDecl(*BestCursor);
3425
3426 // Avoid having the cursor of an expression replace the declaration cursor
3427 // when the expression source range overlaps the declaration range.
3428 // This can happen for C++ constructor expressions whose range generally
3429 // include the variable declaration, e.g.:
3430 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
3431 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
3432 D->getLocation() == Data->TokenBeginLoc)
3433 return CXChildVisit_Break;
3434 }
3435
Douglas Gregor93798e22010-11-05 21:11:19 +00003436 // If our current best cursor is the construction of a temporary object,
3437 // don't replace that cursor with a type reference, because we want
3438 // clang_getCursor() to point at the constructor.
3439 if (clang_isExpression(BestCursor->kind) &&
3440 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003441 cursor.kind == CXCursor_TypeRef) {
3442 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
3443 // as having the actual point on the type reference.
3444 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
Douglas Gregor93798e22010-11-05 21:11:19 +00003445 return CXChildVisit_Recurse;
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003446 }
Douglas Gregor93798e22010-11-05 21:11:19 +00003447
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003448 *BestCursor = cursor;
3449 return CXChildVisit_Recurse;
3450}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003451
Douglas Gregorb9790342010-01-22 21:44:22 +00003452CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3453 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003454 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003455
Ted Kremeneka60ed472010-11-16 08:15:36 +00003456 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003457 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3458
Ted Kremeneka297de22010-01-25 22:34:44 +00003459 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003460 CXCursor Result = cxcursor::getCursor(TU, SLoc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003461
Douglas Gregor40749ee2010-11-03 00:35:38 +00003462 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregor40749ee2010-11-03 00:35:38 +00003463 if (Logging) {
3464 CXFile SearchFile;
3465 unsigned SearchLine, SearchColumn;
3466 CXFile ResultFile;
3467 unsigned ResultLine, ResultColumn;
Douglas Gregor66537982010-11-17 17:14:07 +00003468 CXString SearchFileName, ResultFileName, KindSpelling, USR;
3469 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
Douglas Gregor40749ee2010-11-03 00:35:38 +00003470 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3471
Chandler Carruth20174222011-08-31 16:53:37 +00003472 clang_getExpansionLocation(Loc, &SearchFile, &SearchLine, &SearchColumn, 0);
3473 clang_getExpansionLocation(ResultLoc, &ResultFile, &ResultLine,
3474 &ResultColumn, 0);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003475 SearchFileName = clang_getFileName(SearchFile);
3476 ResultFileName = clang_getFileName(ResultFile);
3477 KindSpelling = clang_getCursorKindSpelling(Result.kind);
Douglas Gregor66537982010-11-17 17:14:07 +00003478 USR = clang_getCursorUSR(Result);
3479 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n",
Douglas Gregor40749ee2010-11-03 00:35:38 +00003480 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3481 clang_getCString(KindSpelling),
Douglas Gregor66537982010-11-17 17:14:07 +00003482 clang_getCString(ResultFileName), ResultLine, ResultColumn,
3483 clang_getCString(USR), IsDef);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003484 clang_disposeString(SearchFileName);
3485 clang_disposeString(ResultFileName);
3486 clang_disposeString(KindSpelling);
Douglas Gregor66537982010-11-17 17:14:07 +00003487 clang_disposeString(USR);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003488
3489 CXCursor Definition = clang_getCursorDefinition(Result);
3490 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
3491 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
3492 CXString DefinitionKindSpelling
3493 = clang_getCursorKindSpelling(Definition.kind);
3494 CXFile DefinitionFile;
3495 unsigned DefinitionLine, DefinitionColumn;
Chandler Carruth20174222011-08-31 16:53:37 +00003496 clang_getExpansionLocation(DefinitionLoc, &DefinitionFile,
3497 &DefinitionLine, &DefinitionColumn, 0);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003498 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
3499 fprintf(stderr, " -> %s(%s:%d:%d)\n",
3500 clang_getCString(DefinitionKindSpelling),
3501 clang_getCString(DefinitionFileName),
3502 DefinitionLine, DefinitionColumn);
3503 clang_disposeString(DefinitionFileName);
3504 clang_disposeString(DefinitionKindSpelling);
3505 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003506 }
3507
Ted Kremeneke68fff62010-02-17 00:41:32 +00003508 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003509}
3510
Ted Kremenek73885552009-11-17 19:28:59 +00003511CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003512 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003513}
3514
3515unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003516 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003517}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003518
Douglas Gregor9ce55842010-11-20 00:09:34 +00003519unsigned clang_hashCursor(CXCursor C) {
3520 unsigned Index = 0;
3521 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
3522 Index = 1;
3523
3524 return llvm::DenseMapInfo<std::pair<unsigned, void*> >::getHashValue(
3525 std::make_pair(C.kind, C.data[Index]));
3526}
3527
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003528unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003529 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3530}
3531
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003532unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003533 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3534}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003535
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003536unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003537 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3538}
3539
Douglas Gregor97b98722010-01-19 23:20:36 +00003540unsigned clang_isExpression(enum CXCursorKind K) {
3541 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3542}
3543
3544unsigned clang_isStatement(enum CXCursorKind K) {
3545 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3546}
3547
Douglas Gregor8be80e12011-07-06 03:00:34 +00003548unsigned clang_isAttribute(enum CXCursorKind K) {
3549 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
3550}
3551
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003552unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3553 return K == CXCursor_TranslationUnit;
3554}
3555
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003556unsigned clang_isPreprocessing(enum CXCursorKind K) {
3557 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3558}
3559
Ted Kremenekad6eff62010-03-08 21:17:29 +00003560unsigned clang_isUnexposed(enum CXCursorKind K) {
3561 switch (K) {
3562 case CXCursor_UnexposedDecl:
3563 case CXCursor_UnexposedExpr:
3564 case CXCursor_UnexposedStmt:
3565 case CXCursor_UnexposedAttr:
3566 return true;
3567 default:
3568 return false;
3569 }
3570}
3571
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003572CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003573 return C.kind;
3574}
3575
Douglas Gregor98258af2010-01-18 22:46:11 +00003576CXSourceLocation clang_getCursorLocation(CXCursor C) {
3577 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003578 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003579 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003580 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3581 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003582 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003583 }
3584
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003585 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003586 std::pair<ObjCProtocolDecl *, SourceLocation> P
3587 = getCursorObjCProtocolRef(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_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003592 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3593 = getCursorObjCClassRef(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 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003596
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003597 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003598 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003599 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003600 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003601
3602 case CXCursor_TemplateRef: {
3603 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3604 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3605 }
3606
Douglas Gregor69319002010-08-31 23:48:11 +00003607 case CXCursor_NamespaceRef: {
3608 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3609 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3610 }
3611
Douglas Gregora67e03f2010-09-09 21:42:20 +00003612 case CXCursor_MemberRef: {
3613 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3614 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3615 }
3616
Ted Kremenek3064ef92010-08-27 21:34:58 +00003617 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003618 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3619 if (!BaseSpec)
3620 return clang_getNullLocation();
3621
3622 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3623 return cxloc::translateSourceLocation(getCursorContext(C),
3624 TSInfo->getTypeLoc().getBeginLoc());
3625
3626 return cxloc::translateSourceLocation(getCursorContext(C),
3627 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003628 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003629
Douglas Gregor36897b02010-09-10 00:22:18 +00003630 case CXCursor_LabelRef: {
3631 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3632 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3633 }
3634
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003635 case CXCursor_OverloadedDeclRef:
3636 return cxloc::translateSourceLocation(getCursorContext(C),
3637 getCursorOverloadedDeclRef(C).second);
3638
Douglas Gregorf46034a2010-01-18 23:41:10 +00003639 default:
3640 // FIXME: Need a way to enumerate all non-reference cases.
3641 llvm_unreachable("Missed a reference kind");
3642 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003643 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003644
3645 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003646 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003647 getLocationFromExpr(getCursorExpr(C)));
3648
Douglas Gregor36897b02010-09-10 00:22:18 +00003649 if (clang_isStatement(C.kind))
3650 return cxloc::translateSourceLocation(getCursorContext(C),
3651 getCursorStmt(C)->getLocStart());
3652
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003653 if (C.kind == CXCursor_PreprocessingDirective) {
3654 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3655 return cxloc::translateSourceLocation(getCursorContext(C), L);
3656 }
Douglas Gregor48072312010-03-18 15:23:44 +00003657
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003658 if (C.kind == CXCursor_MacroExpansion) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003659 SourceLocation L
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003660 = cxcursor::getCursorMacroExpansion(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003661 return cxloc::translateSourceLocation(getCursorContext(C), L);
3662 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003663
3664 if (C.kind == CXCursor_MacroDefinition) {
3665 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3666 return cxloc::translateSourceLocation(getCursorContext(C), L);
3667 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003668
3669 if (C.kind == CXCursor_InclusionDirective) {
3670 SourceLocation L
3671 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3672 return cxloc::translateSourceLocation(getCursorContext(C), L);
3673 }
3674
Ted Kremenek9a700d22010-05-12 06:16:13 +00003675 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003676 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003677
Douglas Gregorf46034a2010-01-18 23:41:10 +00003678 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003679 SourceLocation Loc = D->getLocation();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003680 // FIXME: Multiple variables declared in a single declaration
3681 // currently lack the information needed to correctly determine their
3682 // ranges when accounting for the type-specifier. We use context
3683 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3684 // and if so, whether it is the first decl.
3685 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3686 if (!cxcursor::isFirstInDeclGroup(C))
3687 Loc = VD->getLocation();
3688 }
3689
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003690 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003691}
Douglas Gregora7bde202010-01-19 00:34:46 +00003692
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003693} // end extern "C"
3694
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003695CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
3696 assert(TU);
3697
3698 // Guard against an invalid SourceLocation, or we may assert in one
3699 // of the following calls.
3700 if (SLoc.isInvalid())
3701 return clang_getNullCursor();
3702
3703 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
3704
3705 // Translate the given source location to make it point at the beginning of
3706 // the token under the cursor.
3707 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3708 CXXUnit->getASTContext().getLangOptions());
3709
3710 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3711 if (SLoc.isValid()) {
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003712 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003713 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
3714 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00003715 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003716 SourceLocation(SLoc));
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00003717 CursorVis.visitFileRegion();
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003718 }
3719
3720 return Result;
3721}
3722
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003723static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003724 if (clang_isReference(C.kind)) {
3725 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003726 case CXCursor_ObjCSuperClassRef:
3727 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003728
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003729 case CXCursor_ObjCProtocolRef:
3730 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003731
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003732 case CXCursor_ObjCClassRef:
3733 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003734
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003735 case CXCursor_TypeRef:
3736 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003737
3738 case CXCursor_TemplateRef:
3739 return getCursorTemplateRef(C).second;
3740
Douglas Gregor69319002010-08-31 23:48:11 +00003741 case CXCursor_NamespaceRef:
3742 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003743
3744 case CXCursor_MemberRef:
3745 return getCursorMemberRef(C).second;
3746
Ted Kremenek3064ef92010-08-27 21:34:58 +00003747 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003748 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003749
Douglas Gregor36897b02010-09-10 00:22:18 +00003750 case CXCursor_LabelRef:
3751 return getCursorLabelRef(C).second;
3752
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003753 case CXCursor_OverloadedDeclRef:
3754 return getCursorOverloadedDeclRef(C).second;
3755
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003756 default:
3757 // FIXME: Need a way to enumerate all non-reference cases.
3758 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003759 }
3760 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003761
3762 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003763 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003764
3765 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003766 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003767
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00003768 if (clang_isAttribute(C.kind))
3769 return getCursorAttr(C)->getRange();
3770
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003771 if (C.kind == CXCursor_PreprocessingDirective)
3772 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003773
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00003774 if (C.kind == CXCursor_MacroExpansion) {
3775 ASTUnit *TU = getCursorASTUnit(C);
3776 SourceRange Range = cxcursor::getCursorMacroExpansion(C)->getSourceRange();
3777 return TU->mapRangeFromPreamble(Range);
3778 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003779
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00003780 if (C.kind == CXCursor_MacroDefinition) {
3781 ASTUnit *TU = getCursorASTUnit(C);
3782 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
3783 return TU->mapRangeFromPreamble(Range);
3784 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003785
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00003786 if (C.kind == CXCursor_InclusionDirective) {
3787 ASTUnit *TU = getCursorASTUnit(C);
3788 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3789 return TU->mapRangeFromPreamble(Range);
3790 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003791
Ted Kremenek007a7c92010-11-01 23:26:51 +00003792 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3793 Decl *D = cxcursor::getCursorDecl(C);
3794 SourceRange R = D->getSourceRange();
3795 // FIXME: Multiple variables declared in a single declaration
3796 // currently lack the information needed to correctly determine their
3797 // ranges when accounting for the type-specifier. We use context
3798 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3799 // and if so, whether it is the first decl.
3800 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3801 if (!cxcursor::isFirstInDeclGroup(C))
3802 R.setBegin(VD->getLocation());
3803 }
3804 return R;
3805 }
Douglas Gregor66537982010-11-17 17:14:07 +00003806 return SourceRange();
3807}
3808
3809/// \brief Retrieves the "raw" cursor extent, which is then extended to include
3810/// the decl-specifier-seq for declarations.
3811static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
3812 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3813 Decl *D = cxcursor::getCursorDecl(C);
3814 SourceRange R = D->getSourceRange();
Douglas Gregor66537982010-11-17 17:14:07 +00003815
Douglas Gregor2494dd02011-03-01 01:34:45 +00003816 // Adjust the start of the location for declarations preceded by
3817 // declaration specifiers.
3818 SourceLocation StartLoc;
3819 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
3820 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
3821 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
3822 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
3823 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
3824 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
3825 }
3826
3827 if (StartLoc.isValid() && R.getBegin().isValid() &&
3828 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
3829 R.setBegin(StartLoc);
3830
3831 // FIXME: Multiple variables declared in a single declaration
3832 // currently lack the information needed to correctly determine their
3833 // ranges when accounting for the type-specifier. We use context
3834 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3835 // and if so, whether it is the first decl.
3836 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3837 if (!cxcursor::isFirstInDeclGroup(C))
3838 R.setBegin(VD->getLocation());
Douglas Gregor66537982010-11-17 17:14:07 +00003839 }
3840
3841 return R;
3842 }
3843
3844 return getRawCursorExtent(C);
3845}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003846
3847extern "C" {
3848
3849CXSourceRange clang_getCursorExtent(CXCursor C) {
3850 SourceRange R = getRawCursorExtent(C);
3851 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003852 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003853
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003854 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003855}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003856
3857CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003858 if (clang_isInvalid(C.kind))
3859 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003860
Ted Kremeneka60ed472010-11-16 08:15:36 +00003861 CXTranslationUnit tu = getCursorTU(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003862 if (clang_isDeclaration(C.kind)) {
3863 Decl *D = getCursorDecl(C);
3864 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003865 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003866 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003867 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003868 if (ObjCForwardProtocolDecl *Protocols
3869 = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003870 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), tu);
Chris Lattner5f9e2722011-07-23 10:55:15 +00003871 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00003872 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3873 return MakeCXCursor(Property, tu);
3874
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003875 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003876 }
3877
Douglas Gregor97b98722010-01-19 23:20:36 +00003878 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003879 Expr *E = getCursorExpr(C);
3880 Decl *D = getDeclFromExpr(E);
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003881 if (D) {
3882 CXCursor declCursor = MakeCXCursor(D, tu);
3883 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
3884 declCursor);
3885 return declCursor;
3886 }
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003887
3888 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003889 return MakeCursorOverloadedDeclRef(Ovl, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003890
Douglas Gregor97b98722010-01-19 23:20:36 +00003891 return clang_getNullCursor();
3892 }
3893
Douglas Gregor36897b02010-09-10 00:22:18 +00003894 if (clang_isStatement(C.kind)) {
3895 Stmt *S = getCursorStmt(C);
3896 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Ted Kremenek37c2e962011-03-15 23:47:49 +00003897 if (LabelDecl *label = Goto->getLabel())
3898 if (LabelStmt *labelS = label->getStmt())
3899 return MakeCXCursor(labelS, getCursorDecl(C), tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003900
3901 return clang_getNullCursor();
3902 }
3903
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003904 if (C.kind == CXCursor_MacroExpansion) {
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003905 if (MacroDefinition *Def = getCursorMacroExpansion(C)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003906 return MakeMacroDefinitionCursor(Def, tu);
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003907 }
3908
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003909 if (!clang_isReference(C.kind))
3910 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003911
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003912 switch (C.kind) {
3913 case CXCursor_ObjCSuperClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003914 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003915
3916 case CXCursor_ObjCProtocolRef: {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003917 return MakeCXCursor(getCursorObjCProtocolRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003918
3919 case CXCursor_ObjCClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003920 return MakeCXCursor(getCursorObjCClassRef(C).first, tu );
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003921
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003922 case CXCursor_TypeRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003923 return MakeCXCursor(getCursorTypeRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003924
3925 case CXCursor_TemplateRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003926 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003927
Douglas Gregor69319002010-08-31 23:48:11 +00003928 case CXCursor_NamespaceRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003929 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
Douglas Gregor69319002010-08-31 23:48:11 +00003930
Douglas Gregora67e03f2010-09-09 21:42:20 +00003931 case CXCursor_MemberRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003932 return MakeCXCursor(getCursorMemberRef(C).first, tu );
Douglas Gregora67e03f2010-09-09 21:42:20 +00003933
Ted Kremenek3064ef92010-08-27 21:34:58 +00003934 case CXCursor_CXXBaseSpecifier: {
3935 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3936 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003937 tu ));
Ted Kremenek3064ef92010-08-27 21:34:58 +00003938 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003939
Douglas Gregor36897b02010-09-10 00:22:18 +00003940 case CXCursor_LabelRef:
3941 // FIXME: We end up faking the "parent" declaration here because we
3942 // don't want to make CXCursor larger.
3943 return MakeCXCursor(getCursorLabelRef(C).first,
Ted Kremeneka60ed472010-11-16 08:15:36 +00003944 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
3945 .getTranslationUnitDecl(),
3946 tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003947
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003948 case CXCursor_OverloadedDeclRef:
3949 return C;
3950
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003951 default:
3952 // We would prefer to enumerate all non-reference cursor kinds here.
3953 llvm_unreachable("Unhandled reference cursor kind");
3954 break;
3955 }
3956 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003957
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003958 return clang_getNullCursor();
3959}
3960
Douglas Gregorb6998662010-01-19 19:34:47 +00003961CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003962 if (clang_isInvalid(C.kind))
3963 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003964
Ted Kremeneka60ed472010-11-16 08:15:36 +00003965 CXTranslationUnit TU = getCursorTU(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003966
Douglas Gregorb6998662010-01-19 19:34:47 +00003967 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003968 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003969 C = clang_getCursorReferenced(C);
3970 WasReference = true;
3971 }
3972
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003973 if (C.kind == CXCursor_MacroExpansion)
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003974 return clang_getCursorReferenced(C);
3975
Douglas Gregorb6998662010-01-19 19:34:47 +00003976 if (!clang_isDeclaration(C.kind))
3977 return clang_getNullCursor();
3978
3979 Decl *D = getCursorDecl(C);
3980 if (!D)
3981 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003982
Douglas Gregorb6998662010-01-19 19:34:47 +00003983 switch (D->getKind()) {
3984 // Declaration kinds that don't really separate the notions of
3985 // declaration and definition.
3986 case Decl::Namespace:
3987 case Decl::Typedef:
Richard Smith162e1c12011-04-15 14:24:37 +00003988 case Decl::TypeAlias:
Richard Smith3e4c6c42011-05-05 21:57:07 +00003989 case Decl::TypeAliasTemplate:
Douglas Gregorb6998662010-01-19 19:34:47 +00003990 case Decl::TemplateTypeParm:
3991 case Decl::EnumConstant:
3992 case Decl::Field:
Benjamin Kramerd9811462010-11-21 14:11:41 +00003993 case Decl::IndirectField:
Douglas Gregorb6998662010-01-19 19:34:47 +00003994 case Decl::ObjCIvar:
3995 case Decl::ObjCAtDefsField:
3996 case Decl::ImplicitParam:
3997 case Decl::ParmVar:
3998 case Decl::NonTypeTemplateParm:
3999 case Decl::TemplateTemplateParm:
4000 case Decl::ObjCCategoryImpl:
4001 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00004002 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00004003 case Decl::LinkageSpec:
4004 case Decl::ObjCPropertyImpl:
4005 case Decl::FileScopeAsm:
4006 case Decl::StaticAssert:
4007 case Decl::Block:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00004008 case Decl::Label: // FIXME: Is this right??
Francois Pichetaf0f4d02011-08-14 03:52:19 +00004009 case Decl::ClassScopeFunctionSpecialization:
Douglas Gregor15de72c2011-12-02 23:23:56 +00004010 case Decl::Import:
Douglas Gregorb6998662010-01-19 19:34:47 +00004011 return C;
4012
4013 // Declaration kinds that don't make any sense here, but are
4014 // nonetheless harmless.
4015 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00004016 break;
4017
4018 // Declaration kinds for which the definition is not resolvable.
4019 case Decl::UnresolvedUsingTypename:
4020 case Decl::UnresolvedUsingValue:
4021 break;
4022
4023 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00004024 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004025 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004026
4027 case Decl::NamespaceAlias:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004028 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004029
4030 case Decl::Enum:
4031 case Decl::Record:
4032 case Decl::CXXRecord:
4033 case Decl::ClassTemplateSpecialization:
4034 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00004035 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004036 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004037 return clang_getNullCursor();
4038
4039 case Decl::Function:
4040 case Decl::CXXMethod:
4041 case Decl::CXXConstructor:
4042 case Decl::CXXDestructor:
4043 case Decl::CXXConversion: {
4044 const FunctionDecl *Def = 0;
4045 if (cast<FunctionDecl>(D)->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004046 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004047 return clang_getNullCursor();
4048 }
4049
4050 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00004051 // Ask the variable if it has a definition.
4052 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004053 return MakeCXCursor(Def, TU);
Sebastian Redl31310a22010-02-01 20:16:42 +00004054 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00004055 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004056
Douglas Gregorb6998662010-01-19 19:34:47 +00004057 case Decl::FunctionTemplate: {
4058 const FunctionDecl *Def = 0;
4059 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004060 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004061 return clang_getNullCursor();
4062 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004063
Douglas Gregorb6998662010-01-19 19:34:47 +00004064 case Decl::ClassTemplate: {
4065 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00004066 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00004067 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004068 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004069 return clang_getNullCursor();
4070 }
4071
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004072 case Decl::Using:
4073 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004074 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004075
4076 case Decl::UsingShadow:
4077 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004078 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004079 TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004080
4081 case Decl::ObjCMethod: {
4082 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
4083 if (Method->isThisDeclarationADefinition())
4084 return C;
4085
4086 // Dig out the method definition in the associated
4087 // @implementation, if we have it.
4088 // FIXME: The ASTs should make finding the definition easier.
4089 if (ObjCInterfaceDecl *Class
4090 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
4091 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
4092 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
4093 Method->isInstanceMethod()))
4094 if (Def->isThisDeclarationADefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004095 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004096
4097 return clang_getNullCursor();
4098 }
4099
4100 case Decl::ObjCCategory:
4101 if (ObjCCategoryImplDecl *Impl
4102 = cast<ObjCCategoryDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004103 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004104 return clang_getNullCursor();
4105
4106 case Decl::ObjCProtocol:
4107 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
4108 return C;
4109 return clang_getNullCursor();
4110
4111 case Decl::ObjCInterface:
4112 // There are two notions of a "definition" for an Objective-C
4113 // class: the interface and its implementation. When we resolved a
4114 // reference to an Objective-C class, produce the @interface as
4115 // the definition; when we were provided with the interface,
4116 // produce the @implementation as the definition.
4117 if (WasReference) {
4118 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
4119 return C;
4120 } else if (ObjCImplementationDecl *Impl
4121 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004122 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004123 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004124
Douglas Gregorb6998662010-01-19 19:34:47 +00004125 case Decl::ObjCProperty:
4126 // FIXME: We don't really know where to find the
4127 // ObjCPropertyImplDecls that implement this property.
4128 return clang_getNullCursor();
4129
4130 case Decl::ObjCCompatibleAlias:
4131 if (ObjCInterfaceDecl *Class
4132 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
4133 if (!Class->isForwardDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004134 return MakeCXCursor(Class, TU);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004135
Douglas Gregorb6998662010-01-19 19:34:47 +00004136 return clang_getNullCursor();
4137
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004138 case Decl::ObjCForwardProtocol:
4139 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004140 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004141
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004142 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004143 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004144 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004145
4146 case Decl::Friend:
4147 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004148 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004149 return clang_getNullCursor();
4150
4151 case Decl::FriendTemplate:
4152 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004153 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004154 return clang_getNullCursor();
4155 }
4156
4157 return clang_getNullCursor();
4158}
4159
4160unsigned clang_isCursorDefinition(CXCursor C) {
4161 if (!clang_isDeclaration(C.kind))
4162 return 0;
4163
4164 return clang_getCursorDefinition(C) == C;
4165}
4166
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004167CXCursor clang_getCanonicalCursor(CXCursor C) {
4168 if (!clang_isDeclaration(C.kind))
4169 return C;
4170
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004171 if (Decl *D = getCursorDecl(C)) {
Argyrios Kyrtzidisdebb00f2011-07-15 22:37:58 +00004172 if (ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
4173 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
4174 return MakeCXCursor(CatD, getCursorTU(C));
4175
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004176 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
4177 if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
4178 return MakeCXCursor(IFD, getCursorTU(C));
4179
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004180 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004181 }
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004182
4183 return C;
4184}
4185
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004186unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004187 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004188 return 0;
4189
4190 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
4191 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
4192 return E->getNumDecls();
4193
4194 if (OverloadedTemplateStorage *S
4195 = Storage.dyn_cast<OverloadedTemplateStorage*>())
4196 return S->size();
4197
4198 Decl *D = Storage.get<Decl*>();
4199 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00004200 return Using->shadow_size();
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00004201 if (isa<ObjCClassDecl>(D))
4202 return 1;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004203 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
4204 return Protocols->protocol_size();
4205
4206 return 0;
4207}
4208
4209CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004210 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004211 return clang_getNullCursor();
4212
4213 if (index >= clang_getNumOverloadedDecls(cursor))
4214 return clang_getNullCursor();
4215
Ted Kremeneka60ed472010-11-16 08:15:36 +00004216 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004217 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
4218 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004219 return MakeCXCursor(E->decls_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004220
4221 if (OverloadedTemplateStorage *S
4222 = Storage.dyn_cast<OverloadedTemplateStorage*>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004223 return MakeCXCursor(S->begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004224
4225 Decl *D = Storage.get<Decl*>();
4226 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
4227 // FIXME: This is, unfortunately, linear time.
4228 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
4229 std::advance(Pos, index);
Ted Kremeneka60ed472010-11-16 08:15:36 +00004230 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004231 }
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004232 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00004233 return MakeCXCursor(Classes->getForwardInterfaceDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004234 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004235 return MakeCXCursor(Protocols->protocol_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004236
4237 return clang_getNullCursor();
4238}
4239
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00004240void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00004241 const char **startBuf,
4242 const char **endBuf,
4243 unsigned *startLine,
4244 unsigned *startColumn,
4245 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00004246 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00004247 assert(getCursorDecl(C) && "CXCursor has null decl");
4248 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00004249 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
4250 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004251
Steve Naroff4ade6d62009-09-23 17:52:52 +00004252 SourceManager &SM = FD->getASTContext().getSourceManager();
4253 *startBuf = SM.getCharacterData(Body->getLBracLoc());
4254 *endBuf = SM.getCharacterData(Body->getRBracLoc());
4255 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
4256 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
4257 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
4258 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
4259}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004260
Douglas Gregor430d7a12011-07-25 17:48:11 +00004261
4262CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
4263 unsigned PieceIndex) {
4264 RefNamePieces Pieces;
4265
4266 switch (C.kind) {
4267 case CXCursor_MemberRefExpr:
4268 if (MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
4269 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
4270 E->getQualifierLoc().getSourceRange());
4271 break;
4272
4273 case CXCursor_DeclRefExpr:
4274 if (DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C)))
4275 Pieces = buildPieces(NameFlags, false, E->getNameInfo(),
4276 E->getQualifierLoc().getSourceRange(),
4277 E->getExplicitTemplateArgsOpt());
4278 break;
4279
4280 case CXCursor_CallExpr:
4281 if (CXXOperatorCallExpr *OCE =
4282 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
4283 Expr *Callee = OCE->getCallee();
4284 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
4285 Callee = ICE->getSubExpr();
4286
4287 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
4288 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
4289 DRE->getQualifierLoc().getSourceRange());
4290 }
4291 break;
4292
4293 default:
4294 break;
4295 }
4296
4297 if (Pieces.empty()) {
4298 if (PieceIndex == 0)
4299 return clang_getCursorExtent(C);
4300 } else if (PieceIndex < Pieces.size()) {
4301 SourceRange R = Pieces[PieceIndex];
4302 if (R.isValid())
4303 return cxloc::translateSourceRange(getCursorContext(C), R);
4304 }
4305
4306 return clang_getNullRange();
4307}
4308
Douglas Gregor0a812cf2010-02-18 23:07:20 +00004309void clang_enableStackTraces(void) {
4310 llvm::sys::PrintStackTraceOnErrorSignal();
4311}
4312
Daniel Dunbar995aaf92010-11-04 01:26:29 +00004313void clang_executeOnThread(void (*fn)(void*), void *user_data,
4314 unsigned stack_size) {
4315 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
4316}
4317
Ted Kremenekfb480492010-01-13 21:46:36 +00004318} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00004319
Ted Kremenekfb480492010-01-13 21:46:36 +00004320//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004321// Token-based Operations.
4322//===----------------------------------------------------------------------===//
4323
4324/* CXToken layout:
4325 * int_data[0]: a CXTokenKind
4326 * int_data[1]: starting token location
4327 * int_data[2]: token length
4328 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004329 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004330 * otherwise unused.
4331 */
4332extern "C" {
4333
4334CXTokenKind clang_getTokenKind(CXToken CXTok) {
4335 return static_cast<CXTokenKind>(CXTok.int_data[0]);
4336}
4337
4338CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
4339 switch (clang_getTokenKind(CXTok)) {
4340 case CXToken_Identifier:
4341 case CXToken_Keyword:
4342 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004343 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
4344 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004345
4346 case CXToken_Literal: {
4347 // We have stashed the starting pointer in the ptr_data field. Use it.
4348 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Chris Lattner5f9e2722011-07-23 10:55:15 +00004349 return createCXString(StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004350 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004351
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004352 case CXToken_Punctuation:
4353 case CXToken_Comment:
4354 break;
4355 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004356
4357 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004358 // deconstructing the source location.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004359 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004360 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004361 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004362
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004363 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
4364 std::pair<FileID, unsigned> LocInfo
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004365 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00004366 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004367 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004368 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
4369 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00004370 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004371
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004372 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004373}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004374
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004375CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004376 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004377 if (!CXXUnit)
4378 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004379
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004380 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
4381 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4382}
4383
4384CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004385 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor5352ac02010-01-28 00:27:43 +00004386 if (!CXXUnit)
4387 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004388
4389 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004390 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4391}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004392
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004393static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
4394 SmallVectorImpl<CXToken> &CXTokens) {
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004395 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4396 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004397 = SourceMgr.getDecomposedLoc(Range.getBegin());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004398 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004399 = SourceMgr.getDecomposedLoc(Range.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004400
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004401 // Cannot tokenize across files.
4402 if (BeginLocInfo.first != EndLocInfo.first)
4403 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004404
4405 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004406 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004407 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004408 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00004409 if (Invalid)
4410 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00004411
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004412 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4413 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004414 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004415 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004416
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004417 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004418 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004419 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00004420 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004421 do {
4422 // Lex the next token
4423 Lex.LexFromRawLexer(Tok);
4424 if (Tok.is(tok::eof))
4425 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004426
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004427 // Initialize the CXToken.
4428 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004429
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004430 // - Common fields
4431 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
4432 CXTok.int_data[2] = Tok.getLength();
4433 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004434
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004435 // - Kind-specific fields
4436 if (Tok.isLiteral()) {
4437 CXTok.int_data[0] = CXToken_Literal;
4438 CXTok.ptr_data = (void *)Tok.getLiteralData();
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004439 } else if (Tok.is(tok::raw_identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00004440 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004441 IdentifierInfo *II
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004442 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004443
David Chisnall096428b2010-10-13 21:44:48 +00004444 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004445 CXTok.int_data[0] = CXToken_Keyword;
4446 }
4447 else {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004448 CXTok.int_data[0] = Tok.is(tok::identifier)
4449 ? CXToken_Identifier
4450 : CXToken_Keyword;
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004451 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004452 CXTok.ptr_data = II;
4453 } else if (Tok.is(tok::comment)) {
4454 CXTok.int_data[0] = CXToken_Comment;
4455 CXTok.ptr_data = 0;
4456 } else {
4457 CXTok.int_data[0] = CXToken_Punctuation;
4458 CXTok.ptr_data = 0;
4459 }
4460 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00004461 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004462 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004463}
4464
4465void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
4466 CXToken **Tokens, unsigned *NumTokens) {
4467 if (Tokens)
4468 *Tokens = 0;
4469 if (NumTokens)
4470 *NumTokens = 0;
4471
4472 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4473 if (!CXXUnit || !Tokens || !NumTokens)
4474 return;
4475
4476 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4477
4478 SourceRange R = cxloc::translateCXSourceRange(Range);
4479 if (R.isInvalid())
4480 return;
4481
4482 SmallVector<CXToken, 32> CXTokens;
4483 getTokens(CXXUnit, R, CXTokens);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004484
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004485 if (CXTokens.empty())
4486 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004487
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004488 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
4489 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
4490 *NumTokens = CXTokens.size();
4491}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004492
Ted Kremenek6db61092010-05-05 00:55:15 +00004493void clang_disposeTokens(CXTranslationUnit TU,
4494 CXToken *Tokens, unsigned NumTokens) {
4495 free(Tokens);
4496}
4497
4498} // end: extern "C"
4499
4500//===----------------------------------------------------------------------===//
4501// Token annotation APIs.
4502//===----------------------------------------------------------------------===//
4503
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004504typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004505static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4506 CXCursor parent,
4507 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00004508namespace {
4509class AnnotateTokensWorker {
4510 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004511 CXToken *Tokens;
4512 CXCursor *Cursors;
4513 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004514 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00004515 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004516 CursorVisitor AnnotateVis;
4517 SourceManager &SrcMgr;
Douglas Gregorf5251602011-03-08 17:10:18 +00004518 bool HasContextSensitiveKeywords;
4519
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004520 bool MoreTokens() const { return TokIdx < NumTokens; }
4521 unsigned NextToken() const { return TokIdx; }
4522 void AdvanceToken() { ++TokIdx; }
4523 SourceLocation GetTokenLoc(unsigned tokI) {
4524 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4525 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004526 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004527 return Tokens[tokI].int_data[3] != 0;
4528 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004529 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004530 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[3]);
4531 }
4532
4533 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004534 void annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
4535 SourceRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004536
Ted Kremenek6db61092010-05-05 00:55:15 +00004537public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00004538 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004539 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004540 CXTranslationUnit tu, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00004541 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00004542 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004543 AnnotateVis(tu,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00004544 AnnotateTokensVisitor, this,
4545 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00004546 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00004547 RegionOfInterest),
Douglas Gregorf5251602011-03-08 17:10:18 +00004548 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()),
4549 HasContextSensitiveKeywords(false) { }
Ted Kremenek11949cb2010-05-05 00:55:17 +00004550
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004551 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00004552 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004553 void AnnotateTokens();
Douglas Gregorf5251602011-03-08 17:10:18 +00004554
4555 /// \brief Determine whether the annotator saw any cursors that have
4556 /// context-sensitive keywords.
4557 bool hasContextSensitiveKeywords() const {
4558 return HasContextSensitiveKeywords;
4559 }
Ted Kremenek6db61092010-05-05 00:55:15 +00004560};
4561}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004562
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004563void AnnotateTokensWorker::AnnotateTokens() {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004564 // Walk the AST within the region of interest, annotating tokens
4565 // along the way.
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004566 AnnotateVis.visitFileRegion();
Ted Kremenek11949cb2010-05-05 00:55:17 +00004567
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004568 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4569 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004570 if (Pos != Annotated.end() &&
4571 (clang_isInvalid(Cursors[I].kind) ||
4572 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004573 Cursors[I] = Pos->second;
4574 }
4575
4576 // Finish up annotating any tokens left.
4577 if (!MoreTokens())
4578 return;
4579
4580 const CXCursor &C = clang_getNullCursor();
4581 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004582 if (I < PreprocessingTokIdx && clang_isPreprocessing(Cursors[I].kind))
4583 continue;
4584
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004585 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4586 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004587 }
4588}
4589
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004590/// \brief It annotates and advances tokens with a cursor until the comparison
4591//// between the cursor location and the source range is the same as
4592/// \arg compResult.
4593///
4594/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
4595/// Pass RangeOverlap to annotate tokens inside a range.
4596void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
4597 RangeComparisonResult compResult,
4598 SourceRange range) {
4599 while (MoreTokens()) {
4600 const unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004601 if (isFunctionMacroToken(I))
4602 return annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004603
4604 SourceLocation TokLoc = GetTokenLoc(I);
4605 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4606 Cursors[I] = updateC;
4607 AdvanceToken();
4608 continue;
4609 }
4610 break;
4611 }
4612}
4613
4614/// \brief Special annotation handling for macro argument tokens.
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004615void AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
4616 CXCursor updateC,
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004617 RangeComparisonResult compResult,
4618 SourceRange range) {
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004619 assert(MoreTokens());
4620 assert(isFunctionMacroToken(NextToken()) &&
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004621 "Should be called only for macro arg tokens");
4622
4623 // This works differently than annotateAndAdvanceTokens; because expanded
4624 // macro arguments can have arbitrary translation-unit source order, we do not
4625 // advance the token index one by one until a token fails the range test.
4626 // We only advance once past all of the macro arg tokens if all of them
4627 // pass the range test. If one of them fails we keep the token index pointing
4628 // at the start of the macro arg tokens so that the failing token will be
4629 // annotated by a subsequent annotation try.
4630
4631 bool atLeastOneCompFail = false;
4632
4633 unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004634 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
4635 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004636 if (TokLoc.isFileID())
4637 continue; // not macro arg token, it's parens or comma.
4638 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4639 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
4640 Cursors[I] = updateC;
4641 } else
4642 atLeastOneCompFail = true;
4643 }
4644
4645 if (!atLeastOneCompFail)
4646 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
4647}
4648
Ted Kremenek6db61092010-05-05 00:55:15 +00004649enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004650AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004651 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004652 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004653 if (cursorRange.isInvalid())
4654 return CXChildVisit_Recurse;
Douglas Gregorf5251602011-03-08 17:10:18 +00004655
4656 if (!HasContextSensitiveKeywords) {
4657 // Objective-C properties can have context-sensitive keywords.
4658 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
4659 if (ObjCPropertyDecl *Property
4660 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
4661 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
4662 }
4663 // Objective-C methods can have context-sensitive keywords.
4664 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
4665 cursor.kind == CXCursor_ObjCClassMethodDecl) {
4666 if (ObjCMethodDecl *Method
4667 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
4668 if (Method->getObjCDeclQualifier())
4669 HasContextSensitiveKeywords = true;
4670 else {
4671 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
4672 PEnd = Method->param_end();
4673 P != PEnd; ++P) {
4674 if ((*P)->getObjCDeclQualifier()) {
4675 HasContextSensitiveKeywords = true;
4676 break;
4677 }
4678 }
4679 }
4680 }
4681 }
4682 // C++ methods can have context-sensitive keywords.
4683 else if (cursor.kind == CXCursor_CXXMethod) {
4684 if (CXXMethodDecl *Method
4685 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
4686 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
4687 HasContextSensitiveKeywords = true;
4688 }
4689 }
4690 // C++ classes can have context-sensitive keywords.
4691 else if (cursor.kind == CXCursor_StructDecl ||
4692 cursor.kind == CXCursor_ClassDecl ||
4693 cursor.kind == CXCursor_ClassTemplate ||
4694 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
4695 if (Decl *D = getCursorDecl(cursor))
4696 if (D->hasAttr<FinalAttr>())
4697 HasContextSensitiveKeywords = true;
4698 }
4699 }
4700
Douglas Gregor4419b672010-10-21 06:10:04 +00004701 if (clang_isPreprocessing(cursor.kind)) {
Chandler Carruthcea731a2011-07-14 16:07:57 +00004702 // For macro expansions, just note where the beginning of the macro
4703 // expansion occurs.
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004704 if (cursor.kind == CXCursor_MacroExpansion) {
Douglas Gregor4419b672010-10-21 06:10:04 +00004705 Annotated[Loc.int_data] = cursor;
4706 return CXChildVisit_Recurse;
4707 }
4708
Douglas Gregor4419b672010-10-21 06:10:04 +00004709 // Items in the preprocessing record are kept separate from items in
4710 // declarations, so we keep a separate token index.
4711 unsigned SavedTokIdx = TokIdx;
4712 TokIdx = PreprocessingTokIdx;
4713
4714 // Skip tokens up until we catch up to the beginning of the preprocessing
4715 // entry.
4716 while (MoreTokens()) {
4717 const unsigned I = NextToken();
4718 SourceLocation TokLoc = GetTokenLoc(I);
4719 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4720 case RangeBefore:
4721 AdvanceToken();
4722 continue;
4723 case RangeAfter:
4724 case RangeOverlap:
4725 break;
4726 }
4727 break;
4728 }
4729
4730 // Look at all of the tokens within this range.
4731 while (MoreTokens()) {
4732 const unsigned I = NextToken();
4733 SourceLocation TokLoc = GetTokenLoc(I);
4734 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4735 case RangeBefore:
David Blaikieb219cfc2011-09-23 05:06:16 +00004736 llvm_unreachable("Infeasible");
Douglas Gregor4419b672010-10-21 06:10:04 +00004737 case RangeAfter:
4738 break;
4739 case RangeOverlap:
4740 Cursors[I] = cursor;
4741 AdvanceToken();
4742 continue;
4743 }
4744 break;
4745 }
4746
4747 // Save the preprocessing token index; restore the non-preprocessing
4748 // token index.
4749 PreprocessingTokIdx = TokIdx;
4750 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004751 return CXChildVisit_Recurse;
4752 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004753
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004754 if (cursorRange.isInvalid())
4755 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004756
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004757 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4758
Ted Kremeneka333c662010-05-12 05:29:33 +00004759 // Adjust the annotated range based specific declarations.
4760 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4761 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004762 Decl *D = cxcursor::getCursorDecl(cursor);
Douglas Gregor2494dd02011-03-01 01:34:45 +00004763
4764 SourceLocation StartLoc;
Ted Kremenek23173d72010-05-18 21:09:07 +00004765 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00004766 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
4767 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
4768 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
4769 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
4770 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
Ted Kremeneka333c662010-05-12 05:29:33 +00004771 }
Douglas Gregor2494dd02011-03-01 01:34:45 +00004772
4773 if (StartLoc.isValid() && L.isValid() &&
4774 SrcMgr.isBeforeInTranslationUnit(StartLoc, L))
4775 cursorRange.setBegin(StartLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004776 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004777
Ted Kremenek3f404602010-08-14 01:14:06 +00004778 // If the location of the cursor occurs within a macro instantiation, record
4779 // the spelling location of the cursor in our annotation map. We can then
4780 // paper over the token labelings during a post-processing step to try and
4781 // get cursor mappings for tokens that are the *arguments* of a macro
4782 // instantiation.
4783 if (L.isMacroID()) {
4784 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4785 // Only invalidate the old annotation if it isn't part of a preprocessing
4786 // directive. Here we assume that the default construction of CXCursor
4787 // results in CXCursor.kind being an initialized value (i.e., 0). If
4788 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004789
Ted Kremenek3f404602010-08-14 01:14:06 +00004790 CXCursor &oldC = Annotated[rawEncoding];
4791 if (!clang_isPreprocessing(oldC.kind))
4792 oldC = cursor;
4793 }
4794
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004795 const enum CXCursorKind K = clang_getCursorKind(parent);
4796 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004797 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4798 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004799
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004800 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004801
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00004802 // Avoid having the cursor of an expression "overwrite" the annotation of the
4803 // variable declaration that it belongs to.
4804 // This can happen for C++ constructor expressions whose range generally
4805 // include the variable declaration, e.g.:
4806 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
4807 if (clang_isExpression(cursorK)) {
4808 Expr *E = getCursorExpr(cursor);
Argyrios Kyrtzidis8ccac3d2011-06-29 22:20:07 +00004809 if (Decl *D = getCursorParentDecl(cursor)) {
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00004810 const unsigned I = NextToken();
4811 if (E->getLocStart().isValid() && D->getLocation().isValid() &&
4812 E->getLocStart() == D->getLocation() &&
4813 E->getLocStart() == GetTokenLoc(I)) {
4814 Cursors[I] = updateC;
4815 AdvanceToken();
4816 }
4817 }
4818 }
4819
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004820 // Visit children to get their cursor information.
4821 const unsigned BeforeChildren = NextToken();
4822 VisitChildren(cursor);
4823 const unsigned AfterChildren = NextToken();
4824
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004825 // Scan the tokens that are at the end of the cursor, but are not captured
4826 // but the child cursors.
4827 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
Ted Kremenek6db61092010-05-05 00:55:15 +00004828
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004829 // Scan the tokens that are at the beginning of the cursor, but are not
4830 // capture by the child cursors.
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004831 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4832 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4833 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004834
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004835 Cursors[I] = cursor;
4836 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004837
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004838 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004839}
4840
Ted Kremenek6db61092010-05-05 00:55:15 +00004841static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4842 CXCursor parent,
4843 CXClientData client_data) {
4844 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4845}
4846
Ted Kremenek6628a612011-03-18 22:51:30 +00004847namespace {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004848
4849/// \brief Uses the macro expansions in the preprocessing record to find
4850/// and mark tokens that are macro arguments. This info is used by the
4851/// AnnotateTokensWorker.
4852class MarkMacroArgTokensVisitor {
4853 SourceManager &SM;
4854 CXToken *Tokens;
4855 unsigned NumTokens;
4856 unsigned CurIdx;
4857
4858public:
4859 MarkMacroArgTokensVisitor(SourceManager &SM,
4860 CXToken *tokens, unsigned numTokens)
4861 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
4862
4863 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
4864 if (cursor.kind != CXCursor_MacroExpansion)
4865 return CXChildVisit_Continue;
4866
4867 SourceRange macroRange = getCursorMacroExpansion(cursor)->getSourceRange();
4868 if (macroRange.getBegin() == macroRange.getEnd())
4869 return CXChildVisit_Continue; // it's not a function macro.
4870
4871 for (; CurIdx < NumTokens; ++CurIdx) {
4872 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
4873 macroRange.getBegin()))
4874 break;
4875 }
4876
4877 if (CurIdx == NumTokens)
4878 return CXChildVisit_Break;
4879
4880 for (; CurIdx < NumTokens; ++CurIdx) {
4881 SourceLocation tokLoc = getTokenLoc(CurIdx);
4882 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
4883 break;
4884
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004885 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004886 }
4887
4888 if (CurIdx == NumTokens)
4889 return CXChildVisit_Break;
4890
4891 return CXChildVisit_Continue;
4892 }
4893
4894private:
4895 SourceLocation getTokenLoc(unsigned tokI) {
4896 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4897 }
4898
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004899 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004900 // The third field is reserved and currently not used. Use it here
4901 // to mark macro arg expanded tokens with their expanded locations.
4902 Tokens[tokI].int_data[3] = loc.getRawEncoding();
4903 }
4904};
4905
4906} // end anonymous namespace
4907
4908static CXChildVisitResult
4909MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
4910 CXClientData client_data) {
4911 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
4912 parent);
4913}
4914
4915namespace {
Ted Kremenek6628a612011-03-18 22:51:30 +00004916 struct clang_annotateTokens_Data {
4917 CXTranslationUnit TU;
4918 ASTUnit *CXXUnit;
4919 CXToken *Tokens;
4920 unsigned NumTokens;
4921 CXCursor *Cursors;
4922 };
4923}
4924
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004925static void annotatePreprocessorTokens(CXTranslationUnit TU,
4926 SourceRange RegionOfInterest,
4927 AnnotateTokensData &Annotated) {
4928 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4929
4930 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4931 std::pair<FileID, unsigned> BeginLocInfo
4932 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4933 std::pair<FileID, unsigned> EndLocInfo
4934 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
4935
4936 if (BeginLocInfo.first != EndLocInfo.first)
4937 return;
4938
4939 StringRef Buffer;
4940 bool Invalid = false;
4941 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
4942 if (Buffer.empty() || Invalid)
4943 return;
4944
4945 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4946 CXXUnit->getASTContext().getLangOptions(),
4947 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
4948 Buffer.end());
4949 Lex.SetCommentRetentionState(true);
4950
4951 // Lex tokens in raw mode until we hit the end of the range, to avoid
4952 // entering #includes or expanding macros.
4953 while (true) {
4954 Token Tok;
4955 Lex.LexFromRawLexer(Tok);
4956
4957 reprocess:
4958 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4959 // We have found a preprocessing directive. Gobble it up so that we
4960 // don't see it while preprocessing these tokens later, but keep track
4961 // of all of the token locations inside this preprocessing directive so
4962 // that we can annotate them appropriately.
4963 //
4964 // FIXME: Some simple tests here could identify macro definitions and
4965 // #undefs, to provide specific cursor kinds for those.
4966 SmallVector<SourceLocation, 32> Locations;
4967 do {
4968 Locations.push_back(Tok.getLocation());
4969 Lex.LexFromRawLexer(Tok);
4970 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
4971
4972 using namespace cxcursor;
4973 CXCursor Cursor
4974 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4975 Locations.back()),
4976 TU);
4977 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4978 Annotated[Locations[I].getRawEncoding()] = Cursor;
4979 }
4980
4981 if (Tok.isAtStartOfLine())
4982 goto reprocess;
4983
4984 continue;
4985 }
4986
4987 if (Tok.is(tok::eof))
4988 break;
4989 }
4990}
4991
Ted Kremenekab979612010-11-11 08:05:23 +00004992// This gets run a separate thread to avoid stack blowout.
Ted Kremenek6628a612011-03-18 22:51:30 +00004993static void clang_annotateTokensImpl(void *UserData) {
4994 CXTranslationUnit TU = ((clang_annotateTokens_Data*)UserData)->TU;
4995 ASTUnit *CXXUnit = ((clang_annotateTokens_Data*)UserData)->CXXUnit;
4996 CXToken *Tokens = ((clang_annotateTokens_Data*)UserData)->Tokens;
4997 const unsigned NumTokens = ((clang_annotateTokens_Data*)UserData)->NumTokens;
4998 CXCursor *Cursors = ((clang_annotateTokens_Data*)UserData)->Cursors;
4999
5000 // Determine the region of interest, which contains all of the tokens.
5001 SourceRange RegionOfInterest;
5002 RegionOfInterest.setBegin(
5003 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
5004 RegionOfInterest.setEnd(
5005 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
5006 Tokens[NumTokens-1])));
5007
5008 // A mapping from the source locations found when re-lexing or traversing the
5009 // region of interest to the corresponding cursors.
5010 AnnotateTokensData Annotated;
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005011
Ted Kremenek6628a612011-03-18 22:51:30 +00005012 // Relex the tokens within the source range to look for preprocessing
5013 // directives.
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005014 annotatePreprocessorTokens(TU, RegionOfInterest, Annotated);
Ted Kremenek6628a612011-03-18 22:51:30 +00005015
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005016 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
5017 // Search and mark tokens that are macro argument expansions.
5018 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
5019 Tokens, NumTokens);
5020 CursorVisitor MacroArgMarker(TU,
5021 MarkMacroArgTokensVisitorDelegate, &Visitor,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00005022 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00005023 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00005024 RegionOfInterest);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005025 MacroArgMarker.visitPreprocessedEntitiesInRegion();
5026 }
5027
Ted Kremenek6628a612011-03-18 22:51:30 +00005028 // Annotate all of the source locations in the region of interest that map to
5029 // a specific cursor.
5030 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
5031 TU, RegionOfInterest);
5032
5033 // FIXME: We use a ridiculous stack size here because the data-recursion
5034 // algorithm uses a large stack frame than the non-data recursive version,
5035 // and AnnotationTokensWorker currently transforms the data-recursion
5036 // algorithm back into a traditional recursion by explicitly calling
5037 // VisitChildren(). We will need to remove this explicit recursive call.
5038 W.AnnotateTokens();
5039
5040 // If we ran into any entities that involve context-sensitive keywords,
5041 // take another pass through the tokens to mark them as such.
5042 if (W.hasContextSensitiveKeywords()) {
5043 for (unsigned I = 0; I != NumTokens; ++I) {
5044 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
5045 continue;
5046
5047 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
5048 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5049 if (ObjCPropertyDecl *Property
5050 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
5051 if (Property->getPropertyAttributesAsWritten() != 0 &&
5052 llvm::StringSwitch<bool>(II->getName())
5053 .Case("readonly", true)
5054 .Case("assign", true)
John McCallf85e1932011-06-15 23:02:42 +00005055 .Case("unsafe_unretained", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00005056 .Case("readwrite", true)
5057 .Case("retain", true)
5058 .Case("copy", true)
5059 .Case("nonatomic", true)
5060 .Case("atomic", true)
5061 .Case("getter", true)
5062 .Case("setter", true)
John McCallf85e1932011-06-15 23:02:42 +00005063 .Case("strong", true)
5064 .Case("weak", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00005065 .Default(false))
5066 Tokens[I].int_data[0] = CXToken_Keyword;
5067 }
5068 continue;
5069 }
5070
5071 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
5072 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
5073 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5074 if (llvm::StringSwitch<bool>(II->getName())
5075 .Case("in", true)
5076 .Case("out", true)
5077 .Case("inout", true)
5078 .Case("oneway", true)
5079 .Case("bycopy", true)
5080 .Case("byref", true)
5081 .Default(false))
5082 Tokens[I].int_data[0] = CXToken_Keyword;
5083 continue;
5084 }
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00005085
5086 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
5087 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
5088 Tokens[I].int_data[0] = CXToken_Keyword;
Ted Kremenek6628a612011-03-18 22:51:30 +00005089 continue;
5090 }
5091 }
5092 }
Ted Kremenekab979612010-11-11 08:05:23 +00005093}
5094
Ted Kremenek6db61092010-05-05 00:55:15 +00005095extern "C" {
5096
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005097void clang_annotateTokens(CXTranslationUnit TU,
5098 CXToken *Tokens, unsigned NumTokens,
5099 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005100
5101 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005102 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005103
Douglas Gregor4419b672010-10-21 06:10:04 +00005104 // Any token we don't specifically annotate will have a NULL cursor.
5105 CXCursor C = clang_getNullCursor();
5106 for (unsigned I = 0; I != NumTokens; ++I)
5107 Cursors[I] = C;
5108
Ted Kremeneka60ed472010-11-16 08:15:36 +00005109 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor4419b672010-10-21 06:10:04 +00005110 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005111 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005112
Douglas Gregorbdf60622010-03-05 21:16:25 +00005113 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenek6628a612011-03-18 22:51:30 +00005114
5115 clang_annotateTokens_Data data = { TU, CXXUnit, Tokens, NumTokens, Cursors };
Ted Kremenekab979612010-11-11 08:05:23 +00005116 llvm::CrashRecoveryContext CRC;
Ted Kremenek6628a612011-03-18 22:51:30 +00005117 if (!RunSafely(CRC, clang_annotateTokensImpl, &data,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005118 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00005119 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
5120 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005121}
Ted Kremenek6628a612011-03-18 22:51:30 +00005122
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005123} // end: extern "C"
5124
5125//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00005126// Operations for querying linkage of a cursor.
5127//===----------------------------------------------------------------------===//
5128
5129extern "C" {
5130CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00005131 if (!clang_isDeclaration(cursor.kind))
5132 return CXLinkage_Invalid;
5133
Ted Kremenek16b42592010-03-03 06:36:57 +00005134 Decl *D = cxcursor::getCursorDecl(cursor);
5135 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
5136 switch (ND->getLinkage()) {
5137 case NoLinkage: return CXLinkage_NoLinkage;
5138 case InternalLinkage: return CXLinkage_Internal;
5139 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
5140 case ExternalLinkage: return CXLinkage_External;
5141 };
5142
5143 return CXLinkage_Invalid;
5144}
5145} // end: extern "C"
5146
5147//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005148// Operations for querying language of a cursor.
5149//===----------------------------------------------------------------------===//
5150
5151static CXLanguageKind getDeclLanguage(const Decl *D) {
5152 switch (D->getKind()) {
5153 default:
5154 break;
5155 case Decl::ImplicitParam:
5156 case Decl::ObjCAtDefsField:
5157 case Decl::ObjCCategory:
5158 case Decl::ObjCCategoryImpl:
5159 case Decl::ObjCClass:
5160 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005161 case Decl::ObjCForwardProtocol:
5162 case Decl::ObjCImplementation:
5163 case Decl::ObjCInterface:
5164 case Decl::ObjCIvar:
5165 case Decl::ObjCMethod:
5166 case Decl::ObjCProperty:
5167 case Decl::ObjCPropertyImpl:
5168 case Decl::ObjCProtocol:
5169 return CXLanguage_ObjC;
5170 case Decl::CXXConstructor:
5171 case Decl::CXXConversion:
5172 case Decl::CXXDestructor:
5173 case Decl::CXXMethod:
5174 case Decl::CXXRecord:
5175 case Decl::ClassTemplate:
5176 case Decl::ClassTemplatePartialSpecialization:
5177 case Decl::ClassTemplateSpecialization:
5178 case Decl::Friend:
5179 case Decl::FriendTemplate:
5180 case Decl::FunctionTemplate:
5181 case Decl::LinkageSpec:
5182 case Decl::Namespace:
5183 case Decl::NamespaceAlias:
5184 case Decl::NonTypeTemplateParm:
5185 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005186 case Decl::TemplateTemplateParm:
5187 case Decl::TemplateTypeParm:
5188 case Decl::UnresolvedUsingTypename:
5189 case Decl::UnresolvedUsingValue:
5190 case Decl::Using:
5191 case Decl::UsingDirective:
5192 case Decl::UsingShadow:
5193 return CXLanguage_CPlusPlus;
5194 }
5195
5196 return CXLanguage_C;
5197}
5198
5199extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00005200
5201enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
5202 if (clang_isDeclaration(cursor.kind))
5203 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005204 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Douglas Gregor58ddb602010-08-23 23:00:57 +00005205 return CXAvailability_Available;
5206
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005207 switch (D->getAvailability()) {
5208 case AR_Available:
5209 case AR_NotYetIntroduced:
5210 return CXAvailability_Available;
5211
5212 case AR_Deprecated:
Douglas Gregor58ddb602010-08-23 23:00:57 +00005213 return CXAvailability_Deprecated;
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005214
5215 case AR_Unavailable:
5216 return CXAvailability_NotAvailable;
5217 }
Douglas Gregor58ddb602010-08-23 23:00:57 +00005218 }
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005219
Douglas Gregor58ddb602010-08-23 23:00:57 +00005220 return CXAvailability_Available;
5221}
5222
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005223CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
5224 if (clang_isDeclaration(cursor.kind))
5225 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
5226
5227 return CXLanguage_Invalid;
5228}
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005229
5230 /// \brief If the given cursor is the "templated" declaration
5231 /// descibing a class or function template, return the class or
5232 /// function template.
5233static Decl *maybeGetTemplateCursor(Decl *D) {
5234 if (!D)
5235 return 0;
5236
5237 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
5238 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
5239 return FunTmpl;
5240
5241 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
5242 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
5243 return ClassTmpl;
5244
5245 return D;
5246}
5247
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005248CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
5249 if (clang_isDeclaration(cursor.kind)) {
5250 if (Decl *D = getCursorDecl(cursor)) {
5251 DeclContext *DC = D->getDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005252 if (!DC)
5253 return clang_getNullCursor();
5254
5255 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5256 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005257 }
5258 }
5259
5260 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
5261 if (Decl *D = getCursorDecl(cursor))
Ted Kremeneka60ed472010-11-16 08:15:36 +00005262 return MakeCXCursor(D, getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005263 }
5264
5265 return clang_getNullCursor();
5266}
5267
5268CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
5269 if (clang_isDeclaration(cursor.kind)) {
5270 if (Decl *D = getCursorDecl(cursor)) {
5271 DeclContext *DC = D->getLexicalDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005272 if (!DC)
5273 return clang_getNullCursor();
5274
5275 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5276 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005277 }
5278 }
5279
5280 // FIXME: Note that we can't easily compute the lexical context of a
5281 // statement or expression, so we return nothing.
5282 return clang_getNullCursor();
5283}
5284
Douglas Gregor9f592342010-10-01 20:25:15 +00005285void clang_getOverriddenCursors(CXCursor cursor,
5286 CXCursor **overridden,
5287 unsigned *num_overridden) {
5288 if (overridden)
5289 *overridden = 0;
5290 if (num_overridden)
5291 *num_overridden = 0;
5292 if (!overridden || !num_overridden)
5293 return;
5294
Argyrios Kyrtzidisb11be042011-10-06 07:00:46 +00005295 SmallVector<CXCursor, 8> Overridden;
5296 cxcursor::getOverriddenCursors(cursor, Overridden);
Douglas Gregor9f592342010-10-01 20:25:15 +00005297
Ted Kremenek24077122011-11-14 23:51:37 +00005298 // Don't allocate memory if we have no overriden cursors.
5299 if (Overridden.size() == 0)
5300 return;
5301
Argyrios Kyrtzidisb11be042011-10-06 07:00:46 +00005302 *num_overridden = Overridden.size();
5303 *overridden = new CXCursor [Overridden.size()];
5304 std::copy(Overridden.begin(), Overridden.end(), *overridden);
Douglas Gregor9f592342010-10-01 20:25:15 +00005305}
5306
5307void clang_disposeOverriddenCursors(CXCursor *overridden) {
5308 delete [] overridden;
5309}
5310
Douglas Gregorecdcb882010-10-20 22:00:55 +00005311CXFile clang_getIncludedFile(CXCursor cursor) {
5312 if (cursor.kind != CXCursor_InclusionDirective)
5313 return 0;
5314
5315 InclusionDirective *ID = getCursorInclusionDirective(cursor);
5316 return (void *)ID->getFile();
5317}
5318
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005319} // end: extern "C"
5320
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005321
5322//===----------------------------------------------------------------------===//
5323// C++ AST instrospection.
5324//===----------------------------------------------------------------------===//
5325
5326extern "C" {
5327unsigned clang_CXXMethod_isStatic(CXCursor C) {
5328 if (!clang_isDeclaration(C.kind))
5329 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00005330
5331 CXXMethodDecl *Method = 0;
5332 Decl *D = cxcursor::getCursorDecl(C);
5333 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5334 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5335 else
5336 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5337 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00005338}
Ted Kremenekb12903e2010-05-18 22:32:15 +00005339
Douglas Gregor211924b2011-05-12 15:17:24 +00005340unsigned clang_CXXMethod_isVirtual(CXCursor C) {
5341 if (!clang_isDeclaration(C.kind))
5342 return 0;
5343
5344 CXXMethodDecl *Method = 0;
5345 Decl *D = cxcursor::getCursorDecl(C);
5346 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5347 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5348 else
5349 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5350 return (Method && Method->isVirtual()) ? 1 : 0;
5351}
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005352} // end: extern "C"
5353
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005354//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00005355// Attribute introspection.
5356//===----------------------------------------------------------------------===//
5357
5358extern "C" {
5359CXType clang_getIBOutletCollectionType(CXCursor C) {
5360 if (C.kind != CXCursor_IBOutletCollectionAttr)
Ted Kremeneka60ed472010-11-16 08:15:36 +00005361 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005362
5363 IBOutletCollectionAttr *A =
5364 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
5365
Argyrios Kyrtzidis18aa2ff2011-09-13 18:49:52 +00005366 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005367}
5368} // end: extern "C"
5369
5370//===----------------------------------------------------------------------===//
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005371// Inspecting memory usage.
5372//===----------------------------------------------------------------------===//
5373
Ted Kremenekf7870022011-04-20 16:41:07 +00005374typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005375
Ted Kremenekf7870022011-04-20 16:41:07 +00005376static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
5377 enum CXTUResourceUsageKind k,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005378 unsigned long amount) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005379 CXTUResourceUsageEntry entry = { k, amount };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005380 entries.push_back(entry);
5381}
5382
5383extern "C" {
5384
Ted Kremenekf7870022011-04-20 16:41:07 +00005385const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005386 const char *str = "";
5387 switch (kind) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005388 case CXTUResourceUsage_AST:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005389 str = "ASTContext: expressions, declarations, and types";
5390 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005391 case CXTUResourceUsage_Identifiers:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005392 str = "ASTContext: identifiers";
5393 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005394 case CXTUResourceUsage_Selectors:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005395 str = "ASTContext: selectors";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005396 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005397 case CXTUResourceUsage_GlobalCompletionResults:
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005398 str = "Code completion: cached global results";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005399 break;
Ted Kremenek457aaf02011-04-28 04:10:31 +00005400 case CXTUResourceUsage_SourceManagerContentCache:
5401 str = "SourceManager: content cache allocator";
5402 break;
Ted Kremenekba29bd22011-04-28 04:53:38 +00005403 case CXTUResourceUsage_AST_SideTables:
5404 str = "ASTContext: side tables";
5405 break;
Ted Kremenekf61b8312011-04-28 20:36:42 +00005406 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
5407 str = "SourceManager: malloc'ed memory buffers";
5408 break;
5409 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
5410 str = "SourceManager: mmap'ed memory buffers";
5411 break;
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005412 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
5413 str = "ExternalASTSource: malloc'ed memory buffers";
5414 break;
5415 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
5416 str = "ExternalASTSource: mmap'ed memory buffers";
5417 break;
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005418 case CXTUResourceUsage_Preprocessor:
5419 str = "Preprocessor: malloc'ed memory";
5420 break;
5421 case CXTUResourceUsage_PreprocessingRecord:
5422 str = "Preprocessor: PreprocessingRecord";
5423 break;
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005424 case CXTUResourceUsage_SourceManager_DataStructures:
5425 str = "SourceManager: data structures and tables";
5426 break;
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005427 case CXTUResourceUsage_Preprocessor_HeaderSearch:
5428 str = "Preprocessor: header search tables";
5429 break;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005430 }
5431 return str;
5432}
5433
Ted Kremenekf7870022011-04-20 16:41:07 +00005434CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005435 if (!TU) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005436 CXTUResourceUsage usage = { (void*) 0, 0, 0 };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005437 return usage;
5438 }
5439
5440 ASTUnit *astUnit = static_cast<ASTUnit*>(TU->TUData);
5441 llvm::OwningPtr<MemUsageEntries> entries(new MemUsageEntries());
5442 ASTContext &astContext = astUnit->getASTContext();
5443
5444 // How much memory is used by AST nodes and types?
Ted Kremenekf7870022011-04-20 16:41:07 +00005445 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005446 (unsigned long) astContext.getASTAllocatedMemory());
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005447
5448 // How much memory is used by identifiers?
Ted Kremenekf7870022011-04-20 16:41:07 +00005449 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005450 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
5451
5452 // How much memory is used for selectors?
Ted Kremenekf7870022011-04-20 16:41:07 +00005453 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005454 (unsigned long) astContext.Selectors.getTotalMemory());
5455
Ted Kremenekba29bd22011-04-28 04:53:38 +00005456 // How much memory is used by ASTContext's side tables?
5457 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
5458 (unsigned long) astContext.getSideTableAllocatedMemory());
5459
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005460 // How much memory is used for caching global code completion results?
5461 unsigned long completionBytes = 0;
5462 if (GlobalCodeCompletionAllocator *completionAllocator =
5463 astUnit->getCachedCompletionAllocator().getPtr()) {
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005464 completionBytes = completionAllocator->getTotalMemory();
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005465 }
Ted Kremenek457aaf02011-04-28 04:10:31 +00005466 createCXTUResourceUsageEntry(*entries,
5467 CXTUResourceUsage_GlobalCompletionResults,
5468 completionBytes);
5469
5470 // How much memory is being used by SourceManager's content cache?
5471 createCXTUResourceUsageEntry(*entries,
5472 CXTUResourceUsage_SourceManagerContentCache,
5473 (unsigned long) astContext.getSourceManager().getContentCacheSize());
Ted Kremenekf61b8312011-04-28 20:36:42 +00005474
5475 // How much memory is being used by the MemoryBuffer's in SourceManager?
5476 const SourceManager::MemoryBufferSizes &srcBufs =
5477 astUnit->getSourceManager().getMemoryBufferSizes();
5478
5479 createCXTUResourceUsageEntry(*entries,
5480 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
5481 (unsigned long) srcBufs.malloc_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005482 createCXTUResourceUsageEntry(*entries,
Ted Kremenekf61b8312011-04-28 20:36:42 +00005483 CXTUResourceUsage_SourceManager_Membuffer_MMap,
5484 (unsigned long) srcBufs.mmap_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005485 createCXTUResourceUsageEntry(*entries,
5486 CXTUResourceUsage_SourceManager_DataStructures,
5487 (unsigned long) astContext.getSourceManager()
5488 .getDataStructureSizes());
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005489
5490 // How much memory is being used by the ExternalASTSource?
5491 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
5492 const ExternalASTSource::MemoryBufferSizes &sizes =
5493 esrc->getMemoryBufferSizes();
5494
5495 createCXTUResourceUsageEntry(*entries,
5496 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
5497 (unsigned long) sizes.malloc_bytes);
5498 createCXTUResourceUsageEntry(*entries,
5499 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
5500 (unsigned long) sizes.mmap_bytes);
5501 }
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005502
5503 // How much memory is being used by the Preprocessor?
5504 Preprocessor &pp = astUnit->getPreprocessor();
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005505 createCXTUResourceUsageEntry(*entries,
5506 CXTUResourceUsage_Preprocessor,
Argyrios Kyrtzidisc5c5e922011-06-29 22:20:04 +00005507 pp.getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005508
5509 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
5510 createCXTUResourceUsageEntry(*entries,
5511 CXTUResourceUsage_PreprocessingRecord,
5512 pRec->getTotalMemory());
5513 }
5514
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005515 createCXTUResourceUsageEntry(*entries,
5516 CXTUResourceUsage_Preprocessor_HeaderSearch,
5517 pp.getHeaderSearchInfo().getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005518
Ted Kremenekf7870022011-04-20 16:41:07 +00005519 CXTUResourceUsage usage = { (void*) entries.get(),
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005520 (unsigned) entries->size(),
5521 entries->size() ? &(*entries)[0] : 0 };
5522 entries.take();
5523 return usage;
5524}
5525
Ted Kremenekf7870022011-04-20 16:41:07 +00005526void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005527 if (usage.data)
5528 delete (MemUsageEntries*) usage.data;
5529}
5530
5531} // end extern "C"
5532
Douglas Gregor6df78732011-05-05 20:27:22 +00005533void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
5534 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
5535 for (unsigned I = 0; I != Usage.numEntries; ++I)
5536 fprintf(stderr, " %s: %lu\n",
5537 clang_getTUResourceUsageName(Usage.entries[I].kind),
5538 Usage.entries[I].amount);
5539
5540 clang_disposeCXTUResourceUsage(Usage);
5541}
5542
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005543//===----------------------------------------------------------------------===//
Ted Kremenek04bb7162010-01-22 22:44:15 +00005544// Misc. utility functions.
5545//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00005546
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00005547/// Default to using an 8 MB stack size on "safety" threads.
5548static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005549
5550namespace clang {
5551
5552bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005553 void (*Fn)(void*), void *UserData,
5554 unsigned Size) {
5555 if (!Size)
5556 Size = GetSafetyThreadStackSize();
5557 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005558 return CRC.RunSafelyOnThread(Fn, UserData, Size);
5559 return CRC.RunSafely(Fn, UserData);
5560}
5561
5562unsigned GetSafetyThreadStackSize() {
5563 return SafetyStackThreadSize;
5564}
5565
5566void SetSafetyThreadStackSize(unsigned Value) {
5567 SafetyStackThreadSize = Value;
5568}
5569
5570}
5571
Ted Kremenek04bb7162010-01-22 22:44:15 +00005572extern "C" {
5573
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00005574CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00005575 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00005576}
5577
5578} // end: extern "C"
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005579