blob: 5e1d1234d97b8da7717df4eab38734777dd34e8d [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);
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001740 void VisitDeclRefExpr(DeclRefExpr *D);
Ted Kremenek035dc412010-11-13 00:36:50 +00001741 void VisitDeclStmt(DeclStmt *S);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001742 void VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001743 void VisitDesignatedInitExpr(DesignatedInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001744 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1745 void VisitForStmt(ForStmt *FS);
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001746 void VisitGotoStmt(GotoStmt *GS);
Ted Kremenek28a71942010-11-13 00:36:47 +00001747 void VisitIfStmt(IfStmt *If);
1748 void VisitInitListExpr(InitListExpr *IE);
1749 void VisitMemberExpr(MemberExpr *M);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001750 void VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001751 void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001752 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1753 void VisitOverloadExpr(OverloadExpr *E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001754 void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001755 void VisitStmt(Stmt *S);
1756 void VisitSwitchStmt(SwitchStmt *S);
1757 void VisitWhileStmt(WhileStmt *W);
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001758 void VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Francois Pichet6ad6f282010-12-07 00:08:36 +00001759 void VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E);
John Wiegley21ff2e52011-04-28 00:16:57 +00001760 void VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E);
John Wiegley55262202011-04-25 06:54:41 +00001761 void VisitExpressionTraitExpr(ExpressionTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001762 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001763 void VisitVAArgExpr(VAArgExpr *E);
Douglas Gregor94d96292011-01-19 20:34:17 +00001764 void VisitSizeOfPackExpr(SizeOfPackExpr *E);
John McCall4b9c2d22011-11-06 09:01:30 +00001765 void VisitPseudoObjectExpr(PseudoObjectExpr *E);
1766 void VisitOpaqueValueExpr(OpaqueValueExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00001767
Ted Kremenek28a71942010-11-13 00:36:47 +00001768private:
Ted Kremenekf64d8032010-11-18 00:02:32 +00001769 void AddDeclarationNameInfo(Stmt *S);
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001770 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001771 void AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001772 void AddMemberRef(FieldDecl *D, SourceLocation L);
Ted Kremenek28a71942010-11-13 00:36:47 +00001773 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001774 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001775 void AddTypeLoc(TypeSourceInfo *TI);
1776 void EnqueueChildren(Stmt *S);
1777};
1778} // end anonyous namespace
1779
Ted Kremenekf64d8032010-11-18 00:02:32 +00001780void EnqueueVisitor::AddDeclarationNameInfo(Stmt *S) {
1781 // 'S' should always be non-null, since it comes from the
1782 // statement we are visiting.
1783 WL.push_back(DeclarationNameInfoVisit(S, Parent));
1784}
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001785
1786void
1787EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1788 if (Qualifier)
1789 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
1790}
1791
Ted Kremenek28a71942010-11-13 00:36:47 +00001792void EnqueueVisitor::AddStmt(Stmt *S) {
1793 if (S)
1794 WL.push_back(StmtVisit(S, Parent));
1795}
Ted Kremenek035dc412010-11-13 00:36:50 +00001796void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001797 if (D)
Ted Kremenek035dc412010-11-13 00:36:50 +00001798 WL.push_back(DeclVisit(D, Parent, isFirst));
Ted Kremenek28a71942010-11-13 00:36:47 +00001799}
Ted Kremenek60608ec2010-11-17 00:50:47 +00001800void EnqueueVisitor::
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001801 AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001802 if (A)
1803 WL.push_back(ExplicitTemplateArgsVisit(
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001804 const_cast<ASTTemplateArgumentListInfo*>(A), Parent));
Ted Kremenek60608ec2010-11-17 00:50:47 +00001805}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001806void EnqueueVisitor::AddMemberRef(FieldDecl *D, SourceLocation L) {
1807 if (D)
1808 WL.push_back(MemberRefVisit(D, L, Parent));
1809}
Ted Kremenek28a71942010-11-13 00:36:47 +00001810void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1811 if (TI)
1812 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1813 }
1814void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001815 unsigned size = WL.size();
John McCall7502c1d2011-02-13 04:07:26 +00001816 for (Stmt::child_range Child = S->children(); Child; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001817 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001818 }
1819 if (size == WL.size())
1820 return;
1821 // Now reverse the entries we just added. This will match the DFS
1822 // ordering performed by the worklist.
1823 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1824 std::reverse(I, E);
1825}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001826void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1827 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
1828}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001829void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1830 AddDecl(B->getBlockDecl());
1831}
Ted Kremenek28a71942010-11-13 00:36:47 +00001832void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1833 EnqueueChildren(E);
1834 AddTypeLoc(E->getTypeSourceInfo());
1835}
Ted Kremenek083c7e22010-11-13 05:38:03 +00001836void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1837 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1838 E = S->body_rend(); I != E; ++I) {
1839 AddStmt(*I);
1840 }
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001841}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001842void EnqueueVisitor::
Douglas Gregorba0513d2011-10-25 01:33:02 +00001843VisitMSDependentExistsStmt(MSDependentExistsStmt *S) {
1844 AddStmt(S->getSubStmt());
1845 AddDeclarationNameInfo(S);
1846 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
1847 AddNestedNameSpecifierLoc(QualifierLoc);
1848}
1849
1850void EnqueueVisitor::
Ted Kremenekf64d8032010-11-18 00:02:32 +00001851VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
1852 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1853 AddDeclarationNameInfo(E);
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001854 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1855 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001856 if (!E->isImplicitAccess())
1857 AddStmt(E->getBase());
1858}
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001859void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1860 // Enqueue the initializer or constructor arguments.
1861 for (unsigned I = E->getNumConstructorArgs(); I > 0; --I)
1862 AddStmt(E->getConstructorArg(I-1));
1863 // Enqueue the array size, if any.
1864 AddStmt(E->getArraySize());
1865 // Enqueue the allocated type.
1866 AddTypeLoc(E->getAllocatedTypeSourceInfo());
1867 // Enqueue the placement arguments.
1868 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1869 AddStmt(E->getPlacementArg(I-1));
1870}
Ted Kremenek28a71942010-11-13 00:36:47 +00001871void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
Ted Kremenek8b8d8c92010-11-13 05:55:56 +00001872 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1873 AddStmt(CE->getArg(I-1));
Ted Kremenek28a71942010-11-13 00:36:47 +00001874 AddStmt(CE->getCallee());
1875 AddStmt(CE->getArg(0));
1876}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001877void EnqueueVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1878 // Visit the name of the type being destroyed.
1879 AddTypeLoc(E->getDestroyedTypeInfo());
1880 // Visit the scope type that looks disturbingly like the nested-name-specifier
1881 // but isn't.
1882 AddTypeLoc(E->getScopeTypeInfo());
1883 // Visit the nested-name-specifier.
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001884 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1885 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001886 // Visit base expression.
1887 AddStmt(E->getBase());
1888}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001889void EnqueueVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1890 AddTypeLoc(E->getTypeSourceInfo());
1891}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001892void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1893 EnqueueChildren(E);
1894 AddTypeLoc(E->getTypeSourceInfo());
1895}
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001896void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1897 EnqueueChildren(E);
1898 if (E->isTypeOperand())
1899 AddTypeLoc(E->getTypeOperandSourceInfo());
1900}
Ted Kremenek55b933a2010-11-17 00:50:36 +00001901
1902void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
1903 *E) {
1904 EnqueueChildren(E);
1905 AddTypeLoc(E->getTypeSourceInfo());
1906}
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001907void EnqueueVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1908 EnqueueChildren(E);
1909 if (E->isTypeOperand())
1910 AddTypeLoc(E->getTypeOperandSourceInfo());
1911}
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001912void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001913 if (DR->hasExplicitTemplateArgs()) {
1914 AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
1915 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001916 WL.push_back(DeclRefExprParts(DR, Parent));
1917}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001918void EnqueueVisitor::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
1919 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1920 AddDeclarationNameInfo(E);
Douglas Gregor00cf3cc2011-02-25 20:49:16 +00001921 AddNestedNameSpecifierLoc(E->getQualifierLoc());
Ted Kremenekf64d8032010-11-18 00:02:32 +00001922}
Ted Kremenek035dc412010-11-13 00:36:50 +00001923void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1924 unsigned size = WL.size();
1925 bool isFirst = true;
1926 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1927 D != DEnd; ++D) {
1928 AddDecl(*D, isFirst);
1929 isFirst = false;
1930 }
1931 if (size == WL.size())
1932 return;
1933 // Now reverse the entries we just added. This will match the DFS
1934 // ordering performed by the worklist.
1935 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1936 std::reverse(I, E);
1937}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001938void EnqueueVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1939 AddStmt(E->getInit());
1940 typedef DesignatedInitExpr::Designator Designator;
1941 for (DesignatedInitExpr::reverse_designators_iterator
1942 D = E->designators_rbegin(), DEnd = E->designators_rend();
1943 D != DEnd; ++D) {
1944 if (D->isFieldDesignator()) {
1945 if (FieldDecl *Field = D->getField())
1946 AddMemberRef(Field, D->getFieldLoc());
1947 continue;
1948 }
1949 if (D->isArrayDesignator()) {
1950 AddStmt(E->getArrayIndex(*D));
1951 continue;
1952 }
1953 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1954 AddStmt(E->getArrayRangeEnd(*D));
1955 AddStmt(E->getArrayRangeStart(*D));
1956 }
1957}
Ted Kremenek28a71942010-11-13 00:36:47 +00001958void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1959 EnqueueChildren(E);
1960 AddTypeLoc(E->getTypeInfoAsWritten());
1961}
1962void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1963 AddStmt(FS->getBody());
1964 AddStmt(FS->getInc());
1965 AddStmt(FS->getCond());
1966 AddDecl(FS->getConditionVariable());
1967 AddStmt(FS->getInit());
1968}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001969void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) {
1970 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
1971}
Ted Kremenek28a71942010-11-13 00:36:47 +00001972void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
1973 AddStmt(If->getElse());
1974 AddStmt(If->getThen());
1975 AddStmt(If->getCond());
1976 AddDecl(If->getConditionVariable());
1977}
1978void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
1979 // We care about the syntactic form of the initializer list, only.
1980 if (InitListExpr *Syntactic = IE->getSyntacticForm())
1981 IE = Syntactic;
1982 EnqueueChildren(IE);
1983}
1984void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
Douglas Gregor89629a72010-11-17 17:15:08 +00001985 WL.push_back(MemberExprParts(M, Parent));
1986
1987 // If the base of the member access expression is an implicit 'this', don't
1988 // visit it.
1989 // FIXME: If we ever want to show these implicit accesses, this will be
1990 // unfortunate. However, clang_getCursor() relies on this behavior.
Douglas Gregor75e85042011-03-02 21:06:53 +00001991 if (!M->isImplicitAccess())
1992 AddStmt(M->getBase());
Ted Kremenek28a71942010-11-13 00:36:47 +00001993}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001994void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1995 AddTypeLoc(E->getEncodedTypeSourceInfo());
1996}
Ted Kremenek28a71942010-11-13 00:36:47 +00001997void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
1998 EnqueueChildren(M);
1999 AddTypeLoc(M->getClassReceiverTypeInfo());
2000}
Ted Kremenekcdba6592010-11-18 00:42:18 +00002001void EnqueueVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
2002 // Visit the components of the offsetof expression.
2003 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
2004 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
2005 const OffsetOfNode &Node = E->getComponent(I-1);
2006 switch (Node.getKind()) {
2007 case OffsetOfNode::Array:
2008 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2009 break;
2010 case OffsetOfNode::Field:
Abramo Bagnara06dec892011-03-12 09:45:03 +00002011 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
Ted Kremenekcdba6592010-11-18 00:42:18 +00002012 break;
2013 case OffsetOfNode::Identifier:
2014 case OffsetOfNode::Base:
2015 continue;
2016 }
2017 }
2018 // Visit the type into which we're computing the offset.
2019 AddTypeLoc(E->getTypeSourceInfo());
2020}
Ted Kremenek28a71942010-11-13 00:36:47 +00002021void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00002022 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
Ted Kremenek60458782010-11-12 21:34:16 +00002023 WL.push_back(OverloadExprParts(E, Parent));
2024}
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002025void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
2026 UnaryExprOrTypeTraitExpr *E) {
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00002027 EnqueueChildren(E);
2028 if (E->isArgumentType())
2029 AddTypeLoc(E->getArgumentTypeInfo());
2030}
Ted Kremenek28a71942010-11-13 00:36:47 +00002031void EnqueueVisitor::VisitStmt(Stmt *S) {
2032 EnqueueChildren(S);
2033}
2034void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
2035 AddStmt(S->getBody());
2036 AddStmt(S->getCond());
2037 AddDecl(S->getConditionVariable());
2038}
Ted Kremenekfafa75a2010-11-17 00:50:39 +00002039
Ted Kremenek28a71942010-11-13 00:36:47 +00002040void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
2041 AddStmt(W->getBody());
2042 AddStmt(W->getCond());
2043 AddDecl(W->getConditionVariable());
2044}
John Wiegley21ff2e52011-04-28 00:16:57 +00002045
Ted Kremenek2939b6f2010-11-17 00:50:50 +00002046void EnqueueVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
2047 AddTypeLoc(E->getQueriedTypeSourceInfo());
2048}
Francois Pichet6ad6f282010-12-07 00:08:36 +00002049
2050void EnqueueVisitor::VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
Francois Pichet6ad6f282010-12-07 00:08:36 +00002051 AddTypeLoc(E->getRhsTypeSourceInfo());
Francois Pichet0a03a3f2010-12-08 09:11:05 +00002052 AddTypeLoc(E->getLhsTypeSourceInfo());
Francois Pichet6ad6f282010-12-07 00:08:36 +00002053}
2054
John Wiegley21ff2e52011-04-28 00:16:57 +00002055void EnqueueVisitor::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
2056 AddTypeLoc(E->getQueriedTypeSourceInfo());
2057}
2058
John Wiegley55262202011-04-25 06:54:41 +00002059void EnqueueVisitor::VisitExpressionTraitExpr(ExpressionTraitExpr *E) {
2060 EnqueueChildren(E);
2061}
2062
Ted Kremenek28a71942010-11-13 00:36:47 +00002063void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
2064 VisitOverloadExpr(U);
2065 if (!U->isImplicitAccess())
2066 AddStmt(U->getBase());
2067}
Ted Kremenek9d3bf792010-11-17 00:50:43 +00002068void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) {
2069 AddStmt(E->getSubExpr());
2070 AddTypeLoc(E->getWrittenTypeInfo());
2071}
Douglas Gregor94d96292011-01-19 20:34:17 +00002072void EnqueueVisitor::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
2073 WL.push_back(SizeOfPackExprParts(E, Parent));
2074}
John McCall4b9c2d22011-11-06 09:01:30 +00002075void EnqueueVisitor::VisitOpaqueValueExpr(OpaqueValueExpr *E) {
2076 // If the opaque value has a source expression, just transparently
2077 // visit that. This is useful for (e.g.) pseudo-object expressions.
2078 if (Expr *SourceExpr = E->getSourceExpr())
2079 return Visit(SourceExpr);
2080 AddStmt(E);
2081}
2082void EnqueueVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *E) {
2083 // Treat the expression like its syntactic form.
2084 Visit(E->getSyntacticForm());
2085}
Ted Kremenek60458782010-11-12 21:34:16 +00002086
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002087void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002088 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002089}
2090
2091bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2092 if (RegionOfInterest.isValid()) {
2093 SourceRange Range = getRawCursorExtent(C);
2094 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2095 return false;
2096 }
2097 return true;
2098}
2099
2100bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2101 while (!WL.empty()) {
2102 // Dequeue the worklist item.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002103 VisitorJob LI = WL.back();
2104 WL.pop_back();
2105
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002106 // Set the Parent field, then back to its old value once we're done.
2107 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2108
2109 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00002110 case VisitorJob::DeclVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002111 Decl *D = cast<DeclVisit>(&LI)->get();
Ted Kremenekf1107452010-11-12 18:26:56 +00002112 if (!D)
2113 continue;
2114
2115 // For now, perform default visitation for Decls.
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002116 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2117 cast<DeclVisit>(&LI)->isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00002118 return true;
2119
2120 continue;
2121 }
Ted Kremenek60608ec2010-11-17 00:50:47 +00002122 case VisitorJob::ExplicitTemplateArgsVisitKind: {
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00002123 const ASTTemplateArgumentListInfo *ArgList =
Ted Kremenek60608ec2010-11-17 00:50:47 +00002124 cast<ExplicitTemplateArgsVisit>(&LI)->get();
2125 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2126 *ArgEnd = Arg + ArgList->NumTemplateArgs;
2127 Arg != ArgEnd; ++Arg) {
2128 if (VisitTemplateArgumentLoc(*Arg))
2129 return true;
2130 }
2131 continue;
2132 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002133 case VisitorJob::TypeLocVisitKind: {
2134 // Perform default visitation for TypeLocs.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002135 if (Visit(cast<TypeLocVisit>(&LI)->get()))
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002136 return true;
2137 continue;
2138 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002139 case VisitorJob::LabelRefVisitKind: {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002140 LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Ted Kremeneke7455012011-02-23 04:54:51 +00002141 if (LabelStmt *stmt = LS->getStmt()) {
2142 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2143 TU))) {
2144 return true;
2145 }
2146 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002147 continue;
2148 }
Ted Kremenek47695c82011-08-18 22:25:21 +00002149
Douglas Gregorf3db29f2011-02-25 18:19:59 +00002150 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2151 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2152 if (VisitNestedNameSpecifierLoc(V->get()))
2153 return true;
2154 continue;
2155 }
2156
Ted Kremenekf64d8032010-11-18 00:02:32 +00002157 case VisitorJob::DeclarationNameInfoVisitKind: {
2158 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2159 ->get()))
2160 return true;
2161 continue;
2162 }
Ted Kremenekcdba6592010-11-18 00:42:18 +00002163 case VisitorJob::MemberRefVisitKind: {
2164 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2165 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2166 return true;
2167 continue;
2168 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002169 case VisitorJob::StmtVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002170 Stmt *S = cast<StmtVisit>(&LI)->get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00002171 if (!S)
2172 continue;
2173
Ted Kremenekf1107452010-11-12 18:26:56 +00002174 // Update the current cursor.
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002175 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
Ted Kremenekcdba6592010-11-18 00:42:18 +00002176 if (!IsInRegionOfInterest(Cursor))
2177 continue;
2178 switch (Visitor(Cursor, Parent, ClientData)) {
2179 case CXChildVisit_Break: return true;
2180 case CXChildVisit_Continue: break;
2181 case CXChildVisit_Recurse:
2182 EnqueueWorkList(WL, S);
Ted Kremenek82f3c502010-11-15 22:23:26 +00002183 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002184 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00002185 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002186 }
2187 case VisitorJob::MemberExprPartsKind: {
2188 // Handle the other pieces in the MemberExpr besides the base.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002189 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002190
2191 // Visit the nested-name-specifier
Douglas Gregor40d96a62011-02-28 21:54:11 +00002192 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
2193 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002194 return true;
2195
2196 // Visit the declaration name.
2197 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2198 return true;
2199
2200 // Visit the explicitly-specified template arguments, if any.
2201 if (M->hasExplicitTemplateArgs()) {
2202 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2203 *ArgEnd = Arg + M->getNumTemplateArgs();
2204 Arg != ArgEnd; ++Arg) {
2205 if (VisitTemplateArgumentLoc(*Arg))
2206 return true;
2207 }
2208 }
2209 continue;
2210 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002211 case VisitorJob::DeclRefExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002212 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002213 // Visit nested-name-specifier, if present.
Douglas Gregor40d96a62011-02-28 21:54:11 +00002214 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
2215 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002216 return true;
2217 // Visit declaration name.
2218 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2219 return true;
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002220 continue;
2221 }
Ted Kremenek60458782010-11-12 21:34:16 +00002222 case VisitorJob::OverloadExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002223 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Ted Kremenek60458782010-11-12 21:34:16 +00002224 // Visit the nested-name-specifier.
Douglas Gregor4c9be892011-02-28 20:01:57 +00002225 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
2226 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenek60458782010-11-12 21:34:16 +00002227 return true;
2228 // Visit the declaration name.
2229 if (VisitDeclarationNameInfo(O->getNameInfo()))
2230 return true;
2231 // Visit the overloaded declaration reference.
2232 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2233 return true;
Ted Kremenek60458782010-11-12 21:34:16 +00002234 continue;
2235 }
Douglas Gregor94d96292011-01-19 20:34:17 +00002236 case VisitorJob::SizeOfPackExprPartsKind: {
2237 SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
2238 NamedDecl *Pack = E->getPack();
2239 if (isa<TemplateTypeParmDecl>(Pack)) {
2240 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
2241 E->getPackLoc(), TU)))
2242 return true;
2243
2244 continue;
2245 }
2246
2247 if (isa<TemplateTemplateParmDecl>(Pack)) {
2248 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
2249 E->getPackLoc(), TU)))
2250 return true;
2251
2252 continue;
2253 }
2254
2255 // Non-type template parameter packs and function parameter packs are
2256 // treated like DeclRefExpr cursors.
2257 continue;
2258 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002259 }
2260 }
2261 return false;
2262}
2263
Ted Kremenekcdba6592010-11-18 00:42:18 +00002264bool CursorVisitor::Visit(Stmt *S) {
Ted Kremenekd1ded662010-11-15 23:31:32 +00002265 VisitorWorkList *WL = 0;
2266 if (!WorkListFreeList.empty()) {
2267 WL = WorkListFreeList.back();
2268 WL->clear();
2269 WorkListFreeList.pop_back();
2270 }
2271 else {
2272 WL = new VisitorWorkList();
2273 WorkListCache.push_back(WL);
2274 }
2275 EnqueueWorkList(*WL, S);
2276 bool result = RunVisitorWorkList(*WL);
2277 WorkListFreeList.push_back(WL);
2278 return result;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002279}
2280
Francois Pichet48a8d142011-07-25 22:00:44 +00002281namespace {
2282typedef llvm::SmallVector<SourceRange, 4> RefNamePieces;
2283RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
2284 const DeclarationNameInfo &NI,
2285 const SourceRange &QLoc,
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00002286 const ASTTemplateArgumentListInfo *TemplateArgs = 0){
Francois Pichet48a8d142011-07-25 22:00:44 +00002287 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
2288 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
2289 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
2290
2291 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
2292
2293 RefNamePieces Pieces;
2294
2295 if (WantQualifier && QLoc.isValid())
2296 Pieces.push_back(QLoc);
2297
2298 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
2299 Pieces.push_back(NI.getLoc());
2300
2301 if (WantTemplateArgs && TemplateArgs)
2302 Pieces.push_back(SourceRange(TemplateArgs->LAngleLoc,
2303 TemplateArgs->RAngleLoc));
2304
2305 if (Kind == DeclarationName::CXXOperatorName) {
2306 Pieces.push_back(SourceLocation::getFromRawEncoding(
2307 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
2308 Pieces.push_back(SourceLocation::getFromRawEncoding(
2309 NI.getInfo().CXXOperatorName.EndOpNameLoc));
2310 }
2311
2312 if (WantSinglePiece) {
2313 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
2314 Pieces.clear();
2315 Pieces.push_back(R);
2316 }
2317
2318 return Pieces;
2319}
2320}
2321
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002322//===----------------------------------------------------------------------===//
2323// Misc. API hooks.
2324//===----------------------------------------------------------------------===//
2325
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002326static llvm::sys::Mutex EnableMultithreadingMutex;
2327static bool EnabledMultithreading;
2328
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002329extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002330CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2331 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002332 // Disable pretty stack trace functionality, which will otherwise be a very
2333 // poor citizen of the world and set up all sorts of signal handlers.
2334 llvm::DisablePrettyStackTrace = true;
2335
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002336 // We use crash recovery to make some of our APIs more reliable, implicitly
2337 // enable it.
2338 llvm::CrashRecoveryContext::Enable();
2339
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002340 // Enable support for multithreading in LLVM.
2341 {
2342 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2343 if (!EnabledMultithreading) {
2344 llvm::llvm_start_multithreaded();
2345 EnabledMultithreading = true;
2346 }
2347 }
2348
Douglas Gregora030b7c2010-01-22 20:35:53 +00002349 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002350 if (excludeDeclarationsFromPCH)
2351 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002352 if (displayDiagnostics)
2353 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002354 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002355}
2356
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002357void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002358 if (CIdx)
2359 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002360}
2361
Ted Kremenekd2427dd2011-03-18 23:05:39 +00002362void clang_toggleCrashRecovery(unsigned isEnabled) {
2363 if (isEnabled)
2364 llvm::CrashRecoveryContext::Enable();
2365 else
2366 llvm::CrashRecoveryContext::Disable();
2367}
2368
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002369CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002370 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002371 if (!CIdx)
2372 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002373
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002374 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002375 FileSystemOptions FileSystemOpts;
2376 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002377
David Blaikied6471f72011-09-25 23:23:43 +00002378 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002379 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002380 CXXIdx->getOnlyLocalDecls(),
2381 0, 0, true);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002382 return MakeCXTranslationUnit(TU);
Steve Naroff600866c2009-08-27 19:51:58 +00002383}
2384
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002385unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002386 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregorb5af8432011-08-25 22:54:01 +00002387 CXTranslationUnit_CacheCompletionResults;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002388}
2389
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002390CXTranslationUnit
2391clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2392 const char *source_filename,
2393 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002394 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002395 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002396 struct CXUnsavedFile *unsaved_files) {
Douglas Gregordca8ee82011-05-06 16:33:08 +00002397 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord |
Chandler Carruthba7537f2011-07-14 09:02:10 +00002398 CXTranslationUnit_NestedMacroExpansions;
Douglas Gregor5a430212010-07-21 18:52:53 +00002399 return clang_parseTranslationUnit(CIdx, source_filename,
2400 command_line_args, num_command_line_args,
2401 unsaved_files, num_unsaved_files,
Douglas Gregordca8ee82011-05-06 16:33:08 +00002402 Options);
Douglas Gregor5a430212010-07-21 18:52:53 +00002403}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002404
2405struct ParseTranslationUnitInfo {
2406 CXIndex CIdx;
2407 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002408 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002409 int num_command_line_args;
2410 struct CXUnsavedFile *unsaved_files;
2411 unsigned num_unsaved_files;
2412 unsigned options;
2413 CXTranslationUnit result;
2414};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002415static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002416 ParseTranslationUnitInfo *PTUI =
2417 static_cast<ParseTranslationUnitInfo*>(UserData);
2418 CXIndex CIdx = PTUI->CIdx;
2419 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002420 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002421 int num_command_line_args = PTUI->num_command_line_args;
2422 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2423 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2424 unsigned options = PTUI->options;
2425 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002426
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002427 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002428 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002429
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002430 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2431
Douglas Gregor44c181a2010-07-23 00:33:23 +00002432 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregor467dc882011-08-25 22:30:56 +00002433 // FIXME: Add a flag for modules.
2434 TranslationUnitKind TUKind
2435 = (options & CXTranslationUnit_Incomplete)? TU_Prefix : TU_Complete;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002436 bool CacheCodeCompetionResults
2437 = options & CXTranslationUnit_CacheCompletionResults;
2438
Douglas Gregor5352ac02010-01-28 00:27:43 +00002439 // Configure the diagnostics.
2440 DiagnosticOptions DiagOpts;
David Blaikied6471f72011-09-25 23:23:43 +00002441 llvm::IntrusiveRefCntPtr<DiagnosticsEngine>
Ted Kremenek25a11e12011-03-22 01:15:24 +00002442 Diags(CompilerInstance::createDiagnostics(DiagOpts, num_command_line_args,
2443 command_line_args));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002444
Ted Kremenek25a11e12011-03-22 01:15:24 +00002445 // Recover resources if we crash before exiting this function.
David Blaikied6471f72011-09-25 23:23:43 +00002446 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
2447 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00002448 DiagCleanup(Diags.getPtr());
2449
2450 llvm::OwningPtr<std::vector<ASTUnit::RemappedFile> >
2451 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2452
2453 // Recover resources if we crash before exiting this function.
2454 llvm::CrashRecoveryContextCleanupRegistrar<
2455 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2456
Douglas Gregor4db64a42010-01-23 00:14:00 +00002457 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002458 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002459 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002460 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002461 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2462 Buffer));
Douglas Gregor4db64a42010-01-23 00:14:00 +00002463 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002464
Ted Kremenek25a11e12011-03-22 01:15:24 +00002465 llvm::OwningPtr<std::vector<const char *> >
2466 Args(new std::vector<const char*>());
2467
2468 // Recover resources if we crash before exiting this method.
2469 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
2470 ArgsCleanup(Args.get());
2471
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002472 // Since the Clang C library is primarily used by batch tools dealing with
2473 // (often very broken) source code, where spell-checking can have a
2474 // significant negative impact on performance (particularly when
2475 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002476 // Only do this if we haven't found a spell-checking-related argument.
2477 bool FoundSpellCheckingArgument = false;
2478 for (int I = 0; I != num_command_line_args; ++I) {
2479 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2480 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2481 FoundSpellCheckingArgument = true;
2482 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002483 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002484 }
2485 if (!FoundSpellCheckingArgument)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002486 Args->push_back("-fno-spell-checking");
Douglas Gregorb10daed2010-10-11 16:52:23 +00002487
Ted Kremenek25a11e12011-03-22 01:15:24 +00002488 Args->insert(Args->end(), command_line_args,
2489 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002490
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002491 // The 'source_filename' argument is optional. If the caller does not
2492 // specify it then it is assumed that the source file is specified
2493 // in the actual argument list.
2494 // Put the source file after command_line_args otherwise if '-x' flag is
2495 // present it will be unused.
2496 if (source_filename)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002497 Args->push_back(source_filename);
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002498
Douglas Gregor44c181a2010-07-23 00:33:23 +00002499 // Do we need the detailed preprocessing record?
Chandler Carruthba7537f2011-07-14 09:02:10 +00002500 bool NestedMacroExpansions = false;
Douglas Gregor44c181a2010-07-23 00:33:23 +00002501 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Ted Kremenek25a11e12011-03-22 01:15:24 +00002502 Args->push_back("-Xclang");
2503 Args->push_back("-detailed-preprocessing-record");
Chandler Carruthba7537f2011-07-14 09:02:10 +00002504 NestedMacroExpansions
2505 = (options & CXTranslationUnit_NestedMacroExpansions);
Douglas Gregor44c181a2010-07-23 00:33:23 +00002506 }
2507
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002508 unsigned NumErrors = Diags->getClient()->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002509 llvm::OwningPtr<ASTUnit> Unit(
Ted Kremenek4ee99262011-03-22 20:16:19 +00002510 ASTUnit::LoadFromCommandLine(Args->size() ? &(*Args)[0] : 0
2511 /* vector::data() not portable */,
2512 Args->size() ? (&(*Args)[0] + Args->size()) :0,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002513 Diags,
2514 CXXIdx->getClangResourcesPath(),
2515 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002516 /*CaptureDiagnostics=*/true,
Ted Kremenek4ee99262011-03-22 20:16:19 +00002517 RemappedFiles->size() ? &(*RemappedFiles)[0]:0,
Ted Kremenek25a11e12011-03-22 01:15:24 +00002518 RemappedFiles->size(),
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00002519 /*RemappedFilesKeepOriginalName=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002520 PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00002521 TUKind,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002522 CacheCodeCompetionResults,
Chandler Carruthba7537f2011-07-14 09:02:10 +00002523 NestedMacroExpansions));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002524
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002525 if (NumErrors != Diags->getClient()->getNumErrors()) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002526 // Make sure to check that 'Unit' is non-NULL.
2527 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2528 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2529 DEnd = Unit->stored_diag_end();
2530 D != DEnd; ++D) {
2531 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2532 CXString Msg = clang_formatDiagnostic(&Diag,
2533 clang_defaultDiagnosticDisplayOptions());
2534 fprintf(stderr, "%s\n", clang_getCString(Msg));
2535 clang_disposeString(Msg);
2536 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002537#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002538 // On Windows, force a flush, since there may be multiple copies of
2539 // stderr and stdout in the file system, all with different buffers
2540 // but writing to the same device.
2541 fflush(stderr);
2542#endif
2543 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002544 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002545
Ted Kremeneka60ed472010-11-16 08:15:36 +00002546 PTUI->result = MakeCXTranslationUnit(Unit.take());
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002547}
2548CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2549 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002550 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002551 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002552 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002553 unsigned num_unsaved_files,
2554 unsigned options) {
2555 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002556 num_command_line_args, unsaved_files,
2557 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002558 llvm::CrashRecoveryContext CRC;
2559
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002560 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002561 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2562 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2563 fprintf(stderr, " 'command_line_args' : [");
2564 for (int i = 0; i != num_command_line_args; ++i) {
2565 if (i)
2566 fprintf(stderr, ", ");
2567 fprintf(stderr, "'%s'", command_line_args[i]);
2568 }
2569 fprintf(stderr, "],\n");
2570 fprintf(stderr, " 'unsaved_files' : [");
2571 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2572 if (i)
2573 fprintf(stderr, ", ");
2574 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2575 unsaved_files[i].Length);
2576 }
2577 fprintf(stderr, "],\n");
2578 fprintf(stderr, " 'options' : %d,\n", options);
2579 fprintf(stderr, "}\n");
2580
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002581 return 0;
Douglas Gregor6df78732011-05-05 20:27:22 +00002582 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
2583 PrintLibclangResourceUsage(PTUI.result);
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002584 }
Douglas Gregor6df78732011-05-05 20:27:22 +00002585
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002586 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002587}
2588
Douglas Gregor19998442010-08-13 15:35:05 +00002589unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2590 return CXSaveTranslationUnit_None;
2591}
2592
2593int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2594 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002595 if (!TU)
Douglas Gregor39c411f2011-07-06 16:43:36 +00002596 return CXSaveError_InvalidTU;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002597
Douglas Gregor39c411f2011-07-06 16:43:36 +00002598 CXSaveError result = static_cast<ASTUnit *>(TU->TUData)->Save(FileName);
Douglas Gregor6df78732011-05-05 20:27:22 +00002599 if (getenv("LIBCLANG_RESOURCE_USAGE"))
2600 PrintLibclangResourceUsage(TU);
2601 return result;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002602}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002603
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002604void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002605 if (CTUnit) {
2606 // If the translation unit has been marked as unsafe to free, just discard
2607 // it.
Ted Kremeneka60ed472010-11-16 08:15:36 +00002608 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002609 return;
2610
Ted Kremeneka60ed472010-11-16 08:15:36 +00002611 delete static_cast<ASTUnit *>(CTUnit->TUData);
2612 disposeCXStringPool(CTUnit->StringPool);
Ted Kremenek15322172011-11-10 08:43:12 +00002613 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002614 delete CTUnit;
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002615 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002616}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002617
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002618unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2619 return CXReparse_None;
2620}
2621
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002622struct ReparseTranslationUnitInfo {
2623 CXTranslationUnit TU;
2624 unsigned num_unsaved_files;
2625 struct CXUnsavedFile *unsaved_files;
2626 unsigned options;
2627 int result;
2628};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002629
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002630static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002631 ReparseTranslationUnitInfo *RTUI =
2632 static_cast<ReparseTranslationUnitInfo*>(UserData);
2633 CXTranslationUnit TU = RTUI->TU;
Ted Kremenek15322172011-11-10 08:43:12 +00002634
2635 // Reset the associated diagnostics.
2636 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
2637 TU->Diagnostics = 0;
2638
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002639 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2640 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2641 unsigned options = RTUI->options;
2642 (void) options;
2643 RTUI->result = 1;
2644
Douglas Gregorabc563f2010-07-19 21:46:24 +00002645 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002646 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002647
Ted Kremeneka60ed472010-11-16 08:15:36 +00002648 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor593b0c12010-09-23 18:47:53 +00002649 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002650
Ted Kremenek25a11e12011-03-22 01:15:24 +00002651 llvm::OwningPtr<std::vector<ASTUnit::RemappedFile> >
2652 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2653
2654 // Recover resources if we crash before exiting this function.
2655 llvm::CrashRecoveryContextCleanupRegistrar<
2656 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2657
Douglas Gregorabc563f2010-07-19 21:46:24 +00002658 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002659 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002660 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002661 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002662 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2663 Buffer));
Douglas Gregorabc563f2010-07-19 21:46:24 +00002664 }
2665
Ted Kremenek4ee99262011-03-22 20:16:19 +00002666 if (!CXXUnit->Reparse(RemappedFiles->size() ? &(*RemappedFiles)[0] : 0,
2667 RemappedFiles->size()))
Douglas Gregor593b0c12010-09-23 18:47:53 +00002668 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002669}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002670
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002671int clang_reparseTranslationUnit(CXTranslationUnit TU,
2672 unsigned num_unsaved_files,
2673 struct CXUnsavedFile *unsaved_files,
2674 unsigned options) {
2675 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2676 options, 0 };
Argyrios Kyrtzidis8c4b47e2011-10-28 22:54:33 +00002677
Argyrios Kyrtzidise7de9b42011-10-29 19:32:39 +00002678 if (getenv("LIBCLANG_NOTHREADS")) {
Argyrios Kyrtzidis8c4b47e2011-10-28 22:54:33 +00002679 clang_reparseTranslationUnit_Impl(&RTUI);
2680 return RTUI.result;
2681 }
2682
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002683 llvm::CrashRecoveryContext CRC;
2684
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002685 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002686 fprintf(stderr, "libclang: crash detected during reparsing\n");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002687 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002688 return 1;
Douglas Gregor6df78732011-05-05 20:27:22 +00002689 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
2690 PrintLibclangResourceUsage(TU);
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002691
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002692 return RTUI.result;
2693}
2694
Douglas Gregordf95a132010-08-09 20:45:32 +00002695
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002696CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002697 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002698 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002699
Ted Kremeneka60ed472010-11-16 08:15:36 +00002700 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002701 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002702}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002703
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002704CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002705 CXCursor Result = { CXCursor_TranslationUnit, 0, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002706 return Result;
2707}
2708
Ted Kremenekfb480492010-01-13 21:46:36 +00002709} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002710
Ted Kremenekfb480492010-01-13 21:46:36 +00002711//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002712// CXFile Operations.
2713//===----------------------------------------------------------------------===//
2714
2715extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002716CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002717 if (!SFile)
Ted Kremeneka60ed472010-11-16 08:15:36 +00002718 return createCXString((const char*)NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002719
Steve Naroff88145032009-10-27 14:35:18 +00002720 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002721 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002722}
2723
2724time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002725 if (!SFile)
2726 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002727
Steve Naroff88145032009-10-27 14:35:18 +00002728 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2729 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002730}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002731
Douglas Gregorb9790342010-01-22 21:44:22 +00002732CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2733 if (!tu)
2734 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002735
Ted Kremeneka60ed472010-11-16 08:15:36 +00002736 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002737
Douglas Gregorb9790342010-01-22 21:44:22 +00002738 FileManager &FMgr = CXXUnit->getFileManager();
Chris Lattner39b49bc2010-11-23 08:35:12 +00002739 return const_cast<FileEntry *>(FMgr.getFile(file_name));
Douglas Gregorb9790342010-01-22 21:44:22 +00002740}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002741
Douglas Gregordd3e5542011-05-04 00:14:37 +00002742unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit tu, CXFile file) {
2743 if (!tu || !file)
2744 return 0;
2745
2746 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
2747 FileEntry *FEnt = static_cast<FileEntry *>(file);
2748 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
2749 .isFileMultipleIncludeGuarded(FEnt);
2750}
2751
Ted Kremenekfb480492010-01-13 21:46:36 +00002752} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002753
Ted Kremenekfb480492010-01-13 21:46:36 +00002754//===----------------------------------------------------------------------===//
2755// CXCursor Operations.
2756//===----------------------------------------------------------------------===//
2757
Ted Kremenekfb480492010-01-13 21:46:36 +00002758static Decl *getDeclFromExpr(Stmt *E) {
Argyrios Kyrtzidisc2954612011-09-12 22:17:26 +00002759 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Douglas Gregordb1314e2010-10-01 21:11:22 +00002760 return getDeclFromExpr(CE->getSubExpr());
2761
Ted Kremenekfb480492010-01-13 21:46:36 +00002762 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2763 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002764 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2765 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002766 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2767 return ME->getMemberDecl();
2768 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2769 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002770 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
John McCall12f78a62010-12-02 01:19:52 +00002771 return PRE->isExplicitProperty() ? PRE->getExplicitProperty() : 0;
John McCall4b9c2d22011-11-06 09:01:30 +00002772 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
2773 return getDeclFromExpr(POE->getSyntacticForm());
2774 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
2775 if (Expr *Src = OVE->getSourceExpr())
2776 return getDeclFromExpr(Src);
Douglas Gregordb1314e2010-10-01 21:11:22 +00002777
Ted Kremenekfb480492010-01-13 21:46:36 +00002778 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2779 return getDeclFromExpr(CE->getCallee());
Chris Lattner5f9e2722011-07-23 10:55:15 +00002780 if (CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Douglas Gregor93798e22010-11-05 21:11:19 +00002781 if (!CE->isElidable())
2782 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002783 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2784 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002785
Douglas Gregordb1314e2010-10-01 21:11:22 +00002786 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2787 return PE->getProtocol();
Douglas Gregorc7793c72011-01-15 01:15:58 +00002788 if (SubstNonTypeTemplateParmPackExpr *NTTP
2789 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
2790 return NTTP->getParameterPack();
Douglas Gregor94d96292011-01-19 20:34:17 +00002791 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2792 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
2793 isa<ParmVarDecl>(SizeOfPack->getPack()))
2794 return SizeOfPack->getPack();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002795
Ted Kremenekfb480492010-01-13 21:46:36 +00002796 return 0;
2797}
2798
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002799static SourceLocation getLocationFromExpr(Expr *E) {
Argyrios Kyrtzidisc2954612011-09-12 22:17:26 +00002800 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
2801 return getLocationFromExpr(CE->getSubExpr());
2802
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002803 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2804 return /*FIXME:*/Msg->getLeftLoc();
2805 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2806 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002807 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2808 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002809 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2810 return Member->getMemberLoc();
2811 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2812 return Ivar->getLocation();
Douglas Gregor94d96292011-01-19 20:34:17 +00002813 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2814 return SizeOfPack->getPackLoc();
2815
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002816 return E->getLocStart();
2817}
2818
Ted Kremenekfb480492010-01-13 21:46:36 +00002819extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002820
2821unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002822 CXCursorVisitor visitor,
2823 CXClientData client_data) {
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00002824 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
2825 /*VisitPreprocessorLast=*/false);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002826 return CursorVis.VisitChildren(parent);
2827}
2828
David Chisnall3387c652010-11-03 14:12:26 +00002829#ifndef __has_feature
2830#define __has_feature(x) 0
2831#endif
2832#if __has_feature(blocks)
2833typedef enum CXChildVisitResult
2834 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2835
2836static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2837 CXClientData client_data) {
2838 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2839 return block(cursor, parent);
2840}
2841#else
2842// If we are compiled with a compiler that doesn't have native blocks support,
2843// define and call the block manually, so the
2844typedef struct _CXChildVisitResult
2845{
2846 void *isa;
2847 int flags;
2848 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002849 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2850 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00002851} *CXCursorVisitorBlock;
2852
2853static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2854 CXClientData client_data) {
2855 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2856 return block->invoke(block, cursor, parent);
2857}
2858#endif
2859
2860
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002861unsigned clang_visitChildrenWithBlock(CXCursor parent,
2862 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00002863 return clang_visitChildren(parent, visitWithBlock, block);
2864}
2865
Douglas Gregor78205d42010-01-20 21:45:58 +00002866static CXString getDeclSpelling(Decl *D) {
2867 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
Douglas Gregore3c60a72010-11-17 00:13:31 +00002868 if (!ND) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002869 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00002870 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
2871 return createCXString(Property->getIdentifier()->getName());
2872
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002873 return createCXString("");
Douglas Gregore3c60a72010-11-17 00:13:31 +00002874 }
2875
Douglas Gregor78205d42010-01-20 21:45:58 +00002876 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002877 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002878
Douglas Gregor78205d42010-01-20 21:45:58 +00002879 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2880 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2881 // and returns different names. NamedDecl returns the class name and
2882 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002883 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002884
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002885 if (isa<UsingDirectiveDecl>(D))
2886 return createCXString("");
2887
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002888 llvm::SmallString<1024> S;
2889 llvm::raw_svector_ostream os(S);
2890 ND->printName(os);
2891
2892 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002893}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002894
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002895CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002896 if (clang_isTranslationUnit(C.kind))
Ted Kremeneka60ed472010-11-16 08:15:36 +00002897 return clang_getTranslationUnitSpelling(
2898 static_cast<CXTranslationUnit>(C.data[2]));
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002899
Steve Narofff334b4e2009-09-02 18:26:48 +00002900 if (clang_isReference(C.kind)) {
2901 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002902 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002903 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002904 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002905 }
2906 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002907 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002908 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002909 }
2910 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002911 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002912 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002913 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002914 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002915 case CXCursor_CXXBaseSpecifier: {
2916 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2917 return createCXString(B->getType().getAsString());
2918 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002919 case CXCursor_TypeRef: {
2920 TypeDecl *Type = getCursorTypeRef(C).first;
2921 assert(Type && "Missing type decl");
2922
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002923 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2924 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002925 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002926 case CXCursor_TemplateRef: {
2927 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002928 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002929
2930 return createCXString(Template->getNameAsString());
2931 }
Douglas Gregor69319002010-08-31 23:48:11 +00002932
2933 case CXCursor_NamespaceRef: {
2934 NamedDecl *NS = getCursorNamespaceRef(C).first;
2935 assert(NS && "Missing namespace decl");
2936
2937 return createCXString(NS->getNameAsString());
2938 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002939
Douglas Gregora67e03f2010-09-09 21:42:20 +00002940 case CXCursor_MemberRef: {
2941 FieldDecl *Field = getCursorMemberRef(C).first;
2942 assert(Field && "Missing member decl");
2943
2944 return createCXString(Field->getNameAsString());
2945 }
2946
Douglas Gregor36897b02010-09-10 00:22:18 +00002947 case CXCursor_LabelRef: {
2948 LabelStmt *Label = getCursorLabelRef(C).first;
2949 assert(Label && "Missing label");
2950
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002951 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00002952 }
2953
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002954 case CXCursor_OverloadedDeclRef: {
2955 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2956 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2957 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2958 return createCXString(ND->getNameAsString());
2959 return createCXString("");
2960 }
2961 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2962 return createCXString(E->getName().getAsString());
2963 OverloadedTemplateStorage *Ovl
2964 = Storage.get<OverloadedTemplateStorage*>();
2965 if (Ovl->size() == 0)
2966 return createCXString("");
2967 return createCXString((*Ovl->begin())->getNameAsString());
2968 }
2969
Daniel Dunbaracca7252009-11-30 20:42:49 +00002970 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002971 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002972 }
2973 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002974
2975 if (clang_isExpression(C.kind)) {
2976 Decl *D = getDeclFromExpr(getCursorExpr(C));
2977 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002978 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002979 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002980 }
2981
Douglas Gregor36897b02010-09-10 00:22:18 +00002982 if (clang_isStatement(C.kind)) {
2983 Stmt *S = getCursorStmt(C);
2984 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002985 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00002986
2987 return createCXString("");
2988 }
2989
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00002990 if (C.kind == CXCursor_MacroExpansion)
Chandler Carruth9e5bb852011-07-14 08:20:46 +00002991 return createCXString(getCursorMacroExpansion(C)->getName()
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002992 ->getNameStart());
2993
Douglas Gregor572feb22010-03-18 18:04:21 +00002994 if (C.kind == CXCursor_MacroDefinition)
2995 return createCXString(getCursorMacroDefinition(C)->getName()
2996 ->getNameStart());
2997
Douglas Gregorecdcb882010-10-20 22:00:55 +00002998 if (C.kind == CXCursor_InclusionDirective)
2999 return createCXString(getCursorInclusionDirective(C)->getFileName());
3000
Douglas Gregor60cbfac2010-01-25 16:56:17 +00003001 if (clang_isDeclaration(C.kind))
3002 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00003003
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00003004 if (C.kind == CXCursor_AnnotateAttr) {
3005 AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
3006 return createCXString(AA->getAnnotation());
3007 }
3008
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003009 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00003010}
3011
Douglas Gregor358559d2010-10-02 22:49:11 +00003012CXString clang_getCursorDisplayName(CXCursor C) {
3013 if (!clang_isDeclaration(C.kind))
3014 return clang_getCursorSpelling(C);
3015
3016 Decl *D = getCursorDecl(C);
3017 if (!D)
3018 return createCXString("");
3019
Douglas Gregor30c42402011-09-27 22:38:19 +00003020 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
Douglas Gregor358559d2010-10-02 22:49:11 +00003021 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
3022 D = FunTmpl->getTemplatedDecl();
3023
3024 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
3025 llvm::SmallString<64> Str;
3026 llvm::raw_svector_ostream OS(Str);
3027 OS << Function->getNameAsString();
3028 if (Function->getPrimaryTemplate())
3029 OS << "<>";
3030 OS << "(";
3031 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
3032 if (I)
3033 OS << ", ";
3034 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
3035 }
3036
3037 if (Function->isVariadic()) {
3038 if (Function->getNumParams())
3039 OS << ", ";
3040 OS << "...";
3041 }
3042 OS << ")";
3043 return createCXString(OS.str());
3044 }
3045
3046 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
3047 llvm::SmallString<64> Str;
3048 llvm::raw_svector_ostream OS(Str);
3049 OS << ClassTemplate->getNameAsString();
3050 OS << "<";
3051 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
3052 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3053 if (I)
3054 OS << ", ";
3055
3056 NamedDecl *Param = Params->getParam(I);
3057 if (Param->getIdentifier()) {
3058 OS << Param->getIdentifier()->getName();
3059 continue;
3060 }
3061
3062 // There is no parameter name, which makes this tricky. Try to come up
3063 // with something useful that isn't too long.
3064 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3065 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
3066 else if (NonTypeTemplateParmDecl *NTTP
3067 = dyn_cast<NonTypeTemplateParmDecl>(Param))
3068 OS << NTTP->getType().getAsString(Policy);
3069 else
3070 OS << "template<...> class";
3071 }
3072
3073 OS << ">";
3074 return createCXString(OS.str());
3075 }
3076
3077 if (ClassTemplateSpecializationDecl *ClassSpec
3078 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
3079 // If the type was explicitly written, use that.
3080 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
3081 return createCXString(TSInfo->getType().getAsString(Policy));
3082
3083 llvm::SmallString<64> Str;
3084 llvm::raw_svector_ostream OS(Str);
3085 OS << ClassSpec->getNameAsString();
3086 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00003087 ClassSpec->getTemplateArgs().data(),
3088 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00003089 Policy);
3090 return createCXString(OS.str());
3091 }
3092
3093 return clang_getCursorSpelling(C);
3094}
3095
Ted Kremeneke68fff62010-02-17 00:41:32 +00003096CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00003097 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00003098 case CXCursor_FunctionDecl:
3099 return createCXString("FunctionDecl");
3100 case CXCursor_TypedefDecl:
3101 return createCXString("TypedefDecl");
3102 case CXCursor_EnumDecl:
3103 return createCXString("EnumDecl");
3104 case CXCursor_EnumConstantDecl:
3105 return createCXString("EnumConstantDecl");
3106 case CXCursor_StructDecl:
3107 return createCXString("StructDecl");
3108 case CXCursor_UnionDecl:
3109 return createCXString("UnionDecl");
3110 case CXCursor_ClassDecl:
3111 return createCXString("ClassDecl");
3112 case CXCursor_FieldDecl:
3113 return createCXString("FieldDecl");
3114 case CXCursor_VarDecl:
3115 return createCXString("VarDecl");
3116 case CXCursor_ParmDecl:
3117 return createCXString("ParmDecl");
3118 case CXCursor_ObjCInterfaceDecl:
3119 return createCXString("ObjCInterfaceDecl");
3120 case CXCursor_ObjCCategoryDecl:
3121 return createCXString("ObjCCategoryDecl");
3122 case CXCursor_ObjCProtocolDecl:
3123 return createCXString("ObjCProtocolDecl");
3124 case CXCursor_ObjCPropertyDecl:
3125 return createCXString("ObjCPropertyDecl");
3126 case CXCursor_ObjCIvarDecl:
3127 return createCXString("ObjCIvarDecl");
3128 case CXCursor_ObjCInstanceMethodDecl:
3129 return createCXString("ObjCInstanceMethodDecl");
3130 case CXCursor_ObjCClassMethodDecl:
3131 return createCXString("ObjCClassMethodDecl");
3132 case CXCursor_ObjCImplementationDecl:
3133 return createCXString("ObjCImplementationDecl");
3134 case CXCursor_ObjCCategoryImplDecl:
3135 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00003136 case CXCursor_CXXMethod:
3137 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003138 case CXCursor_UnexposedDecl:
3139 return createCXString("UnexposedDecl");
3140 case CXCursor_ObjCSuperClassRef:
3141 return createCXString("ObjCSuperClassRef");
3142 case CXCursor_ObjCProtocolRef:
3143 return createCXString("ObjCProtocolRef");
3144 case CXCursor_ObjCClassRef:
3145 return createCXString("ObjCClassRef");
3146 case CXCursor_TypeRef:
3147 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003148 case CXCursor_TemplateRef:
3149 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00003150 case CXCursor_NamespaceRef:
3151 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00003152 case CXCursor_MemberRef:
3153 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00003154 case CXCursor_LabelRef:
3155 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003156 case CXCursor_OverloadedDeclRef:
3157 return createCXString("OverloadedDeclRef");
Douglas Gregor42b29842011-10-05 19:00:14 +00003158 case CXCursor_IntegerLiteral:
3159 return createCXString("IntegerLiteral");
3160 case CXCursor_FloatingLiteral:
3161 return createCXString("FloatingLiteral");
3162 case CXCursor_ImaginaryLiteral:
3163 return createCXString("ImaginaryLiteral");
3164 case CXCursor_StringLiteral:
3165 return createCXString("StringLiteral");
3166 case CXCursor_CharacterLiteral:
3167 return createCXString("CharacterLiteral");
3168 case CXCursor_ParenExpr:
3169 return createCXString("ParenExpr");
3170 case CXCursor_UnaryOperator:
3171 return createCXString("UnaryOperator");
3172 case CXCursor_ArraySubscriptExpr:
3173 return createCXString("ArraySubscriptExpr");
3174 case CXCursor_BinaryOperator:
3175 return createCXString("BinaryOperator");
3176 case CXCursor_CompoundAssignOperator:
3177 return createCXString("CompoundAssignOperator");
3178 case CXCursor_ConditionalOperator:
3179 return createCXString("ConditionalOperator");
3180 case CXCursor_CStyleCastExpr:
3181 return createCXString("CStyleCastExpr");
3182 case CXCursor_CompoundLiteralExpr:
3183 return createCXString("CompoundLiteralExpr");
3184 case CXCursor_InitListExpr:
3185 return createCXString("InitListExpr");
3186 case CXCursor_AddrLabelExpr:
3187 return createCXString("AddrLabelExpr");
3188 case CXCursor_StmtExpr:
3189 return createCXString("StmtExpr");
3190 case CXCursor_GenericSelectionExpr:
3191 return createCXString("GenericSelectionExpr");
3192 case CXCursor_GNUNullExpr:
3193 return createCXString("GNUNullExpr");
3194 case CXCursor_CXXStaticCastExpr:
3195 return createCXString("CXXStaticCastExpr");
3196 case CXCursor_CXXDynamicCastExpr:
3197 return createCXString("CXXDynamicCastExpr");
3198 case CXCursor_CXXReinterpretCastExpr:
3199 return createCXString("CXXReinterpretCastExpr");
3200 case CXCursor_CXXConstCastExpr:
3201 return createCXString("CXXConstCastExpr");
3202 case CXCursor_CXXFunctionalCastExpr:
3203 return createCXString("CXXFunctionalCastExpr");
3204 case CXCursor_CXXTypeidExpr:
3205 return createCXString("CXXTypeidExpr");
3206 case CXCursor_CXXBoolLiteralExpr:
3207 return createCXString("CXXBoolLiteralExpr");
3208 case CXCursor_CXXNullPtrLiteralExpr:
3209 return createCXString("CXXNullPtrLiteralExpr");
3210 case CXCursor_CXXThisExpr:
3211 return createCXString("CXXThisExpr");
3212 case CXCursor_CXXThrowExpr:
3213 return createCXString("CXXThrowExpr");
3214 case CXCursor_CXXNewExpr:
3215 return createCXString("CXXNewExpr");
3216 case CXCursor_CXXDeleteExpr:
3217 return createCXString("CXXDeleteExpr");
3218 case CXCursor_UnaryExpr:
3219 return createCXString("UnaryExpr");
3220 case CXCursor_ObjCStringLiteral:
3221 return createCXString("ObjCStringLiteral");
3222 case CXCursor_ObjCEncodeExpr:
3223 return createCXString("ObjCEncodeExpr");
3224 case CXCursor_ObjCSelectorExpr:
3225 return createCXString("ObjCSelectorExpr");
3226 case CXCursor_ObjCProtocolExpr:
3227 return createCXString("ObjCProtocolExpr");
3228 case CXCursor_ObjCBridgedCastExpr:
3229 return createCXString("ObjCBridgedCastExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00003230 case CXCursor_BlockExpr:
3231 return createCXString("BlockExpr");
Douglas Gregor42b29842011-10-05 19:00:14 +00003232 case CXCursor_PackExpansionExpr:
3233 return createCXString("PackExpansionExpr");
3234 case CXCursor_SizeOfPackExpr:
3235 return createCXString("SizeOfPackExpr");
3236 case CXCursor_UnexposedExpr:
3237 return createCXString("UnexposedExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003238 case CXCursor_DeclRefExpr:
3239 return createCXString("DeclRefExpr");
3240 case CXCursor_MemberRefExpr:
3241 return createCXString("MemberRefExpr");
3242 case CXCursor_CallExpr:
3243 return createCXString("CallExpr");
3244 case CXCursor_ObjCMessageExpr:
3245 return createCXString("ObjCMessageExpr");
3246 case CXCursor_UnexposedStmt:
3247 return createCXString("UnexposedStmt");
Douglas Gregor42b29842011-10-05 19:00:14 +00003248 case CXCursor_DeclStmt:
3249 return createCXString("DeclStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00003250 case CXCursor_LabelStmt:
3251 return createCXString("LabelStmt");
Douglas Gregor42b29842011-10-05 19:00:14 +00003252 case CXCursor_CompoundStmt:
3253 return createCXString("CompoundStmt");
3254 case CXCursor_CaseStmt:
3255 return createCXString("CaseStmt");
3256 case CXCursor_DefaultStmt:
3257 return createCXString("DefaultStmt");
3258 case CXCursor_IfStmt:
3259 return createCXString("IfStmt");
3260 case CXCursor_SwitchStmt:
3261 return createCXString("SwitchStmt");
3262 case CXCursor_WhileStmt:
3263 return createCXString("WhileStmt");
3264 case CXCursor_DoStmt:
3265 return createCXString("DoStmt");
3266 case CXCursor_ForStmt:
3267 return createCXString("ForStmt");
3268 case CXCursor_GotoStmt:
3269 return createCXString("GotoStmt");
3270 case CXCursor_IndirectGotoStmt:
3271 return createCXString("IndirectGotoStmt");
3272 case CXCursor_ContinueStmt:
3273 return createCXString("ContinueStmt");
3274 case CXCursor_BreakStmt:
3275 return createCXString("BreakStmt");
3276 case CXCursor_ReturnStmt:
3277 return createCXString("ReturnStmt");
3278 case CXCursor_AsmStmt:
3279 return createCXString("AsmStmt");
3280 case CXCursor_ObjCAtTryStmt:
3281 return createCXString("ObjCAtTryStmt");
3282 case CXCursor_ObjCAtCatchStmt:
3283 return createCXString("ObjCAtCatchStmt");
3284 case CXCursor_ObjCAtFinallyStmt:
3285 return createCXString("ObjCAtFinallyStmt");
3286 case CXCursor_ObjCAtThrowStmt:
3287 return createCXString("ObjCAtThrowStmt");
3288 case CXCursor_ObjCAtSynchronizedStmt:
3289 return createCXString("ObjCAtSynchronizedStmt");
3290 case CXCursor_ObjCAutoreleasePoolStmt:
3291 return createCXString("ObjCAutoreleasePoolStmt");
3292 case CXCursor_ObjCForCollectionStmt:
3293 return createCXString("ObjCForCollectionStmt");
3294 case CXCursor_CXXCatchStmt:
3295 return createCXString("CXXCatchStmt");
3296 case CXCursor_CXXTryStmt:
3297 return createCXString("CXXTryStmt");
3298 case CXCursor_CXXForRangeStmt:
3299 return createCXString("CXXForRangeStmt");
3300 case CXCursor_SEHTryStmt:
3301 return createCXString("SEHTryStmt");
3302 case CXCursor_SEHExceptStmt:
3303 return createCXString("SEHExceptStmt");
3304 case CXCursor_SEHFinallyStmt:
3305 return createCXString("SEHFinallyStmt");
3306 case CXCursor_NullStmt:
3307 return createCXString("NullStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003308 case CXCursor_InvalidFile:
3309 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00003310 case CXCursor_InvalidCode:
3311 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003312 case CXCursor_NoDeclFound:
3313 return createCXString("NoDeclFound");
3314 case CXCursor_NotImplemented:
3315 return createCXString("NotImplemented");
3316 case CXCursor_TranslationUnit:
3317 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00003318 case CXCursor_UnexposedAttr:
3319 return createCXString("UnexposedAttr");
3320 case CXCursor_IBActionAttr:
3321 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003322 case CXCursor_IBOutletAttr:
3323 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003324 case CXCursor_IBOutletCollectionAttr:
3325 return createCXString("attribute(iboutletcollection)");
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00003326 case CXCursor_CXXFinalAttr:
3327 return createCXString("attribute(final)");
3328 case CXCursor_CXXOverrideAttr:
3329 return createCXString("attribute(override)");
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00003330 case CXCursor_AnnotateAttr:
3331 return createCXString("attribute(annotate)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003332 case CXCursor_PreprocessingDirective:
3333 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003334 case CXCursor_MacroDefinition:
3335 return createCXString("macro definition");
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003336 case CXCursor_MacroExpansion:
3337 return createCXString("macro expansion");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003338 case CXCursor_InclusionDirective:
3339 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003340 case CXCursor_Namespace:
3341 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003342 case CXCursor_LinkageSpec:
3343 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003344 case CXCursor_CXXBaseSpecifier:
3345 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003346 case CXCursor_Constructor:
3347 return createCXString("CXXConstructor");
3348 case CXCursor_Destructor:
3349 return createCXString("CXXDestructor");
3350 case CXCursor_ConversionFunction:
3351 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003352 case CXCursor_TemplateTypeParameter:
3353 return createCXString("TemplateTypeParameter");
3354 case CXCursor_NonTypeTemplateParameter:
3355 return createCXString("NonTypeTemplateParameter");
3356 case CXCursor_TemplateTemplateParameter:
3357 return createCXString("TemplateTemplateParameter");
3358 case CXCursor_FunctionTemplate:
3359 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003360 case CXCursor_ClassTemplate:
3361 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003362 case CXCursor_ClassTemplatePartialSpecialization:
3363 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003364 case CXCursor_NamespaceAlias:
3365 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003366 case CXCursor_UsingDirective:
3367 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003368 case CXCursor_UsingDeclaration:
3369 return createCXString("UsingDeclaration");
Richard Smith162e1c12011-04-15 14:24:37 +00003370 case CXCursor_TypeAliasDecl:
Douglas Gregor352697a2011-06-03 23:08:58 +00003371 return createCXString("TypeAliasDecl");
3372 case CXCursor_ObjCSynthesizeDecl:
3373 return createCXString("ObjCSynthesizeDecl");
3374 case CXCursor_ObjCDynamicDecl:
3375 return createCXString("ObjCDynamicDecl");
Argyrios Kyrtzidis2dfdb942011-09-30 17:58:23 +00003376 case CXCursor_CXXAccessSpecifier:
3377 return createCXString("CXXAccessSpecifier");
Steve Naroff89922f82009-08-31 00:59:03 +00003378 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003379
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003380 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneka60ed472010-11-16 08:15:36 +00003381 return createCXString((const char*) 0);
Steve Naroff600866c2009-08-27 19:51:58 +00003382}
Steve Naroff89922f82009-08-31 00:59:03 +00003383
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003384struct GetCursorData {
3385 SourceLocation TokenBeginLoc;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003386 bool PointsAtMacroArgExpansion;
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003387 CXCursor &BestCursor;
3388
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003389 GetCursorData(SourceManager &SM,
3390 SourceLocation tokenBegin, CXCursor &outputCursor)
3391 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
3392 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
3393 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003394};
3395
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003396static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3397 CXCursor parent,
3398 CXClientData client_data) {
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003399 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
3400 CXCursor *BestCursor = &Data->BestCursor;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003401
3402 // If we point inside a macro argument we should provide info of what the
3403 // token is so use the actual cursor, don't replace it with a macro expansion
3404 // cursor.
3405 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
3406 return CXChildVisit_Recurse;
Argyrios Kyrtzidis65ab9072011-09-26 19:05:37 +00003407
3408 if (clang_isDeclaration(cursor.kind)) {
3409 // Avoid having the implicit methods override the property decls.
3410 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(getCursorDecl(cursor)))
3411 if (MD->isImplicit())
3412 return CXChildVisit_Break;
3413 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003414
3415 if (clang_isExpression(cursor.kind) &&
3416 clang_isDeclaration(BestCursor->kind)) {
3417 Decl *D = getCursorDecl(*BestCursor);
3418
3419 // Avoid having the cursor of an expression replace the declaration cursor
3420 // when the expression source range overlaps the declaration range.
3421 // This can happen for C++ constructor expressions whose range generally
3422 // include the variable declaration, e.g.:
3423 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
3424 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
3425 D->getLocation() == Data->TokenBeginLoc)
3426 return CXChildVisit_Break;
3427 }
3428
Douglas Gregor93798e22010-11-05 21:11:19 +00003429 // If our current best cursor is the construction of a temporary object,
3430 // don't replace that cursor with a type reference, because we want
3431 // clang_getCursor() to point at the constructor.
3432 if (clang_isExpression(BestCursor->kind) &&
3433 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003434 cursor.kind == CXCursor_TypeRef) {
3435 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
3436 // as having the actual point on the type reference.
3437 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
Douglas Gregor93798e22010-11-05 21:11:19 +00003438 return CXChildVisit_Recurse;
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003439 }
Douglas Gregor93798e22010-11-05 21:11:19 +00003440
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003441 *BestCursor = cursor;
3442 return CXChildVisit_Recurse;
3443}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003444
Douglas Gregorb9790342010-01-22 21:44:22 +00003445CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3446 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003447 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003448
Ted Kremeneka60ed472010-11-16 08:15:36 +00003449 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003450 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3451
Ted Kremeneka297de22010-01-25 22:34:44 +00003452 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003453 CXCursor Result = cxcursor::getCursor(TU, SLoc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003454
Douglas Gregor40749ee2010-11-03 00:35:38 +00003455 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregor40749ee2010-11-03 00:35:38 +00003456 if (Logging) {
3457 CXFile SearchFile;
3458 unsigned SearchLine, SearchColumn;
3459 CXFile ResultFile;
3460 unsigned ResultLine, ResultColumn;
Douglas Gregor66537982010-11-17 17:14:07 +00003461 CXString SearchFileName, ResultFileName, KindSpelling, USR;
3462 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
Douglas Gregor40749ee2010-11-03 00:35:38 +00003463 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3464
Chandler Carruth20174222011-08-31 16:53:37 +00003465 clang_getExpansionLocation(Loc, &SearchFile, &SearchLine, &SearchColumn, 0);
3466 clang_getExpansionLocation(ResultLoc, &ResultFile, &ResultLine,
3467 &ResultColumn, 0);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003468 SearchFileName = clang_getFileName(SearchFile);
3469 ResultFileName = clang_getFileName(ResultFile);
3470 KindSpelling = clang_getCursorKindSpelling(Result.kind);
Douglas Gregor66537982010-11-17 17:14:07 +00003471 USR = clang_getCursorUSR(Result);
3472 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n",
Douglas Gregor40749ee2010-11-03 00:35:38 +00003473 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3474 clang_getCString(KindSpelling),
Douglas Gregor66537982010-11-17 17:14:07 +00003475 clang_getCString(ResultFileName), ResultLine, ResultColumn,
3476 clang_getCString(USR), IsDef);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003477 clang_disposeString(SearchFileName);
3478 clang_disposeString(ResultFileName);
3479 clang_disposeString(KindSpelling);
Douglas Gregor66537982010-11-17 17:14:07 +00003480 clang_disposeString(USR);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003481
3482 CXCursor Definition = clang_getCursorDefinition(Result);
3483 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
3484 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
3485 CXString DefinitionKindSpelling
3486 = clang_getCursorKindSpelling(Definition.kind);
3487 CXFile DefinitionFile;
3488 unsigned DefinitionLine, DefinitionColumn;
Chandler Carruth20174222011-08-31 16:53:37 +00003489 clang_getExpansionLocation(DefinitionLoc, &DefinitionFile,
3490 &DefinitionLine, &DefinitionColumn, 0);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003491 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
3492 fprintf(stderr, " -> %s(%s:%d:%d)\n",
3493 clang_getCString(DefinitionKindSpelling),
3494 clang_getCString(DefinitionFileName),
3495 DefinitionLine, DefinitionColumn);
3496 clang_disposeString(DefinitionFileName);
3497 clang_disposeString(DefinitionKindSpelling);
3498 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003499 }
3500
Ted Kremeneke68fff62010-02-17 00:41:32 +00003501 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003502}
3503
Ted Kremenek73885552009-11-17 19:28:59 +00003504CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003505 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003506}
3507
3508unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003509 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003510}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003511
Douglas Gregor9ce55842010-11-20 00:09:34 +00003512unsigned clang_hashCursor(CXCursor C) {
3513 unsigned Index = 0;
3514 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
3515 Index = 1;
3516
3517 return llvm::DenseMapInfo<std::pair<unsigned, void*> >::getHashValue(
3518 std::make_pair(C.kind, C.data[Index]));
3519}
3520
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003521unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003522 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3523}
3524
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003525unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003526 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3527}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003528
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003529unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003530 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3531}
3532
Douglas Gregor97b98722010-01-19 23:20:36 +00003533unsigned clang_isExpression(enum CXCursorKind K) {
3534 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3535}
3536
3537unsigned clang_isStatement(enum CXCursorKind K) {
3538 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3539}
3540
Douglas Gregor8be80e12011-07-06 03:00:34 +00003541unsigned clang_isAttribute(enum CXCursorKind K) {
3542 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
3543}
3544
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003545unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3546 return K == CXCursor_TranslationUnit;
3547}
3548
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003549unsigned clang_isPreprocessing(enum CXCursorKind K) {
3550 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3551}
3552
Ted Kremenekad6eff62010-03-08 21:17:29 +00003553unsigned clang_isUnexposed(enum CXCursorKind K) {
3554 switch (K) {
3555 case CXCursor_UnexposedDecl:
3556 case CXCursor_UnexposedExpr:
3557 case CXCursor_UnexposedStmt:
3558 case CXCursor_UnexposedAttr:
3559 return true;
3560 default:
3561 return false;
3562 }
3563}
3564
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003565CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003566 return C.kind;
3567}
3568
Douglas Gregor98258af2010-01-18 22:46:11 +00003569CXSourceLocation clang_getCursorLocation(CXCursor C) {
3570 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003571 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003572 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003573 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3574 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003575 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003576 }
3577
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003578 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003579 std::pair<ObjCProtocolDecl *, SourceLocation> P
3580 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003581 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003582 }
3583
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003584 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003585 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3586 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003587 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003588 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003589
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003590 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003591 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003592 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003593 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003594
3595 case CXCursor_TemplateRef: {
3596 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3597 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3598 }
3599
Douglas Gregor69319002010-08-31 23:48:11 +00003600 case CXCursor_NamespaceRef: {
3601 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3602 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3603 }
3604
Douglas Gregora67e03f2010-09-09 21:42:20 +00003605 case CXCursor_MemberRef: {
3606 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3607 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3608 }
3609
Ted Kremenek3064ef92010-08-27 21:34:58 +00003610 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003611 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3612 if (!BaseSpec)
3613 return clang_getNullLocation();
3614
3615 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3616 return cxloc::translateSourceLocation(getCursorContext(C),
3617 TSInfo->getTypeLoc().getBeginLoc());
3618
3619 return cxloc::translateSourceLocation(getCursorContext(C),
3620 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003621 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003622
Douglas Gregor36897b02010-09-10 00:22:18 +00003623 case CXCursor_LabelRef: {
3624 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3625 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3626 }
3627
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003628 case CXCursor_OverloadedDeclRef:
3629 return cxloc::translateSourceLocation(getCursorContext(C),
3630 getCursorOverloadedDeclRef(C).second);
3631
Douglas Gregorf46034a2010-01-18 23:41:10 +00003632 default:
3633 // FIXME: Need a way to enumerate all non-reference cases.
3634 llvm_unreachable("Missed a reference kind");
3635 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003636 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003637
3638 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003639 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003640 getLocationFromExpr(getCursorExpr(C)));
3641
Douglas Gregor36897b02010-09-10 00:22:18 +00003642 if (clang_isStatement(C.kind))
3643 return cxloc::translateSourceLocation(getCursorContext(C),
3644 getCursorStmt(C)->getLocStart());
3645
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003646 if (C.kind == CXCursor_PreprocessingDirective) {
3647 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3648 return cxloc::translateSourceLocation(getCursorContext(C), L);
3649 }
Douglas Gregor48072312010-03-18 15:23:44 +00003650
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003651 if (C.kind == CXCursor_MacroExpansion) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003652 SourceLocation L
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003653 = cxcursor::getCursorMacroExpansion(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003654 return cxloc::translateSourceLocation(getCursorContext(C), L);
3655 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003656
3657 if (C.kind == CXCursor_MacroDefinition) {
3658 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3659 return cxloc::translateSourceLocation(getCursorContext(C), L);
3660 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003661
3662 if (C.kind == CXCursor_InclusionDirective) {
3663 SourceLocation L
3664 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3665 return cxloc::translateSourceLocation(getCursorContext(C), L);
3666 }
3667
Ted Kremenek9a700d22010-05-12 06:16:13 +00003668 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003669 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003670
Douglas Gregorf46034a2010-01-18 23:41:10 +00003671 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003672 SourceLocation Loc = D->getLocation();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003673 // FIXME: Multiple variables declared in a single declaration
3674 // currently lack the information needed to correctly determine their
3675 // ranges when accounting for the type-specifier. We use context
3676 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3677 // and if so, whether it is the first decl.
3678 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3679 if (!cxcursor::isFirstInDeclGroup(C))
3680 Loc = VD->getLocation();
3681 }
3682
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003683 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003684}
Douglas Gregora7bde202010-01-19 00:34:46 +00003685
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003686} // end extern "C"
3687
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003688CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
3689 assert(TU);
3690
3691 // Guard against an invalid SourceLocation, or we may assert in one
3692 // of the following calls.
3693 if (SLoc.isInvalid())
3694 return clang_getNullCursor();
3695
3696 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
3697
3698 // Translate the given source location to make it point at the beginning of
3699 // the token under the cursor.
3700 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3701 CXXUnit->getASTContext().getLangOptions());
3702
3703 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3704 if (SLoc.isValid()) {
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003705 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003706 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
3707 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00003708 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003709 SourceLocation(SLoc));
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00003710 CursorVis.visitFileRegion();
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003711 }
3712
3713 return Result;
3714}
3715
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003716static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003717 if (clang_isReference(C.kind)) {
3718 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003719 case CXCursor_ObjCSuperClassRef:
3720 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003721
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003722 case CXCursor_ObjCProtocolRef:
3723 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003724
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003725 case CXCursor_ObjCClassRef:
3726 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003727
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003728 case CXCursor_TypeRef:
3729 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003730
3731 case CXCursor_TemplateRef:
3732 return getCursorTemplateRef(C).second;
3733
Douglas Gregor69319002010-08-31 23:48:11 +00003734 case CXCursor_NamespaceRef:
3735 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003736
3737 case CXCursor_MemberRef:
3738 return getCursorMemberRef(C).second;
3739
Ted Kremenek3064ef92010-08-27 21:34:58 +00003740 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003741 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003742
Douglas Gregor36897b02010-09-10 00:22:18 +00003743 case CXCursor_LabelRef:
3744 return getCursorLabelRef(C).second;
3745
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003746 case CXCursor_OverloadedDeclRef:
3747 return getCursorOverloadedDeclRef(C).second;
3748
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003749 default:
3750 // FIXME: Need a way to enumerate all non-reference cases.
3751 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003752 }
3753 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003754
3755 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003756 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003757
3758 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003759 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003760
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00003761 if (clang_isAttribute(C.kind))
3762 return getCursorAttr(C)->getRange();
3763
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003764 if (C.kind == CXCursor_PreprocessingDirective)
3765 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003766
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00003767 if (C.kind == CXCursor_MacroExpansion) {
3768 ASTUnit *TU = getCursorASTUnit(C);
3769 SourceRange Range = cxcursor::getCursorMacroExpansion(C)->getSourceRange();
3770 return TU->mapRangeFromPreamble(Range);
3771 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003772
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00003773 if (C.kind == CXCursor_MacroDefinition) {
3774 ASTUnit *TU = getCursorASTUnit(C);
3775 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
3776 return TU->mapRangeFromPreamble(Range);
3777 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003778
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00003779 if (C.kind == CXCursor_InclusionDirective) {
3780 ASTUnit *TU = getCursorASTUnit(C);
3781 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3782 return TU->mapRangeFromPreamble(Range);
3783 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003784
Ted Kremenek007a7c92010-11-01 23:26:51 +00003785 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3786 Decl *D = cxcursor::getCursorDecl(C);
3787 SourceRange R = D->getSourceRange();
3788 // FIXME: Multiple variables declared in a single declaration
3789 // currently lack the information needed to correctly determine their
3790 // ranges when accounting for the type-specifier. We use context
3791 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3792 // and if so, whether it is the first decl.
3793 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3794 if (!cxcursor::isFirstInDeclGroup(C))
3795 R.setBegin(VD->getLocation());
3796 }
3797 return R;
3798 }
Douglas Gregor66537982010-11-17 17:14:07 +00003799 return SourceRange();
3800}
3801
3802/// \brief Retrieves the "raw" cursor extent, which is then extended to include
3803/// the decl-specifier-seq for declarations.
3804static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
3805 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3806 Decl *D = cxcursor::getCursorDecl(C);
3807 SourceRange R = D->getSourceRange();
Douglas Gregor66537982010-11-17 17:14:07 +00003808
Douglas Gregor2494dd02011-03-01 01:34:45 +00003809 // Adjust the start of the location for declarations preceded by
3810 // declaration specifiers.
3811 SourceLocation StartLoc;
3812 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
3813 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
3814 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
3815 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
3816 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
3817 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
3818 }
3819
3820 if (StartLoc.isValid() && R.getBegin().isValid() &&
3821 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
3822 R.setBegin(StartLoc);
3823
3824 // FIXME: Multiple variables declared in a single declaration
3825 // currently lack the information needed to correctly determine their
3826 // ranges when accounting for the type-specifier. We use context
3827 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3828 // and if so, whether it is the first decl.
3829 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3830 if (!cxcursor::isFirstInDeclGroup(C))
3831 R.setBegin(VD->getLocation());
Douglas Gregor66537982010-11-17 17:14:07 +00003832 }
3833
3834 return R;
3835 }
3836
3837 return getRawCursorExtent(C);
3838}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003839
3840extern "C" {
3841
3842CXSourceRange clang_getCursorExtent(CXCursor C) {
3843 SourceRange R = getRawCursorExtent(C);
3844 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003845 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003846
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003847 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003848}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003849
3850CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003851 if (clang_isInvalid(C.kind))
3852 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003853
Ted Kremeneka60ed472010-11-16 08:15:36 +00003854 CXTranslationUnit tu = getCursorTU(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003855 if (clang_isDeclaration(C.kind)) {
3856 Decl *D = getCursorDecl(C);
3857 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003858 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003859 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003860 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003861 if (ObjCForwardProtocolDecl *Protocols
3862 = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003863 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), tu);
Chris Lattner5f9e2722011-07-23 10:55:15 +00003864 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00003865 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3866 return MakeCXCursor(Property, tu);
3867
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003868 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003869 }
3870
Douglas Gregor97b98722010-01-19 23:20:36 +00003871 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003872 Expr *E = getCursorExpr(C);
3873 Decl *D = getDeclFromExpr(E);
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003874 if (D) {
3875 CXCursor declCursor = MakeCXCursor(D, tu);
3876 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
3877 declCursor);
3878 return declCursor;
3879 }
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003880
3881 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003882 return MakeCursorOverloadedDeclRef(Ovl, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003883
Douglas Gregor97b98722010-01-19 23:20:36 +00003884 return clang_getNullCursor();
3885 }
3886
Douglas Gregor36897b02010-09-10 00:22:18 +00003887 if (clang_isStatement(C.kind)) {
3888 Stmt *S = getCursorStmt(C);
3889 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Ted Kremenek37c2e962011-03-15 23:47:49 +00003890 if (LabelDecl *label = Goto->getLabel())
3891 if (LabelStmt *labelS = label->getStmt())
3892 return MakeCXCursor(labelS, getCursorDecl(C), tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003893
3894 return clang_getNullCursor();
3895 }
3896
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003897 if (C.kind == CXCursor_MacroExpansion) {
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003898 if (MacroDefinition *Def = getCursorMacroExpansion(C)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003899 return MakeMacroDefinitionCursor(Def, tu);
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003900 }
3901
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003902 if (!clang_isReference(C.kind))
3903 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003904
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003905 switch (C.kind) {
3906 case CXCursor_ObjCSuperClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003907 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003908
3909 case CXCursor_ObjCProtocolRef: {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003910 return MakeCXCursor(getCursorObjCProtocolRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003911
3912 case CXCursor_ObjCClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003913 return MakeCXCursor(getCursorObjCClassRef(C).first, tu );
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003914
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003915 case CXCursor_TypeRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003916 return MakeCXCursor(getCursorTypeRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003917
3918 case CXCursor_TemplateRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003919 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003920
Douglas Gregor69319002010-08-31 23:48:11 +00003921 case CXCursor_NamespaceRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003922 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
Douglas Gregor69319002010-08-31 23:48:11 +00003923
Douglas Gregora67e03f2010-09-09 21:42:20 +00003924 case CXCursor_MemberRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003925 return MakeCXCursor(getCursorMemberRef(C).first, tu );
Douglas Gregora67e03f2010-09-09 21:42:20 +00003926
Ted Kremenek3064ef92010-08-27 21:34:58 +00003927 case CXCursor_CXXBaseSpecifier: {
3928 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3929 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003930 tu ));
Ted Kremenek3064ef92010-08-27 21:34:58 +00003931 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003932
Douglas Gregor36897b02010-09-10 00:22:18 +00003933 case CXCursor_LabelRef:
3934 // FIXME: We end up faking the "parent" declaration here because we
3935 // don't want to make CXCursor larger.
3936 return MakeCXCursor(getCursorLabelRef(C).first,
Ted Kremeneka60ed472010-11-16 08:15:36 +00003937 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
3938 .getTranslationUnitDecl(),
3939 tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003940
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003941 case CXCursor_OverloadedDeclRef:
3942 return C;
3943
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003944 default:
3945 // We would prefer to enumerate all non-reference cursor kinds here.
3946 llvm_unreachable("Unhandled reference cursor kind");
3947 break;
3948 }
3949 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003950
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003951 return clang_getNullCursor();
3952}
3953
Douglas Gregorb6998662010-01-19 19:34:47 +00003954CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003955 if (clang_isInvalid(C.kind))
3956 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003957
Ted Kremeneka60ed472010-11-16 08:15:36 +00003958 CXTranslationUnit TU = getCursorTU(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003959
Douglas Gregorb6998662010-01-19 19:34:47 +00003960 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003961 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003962 C = clang_getCursorReferenced(C);
3963 WasReference = true;
3964 }
3965
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003966 if (C.kind == CXCursor_MacroExpansion)
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003967 return clang_getCursorReferenced(C);
3968
Douglas Gregorb6998662010-01-19 19:34:47 +00003969 if (!clang_isDeclaration(C.kind))
3970 return clang_getNullCursor();
3971
3972 Decl *D = getCursorDecl(C);
3973 if (!D)
3974 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003975
Douglas Gregorb6998662010-01-19 19:34:47 +00003976 switch (D->getKind()) {
3977 // Declaration kinds that don't really separate the notions of
3978 // declaration and definition.
3979 case Decl::Namespace:
3980 case Decl::Typedef:
Richard Smith162e1c12011-04-15 14:24:37 +00003981 case Decl::TypeAlias:
Richard Smith3e4c6c42011-05-05 21:57:07 +00003982 case Decl::TypeAliasTemplate:
Douglas Gregorb6998662010-01-19 19:34:47 +00003983 case Decl::TemplateTypeParm:
3984 case Decl::EnumConstant:
3985 case Decl::Field:
Benjamin Kramerd9811462010-11-21 14:11:41 +00003986 case Decl::IndirectField:
Douglas Gregorb6998662010-01-19 19:34:47 +00003987 case Decl::ObjCIvar:
3988 case Decl::ObjCAtDefsField:
3989 case Decl::ImplicitParam:
3990 case Decl::ParmVar:
3991 case Decl::NonTypeTemplateParm:
3992 case Decl::TemplateTemplateParm:
3993 case Decl::ObjCCategoryImpl:
3994 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00003995 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00003996 case Decl::LinkageSpec:
3997 case Decl::ObjCPropertyImpl:
3998 case Decl::FileScopeAsm:
3999 case Decl::StaticAssert:
4000 case Decl::Block:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00004001 case Decl::Label: // FIXME: Is this right??
Francois Pichetaf0f4d02011-08-14 03:52:19 +00004002 case Decl::ClassScopeFunctionSpecialization:
Douglas Gregor15de72c2011-12-02 23:23:56 +00004003 case Decl::Import:
Douglas Gregorb6998662010-01-19 19:34:47 +00004004 return C;
4005
4006 // Declaration kinds that don't make any sense here, but are
4007 // nonetheless harmless.
4008 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00004009 break;
4010
4011 // Declaration kinds for which the definition is not resolvable.
4012 case Decl::UnresolvedUsingTypename:
4013 case Decl::UnresolvedUsingValue:
4014 break;
4015
4016 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00004017 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004018 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004019
4020 case Decl::NamespaceAlias:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004021 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004022
4023 case Decl::Enum:
4024 case Decl::Record:
4025 case Decl::CXXRecord:
4026 case Decl::ClassTemplateSpecialization:
4027 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00004028 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004029 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004030 return clang_getNullCursor();
4031
4032 case Decl::Function:
4033 case Decl::CXXMethod:
4034 case Decl::CXXConstructor:
4035 case Decl::CXXDestructor:
4036 case Decl::CXXConversion: {
4037 const FunctionDecl *Def = 0;
4038 if (cast<FunctionDecl>(D)->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004039 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004040 return clang_getNullCursor();
4041 }
4042
4043 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00004044 // Ask the variable if it has a definition.
4045 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004046 return MakeCXCursor(Def, TU);
Sebastian Redl31310a22010-02-01 20:16:42 +00004047 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00004048 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004049
Douglas Gregorb6998662010-01-19 19:34:47 +00004050 case Decl::FunctionTemplate: {
4051 const FunctionDecl *Def = 0;
4052 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004053 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004054 return clang_getNullCursor();
4055 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004056
Douglas Gregorb6998662010-01-19 19:34:47 +00004057 case Decl::ClassTemplate: {
4058 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00004059 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00004060 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004061 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004062 return clang_getNullCursor();
4063 }
4064
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004065 case Decl::Using:
4066 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004067 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004068
4069 case Decl::UsingShadow:
4070 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004071 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004072 TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004073
4074 case Decl::ObjCMethod: {
4075 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
4076 if (Method->isThisDeclarationADefinition())
4077 return C;
4078
4079 // Dig out the method definition in the associated
4080 // @implementation, if we have it.
4081 // FIXME: The ASTs should make finding the definition easier.
4082 if (ObjCInterfaceDecl *Class
4083 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
4084 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
4085 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
4086 Method->isInstanceMethod()))
4087 if (Def->isThisDeclarationADefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004088 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004089
4090 return clang_getNullCursor();
4091 }
4092
4093 case Decl::ObjCCategory:
4094 if (ObjCCategoryImplDecl *Impl
4095 = cast<ObjCCategoryDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004096 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004097 return clang_getNullCursor();
4098
4099 case Decl::ObjCProtocol:
4100 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
4101 return C;
4102 return clang_getNullCursor();
4103
4104 case Decl::ObjCInterface:
4105 // There are two notions of a "definition" for an Objective-C
4106 // class: the interface and its implementation. When we resolved a
4107 // reference to an Objective-C class, produce the @interface as
4108 // the definition; when we were provided with the interface,
4109 // produce the @implementation as the definition.
4110 if (WasReference) {
4111 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
4112 return C;
4113 } else if (ObjCImplementationDecl *Impl
4114 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004115 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004116 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004117
Douglas Gregorb6998662010-01-19 19:34:47 +00004118 case Decl::ObjCProperty:
4119 // FIXME: We don't really know where to find the
4120 // ObjCPropertyImplDecls that implement this property.
4121 return clang_getNullCursor();
4122
4123 case Decl::ObjCCompatibleAlias:
4124 if (ObjCInterfaceDecl *Class
4125 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
4126 if (!Class->isForwardDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004127 return MakeCXCursor(Class, TU);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004128
Douglas Gregorb6998662010-01-19 19:34:47 +00004129 return clang_getNullCursor();
4130
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004131 case Decl::ObjCForwardProtocol:
4132 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004133 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004134
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004135 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004136 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004137 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004138
4139 case Decl::Friend:
4140 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004141 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004142 return clang_getNullCursor();
4143
4144 case Decl::FriendTemplate:
4145 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004146 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004147 return clang_getNullCursor();
4148 }
4149
4150 return clang_getNullCursor();
4151}
4152
4153unsigned clang_isCursorDefinition(CXCursor C) {
4154 if (!clang_isDeclaration(C.kind))
4155 return 0;
4156
4157 return clang_getCursorDefinition(C) == C;
4158}
4159
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004160CXCursor clang_getCanonicalCursor(CXCursor C) {
4161 if (!clang_isDeclaration(C.kind))
4162 return C;
4163
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004164 if (Decl *D = getCursorDecl(C)) {
Argyrios Kyrtzidisdebb00f2011-07-15 22:37:58 +00004165 if (ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
4166 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
4167 return MakeCXCursor(CatD, getCursorTU(C));
4168
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004169 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
4170 if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
4171 return MakeCXCursor(IFD, getCursorTU(C));
4172
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004173 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004174 }
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004175
4176 return C;
4177}
4178
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004179unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004180 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004181 return 0;
4182
4183 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
4184 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
4185 return E->getNumDecls();
4186
4187 if (OverloadedTemplateStorage *S
4188 = Storage.dyn_cast<OverloadedTemplateStorage*>())
4189 return S->size();
4190
4191 Decl *D = Storage.get<Decl*>();
4192 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00004193 return Using->shadow_size();
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00004194 if (isa<ObjCClassDecl>(D))
4195 return 1;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004196 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
4197 return Protocols->protocol_size();
4198
4199 return 0;
4200}
4201
4202CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004203 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004204 return clang_getNullCursor();
4205
4206 if (index >= clang_getNumOverloadedDecls(cursor))
4207 return clang_getNullCursor();
4208
Ted Kremeneka60ed472010-11-16 08:15:36 +00004209 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004210 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
4211 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004212 return MakeCXCursor(E->decls_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004213
4214 if (OverloadedTemplateStorage *S
4215 = Storage.dyn_cast<OverloadedTemplateStorage*>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004216 return MakeCXCursor(S->begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004217
4218 Decl *D = Storage.get<Decl*>();
4219 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
4220 // FIXME: This is, unfortunately, linear time.
4221 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
4222 std::advance(Pos, index);
Ted Kremeneka60ed472010-11-16 08:15:36 +00004223 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004224 }
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004225 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00004226 return MakeCXCursor(Classes->getForwardInterfaceDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004227 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004228 return MakeCXCursor(Protocols->protocol_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004229
4230 return clang_getNullCursor();
4231}
4232
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00004233void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00004234 const char **startBuf,
4235 const char **endBuf,
4236 unsigned *startLine,
4237 unsigned *startColumn,
4238 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00004239 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00004240 assert(getCursorDecl(C) && "CXCursor has null decl");
4241 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00004242 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
4243 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004244
Steve Naroff4ade6d62009-09-23 17:52:52 +00004245 SourceManager &SM = FD->getASTContext().getSourceManager();
4246 *startBuf = SM.getCharacterData(Body->getLBracLoc());
4247 *endBuf = SM.getCharacterData(Body->getRBracLoc());
4248 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
4249 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
4250 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
4251 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
4252}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004253
Douglas Gregor430d7a12011-07-25 17:48:11 +00004254
4255CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
4256 unsigned PieceIndex) {
4257 RefNamePieces Pieces;
4258
4259 switch (C.kind) {
4260 case CXCursor_MemberRefExpr:
4261 if (MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
4262 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
4263 E->getQualifierLoc().getSourceRange());
4264 break;
4265
4266 case CXCursor_DeclRefExpr:
4267 if (DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C)))
4268 Pieces = buildPieces(NameFlags, false, E->getNameInfo(),
4269 E->getQualifierLoc().getSourceRange(),
4270 E->getExplicitTemplateArgsOpt());
4271 break;
4272
4273 case CXCursor_CallExpr:
4274 if (CXXOperatorCallExpr *OCE =
4275 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
4276 Expr *Callee = OCE->getCallee();
4277 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
4278 Callee = ICE->getSubExpr();
4279
4280 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
4281 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
4282 DRE->getQualifierLoc().getSourceRange());
4283 }
4284 break;
4285
4286 default:
4287 break;
4288 }
4289
4290 if (Pieces.empty()) {
4291 if (PieceIndex == 0)
4292 return clang_getCursorExtent(C);
4293 } else if (PieceIndex < Pieces.size()) {
4294 SourceRange R = Pieces[PieceIndex];
4295 if (R.isValid())
4296 return cxloc::translateSourceRange(getCursorContext(C), R);
4297 }
4298
4299 return clang_getNullRange();
4300}
4301
Douglas Gregor0a812cf2010-02-18 23:07:20 +00004302void clang_enableStackTraces(void) {
4303 llvm::sys::PrintStackTraceOnErrorSignal();
4304}
4305
Daniel Dunbar995aaf92010-11-04 01:26:29 +00004306void clang_executeOnThread(void (*fn)(void*), void *user_data,
4307 unsigned stack_size) {
4308 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
4309}
4310
Ted Kremenekfb480492010-01-13 21:46:36 +00004311} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00004312
Ted Kremenekfb480492010-01-13 21:46:36 +00004313//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004314// Token-based Operations.
4315//===----------------------------------------------------------------------===//
4316
4317/* CXToken layout:
4318 * int_data[0]: a CXTokenKind
4319 * int_data[1]: starting token location
4320 * int_data[2]: token length
4321 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004322 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004323 * otherwise unused.
4324 */
4325extern "C" {
4326
4327CXTokenKind clang_getTokenKind(CXToken CXTok) {
4328 return static_cast<CXTokenKind>(CXTok.int_data[0]);
4329}
4330
4331CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
4332 switch (clang_getTokenKind(CXTok)) {
4333 case CXToken_Identifier:
4334 case CXToken_Keyword:
4335 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004336 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
4337 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004338
4339 case CXToken_Literal: {
4340 // We have stashed the starting pointer in the ptr_data field. Use it.
4341 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Chris Lattner5f9e2722011-07-23 10:55:15 +00004342 return createCXString(StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004343 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004344
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004345 case CXToken_Punctuation:
4346 case CXToken_Comment:
4347 break;
4348 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004349
4350 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004351 // deconstructing the source location.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004352 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004353 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004354 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004355
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004356 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
4357 std::pair<FileID, unsigned> LocInfo
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004358 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00004359 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004360 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004361 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
4362 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00004363 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004364
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004365 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004366}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004367
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004368CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004369 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004370 if (!CXXUnit)
4371 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004372
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004373 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
4374 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4375}
4376
4377CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004378 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor5352ac02010-01-28 00:27:43 +00004379 if (!CXXUnit)
4380 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004381
4382 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004383 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4384}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004385
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004386static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
4387 SmallVectorImpl<CXToken> &CXTokens) {
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004388 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4389 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004390 = SourceMgr.getDecomposedLoc(Range.getBegin());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004391 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004392 = SourceMgr.getDecomposedLoc(Range.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004393
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004394 // Cannot tokenize across files.
4395 if (BeginLocInfo.first != EndLocInfo.first)
4396 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004397
4398 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004399 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004400 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004401 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00004402 if (Invalid)
4403 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00004404
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004405 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4406 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004407 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004408 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004409
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004410 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004411 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004412 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00004413 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004414 do {
4415 // Lex the next token
4416 Lex.LexFromRawLexer(Tok);
4417 if (Tok.is(tok::eof))
4418 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004419
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004420 // Initialize the CXToken.
4421 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004422
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004423 // - Common fields
4424 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
4425 CXTok.int_data[2] = Tok.getLength();
4426 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004427
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004428 // - Kind-specific fields
4429 if (Tok.isLiteral()) {
4430 CXTok.int_data[0] = CXToken_Literal;
4431 CXTok.ptr_data = (void *)Tok.getLiteralData();
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004432 } else if (Tok.is(tok::raw_identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00004433 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004434 IdentifierInfo *II
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004435 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004436
David Chisnall096428b2010-10-13 21:44:48 +00004437 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004438 CXTok.int_data[0] = CXToken_Keyword;
4439 }
4440 else {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004441 CXTok.int_data[0] = Tok.is(tok::identifier)
4442 ? CXToken_Identifier
4443 : CXToken_Keyword;
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004444 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004445 CXTok.ptr_data = II;
4446 } else if (Tok.is(tok::comment)) {
4447 CXTok.int_data[0] = CXToken_Comment;
4448 CXTok.ptr_data = 0;
4449 } else {
4450 CXTok.int_data[0] = CXToken_Punctuation;
4451 CXTok.ptr_data = 0;
4452 }
4453 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00004454 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004455 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004456}
4457
4458void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
4459 CXToken **Tokens, unsigned *NumTokens) {
4460 if (Tokens)
4461 *Tokens = 0;
4462 if (NumTokens)
4463 *NumTokens = 0;
4464
4465 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4466 if (!CXXUnit || !Tokens || !NumTokens)
4467 return;
4468
4469 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4470
4471 SourceRange R = cxloc::translateCXSourceRange(Range);
4472 if (R.isInvalid())
4473 return;
4474
4475 SmallVector<CXToken, 32> CXTokens;
4476 getTokens(CXXUnit, R, CXTokens);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004477
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004478 if (CXTokens.empty())
4479 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004480
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004481 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
4482 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
4483 *NumTokens = CXTokens.size();
4484}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004485
Ted Kremenek6db61092010-05-05 00:55:15 +00004486void clang_disposeTokens(CXTranslationUnit TU,
4487 CXToken *Tokens, unsigned NumTokens) {
4488 free(Tokens);
4489}
4490
4491} // end: extern "C"
4492
4493//===----------------------------------------------------------------------===//
4494// Token annotation APIs.
4495//===----------------------------------------------------------------------===//
4496
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004497typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004498static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4499 CXCursor parent,
4500 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00004501namespace {
4502class AnnotateTokensWorker {
4503 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004504 CXToken *Tokens;
4505 CXCursor *Cursors;
4506 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004507 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00004508 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004509 CursorVisitor AnnotateVis;
4510 SourceManager &SrcMgr;
Douglas Gregorf5251602011-03-08 17:10:18 +00004511 bool HasContextSensitiveKeywords;
4512
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004513 bool MoreTokens() const { return TokIdx < NumTokens; }
4514 unsigned NextToken() const { return TokIdx; }
4515 void AdvanceToken() { ++TokIdx; }
4516 SourceLocation GetTokenLoc(unsigned tokI) {
4517 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4518 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004519 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004520 return Tokens[tokI].int_data[3] != 0;
4521 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004522 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004523 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[3]);
4524 }
4525
4526 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004527 void annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
4528 SourceRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004529
Ted Kremenek6db61092010-05-05 00:55:15 +00004530public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00004531 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004532 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004533 CXTranslationUnit tu, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00004534 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00004535 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004536 AnnotateVis(tu,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00004537 AnnotateTokensVisitor, this,
4538 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00004539 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00004540 RegionOfInterest),
Douglas Gregorf5251602011-03-08 17:10:18 +00004541 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()),
4542 HasContextSensitiveKeywords(false) { }
Ted Kremenek11949cb2010-05-05 00:55:17 +00004543
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004544 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00004545 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004546 void AnnotateTokens();
Douglas Gregorf5251602011-03-08 17:10:18 +00004547
4548 /// \brief Determine whether the annotator saw any cursors that have
4549 /// context-sensitive keywords.
4550 bool hasContextSensitiveKeywords() const {
4551 return HasContextSensitiveKeywords;
4552 }
Ted Kremenek6db61092010-05-05 00:55:15 +00004553};
4554}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004555
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004556void AnnotateTokensWorker::AnnotateTokens() {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004557 // Walk the AST within the region of interest, annotating tokens
4558 // along the way.
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004559 AnnotateVis.visitFileRegion();
Ted Kremenek11949cb2010-05-05 00:55:17 +00004560
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004561 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4562 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004563 if (Pos != Annotated.end() &&
4564 (clang_isInvalid(Cursors[I].kind) ||
4565 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004566 Cursors[I] = Pos->second;
4567 }
4568
4569 // Finish up annotating any tokens left.
4570 if (!MoreTokens())
4571 return;
4572
4573 const CXCursor &C = clang_getNullCursor();
4574 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004575 if (I < PreprocessingTokIdx && clang_isPreprocessing(Cursors[I].kind))
4576 continue;
4577
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004578 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4579 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004580 }
4581}
4582
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004583/// \brief It annotates and advances tokens with a cursor until the comparison
4584//// between the cursor location and the source range is the same as
4585/// \arg compResult.
4586///
4587/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
4588/// Pass RangeOverlap to annotate tokens inside a range.
4589void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
4590 RangeComparisonResult compResult,
4591 SourceRange range) {
4592 while (MoreTokens()) {
4593 const unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004594 if (isFunctionMacroToken(I))
4595 return annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004596
4597 SourceLocation TokLoc = GetTokenLoc(I);
4598 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4599 Cursors[I] = updateC;
4600 AdvanceToken();
4601 continue;
4602 }
4603 break;
4604 }
4605}
4606
4607/// \brief Special annotation handling for macro argument tokens.
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004608void AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
4609 CXCursor updateC,
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004610 RangeComparisonResult compResult,
4611 SourceRange range) {
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004612 assert(MoreTokens());
4613 assert(isFunctionMacroToken(NextToken()) &&
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004614 "Should be called only for macro arg tokens");
4615
4616 // This works differently than annotateAndAdvanceTokens; because expanded
4617 // macro arguments can have arbitrary translation-unit source order, we do not
4618 // advance the token index one by one until a token fails the range test.
4619 // We only advance once past all of the macro arg tokens if all of them
4620 // pass the range test. If one of them fails we keep the token index pointing
4621 // at the start of the macro arg tokens so that the failing token will be
4622 // annotated by a subsequent annotation try.
4623
4624 bool atLeastOneCompFail = false;
4625
4626 unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004627 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
4628 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004629 if (TokLoc.isFileID())
4630 continue; // not macro arg token, it's parens or comma.
4631 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4632 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
4633 Cursors[I] = updateC;
4634 } else
4635 atLeastOneCompFail = true;
4636 }
4637
4638 if (!atLeastOneCompFail)
4639 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
4640}
4641
Ted Kremenek6db61092010-05-05 00:55:15 +00004642enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004643AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004644 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004645 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004646 if (cursorRange.isInvalid())
4647 return CXChildVisit_Recurse;
Douglas Gregorf5251602011-03-08 17:10:18 +00004648
4649 if (!HasContextSensitiveKeywords) {
4650 // Objective-C properties can have context-sensitive keywords.
4651 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
4652 if (ObjCPropertyDecl *Property
4653 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
4654 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
4655 }
4656 // Objective-C methods can have context-sensitive keywords.
4657 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
4658 cursor.kind == CXCursor_ObjCClassMethodDecl) {
4659 if (ObjCMethodDecl *Method
4660 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
4661 if (Method->getObjCDeclQualifier())
4662 HasContextSensitiveKeywords = true;
4663 else {
4664 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
4665 PEnd = Method->param_end();
4666 P != PEnd; ++P) {
4667 if ((*P)->getObjCDeclQualifier()) {
4668 HasContextSensitiveKeywords = true;
4669 break;
4670 }
4671 }
4672 }
4673 }
4674 }
4675 // C++ methods can have context-sensitive keywords.
4676 else if (cursor.kind == CXCursor_CXXMethod) {
4677 if (CXXMethodDecl *Method
4678 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
4679 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
4680 HasContextSensitiveKeywords = true;
4681 }
4682 }
4683 // C++ classes can have context-sensitive keywords.
4684 else if (cursor.kind == CXCursor_StructDecl ||
4685 cursor.kind == CXCursor_ClassDecl ||
4686 cursor.kind == CXCursor_ClassTemplate ||
4687 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
4688 if (Decl *D = getCursorDecl(cursor))
4689 if (D->hasAttr<FinalAttr>())
4690 HasContextSensitiveKeywords = true;
4691 }
4692 }
4693
Douglas Gregor4419b672010-10-21 06:10:04 +00004694 if (clang_isPreprocessing(cursor.kind)) {
Chandler Carruthcea731a2011-07-14 16:07:57 +00004695 // For macro expansions, just note where the beginning of the macro
4696 // expansion occurs.
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004697 if (cursor.kind == CXCursor_MacroExpansion) {
Douglas Gregor4419b672010-10-21 06:10:04 +00004698 Annotated[Loc.int_data] = cursor;
4699 return CXChildVisit_Recurse;
4700 }
4701
Douglas Gregor4419b672010-10-21 06:10:04 +00004702 // Items in the preprocessing record are kept separate from items in
4703 // declarations, so we keep a separate token index.
4704 unsigned SavedTokIdx = TokIdx;
4705 TokIdx = PreprocessingTokIdx;
4706
4707 // Skip tokens up until we catch up to the beginning of the preprocessing
4708 // entry.
4709 while (MoreTokens()) {
4710 const unsigned I = NextToken();
4711 SourceLocation TokLoc = GetTokenLoc(I);
4712 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4713 case RangeBefore:
4714 AdvanceToken();
4715 continue;
4716 case RangeAfter:
4717 case RangeOverlap:
4718 break;
4719 }
4720 break;
4721 }
4722
4723 // Look at all of the tokens within this range.
4724 while (MoreTokens()) {
4725 const unsigned I = NextToken();
4726 SourceLocation TokLoc = GetTokenLoc(I);
4727 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4728 case RangeBefore:
David Blaikieb219cfc2011-09-23 05:06:16 +00004729 llvm_unreachable("Infeasible");
Douglas Gregor4419b672010-10-21 06:10:04 +00004730 case RangeAfter:
4731 break;
4732 case RangeOverlap:
4733 Cursors[I] = cursor;
4734 AdvanceToken();
4735 continue;
4736 }
4737 break;
4738 }
4739
4740 // Save the preprocessing token index; restore the non-preprocessing
4741 // token index.
4742 PreprocessingTokIdx = TokIdx;
4743 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004744 return CXChildVisit_Recurse;
4745 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004746
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004747 if (cursorRange.isInvalid())
4748 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004749
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004750 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4751
Ted Kremeneka333c662010-05-12 05:29:33 +00004752 // Adjust the annotated range based specific declarations.
4753 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4754 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004755 Decl *D = cxcursor::getCursorDecl(cursor);
Douglas Gregor2494dd02011-03-01 01:34:45 +00004756
4757 SourceLocation StartLoc;
Ted Kremenek23173d72010-05-18 21:09:07 +00004758 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00004759 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
4760 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
4761 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
4762 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
4763 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
Ted Kremeneka333c662010-05-12 05:29:33 +00004764 }
Douglas Gregor2494dd02011-03-01 01:34:45 +00004765
4766 if (StartLoc.isValid() && L.isValid() &&
4767 SrcMgr.isBeforeInTranslationUnit(StartLoc, L))
4768 cursorRange.setBegin(StartLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004769 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004770
Ted Kremenek3f404602010-08-14 01:14:06 +00004771 // If the location of the cursor occurs within a macro instantiation, record
4772 // the spelling location of the cursor in our annotation map. We can then
4773 // paper over the token labelings during a post-processing step to try and
4774 // get cursor mappings for tokens that are the *arguments* of a macro
4775 // instantiation.
4776 if (L.isMacroID()) {
4777 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4778 // Only invalidate the old annotation if it isn't part of a preprocessing
4779 // directive. Here we assume that the default construction of CXCursor
4780 // results in CXCursor.kind being an initialized value (i.e., 0). If
4781 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004782
Ted Kremenek3f404602010-08-14 01:14:06 +00004783 CXCursor &oldC = Annotated[rawEncoding];
4784 if (!clang_isPreprocessing(oldC.kind))
4785 oldC = cursor;
4786 }
4787
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004788 const enum CXCursorKind K = clang_getCursorKind(parent);
4789 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004790 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4791 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004792
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004793 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004794
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00004795 // Avoid having the cursor of an expression "overwrite" the annotation of the
4796 // variable declaration that it belongs to.
4797 // This can happen for C++ constructor expressions whose range generally
4798 // include the variable declaration, e.g.:
4799 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
4800 if (clang_isExpression(cursorK)) {
4801 Expr *E = getCursorExpr(cursor);
Argyrios Kyrtzidis8ccac3d2011-06-29 22:20:07 +00004802 if (Decl *D = getCursorParentDecl(cursor)) {
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00004803 const unsigned I = NextToken();
4804 if (E->getLocStart().isValid() && D->getLocation().isValid() &&
4805 E->getLocStart() == D->getLocation() &&
4806 E->getLocStart() == GetTokenLoc(I)) {
4807 Cursors[I] = updateC;
4808 AdvanceToken();
4809 }
4810 }
4811 }
4812
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004813 // Visit children to get their cursor information.
4814 const unsigned BeforeChildren = NextToken();
4815 VisitChildren(cursor);
4816 const unsigned AfterChildren = NextToken();
4817
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004818 // Scan the tokens that are at the end of the cursor, but are not captured
4819 // but the child cursors.
4820 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
Ted Kremenek6db61092010-05-05 00:55:15 +00004821
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004822 // Scan the tokens that are at the beginning of the cursor, but are not
4823 // capture by the child cursors.
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004824 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4825 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4826 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004827
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004828 Cursors[I] = cursor;
4829 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004830
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004831 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004832}
4833
Ted Kremenek6db61092010-05-05 00:55:15 +00004834static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4835 CXCursor parent,
4836 CXClientData client_data) {
4837 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4838}
4839
Ted Kremenek6628a612011-03-18 22:51:30 +00004840namespace {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004841
4842/// \brief Uses the macro expansions in the preprocessing record to find
4843/// and mark tokens that are macro arguments. This info is used by the
4844/// AnnotateTokensWorker.
4845class MarkMacroArgTokensVisitor {
4846 SourceManager &SM;
4847 CXToken *Tokens;
4848 unsigned NumTokens;
4849 unsigned CurIdx;
4850
4851public:
4852 MarkMacroArgTokensVisitor(SourceManager &SM,
4853 CXToken *tokens, unsigned numTokens)
4854 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
4855
4856 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
4857 if (cursor.kind != CXCursor_MacroExpansion)
4858 return CXChildVisit_Continue;
4859
4860 SourceRange macroRange = getCursorMacroExpansion(cursor)->getSourceRange();
4861 if (macroRange.getBegin() == macroRange.getEnd())
4862 return CXChildVisit_Continue; // it's not a function macro.
4863
4864 for (; CurIdx < NumTokens; ++CurIdx) {
4865 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
4866 macroRange.getBegin()))
4867 break;
4868 }
4869
4870 if (CurIdx == NumTokens)
4871 return CXChildVisit_Break;
4872
4873 for (; CurIdx < NumTokens; ++CurIdx) {
4874 SourceLocation tokLoc = getTokenLoc(CurIdx);
4875 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
4876 break;
4877
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004878 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004879 }
4880
4881 if (CurIdx == NumTokens)
4882 return CXChildVisit_Break;
4883
4884 return CXChildVisit_Continue;
4885 }
4886
4887private:
4888 SourceLocation getTokenLoc(unsigned tokI) {
4889 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4890 }
4891
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004892 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004893 // The third field is reserved and currently not used. Use it here
4894 // to mark macro arg expanded tokens with their expanded locations.
4895 Tokens[tokI].int_data[3] = loc.getRawEncoding();
4896 }
4897};
4898
4899} // end anonymous namespace
4900
4901static CXChildVisitResult
4902MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
4903 CXClientData client_data) {
4904 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
4905 parent);
4906}
4907
4908namespace {
Ted Kremenek6628a612011-03-18 22:51:30 +00004909 struct clang_annotateTokens_Data {
4910 CXTranslationUnit TU;
4911 ASTUnit *CXXUnit;
4912 CXToken *Tokens;
4913 unsigned NumTokens;
4914 CXCursor *Cursors;
4915 };
4916}
4917
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004918static void annotatePreprocessorTokens(CXTranslationUnit TU,
4919 SourceRange RegionOfInterest,
4920 AnnotateTokensData &Annotated) {
4921 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4922
4923 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4924 std::pair<FileID, unsigned> BeginLocInfo
4925 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4926 std::pair<FileID, unsigned> EndLocInfo
4927 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
4928
4929 if (BeginLocInfo.first != EndLocInfo.first)
4930 return;
4931
4932 StringRef Buffer;
4933 bool Invalid = false;
4934 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
4935 if (Buffer.empty() || Invalid)
4936 return;
4937
4938 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4939 CXXUnit->getASTContext().getLangOptions(),
4940 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
4941 Buffer.end());
4942 Lex.SetCommentRetentionState(true);
4943
4944 // Lex tokens in raw mode until we hit the end of the range, to avoid
4945 // entering #includes or expanding macros.
4946 while (true) {
4947 Token Tok;
4948 Lex.LexFromRawLexer(Tok);
4949
4950 reprocess:
4951 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4952 // We have found a preprocessing directive. Gobble it up so that we
4953 // don't see it while preprocessing these tokens later, but keep track
4954 // of all of the token locations inside this preprocessing directive so
4955 // that we can annotate them appropriately.
4956 //
4957 // FIXME: Some simple tests here could identify macro definitions and
4958 // #undefs, to provide specific cursor kinds for those.
4959 SmallVector<SourceLocation, 32> Locations;
4960 do {
4961 Locations.push_back(Tok.getLocation());
4962 Lex.LexFromRawLexer(Tok);
4963 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
4964
4965 using namespace cxcursor;
4966 CXCursor Cursor
4967 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4968 Locations.back()),
4969 TU);
4970 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4971 Annotated[Locations[I].getRawEncoding()] = Cursor;
4972 }
4973
4974 if (Tok.isAtStartOfLine())
4975 goto reprocess;
4976
4977 continue;
4978 }
4979
4980 if (Tok.is(tok::eof))
4981 break;
4982 }
4983}
4984
Ted Kremenekab979612010-11-11 08:05:23 +00004985// This gets run a separate thread to avoid stack blowout.
Ted Kremenek6628a612011-03-18 22:51:30 +00004986static void clang_annotateTokensImpl(void *UserData) {
4987 CXTranslationUnit TU = ((clang_annotateTokens_Data*)UserData)->TU;
4988 ASTUnit *CXXUnit = ((clang_annotateTokens_Data*)UserData)->CXXUnit;
4989 CXToken *Tokens = ((clang_annotateTokens_Data*)UserData)->Tokens;
4990 const unsigned NumTokens = ((clang_annotateTokens_Data*)UserData)->NumTokens;
4991 CXCursor *Cursors = ((clang_annotateTokens_Data*)UserData)->Cursors;
4992
4993 // Determine the region of interest, which contains all of the tokens.
4994 SourceRange RegionOfInterest;
4995 RegionOfInterest.setBegin(
4996 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
4997 RegionOfInterest.setEnd(
4998 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
4999 Tokens[NumTokens-1])));
5000
5001 // A mapping from the source locations found when re-lexing or traversing the
5002 // region of interest to the corresponding cursors.
5003 AnnotateTokensData Annotated;
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005004
Ted Kremenek6628a612011-03-18 22:51:30 +00005005 // Relex the tokens within the source range to look for preprocessing
5006 // directives.
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005007 annotatePreprocessorTokens(TU, RegionOfInterest, Annotated);
Ted Kremenek6628a612011-03-18 22:51:30 +00005008
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005009 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
5010 // Search and mark tokens that are macro argument expansions.
5011 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
5012 Tokens, NumTokens);
5013 CursorVisitor MacroArgMarker(TU,
5014 MarkMacroArgTokensVisitorDelegate, &Visitor,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00005015 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00005016 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00005017 RegionOfInterest);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005018 MacroArgMarker.visitPreprocessedEntitiesInRegion();
5019 }
5020
Ted Kremenek6628a612011-03-18 22:51:30 +00005021 // Annotate all of the source locations in the region of interest that map to
5022 // a specific cursor.
5023 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
5024 TU, RegionOfInterest);
5025
5026 // FIXME: We use a ridiculous stack size here because the data-recursion
5027 // algorithm uses a large stack frame than the non-data recursive version,
5028 // and AnnotationTokensWorker currently transforms the data-recursion
5029 // algorithm back into a traditional recursion by explicitly calling
5030 // VisitChildren(). We will need to remove this explicit recursive call.
5031 W.AnnotateTokens();
5032
5033 // If we ran into any entities that involve context-sensitive keywords,
5034 // take another pass through the tokens to mark them as such.
5035 if (W.hasContextSensitiveKeywords()) {
5036 for (unsigned I = 0; I != NumTokens; ++I) {
5037 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
5038 continue;
5039
5040 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
5041 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5042 if (ObjCPropertyDecl *Property
5043 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
5044 if (Property->getPropertyAttributesAsWritten() != 0 &&
5045 llvm::StringSwitch<bool>(II->getName())
5046 .Case("readonly", true)
5047 .Case("assign", true)
John McCallf85e1932011-06-15 23:02:42 +00005048 .Case("unsafe_unretained", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00005049 .Case("readwrite", true)
5050 .Case("retain", true)
5051 .Case("copy", true)
5052 .Case("nonatomic", true)
5053 .Case("atomic", true)
5054 .Case("getter", true)
5055 .Case("setter", true)
John McCallf85e1932011-06-15 23:02:42 +00005056 .Case("strong", true)
5057 .Case("weak", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00005058 .Default(false))
5059 Tokens[I].int_data[0] = CXToken_Keyword;
5060 }
5061 continue;
5062 }
5063
5064 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
5065 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
5066 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5067 if (llvm::StringSwitch<bool>(II->getName())
5068 .Case("in", true)
5069 .Case("out", true)
5070 .Case("inout", true)
5071 .Case("oneway", true)
5072 .Case("bycopy", true)
5073 .Case("byref", true)
5074 .Default(false))
5075 Tokens[I].int_data[0] = CXToken_Keyword;
5076 continue;
5077 }
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00005078
5079 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
5080 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
5081 Tokens[I].int_data[0] = CXToken_Keyword;
Ted Kremenek6628a612011-03-18 22:51:30 +00005082 continue;
5083 }
5084 }
5085 }
Ted Kremenekab979612010-11-11 08:05:23 +00005086}
5087
Ted Kremenek6db61092010-05-05 00:55:15 +00005088extern "C" {
5089
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005090void clang_annotateTokens(CXTranslationUnit TU,
5091 CXToken *Tokens, unsigned NumTokens,
5092 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005093
5094 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005095 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005096
Douglas Gregor4419b672010-10-21 06:10:04 +00005097 // Any token we don't specifically annotate will have a NULL cursor.
5098 CXCursor C = clang_getNullCursor();
5099 for (unsigned I = 0; I != NumTokens; ++I)
5100 Cursors[I] = C;
5101
Ted Kremeneka60ed472010-11-16 08:15:36 +00005102 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor4419b672010-10-21 06:10:04 +00005103 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005104 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005105
Douglas Gregorbdf60622010-03-05 21:16:25 +00005106 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenek6628a612011-03-18 22:51:30 +00005107
5108 clang_annotateTokens_Data data = { TU, CXXUnit, Tokens, NumTokens, Cursors };
Ted Kremenekab979612010-11-11 08:05:23 +00005109 llvm::CrashRecoveryContext CRC;
Ted Kremenek6628a612011-03-18 22:51:30 +00005110 if (!RunSafely(CRC, clang_annotateTokensImpl, &data,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005111 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00005112 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
5113 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005114}
Ted Kremenek6628a612011-03-18 22:51:30 +00005115
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005116} // end: extern "C"
5117
5118//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00005119// Operations for querying linkage of a cursor.
5120//===----------------------------------------------------------------------===//
5121
5122extern "C" {
5123CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00005124 if (!clang_isDeclaration(cursor.kind))
5125 return CXLinkage_Invalid;
5126
Ted Kremenek16b42592010-03-03 06:36:57 +00005127 Decl *D = cxcursor::getCursorDecl(cursor);
5128 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
5129 switch (ND->getLinkage()) {
5130 case NoLinkage: return CXLinkage_NoLinkage;
5131 case InternalLinkage: return CXLinkage_Internal;
5132 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
5133 case ExternalLinkage: return CXLinkage_External;
5134 };
5135
5136 return CXLinkage_Invalid;
5137}
5138} // end: extern "C"
5139
5140//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005141// Operations for querying language of a cursor.
5142//===----------------------------------------------------------------------===//
5143
5144static CXLanguageKind getDeclLanguage(const Decl *D) {
5145 switch (D->getKind()) {
5146 default:
5147 break;
5148 case Decl::ImplicitParam:
5149 case Decl::ObjCAtDefsField:
5150 case Decl::ObjCCategory:
5151 case Decl::ObjCCategoryImpl:
5152 case Decl::ObjCClass:
5153 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005154 case Decl::ObjCForwardProtocol:
5155 case Decl::ObjCImplementation:
5156 case Decl::ObjCInterface:
5157 case Decl::ObjCIvar:
5158 case Decl::ObjCMethod:
5159 case Decl::ObjCProperty:
5160 case Decl::ObjCPropertyImpl:
5161 case Decl::ObjCProtocol:
5162 return CXLanguage_ObjC;
5163 case Decl::CXXConstructor:
5164 case Decl::CXXConversion:
5165 case Decl::CXXDestructor:
5166 case Decl::CXXMethod:
5167 case Decl::CXXRecord:
5168 case Decl::ClassTemplate:
5169 case Decl::ClassTemplatePartialSpecialization:
5170 case Decl::ClassTemplateSpecialization:
5171 case Decl::Friend:
5172 case Decl::FriendTemplate:
5173 case Decl::FunctionTemplate:
5174 case Decl::LinkageSpec:
5175 case Decl::Namespace:
5176 case Decl::NamespaceAlias:
5177 case Decl::NonTypeTemplateParm:
5178 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005179 case Decl::TemplateTemplateParm:
5180 case Decl::TemplateTypeParm:
5181 case Decl::UnresolvedUsingTypename:
5182 case Decl::UnresolvedUsingValue:
5183 case Decl::Using:
5184 case Decl::UsingDirective:
5185 case Decl::UsingShadow:
5186 return CXLanguage_CPlusPlus;
5187 }
5188
5189 return CXLanguage_C;
5190}
5191
5192extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00005193
5194enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
5195 if (clang_isDeclaration(cursor.kind))
5196 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005197 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Douglas Gregor58ddb602010-08-23 23:00:57 +00005198 return CXAvailability_Available;
5199
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005200 switch (D->getAvailability()) {
5201 case AR_Available:
5202 case AR_NotYetIntroduced:
5203 return CXAvailability_Available;
5204
5205 case AR_Deprecated:
Douglas Gregor58ddb602010-08-23 23:00:57 +00005206 return CXAvailability_Deprecated;
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005207
5208 case AR_Unavailable:
5209 return CXAvailability_NotAvailable;
5210 }
Douglas Gregor58ddb602010-08-23 23:00:57 +00005211 }
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005212
Douglas Gregor58ddb602010-08-23 23:00:57 +00005213 return CXAvailability_Available;
5214}
5215
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005216CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
5217 if (clang_isDeclaration(cursor.kind))
5218 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
5219
5220 return CXLanguage_Invalid;
5221}
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005222
5223 /// \brief If the given cursor is the "templated" declaration
5224 /// descibing a class or function template, return the class or
5225 /// function template.
5226static Decl *maybeGetTemplateCursor(Decl *D) {
5227 if (!D)
5228 return 0;
5229
5230 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
5231 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
5232 return FunTmpl;
5233
5234 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
5235 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
5236 return ClassTmpl;
5237
5238 return D;
5239}
5240
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005241CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
5242 if (clang_isDeclaration(cursor.kind)) {
5243 if (Decl *D = getCursorDecl(cursor)) {
5244 DeclContext *DC = D->getDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005245 if (!DC)
5246 return clang_getNullCursor();
5247
5248 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5249 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005250 }
5251 }
5252
5253 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
5254 if (Decl *D = getCursorDecl(cursor))
Ted Kremeneka60ed472010-11-16 08:15:36 +00005255 return MakeCXCursor(D, getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005256 }
5257
5258 return clang_getNullCursor();
5259}
5260
5261CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
5262 if (clang_isDeclaration(cursor.kind)) {
5263 if (Decl *D = getCursorDecl(cursor)) {
5264 DeclContext *DC = D->getLexicalDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005265 if (!DC)
5266 return clang_getNullCursor();
5267
5268 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5269 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005270 }
5271 }
5272
5273 // FIXME: Note that we can't easily compute the lexical context of a
5274 // statement or expression, so we return nothing.
5275 return clang_getNullCursor();
5276}
5277
Douglas Gregor9f592342010-10-01 20:25:15 +00005278void clang_getOverriddenCursors(CXCursor cursor,
5279 CXCursor **overridden,
5280 unsigned *num_overridden) {
5281 if (overridden)
5282 *overridden = 0;
5283 if (num_overridden)
5284 *num_overridden = 0;
5285 if (!overridden || !num_overridden)
5286 return;
5287
Argyrios Kyrtzidisb11be042011-10-06 07:00:46 +00005288 SmallVector<CXCursor, 8> Overridden;
5289 cxcursor::getOverriddenCursors(cursor, Overridden);
Douglas Gregor9f592342010-10-01 20:25:15 +00005290
Ted Kremenek24077122011-11-14 23:51:37 +00005291 // Don't allocate memory if we have no overriden cursors.
5292 if (Overridden.size() == 0)
5293 return;
5294
Argyrios Kyrtzidisb11be042011-10-06 07:00:46 +00005295 *num_overridden = Overridden.size();
5296 *overridden = new CXCursor [Overridden.size()];
5297 std::copy(Overridden.begin(), Overridden.end(), *overridden);
Douglas Gregor9f592342010-10-01 20:25:15 +00005298}
5299
5300void clang_disposeOverriddenCursors(CXCursor *overridden) {
5301 delete [] overridden;
5302}
5303
Douglas Gregorecdcb882010-10-20 22:00:55 +00005304CXFile clang_getIncludedFile(CXCursor cursor) {
5305 if (cursor.kind != CXCursor_InclusionDirective)
5306 return 0;
5307
5308 InclusionDirective *ID = getCursorInclusionDirective(cursor);
5309 return (void *)ID->getFile();
5310}
5311
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005312} // end: extern "C"
5313
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005314
5315//===----------------------------------------------------------------------===//
5316// C++ AST instrospection.
5317//===----------------------------------------------------------------------===//
5318
5319extern "C" {
5320unsigned clang_CXXMethod_isStatic(CXCursor C) {
5321 if (!clang_isDeclaration(C.kind))
5322 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00005323
5324 CXXMethodDecl *Method = 0;
5325 Decl *D = cxcursor::getCursorDecl(C);
5326 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5327 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5328 else
5329 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5330 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00005331}
Ted Kremenekb12903e2010-05-18 22:32:15 +00005332
Douglas Gregor211924b2011-05-12 15:17:24 +00005333unsigned clang_CXXMethod_isVirtual(CXCursor C) {
5334 if (!clang_isDeclaration(C.kind))
5335 return 0;
5336
5337 CXXMethodDecl *Method = 0;
5338 Decl *D = cxcursor::getCursorDecl(C);
5339 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5340 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5341 else
5342 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5343 return (Method && Method->isVirtual()) ? 1 : 0;
5344}
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005345} // end: extern "C"
5346
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005347//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00005348// Attribute introspection.
5349//===----------------------------------------------------------------------===//
5350
5351extern "C" {
5352CXType clang_getIBOutletCollectionType(CXCursor C) {
5353 if (C.kind != CXCursor_IBOutletCollectionAttr)
Ted Kremeneka60ed472010-11-16 08:15:36 +00005354 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005355
5356 IBOutletCollectionAttr *A =
5357 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
5358
Argyrios Kyrtzidis18aa2ff2011-09-13 18:49:52 +00005359 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005360}
5361} // end: extern "C"
5362
5363//===----------------------------------------------------------------------===//
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005364// Inspecting memory usage.
5365//===----------------------------------------------------------------------===//
5366
Ted Kremenekf7870022011-04-20 16:41:07 +00005367typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005368
Ted Kremenekf7870022011-04-20 16:41:07 +00005369static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
5370 enum CXTUResourceUsageKind k,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005371 unsigned long amount) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005372 CXTUResourceUsageEntry entry = { k, amount };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005373 entries.push_back(entry);
5374}
5375
5376extern "C" {
5377
Ted Kremenekf7870022011-04-20 16:41:07 +00005378const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005379 const char *str = "";
5380 switch (kind) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005381 case CXTUResourceUsage_AST:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005382 str = "ASTContext: expressions, declarations, and types";
5383 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005384 case CXTUResourceUsage_Identifiers:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005385 str = "ASTContext: identifiers";
5386 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005387 case CXTUResourceUsage_Selectors:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005388 str = "ASTContext: selectors";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005389 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005390 case CXTUResourceUsage_GlobalCompletionResults:
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005391 str = "Code completion: cached global results";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005392 break;
Ted Kremenek457aaf02011-04-28 04:10:31 +00005393 case CXTUResourceUsage_SourceManagerContentCache:
5394 str = "SourceManager: content cache allocator";
5395 break;
Ted Kremenekba29bd22011-04-28 04:53:38 +00005396 case CXTUResourceUsage_AST_SideTables:
5397 str = "ASTContext: side tables";
5398 break;
Ted Kremenekf61b8312011-04-28 20:36:42 +00005399 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
5400 str = "SourceManager: malloc'ed memory buffers";
5401 break;
5402 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
5403 str = "SourceManager: mmap'ed memory buffers";
5404 break;
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005405 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
5406 str = "ExternalASTSource: malloc'ed memory buffers";
5407 break;
5408 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
5409 str = "ExternalASTSource: mmap'ed memory buffers";
5410 break;
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005411 case CXTUResourceUsage_Preprocessor:
5412 str = "Preprocessor: malloc'ed memory";
5413 break;
5414 case CXTUResourceUsage_PreprocessingRecord:
5415 str = "Preprocessor: PreprocessingRecord";
5416 break;
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005417 case CXTUResourceUsage_SourceManager_DataStructures:
5418 str = "SourceManager: data structures and tables";
5419 break;
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005420 case CXTUResourceUsage_Preprocessor_HeaderSearch:
5421 str = "Preprocessor: header search tables";
5422 break;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005423 }
5424 return str;
5425}
5426
Ted Kremenekf7870022011-04-20 16:41:07 +00005427CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005428 if (!TU) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005429 CXTUResourceUsage usage = { (void*) 0, 0, 0 };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005430 return usage;
5431 }
5432
5433 ASTUnit *astUnit = static_cast<ASTUnit*>(TU->TUData);
5434 llvm::OwningPtr<MemUsageEntries> entries(new MemUsageEntries());
5435 ASTContext &astContext = astUnit->getASTContext();
5436
5437 // How much memory is used by AST nodes and types?
Ted Kremenekf7870022011-04-20 16:41:07 +00005438 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005439 (unsigned long) astContext.getASTAllocatedMemory());
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005440
5441 // How much memory is used by identifiers?
Ted Kremenekf7870022011-04-20 16:41:07 +00005442 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005443 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
5444
5445 // How much memory is used for selectors?
Ted Kremenekf7870022011-04-20 16:41:07 +00005446 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005447 (unsigned long) astContext.Selectors.getTotalMemory());
5448
Ted Kremenekba29bd22011-04-28 04:53:38 +00005449 // How much memory is used by ASTContext's side tables?
5450 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
5451 (unsigned long) astContext.getSideTableAllocatedMemory());
5452
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005453 // How much memory is used for caching global code completion results?
5454 unsigned long completionBytes = 0;
5455 if (GlobalCodeCompletionAllocator *completionAllocator =
5456 astUnit->getCachedCompletionAllocator().getPtr()) {
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005457 completionBytes = completionAllocator->getTotalMemory();
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005458 }
Ted Kremenek457aaf02011-04-28 04:10:31 +00005459 createCXTUResourceUsageEntry(*entries,
5460 CXTUResourceUsage_GlobalCompletionResults,
5461 completionBytes);
5462
5463 // How much memory is being used by SourceManager's content cache?
5464 createCXTUResourceUsageEntry(*entries,
5465 CXTUResourceUsage_SourceManagerContentCache,
5466 (unsigned long) astContext.getSourceManager().getContentCacheSize());
Ted Kremenekf61b8312011-04-28 20:36:42 +00005467
5468 // How much memory is being used by the MemoryBuffer's in SourceManager?
5469 const SourceManager::MemoryBufferSizes &srcBufs =
5470 astUnit->getSourceManager().getMemoryBufferSizes();
5471
5472 createCXTUResourceUsageEntry(*entries,
5473 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
5474 (unsigned long) srcBufs.malloc_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005475 createCXTUResourceUsageEntry(*entries,
Ted Kremenekf61b8312011-04-28 20:36:42 +00005476 CXTUResourceUsage_SourceManager_Membuffer_MMap,
5477 (unsigned long) srcBufs.mmap_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005478 createCXTUResourceUsageEntry(*entries,
5479 CXTUResourceUsage_SourceManager_DataStructures,
5480 (unsigned long) astContext.getSourceManager()
5481 .getDataStructureSizes());
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005482
5483 // How much memory is being used by the ExternalASTSource?
5484 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
5485 const ExternalASTSource::MemoryBufferSizes &sizes =
5486 esrc->getMemoryBufferSizes();
5487
5488 createCXTUResourceUsageEntry(*entries,
5489 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
5490 (unsigned long) sizes.malloc_bytes);
5491 createCXTUResourceUsageEntry(*entries,
5492 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
5493 (unsigned long) sizes.mmap_bytes);
5494 }
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005495
5496 // How much memory is being used by the Preprocessor?
5497 Preprocessor &pp = astUnit->getPreprocessor();
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005498 createCXTUResourceUsageEntry(*entries,
5499 CXTUResourceUsage_Preprocessor,
Argyrios Kyrtzidisc5c5e922011-06-29 22:20:04 +00005500 pp.getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005501
5502 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
5503 createCXTUResourceUsageEntry(*entries,
5504 CXTUResourceUsage_PreprocessingRecord,
5505 pRec->getTotalMemory());
5506 }
5507
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005508 createCXTUResourceUsageEntry(*entries,
5509 CXTUResourceUsage_Preprocessor_HeaderSearch,
5510 pp.getHeaderSearchInfo().getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005511
Ted Kremenekf7870022011-04-20 16:41:07 +00005512 CXTUResourceUsage usage = { (void*) entries.get(),
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005513 (unsigned) entries->size(),
5514 entries->size() ? &(*entries)[0] : 0 };
5515 entries.take();
5516 return usage;
5517}
5518
Ted Kremenekf7870022011-04-20 16:41:07 +00005519void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005520 if (usage.data)
5521 delete (MemUsageEntries*) usage.data;
5522}
5523
5524} // end extern "C"
5525
Douglas Gregor6df78732011-05-05 20:27:22 +00005526void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
5527 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
5528 for (unsigned I = 0; I != Usage.numEntries; ++I)
5529 fprintf(stderr, " %s: %lu\n",
5530 clang_getTUResourceUsageName(Usage.entries[I].kind),
5531 Usage.entries[I].amount);
5532
5533 clang_disposeCXTUResourceUsage(Usage);
5534}
5535
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005536//===----------------------------------------------------------------------===//
Ted Kremenek04bb7162010-01-22 22:44:15 +00005537// Misc. utility functions.
5538//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00005539
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00005540/// Default to using an 8 MB stack size on "safety" threads.
5541static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005542
5543namespace clang {
5544
5545bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005546 void (*Fn)(void*), void *UserData,
5547 unsigned Size) {
5548 if (!Size)
5549 Size = GetSafetyThreadStackSize();
5550 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005551 return CRC.RunSafelyOnThread(Fn, UserData, Size);
5552 return CRC.RunSafely(Fn, UserData);
5553}
5554
5555unsigned GetSafetyThreadStackSize() {
5556 return SafetyStackThreadSize;
5557}
5558
5559void SetSafetyThreadStackSize(unsigned Value) {
5560 SafetyStackThreadSize = Value;
5561}
5562
5563}
5564
Ted Kremenek04bb7162010-01-22 22:44:15 +00005565extern "C" {
5566
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00005567CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00005568 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00005569}
5570
5571} // end: extern "C"
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005572