blob: 42adfa1cbc6f0b7cb872e92aea618412dd19c2c8 [file] [log] [blame]
Ted Kremenekd2fa5662009-08-26 22:36:44 +00001//===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00007//
Ted Kremenekd2fa5662009-08-26 22:36:44 +00008//===----------------------------------------------------------------------===//
9//
Ted Kremenekab188932010-01-05 19:32:54 +000010// This file implements the main API hooks in the Clang-C Source Indexing
11// library.
Ted Kremenekd2fa5662009-08-26 22:36:44 +000012//
13//===----------------------------------------------------------------------===//
14
Ted Kremenekab188932010-01-05 19:32:54 +000015#include "CIndexer.h"
Ted Kremenek16c440a2010-01-15 20:35:54 +000016#include "CXCursor.h"
Ted Kremenek0a90d322010-11-17 23:24:11 +000017#include "CXTranslationUnit.h"
Ted Kremeneked122732010-11-16 01:56:27 +000018#include "CXString.h"
Ted Kremenek95f33552010-08-26 01:42:22 +000019#include "CXType.h"
Ted Kremeneka297de22010-01-25 22:34:44 +000020#include "CXSourceLocation.h"
Douglas Gregor5352ac02010-01-28 00:27:43 +000021#include "CIndexDiagnostic.h"
Argyrios Kyrtzidise397bf12011-11-03 19:02:34 +000022#include "CursorVisitor.h"
Ted Kremenekab188932010-01-05 19:32:54 +000023
Ted Kremenek04bb7162010-01-22 22:44:15 +000024#include "clang/Basic/Version.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000025
Steve Narofffb570422009-09-22 19:25:29 +000026#include "clang/AST/StmtVisitor.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000027#include "clang/Basic/Diagnostic.h"
28#include "clang/Frontend/ASTUnit.h"
29#include "clang/Frontend/CompilerInstance.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000030#include "clang/Frontend/FrontendDiagnostic.h"
Ted Kremenekd8210652010-01-06 23:43:31 +000031#include "clang/Lex/Lexer.h"
Douglas Gregordd3e5542011-05-04 00:14:37 +000032#include "clang/Lex/HeaderSearch.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000033#include "clang/Lex/PreprocessingRecord.h"
Douglas Gregor33e9abd2010-01-22 19:49:59 +000034#include "clang/Lex/Preprocessor.h"
Douglas Gregora67e03f2010-09-09 21:42:20 +000035#include "llvm/ADT/STLExtras.h"
Ted Kremenekd8c370c2010-11-02 23:10:24 +000036#include "llvm/ADT/Optional.h"
Douglas Gregorf5251602011-03-08 17:10:18 +000037#include "llvm/ADT/StringSwitch.h"
Ted Kremenekd8c370c2010-11-02 23:10:24 +000038#include "clang/Analysis/Support/SaveAndRestore.h"
Daniel Dunbarc7df4f32010-08-18 18:43:14 +000039#include "llvm/Support/CrashRecoveryContext.h"
Daniel Dunbar48615ff2010-10-08 19:30:33 +000040#include "llvm/Support/PrettyStackTrace.h"
Douglas Gregor02465752009-10-16 21:24:31 +000041#include "llvm/Support/MemoryBuffer.h"
Douglas Gregor358559d2010-10-02 22:49:11 +000042#include "llvm/Support/raw_ostream.h"
Douglas Gregor7a07fcb2010-08-09 21:00:09 +000043#include "llvm/Support/Timer.h"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000044#include "llvm/Support/Mutex.h"
45#include "llvm/Support/Program.h"
46#include "llvm/Support/Signals.h"
47#include "llvm/Support/Threading.h"
Ted Kremenek37f1ea02010-11-15 23:11:54 +000048#include "llvm/Support/Compiler.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000049
Steve Naroff50398192009-08-28 15:28:48 +000050using namespace clang;
Ted Kremenek16c440a2010-01-15 20:35:54 +000051using namespace clang::cxcursor;
Ted Kremenekee4db4f2010-02-17 00:41:08 +000052using namespace clang::cxstring;
Argyrios Kyrtzidis9049cf62011-10-12 07:07:33 +000053using namespace clang::cxtu;
Steve Naroff50398192009-08-28 15:28:48 +000054
Argyrios Kyrtzidis9049cf62011-10-12 07:07:33 +000055CXTranslationUnit cxtu::MakeCXTranslationUnit(ASTUnit *TU) {
Ted Kremeneka60ed472010-11-16 08:15:36 +000056 if (!TU)
57 return 0;
58 CXTranslationUnit D = new CXTranslationUnitImpl();
59 D->TUData = TU;
60 D->StringPool = createCXStringPool();
Ted Kremenek15322172011-11-10 08:43:12 +000061 D->Diagnostics = 0;
Ted Kremeneka60ed472010-11-16 08:15:36 +000062 return D;
63}
64
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +000065cxtu::CXTUOwner::~CXTUOwner() {
66 if (TU)
67 clang_disposeTranslationUnit(TU);
68}
69
Ted Kremenekf0e23e82010-02-17 00:41:40 +000070/// \brief Compare two source ranges to determine their relative position in
Douglas Gregor33e9abd2010-01-22 19:49:59 +000071/// the translation unit.
Ted Kremenekf0e23e82010-02-17 00:41:40 +000072static RangeComparisonResult RangeCompare(SourceManager &SM,
73 SourceRange R1,
Douglas Gregor33e9abd2010-01-22 19:49:59 +000074 SourceRange R2) {
75 assert(R1.isValid() && "First range is invalid?");
76 assert(R2.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000077 if (R1.getEnd() != R2.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000078 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000079 return RangeBefore;
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000080 if (R2.getEnd() != R1.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000081 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000082 return RangeAfter;
83 return RangeOverlap;
84}
85
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000086/// \brief Determine if a source location falls within, before, or after a
87/// a given source range.
88static RangeComparisonResult LocationCompare(SourceManager &SM,
89 SourceLocation L, SourceRange R) {
90 assert(R.isValid() && "First range is invalid?");
91 assert(L.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000092 if (L == R.getBegin() || L == R.getEnd())
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000093 return RangeOverlap;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000094 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
95 return RangeBefore;
96 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
97 return RangeAfter;
98 return RangeOverlap;
99}
100
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000101/// \brief Translate a Clang source range into a CIndex source range.
102///
103/// Clang internally represents ranges where the end location points to the
104/// start of the token at the end. However, for external clients it is more
105/// useful to have a CXSourceRange be a proper half-open interval. This routine
106/// does the appropriate translation.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000107CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000108 const LangOptions &LangOpts,
Chris Lattner0a76aae2010-06-18 22:45:06 +0000109 const CharSourceRange &R) {
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000110 // We want the last character in this location, so we will adjust the
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000111 // location accordingly.
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000112 SourceLocation EndLoc = R.getEnd();
Douglas Gregora9b06d42010-11-09 06:24:54 +0000113 if (EndLoc.isValid() && EndLoc.isMacroID())
Chandler Carruthedc3dcc2011-07-25 16:56:02 +0000114 EndLoc = SM.getExpansionRange(EndLoc).second;
Chris Lattner0a76aae2010-06-18 22:45:06 +0000115 if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) {
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000116 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000117 EndLoc = EndLoc.getLocWithOffset(Length);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000118 }
119
120 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
121 R.getBegin().getRawEncoding(),
122 EndLoc.getRawEncoding() };
123 return Result;
124}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000125
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000126//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000127// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000128//===----------------------------------------------------------------------===//
129
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000130static SourceRange getRawCursorExtent(CXCursor C);
Douglas Gregor66537982010-11-17 17:14:07 +0000131static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
132
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000133
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000134RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000135 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000136}
137
Douglas Gregorb1373d02010-01-20 20:59:29 +0000138/// \brief Visit the given cursor and, if requested by the visitor,
139/// its children.
140///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000141/// \param Cursor the cursor to visit.
142///
143/// \param CheckRegionOfInterest if true, then the caller already checked that
144/// this cursor is within the region of interest.
145///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000146/// \returns true if the visitation should be aborted, false if it
147/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000148bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000149 if (clang_isInvalid(Cursor.kind))
150 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000151
Douglas Gregorb1373d02010-01-20 20:59:29 +0000152 if (clang_isDeclaration(Cursor.kind)) {
153 Decl *D = getCursorDecl(Cursor);
154 assert(D && "Invalid declaration cursor");
Argyrios Kyrtzidis65ab9072011-09-26 19:05:37 +0000155 // Ignore implicit declarations, unless it's an objc method because
156 // currently we should report implicit methods for properties when indexing.
157 if (D->isImplicit() && !isa<ObjCMethodDecl>(D))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000158 return false;
159 }
160
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000161 // If we have a range of interest, and this cursor doesn't intersect with it,
162 // we're done.
163 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000164 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000165 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000166 return false;
167 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000168
Douglas Gregorb1373d02010-01-20 20:59:29 +0000169 switch (Visitor(Cursor, Parent, ClientData)) {
170 case CXChildVisit_Break:
171 return true;
172
173 case CXChildVisit_Continue:
174 return false;
175
176 case CXChildVisit_Recurse:
177 return VisitChildren(Cursor);
178 }
179
Douglas Gregorfd643772010-01-25 16:45:46 +0000180 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000181}
182
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000183static bool visitPreprocessedEntitiesInRange(SourceRange R,
184 PreprocessingRecord &PPRec,
185 CursorVisitor &Visitor) {
186 SourceManager &SM = Visitor.getASTUnit()->getSourceManager();
187 FileID FID;
188
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +0000189 if (!Visitor.shouldVisitIncludedEntities()) {
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000190 // If the begin/end of the range lie in the same FileID, do the optimization
191 // where we skip preprocessed entities that do not come from the same FileID.
192 FID = SM.getFileID(R.getBegin());
193 if (FID != SM.getFileID(R.getEnd()))
194 FID = FileID();
195 }
196
197 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
198 Entities = PPRec.getPreprocessedEntitiesInRange(R);
199 return Visitor.visitPreprocessedEntities(Entities.first, Entities.second,
200 PPRec, FID);
201}
202
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000203void CursorVisitor::visitFileRegion() {
204 if (RegionOfInterest.isInvalid())
205 return;
206
207 ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData);
208 SourceManager &SM = Unit->getSourceManager();
209
210 std::pair<FileID, unsigned>
211 Begin = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getBegin())),
212 End = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getEnd()));
213
214 if (End.first != Begin.first) {
215 // If the end does not reside in the same file, try to recover by
216 // picking the end of the file of begin location.
217 End.first = Begin.first;
218 End.second = SM.getFileIDSize(Begin.first);
219 }
220
221 assert(Begin.first == End.first);
222 if (Begin.second > End.second)
223 return;
224
225 FileID File = Begin.first;
226 unsigned Offset = Begin.second;
227 unsigned Length = End.second - Begin.second;
228
229 if (!VisitPreprocessorLast &&
230 Unit->getPreprocessor().getPreprocessingRecord())
231 visitPreprocessedEntitiesInRegion();
232
233 visitDeclsFromFileRegion(File, Offset, Length);
234
235 if (VisitPreprocessorLast &&
236 Unit->getPreprocessor().getPreprocessingRecord())
237 visitPreprocessedEntitiesInRegion();
238}
239
Argyrios Kyrtzidise2079cf2011-11-16 08:58:54 +0000240static bool isInLexicalContext(Decl *D, DeclContext *DC) {
241 if (!DC)
242 return false;
243
244 for (DeclContext *DeclDC = D->getLexicalDeclContext();
245 DeclDC; DeclDC = DeclDC->getLexicalParent()) {
246 if (DeclDC == DC)
247 return true;
248 }
249 return false;
250}
251
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000252void CursorVisitor::visitDeclsFromFileRegion(FileID File,
253 unsigned Offset, unsigned Length) {
254 ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData);
255 SourceManager &SM = Unit->getSourceManager();
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000256 SourceRange Range = RegionOfInterest;
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000257
258 SmallVector<Decl *, 16> Decls;
259 Unit->findFileRegionDecls(File, Offset, Length, Decls);
260
261 // If we didn't find any file level decls for the file, try looking at the
262 // file that it was included from.
263 while (Decls.empty()) {
264 bool Invalid = false;
265 const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid);
266 if (Invalid)
267 return;
268
269 SourceLocation Outer;
270 if (SLEntry.isFile())
271 Outer = SLEntry.getFile().getIncludeLoc();
272 else
273 Outer = SLEntry.getExpansion().getExpansionLocStart();
274 if (Outer.isInvalid())
275 return;
276
277 llvm::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer);
278 Length = 0;
279 Unit->findFileRegionDecls(File, Offset, Length, Decls);
280 }
281
282 assert(!Decls.empty());
283
284 bool VisitedAtLeastOnce = false;
Argyrios Kyrtzidise2079cf2011-11-16 08:58:54 +0000285 DeclContext *CurDC = 0;
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000286 SmallVector<Decl *, 16>::iterator DIt = Decls.begin();
287 for (SmallVector<Decl *, 16>::iterator DE = Decls.end(); DIt != DE; ++DIt) {
288 Decl *D = *DIt;
289
Argyrios Kyrtzidise2079cf2011-11-16 08:58:54 +0000290 if (isInLexicalContext(D, CurDC))
291 continue;
292
293 CurDC = dyn_cast<DeclContext>(D);
294
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000295 // We handle forward decls via ObjCClassDecl.
296 if (ObjCInterfaceDecl *InterD = dyn_cast<ObjCInterfaceDecl>(D)) {
297 if (InterD->isForwardDecl())
298 continue;
299 // An interface that started as a forward decl may have changed location
300 // because its @interface was parsed.
301 if (InterD->isInitiallyForwardDecl() &&
302 !SM.isInFileID(SM.getFileLoc(InterD->getLocation()), File))
303 continue;
304 }
305
Argyrios Kyrtzidise2079cf2011-11-16 08:58:54 +0000306 if (TagDecl *TD = dyn_cast<TagDecl>(D))
307 if (!TD->isFreeStanding())
308 continue;
309
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000310 RangeComparisonResult CompRes = RangeCompare(SM, D->getSourceRange(),Range);
311 if (CompRes == RangeBefore)
312 continue;
313 if (CompRes == RangeAfter)
314 break;
315
316 assert(CompRes == RangeOverlap);
317 VisitedAtLeastOnce = true;
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +0000318
319 if (isa<ObjCContainerDecl>(D)) {
320 FileDI_current = &DIt;
321 FileDE_current = DE;
322 } else {
323 FileDI_current = 0;
324 }
325
Argyrios Kyrtzidisba986172011-11-03 19:02:28 +0000326 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000327 break;
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000328 }
329
330 if (VisitedAtLeastOnce)
331 return;
332
333 // No Decls overlapped with the range. Move up the lexical context until there
334 // is a context that contains the range or we reach the translation unit
335 // level.
336 DeclContext *DC = DIt == Decls.begin() ? (*DIt)->getLexicalDeclContext()
337 : (*(DIt-1))->getLexicalDeclContext();
338
339 while (DC && !DC->isTranslationUnit()) {
340 Decl *D = cast<Decl>(DC);
341 SourceRange CurDeclRange = D->getSourceRange();
342 if (CurDeclRange.isInvalid())
343 break;
344
345 if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) {
Argyrios Kyrtzidisba986172011-11-03 19:02:28 +0000346 Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true);
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000347 break;
348 }
349
350 DC = D->getLexicalDeclContext();
351 }
352}
353
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000354bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
Douglas Gregor788f5a12010-03-20 00:41:21 +0000355 PreprocessingRecord &PPRec
Ted Kremeneka60ed472010-11-16 08:15:36 +0000356 = *AU->getPreprocessor().getPreprocessingRecord();
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000357 SourceManager &SM = AU->getSourceManager();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000358
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000359 if (RegionOfInterest.isValid()) {
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +0000360 SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000361 SourceLocation B = MappedRange.getBegin();
362 SourceLocation E = MappedRange.getEnd();
363
364 if (AU->isInPreambleFileID(B)) {
365 if (SM.isLoadedSourceLocation(E))
366 return visitPreprocessedEntitiesInRange(SourceRange(B, E),
367 PPRec, *this);
368
369 // Beginning of range lies in the preamble but it also extends beyond
370 // it into the main file. Split the range into 2 parts, one covering
371 // the preamble and another covering the main file. This allows subsequent
372 // calls to visitPreprocessedEntitiesInRange to accept a source range that
373 // lies in the same FileID, allowing it to skip preprocessed entities that
374 // do not come from the same FileID.
375 bool breaked =
376 visitPreprocessedEntitiesInRange(
377 SourceRange(B, AU->getEndOfPreambleFileID()),
378 PPRec, *this);
379 if (breaked) return true;
380 return visitPreprocessedEntitiesInRange(
381 SourceRange(AU->getStartOfMainFileID(), E),
382 PPRec, *this);
383 }
384
385 return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this);
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000386 }
387
Douglas Gregor788f5a12010-03-20 00:41:21 +0000388 bool OnlyLocalDecls
Douglas Gregor32038bb2010-12-21 19:07:48 +0000389 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
390
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000391 if (OnlyLocalDecls)
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000392 return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(),
393 PPRec);
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000394
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000395 return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec);
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000396}
397
398template<typename InputIterator>
399bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000400 InputIterator Last,
401 PreprocessingRecord &PPRec,
402 FileID FID) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000403 for (; First != Last; ++First) {
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000404 if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID))
405 continue;
406
407 PreprocessedEntity *PPE = *First;
408 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000409 if (Visit(MakeMacroExpansionCursor(ME, TU)))
410 return true;
411
412 continue;
413 }
414
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000415 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(PPE)) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000416 if (Visit(MakeMacroDefinitionCursor(MD, TU)))
417 return true;
418
419 continue;
420 }
421
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000422 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000423 if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
424 return true;
425
426 continue;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000427 }
428 }
429
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000430 return false;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000431}
432
Douglas Gregorb1373d02010-01-20 20:59:29 +0000433/// \brief Visit the children of the given cursor.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000434///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000435/// \returns true if the visitation should be aborted, false if it
436/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000437bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregorc314aa42011-03-02 19:17:03 +0000438 if (clang_isReference(Cursor.kind) &&
439 Cursor.kind != CXCursor_CXXBaseSpecifier) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000440 // By definition, references have no children.
441 return false;
442 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000443
444 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000445 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000446 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000447
Douglas Gregorb1373d02010-01-20 20:59:29 +0000448 if (clang_isDeclaration(Cursor.kind)) {
449 Decl *D = getCursorDecl(Cursor);
Douglas Gregor06d9b1a2011-04-14 21:41:34 +0000450 if (!D)
451 return false;
452
Ted Kremenek539311e2010-02-18 18:47:01 +0000453 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000454 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000455
Douglas Gregor06d9b1a2011-04-14 21:41:34 +0000456 if (clang_isStatement(Cursor.kind)) {
457 if (Stmt *S = getCursorStmt(Cursor))
458 return Visit(S);
459
460 return false;
461 }
462
463 if (clang_isExpression(Cursor.kind)) {
464 if (Expr *E = getCursorExpr(Cursor))
465 return Visit(E);
466
467 return false;
468 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000469
Douglas Gregorb1373d02010-01-20 20:59:29 +0000470 if (clang_isTranslationUnit(Cursor.kind)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000471 CXTranslationUnit tu = getCursorTU(Cursor);
472 ASTUnit *CXXUnit = static_cast<ASTUnit*>(tu->TUData);
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000473
474 int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
475 for (unsigned I = 0; I != 2; ++I) {
476 if (VisitOrder[I]) {
477 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
478 RegionOfInterest.isInvalid()) {
479 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
480 TLEnd = CXXUnit->top_level_end();
481 TL != TLEnd; ++TL) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000482 if (Visit(MakeCXCursor(*TL, tu, RegionOfInterest), true))
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000483 return true;
484 }
485 } else if (VisitDeclContext(
486 CXXUnit->getASTContext().getTranslationUnitDecl()))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000487 return true;
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000488 continue;
Douglas Gregor7b691f332010-01-20 21:13:59 +0000489 }
Bob Wilson3178cb62010-03-19 03:57:57 +0000490
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000491 // Walk the preprocessing record.
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000492 if (CXXUnit->getPreprocessor().getPreprocessingRecord())
493 visitPreprocessedEntitiesInRegion();
Douglas Gregor0396f462010-03-19 05:22:59 +0000494 }
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000495
Douglas Gregor7b691f332010-01-20 21:13:59 +0000496 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000497 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000498
Douglas Gregorc314aa42011-03-02 19:17:03 +0000499 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
500 if (CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
501 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
502 return Visit(BaseTSInfo->getTypeLoc());
503 }
504 }
505 }
Argyrios Kyrtzidis221d5a52011-09-13 18:49:56 +0000506
507 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
508 IBOutletCollectionAttr *A =
509 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
510 if (const ObjCInterfaceType *InterT = A->getInterface()->getAs<ObjCInterfaceType>())
511 return Visit(cxcursor::MakeCursorObjCClassRef(InterT->getInterface(),
512 A->getInterfaceLoc(), TU));
513 }
514
Douglas Gregorb1373d02010-01-20 20:59:29 +0000515 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000516 return false;
517}
518
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000519bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
Douglas Gregor13c8ccb2011-04-22 23:49:24 +0000520 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
521 if (Visit(TSInfo->getTypeLoc()))
522 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000523
Ted Kremenek664cffd2010-07-22 11:30:19 +0000524 if (Stmt *Body = B->getBody())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000525 return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest));
Ted Kremenek664cffd2010-07-22 11:30:19 +0000526
527 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000528}
529
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000530llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
531 if (RegionOfInterest.isValid()) {
Douglas Gregor66537982010-11-17 17:14:07 +0000532 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000533 if (Range.isInvalid())
534 return llvm::Optional<bool>();
Douglas Gregor66537982010-11-17 17:14:07 +0000535
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000536 switch (CompareRegionOfInterest(Range)) {
537 case RangeBefore:
538 // This declaration comes before the region of interest; skip it.
539 return llvm::Optional<bool>();
540
541 case RangeAfter:
542 // This declaration comes after the region of interest; we're done.
543 return false;
544
545 case RangeOverlap:
546 // This declaration overlaps the region of interest; visit it.
547 break;
548 }
549 }
550 return true;
551}
552
553bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
554 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
555
556 // FIXME: Eventually remove. This part of a hack to support proper
557 // iteration over all Decls contained lexically within an ObjC container.
558 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
559 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
560
561 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000562 Decl *D = *I;
563 if (D->getLexicalDeclContext() != DC)
564 continue;
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000565 CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000566 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
567 if (!V.hasValue())
568 continue;
569 if (!V.getValue())
570 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000571 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000572 return true;
573 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000574 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000575}
576
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000577bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
578 llvm_unreachable("Translation units are visited directly by Visit()");
579 return false;
580}
581
Richard Smith162e1c12011-04-15 14:24:37 +0000582bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
583 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
584 return Visit(TSInfo->getTypeLoc());
585
586 return false;
587}
588
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000589bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
590 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
591 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000592
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000593 return false;
594}
595
596bool CursorVisitor::VisitTagDecl(TagDecl *D) {
597 return VisitDeclContext(D);
598}
599
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000600bool CursorVisitor::VisitClassTemplateSpecializationDecl(
601 ClassTemplateSpecializationDecl *D) {
602 bool ShouldVisitBody = false;
603 switch (D->getSpecializationKind()) {
604 case TSK_Undeclared:
605 case TSK_ImplicitInstantiation:
606 // Nothing to visit
607 return false;
608
609 case TSK_ExplicitInstantiationDeclaration:
610 case TSK_ExplicitInstantiationDefinition:
611 break;
612
613 case TSK_ExplicitSpecialization:
614 ShouldVisitBody = true;
615 break;
616 }
617
618 // Visit the template arguments used in the specialization.
619 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
620 TypeLoc TL = SpecType->getTypeLoc();
621 if (TemplateSpecializationTypeLoc *TSTLoc
622 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
623 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
624 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
625 return true;
626 }
627 }
628
629 if (ShouldVisitBody && VisitCXXRecordDecl(D))
630 return true;
631
632 return false;
633}
634
Douglas Gregor74dbe642010-08-31 19:31:58 +0000635bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
636 ClassTemplatePartialSpecializationDecl *D) {
637 // FIXME: Visit the "outer" template parameter lists on the TagDecl
638 // before visiting these template parameters.
639 if (VisitTemplateParameters(D->getTemplateParameters()))
640 return true;
641
642 // Visit the partial specialization arguments.
643 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
644 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
645 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
646 return true;
647
648 return VisitCXXRecordDecl(D);
649}
650
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000651bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000652 // Visit the default argument.
653 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
654 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
655 if (Visit(DefArg->getTypeLoc()))
656 return true;
657
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000658 return false;
659}
660
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000661bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
662 if (Expr *Init = D->getInitExpr())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000663 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000664 return false;
665}
666
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000667bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
668 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
669 if (Visit(TSInfo->getTypeLoc()))
670 return true;
671
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000672 // Visit the nested-name-specifier, if present.
673 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
674 if (VisitNestedNameSpecifierLoc(QualifierLoc))
675 return true;
676
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000677 return false;
678}
679
Douglas Gregora67e03f2010-09-09 21:42:20 +0000680/// \brief Compare two base or member initializers based on their source order.
Sean Huntcbb67482011-01-08 20:30:50 +0000681static int CompareCXXCtorInitializers(const void* Xp, const void *Yp) {
682 CXXCtorInitializer const * const *X
683 = static_cast<CXXCtorInitializer const * const *>(Xp);
684 CXXCtorInitializer const * const *Y
685 = static_cast<CXXCtorInitializer const * const *>(Yp);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000686
687 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
688 return -1;
689 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
690 return 1;
691 else
692 return 0;
693}
694
Douglas Gregorb1373d02010-01-20 20:59:29 +0000695bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000696 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
697 // Visit the function declaration's syntactic components in the order
698 // written. This requires a bit of work.
Abramo Bagnara723df242010-12-14 22:11:44 +0000699 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
Douglas Gregor01829d32010-08-31 14:41:23 +0000700 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
701
702 // If we have a function declared directly (without the use of a typedef),
703 // visit just the return type. Otherwise, just visit the function's type
704 // now.
705 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
706 (!FTL && Visit(TL)))
707 return true;
708
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000709 // Visit the nested-name-specifier, if present.
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000710 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
711 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000712 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000713
714 // Visit the declaration name.
715 if (VisitDeclarationNameInfo(ND->getNameInfo()))
716 return true;
717
718 // FIXME: Visit explicitly-specified template arguments!
719
720 // Visit the function parameters, if we have a function type.
721 if (FTL && VisitFunctionTypeLoc(*FTL, true))
722 return true;
723
724 // FIXME: Attributes?
725 }
726
Sean Hunt10620eb2011-05-06 20:44:56 +0000727 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
Douglas Gregora67e03f2010-09-09 21:42:20 +0000728 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
729 // Find the initializers that were written in the source.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000730 SmallVector<CXXCtorInitializer *, 4> WrittenInits;
Douglas Gregora67e03f2010-09-09 21:42:20 +0000731 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
732 IEnd = Constructor->init_end();
733 I != IEnd; ++I) {
734 if (!(*I)->isWritten())
735 continue;
736
737 WrittenInits.push_back(*I);
738 }
739
740 // Sort the initializers in source order
741 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
Sean Huntcbb67482011-01-08 20:30:50 +0000742 &CompareCXXCtorInitializers);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000743
744 // Visit the initializers in source order
745 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
Sean Huntcbb67482011-01-08 20:30:50 +0000746 CXXCtorInitializer *Init = WrittenInits[I];
Francois Pichet00eb3f92010-12-04 09:14:42 +0000747 if (Init->isAnyMemberInitializer()) {
748 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
Douglas Gregora67e03f2010-09-09 21:42:20 +0000749 Init->getMemberLocation(), TU)))
750 return true;
Douglas Gregor76852c22011-11-01 01:16:03 +0000751 } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) {
752 if (Visit(TInfo->getTypeLoc()))
Douglas Gregora67e03f2010-09-09 21:42:20 +0000753 return true;
754 }
755
756 // Visit the initializer value.
757 if (Expr *Initializer = Init->getInit())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000758 if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
Douglas Gregora67e03f2010-09-09 21:42:20 +0000759 return true;
760 }
761 }
762
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000763 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
Douglas Gregora67e03f2010-09-09 21:42:20 +0000764 return true;
765 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000766
Douglas Gregorb1373d02010-01-20 20:59:29 +0000767 return false;
768}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000769
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000770bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
771 if (VisitDeclaratorDecl(D))
772 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000773
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000774 if (Expr *BitWidth = D->getBitWidth())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000775 return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000776
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000777 return false;
778}
779
780bool CursorVisitor::VisitVarDecl(VarDecl *D) {
781 if (VisitDeclaratorDecl(D))
782 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000783
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000784 if (Expr *Init = D->getInit())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000785 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000786
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000787 return false;
788}
789
Douglas Gregor84b51d72010-09-01 20:16:53 +0000790bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
791 if (VisitDeclaratorDecl(D))
792 return true;
793
794 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
795 if (Expr *DefArg = D->getDefaultArgument())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000796 return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
Douglas Gregor84b51d72010-09-01 20:16:53 +0000797
798 return false;
799}
800
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000801bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
802 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
803 // before visiting these template parameters.
804 if (VisitTemplateParameters(D->getTemplateParameters()))
805 return true;
806
807 return VisitFunctionDecl(D->getTemplatedDecl());
808}
809
Douglas Gregor39d6f072010-08-31 19:02:00 +0000810bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
811 // FIXME: Visit the "outer" template parameter lists on the TagDecl
812 // before visiting these template parameters.
813 if (VisitTemplateParameters(D->getTemplateParameters()))
814 return true;
815
816 return VisitCXXRecordDecl(D->getTemplatedDecl());
817}
818
Douglas Gregor84b51d72010-09-01 20:16:53 +0000819bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
820 if (VisitTemplateParameters(D->getTemplateParameters()))
821 return true;
822
823 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
824 VisitTemplateArgumentLoc(D->getDefaultArgument()))
825 return true;
826
827 return false;
828}
829
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000830bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000831 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
832 if (Visit(TSInfo->getTypeLoc()))
833 return true;
834
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000835 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000836 PEnd = ND->param_end();
837 P != PEnd; ++P) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000838 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000839 return true;
840 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000841
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000842 if (ND->isThisDeclarationADefinition() &&
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000843 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000844 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000845
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000846 return false;
847}
848
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +0000849template <typename DeclIt>
850static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current,
851 SourceManager &SM, SourceLocation EndLoc,
852 SmallVectorImpl<Decl *> &Decls) {
853 DeclIt next = *DI_current;
854 while (++next != DE_current) {
855 Decl *D_next = *next;
856 if (!D_next)
857 break;
858 SourceLocation L = D_next->getLocStart();
859 if (!L.isValid())
860 break;
861 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
862 *DI_current = next;
863 Decls.push_back(D_next);
864 continue;
865 }
866 break;
867 }
868}
869
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000870namespace {
871 struct ContainerDeclsSort {
872 SourceManager &SM;
873 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
874 bool operator()(Decl *A, Decl *B) {
875 SourceLocation L_A = A->getLocStart();
876 SourceLocation L_B = B->getLocStart();
877 assert(L_A.isValid() && L_B.isValid());
878 return SM.isBeforeInTranslationUnit(L_A, L_B);
879 }
880 };
881}
882
Douglas Gregora59e3902010-01-21 23:27:09 +0000883bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000884 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
885 // an @implementation can lexically contain Decls that are not properly
886 // nested in the AST. When we identify such cases, we need to retrofit
887 // this nesting here.
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +0000888 if (!DI_current && !FileDI_current)
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000889 return VisitDeclContext(D);
890
891 // Scan the Decls that immediately come after the container
892 // in the current DeclContext. If any fall within the
893 // container's lexical region, stash them into a vector
894 // for later processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000895 SmallVector<Decl *, 24> DeclsInContainer;
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000896 SourceLocation EndLoc = D->getSourceRange().getEnd();
Ted Kremeneka60ed472010-11-16 08:15:36 +0000897 SourceManager &SM = AU->getSourceManager();
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000898 if (EndLoc.isValid()) {
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +0000899 if (DI_current) {
900 addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc,
901 DeclsInContainer);
902 } else {
903 addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc,
904 DeclsInContainer);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000905 }
906 }
907
908 // The common case.
909 if (DeclsInContainer.empty())
910 return VisitDeclContext(D);
911
912 // Get all the Decls in the DeclContext, and sort them with the
913 // additional ones we've collected. Then visit them.
914 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
915 I!=E; ++I) {
916 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000917 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
918 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000919 continue;
920 DeclsInContainer.push_back(subDecl);
921 }
922
923 // Now sort the Decls so that they appear in lexical order.
924 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
925 ContainerDeclsSort(SM));
926
927 // Now visit the decls.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000928 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000929 E = DeclsInContainer.end(); I != E; ++I) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000930 CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000931 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
932 if (!V.hasValue())
933 continue;
934 if (!V.getValue())
935 return false;
936 if (Visit(Cursor, true))
937 return true;
938 }
939 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000940}
941
Douglas Gregorb1373d02010-01-20 20:59:29 +0000942bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000943 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
944 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000945 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000946
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000947 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
948 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
949 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000950 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000951 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000952
Douglas Gregora59e3902010-01-21 23:27:09 +0000953 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000954}
955
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000956bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
957 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
958 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
959 E = PID->protocol_end(); I != E; ++I, ++PL)
960 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
961 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000962
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000963 return VisitObjCContainerDecl(PID);
964}
965
Ted Kremenek23173d72010-05-18 21:09:07 +0000966bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000967 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000968 return true;
969
Ted Kremenek23173d72010-05-18 21:09:07 +0000970 // FIXME: This implements a workaround with @property declarations also being
971 // installed in the DeclContext for the @interface. Eventually this code
972 // should be removed.
973 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
974 if (!CDecl || !CDecl->IsClassExtension())
975 return false;
976
977 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
978 if (!ID)
979 return false;
980
981 IdentifierInfo *PropertyId = PD->getIdentifier();
982 ObjCPropertyDecl *prevDecl =
983 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
984
985 if (!prevDecl)
986 return false;
987
988 // Visit synthesized methods since they will be skipped when visiting
989 // the @interface.
990 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000991 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000992 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
Ted Kremenek23173d72010-05-18 21:09:07 +0000993 return true;
994
995 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000996 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000997 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
Ted Kremenek23173d72010-05-18 21:09:07 +0000998 return true;
999
1000 return false;
1001}
1002
Douglas Gregorb1373d02010-01-20 20:59:29 +00001003bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001004 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +00001005 if (D->getSuperClass() &&
1006 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001007 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001008 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001009 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001010
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001011 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1012 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1013 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001014 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001015 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001016
Douglas Gregora59e3902010-01-21 23:27:09 +00001017 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001018}
1019
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001020bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1021 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001022}
1023
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001024bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +00001025 // 'ID' could be null when dealing with invalid code.
1026 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1027 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1028 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001029
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001030 return VisitObjCImplDecl(D);
1031}
1032
1033bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1034#if 0
1035 // Issue callbacks for super class.
1036 // FIXME: No source location information!
1037 if (D->getSuperClass() &&
1038 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001039 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001040 TU)))
1041 return true;
1042#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001043
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001044 return VisitObjCImplDecl(D);
1045}
1046
1047bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1048 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1049 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1050 E = D->protocol_end();
1051 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001052 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001053 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001054
1055 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001056}
1057
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001058bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00001059 if (Visit(MakeCursorObjCClassRef(D->getForwardInterfaceDecl(),
1060 D->getForwardDecl()->getLocation(), TU)))
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001061 return true;
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001062 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001063}
1064
Douglas Gregora4ffd852010-11-17 01:03:52 +00001065bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1066 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1067 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1068
1069 return false;
1070}
1071
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001072bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1073 return VisitDeclContext(D);
1074}
1075
Douglas Gregor69319002010-08-31 23:48:11 +00001076bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001077 // Visit nested-name-specifier.
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00001078 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1079 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001080 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001081
1082 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1083 D->getTargetNameLoc(), TU));
1084}
1085
Douglas Gregor7e242562010-09-01 19:52:22 +00001086bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001087 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001088 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1089 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001090 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001091 }
Douglas Gregor7e242562010-09-01 19:52:22 +00001092
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001093 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1094 return true;
1095
Douglas Gregor7e242562010-09-01 19:52:22 +00001096 return VisitDeclarationNameInfo(D->getNameInfo());
1097}
1098
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001099bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001100 // Visit nested-name-specifier.
Douglas Gregordb992412011-02-25 16:33:46 +00001101 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1102 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001103 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001104
1105 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1106 D->getIdentLocation(), TU));
1107}
1108
Douglas Gregor7e242562010-09-01 19:52:22 +00001109bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001110 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001111 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1112 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001113 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001114 }
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001115
Douglas Gregor7e242562010-09-01 19:52:22 +00001116 return VisitDeclarationNameInfo(D->getNameInfo());
1117}
1118
1119bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1120 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001121 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001122 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1123 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001124 return true;
1125
Douglas Gregor7e242562010-09-01 19:52:22 +00001126 return false;
1127}
1128
Douglas Gregor01829d32010-08-31 14:41:23 +00001129bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1130 switch (Name.getName().getNameKind()) {
1131 case clang::DeclarationName::Identifier:
1132 case clang::DeclarationName::CXXLiteralOperatorName:
1133 case clang::DeclarationName::CXXOperatorName:
1134 case clang::DeclarationName::CXXUsingDirective:
1135 return false;
1136
1137 case clang::DeclarationName::CXXConstructorName:
1138 case clang::DeclarationName::CXXDestructorName:
1139 case clang::DeclarationName::CXXConversionFunctionName:
1140 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1141 return Visit(TSInfo->getTypeLoc());
1142 return false;
1143
1144 case clang::DeclarationName::ObjCZeroArgSelector:
1145 case clang::DeclarationName::ObjCOneArgSelector:
1146 case clang::DeclarationName::ObjCMultiArgSelector:
1147 // FIXME: Per-identifier location info?
1148 return false;
1149 }
1150
1151 return false;
1152}
1153
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001154bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1155 SourceRange Range) {
1156 // FIXME: This whole routine is a hack to work around the lack of proper
1157 // source information in nested-name-specifiers (PR5791). Since we do have
1158 // a beginning source location, we can visit the first component of the
1159 // nested-name-specifier, if it's a single-token component.
1160 if (!NNS)
1161 return false;
1162
1163 // Get the first component in the nested-name-specifier.
1164 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1165 NNS = Prefix;
1166
1167 switch (NNS->getKind()) {
1168 case NestedNameSpecifier::Namespace:
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001169 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1170 TU));
1171
Douglas Gregor14aba762011-02-24 02:36:08 +00001172 case NestedNameSpecifier::NamespaceAlias:
1173 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1174 Range.getBegin(), TU));
1175
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001176 case NestedNameSpecifier::TypeSpec: {
1177 // If the type has a form where we know that the beginning of the source
1178 // range matches up with a reference cursor. Visit the appropriate reference
1179 // cursor.
John McCallf4c73712011-01-19 06:33:43 +00001180 const Type *T = NNS->getAsType();
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001181 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1182 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1183 if (const TagType *Tag = dyn_cast<TagType>(T))
1184 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1185 if (const TemplateSpecializationType *TST
1186 = dyn_cast<TemplateSpecializationType>(T))
1187 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1188 break;
1189 }
1190
1191 case NestedNameSpecifier::TypeSpecWithTemplate:
1192 case NestedNameSpecifier::Global:
1193 case NestedNameSpecifier::Identifier:
1194 break;
1195 }
1196
1197 return false;
1198}
1199
Douglas Gregordc355712011-02-25 00:36:19 +00001200bool
1201CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001202 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
Douglas Gregordc355712011-02-25 00:36:19 +00001203 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1204 Qualifiers.push_back(Qualifier);
1205
1206 while (!Qualifiers.empty()) {
1207 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1208 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1209 switch (NNS->getKind()) {
1210 case NestedNameSpecifier::Namespace:
1211 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001212 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001213 TU)))
1214 return true;
1215
1216 break;
1217
1218 case NestedNameSpecifier::NamespaceAlias:
1219 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001220 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001221 TU)))
1222 return true;
1223
1224 break;
1225
1226 case NestedNameSpecifier::TypeSpec:
1227 case NestedNameSpecifier::TypeSpecWithTemplate:
1228 if (Visit(Q.getTypeLoc()))
1229 return true;
1230
1231 break;
1232
1233 case NestedNameSpecifier::Global:
1234 case NestedNameSpecifier::Identifier:
1235 break;
1236 }
1237 }
1238
1239 return false;
1240}
1241
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001242bool CursorVisitor::VisitTemplateParameters(
1243 const TemplateParameterList *Params) {
1244 if (!Params)
1245 return false;
1246
1247 for (TemplateParameterList::const_iterator P = Params->begin(),
1248 PEnd = Params->end();
1249 P != PEnd; ++P) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001250 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001251 return true;
1252 }
1253
1254 return false;
1255}
1256
Douglas Gregor0b36e612010-08-31 20:37:03 +00001257bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1258 switch (Name.getKind()) {
1259 case TemplateName::Template:
1260 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1261
1262 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001263 // Visit the overloaded template set.
1264 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1265 return true;
1266
Douglas Gregor0b36e612010-08-31 20:37:03 +00001267 return false;
1268
1269 case TemplateName::DependentTemplate:
1270 // FIXME: Visit nested-name-specifier.
1271 return false;
1272
1273 case TemplateName::QualifiedTemplate:
1274 // FIXME: Visit nested-name-specifier.
1275 return Visit(MakeCursorTemplateRef(
1276 Name.getAsQualifiedTemplateName()->getDecl(),
1277 Loc, TU));
John McCall14606042011-06-30 08:33:18 +00001278
1279 case TemplateName::SubstTemplateTemplateParm:
1280 return Visit(MakeCursorTemplateRef(
1281 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1282 Loc, TU));
Douglas Gregor1aee05d2011-01-15 06:45:20 +00001283
1284 case TemplateName::SubstTemplateTemplateParmPack:
1285 return Visit(MakeCursorTemplateRef(
1286 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1287 Loc, TU));
Douglas Gregor0b36e612010-08-31 20:37:03 +00001288 }
1289
1290 return false;
1291}
1292
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001293bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1294 switch (TAL.getArgument().getKind()) {
1295 case TemplateArgument::Null:
1296 case TemplateArgument::Integral:
Douglas Gregor87dd6972010-12-20 16:52:59 +00001297 case TemplateArgument::Pack:
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001298 return false;
1299
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001300 case TemplateArgument::Type:
1301 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1302 return Visit(TSInfo->getTypeLoc());
1303 return false;
1304
1305 case TemplateArgument::Declaration:
1306 if (Expr *E = TAL.getSourceDeclExpression())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001307 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001308 return false;
1309
1310 case TemplateArgument::Expression:
1311 if (Expr *E = TAL.getSourceExpression())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001312 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001313 return false;
1314
1315 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001316 case TemplateArgument::TemplateExpansion:
Douglas Gregorb6744ef2011-03-02 17:09:35 +00001317 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1318 return true;
1319
Douglas Gregora7fc9012011-01-05 18:58:31 +00001320 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
Douglas Gregor0b36e612010-08-31 20:37:03 +00001321 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001322 }
1323
1324 return false;
1325}
1326
Ted Kremeneka0536d82010-05-07 01:04:29 +00001327bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1328 return VisitDeclContext(D);
1329}
1330
Douglas Gregor01829d32010-08-31 14:41:23 +00001331bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1332 return Visit(TL.getUnqualifiedLoc());
1333}
1334
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001335bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00001336 ASTContext &Context = AU->getASTContext();
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001337
1338 // Some builtin types (such as Objective-C's "id", "sel", and
1339 // "Class") have associated declarations. Create cursors for those.
1340 QualType VisitType;
John McCalle0a22d02011-10-18 21:02:43 +00001341 switch (TL.getTypePtr()->getKind()) {
John McCall2dde35b2011-10-18 22:28:37 +00001342
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001343 case BuiltinType::Void:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001344 case BuiltinType::NullPtr:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001345 case BuiltinType::Dependent:
John McCall2dde35b2011-10-18 22:28:37 +00001346#define BUILTIN_TYPE(Id, SingletonId)
1347#define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1348#define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1349#define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
1350#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
1351#include "clang/AST/BuiltinTypes.def"
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001352 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001353
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001354 case BuiltinType::ObjCId:
1355 VisitType = Context.getObjCIdType();
1356 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001357
1358 case BuiltinType::ObjCClass:
1359 VisitType = Context.getObjCClassType();
1360 break;
1361
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001362 case BuiltinType::ObjCSel:
1363 VisitType = Context.getObjCSelType();
1364 break;
1365 }
1366
1367 if (!VisitType.isNull()) {
1368 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001369 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001370 TU));
1371 }
1372
1373 return false;
1374}
1375
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001376bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
Richard Smith162e1c12011-04-15 14:24:37 +00001377 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001378}
1379
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001380bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1381 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1382}
1383
1384bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
Argyrios Kyrtzidis6f155de2011-08-25 22:24:47 +00001385 if (TL.isDefinition())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001386 return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
Argyrios Kyrtzidis6f155de2011-08-25 22:24:47 +00001387
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001388 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1389}
1390
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001391bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Chandler Carruth960d13d2011-05-01 09:53:37 +00001392 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001393}
1394
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001395bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1396 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1397 return true;
1398
John McCallc12c5bb2010-05-15 11:32:37 +00001399 return false;
1400}
1401
1402bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1403 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1404 return true;
1405
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001406 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1407 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1408 TU)))
1409 return true;
1410 }
1411
1412 return false;
1413}
1414
1415bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001416 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001417}
1418
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001419bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1420 return Visit(TL.getInnerLoc());
1421}
1422
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001423bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1424 return Visit(TL.getPointeeLoc());
1425}
1426
1427bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1428 return Visit(TL.getPointeeLoc());
1429}
1430
1431bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1432 return Visit(TL.getPointeeLoc());
1433}
1434
1435bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001436 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001437}
1438
1439bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001440 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001441}
1442
Argyrios Kyrtzidis3422fbc2011-08-15 18:44:43 +00001443bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1444 return Visit(TL.getModifiedLoc());
1445}
1446
Douglas Gregor01829d32010-08-31 14:41:23 +00001447bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1448 bool SkipResultType) {
1449 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001450 return true;
1451
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001452 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001453 if (Decl *D = TL.getArg(I))
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001454 if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001455 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001456
1457 return false;
1458}
1459
1460bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1461 if (Visit(TL.getElementLoc()))
1462 return true;
1463
1464 if (Expr *Size = TL.getSizeExpr())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001465 return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001466
1467 return false;
1468}
1469
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001470bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1471 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001472 // Visit the template name.
1473 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1474 TL.getTemplateNameLoc()))
1475 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001476
1477 // Visit the template arguments.
1478 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1479 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1480 return true;
1481
1482 return false;
1483}
1484
Douglas Gregor2332c112010-01-21 20:48:56 +00001485bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1486 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1487}
1488
1489bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1490 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1491 return Visit(TSInfo->getTypeLoc());
1492
1493 return false;
1494}
1495
Sean Huntca63c202011-05-24 22:41:36 +00001496bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1497 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1498 return Visit(TSInfo->getTypeLoc());
1499
1500 return false;
1501}
1502
Douglas Gregor2494dd02011-03-01 01:34:45 +00001503bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
1504 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1505 return true;
1506
1507 return false;
1508}
1509
Douglas Gregor94fdffa2011-03-01 20:11:18 +00001510bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1511 DependentTemplateSpecializationTypeLoc TL) {
1512 // Visit the nested-name-specifier, if there is one.
1513 if (TL.getQualifierLoc() &&
1514 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1515 return true;
1516
1517 // Visit the template arguments.
1518 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1519 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1520 return true;
1521
1522 return false;
1523}
1524
Douglas Gregor9e876872011-03-01 18:12:44 +00001525bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1526 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1527 return true;
1528
1529 return Visit(TL.getNamedTypeLoc());
1530}
1531
Douglas Gregor7536dd52010-12-20 02:24:11 +00001532bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1533 return Visit(TL.getPatternLoc());
1534}
1535
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +00001536bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1537 if (Expr *E = TL.getUnderlyingExpr())
1538 return Visit(MakeCXCursor(E, StmtParent, TU));
1539
1540 return false;
1541}
1542
1543bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1544 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1545}
1546
Eli Friedmanb001de72011-10-06 23:00:33 +00001547bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1548 return Visit(TL.getValueLoc());
1549}
1550
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +00001551#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1552bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1553 return Visit##PARENT##Loc(TL); \
1554}
1555
1556DEFAULT_TYPELOC_IMPL(Complex, Type)
1557DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1558DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1559DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1560DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
1561DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1562DEFAULT_TYPELOC_IMPL(Vector, Type)
1563DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1564DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1565DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1566DEFAULT_TYPELOC_IMPL(Record, TagType)
1567DEFAULT_TYPELOC_IMPL(Enum, TagType)
1568DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1569DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1570DEFAULT_TYPELOC_IMPL(Auto, Type)
1571
Ted Kremenek3064ef92010-08-27 21:34:58 +00001572bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001573 // Visit the nested-name-specifier, if present.
1574 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1575 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1576 return true;
1577
John McCall5e1cdac2011-10-07 06:10:15 +00001578 if (D->isCompleteDefinition()) {
Ted Kremenek3064ef92010-08-27 21:34:58 +00001579 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1580 E = D->bases_end(); I != E; ++I) {
1581 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1582 return true;
1583 }
1584 }
1585
1586 return VisitTagDecl(D);
1587}
1588
Ted Kremenek09dfa372010-02-18 05:46:33 +00001589bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001590 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1591 i != e; ++i)
1592 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001593 return true;
1594
1595 return false;
1596}
1597
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001598//===----------------------------------------------------------------------===//
1599// Data-recursive visitor methods.
1600//===----------------------------------------------------------------------===//
1601
Ted Kremenek28a71942010-11-13 00:36:47 +00001602namespace {
Ted Kremenek035dc412010-11-13 00:36:50 +00001603#define DEF_JOB(NAME, DATA, KIND)\
1604class NAME : public VisitorJob {\
1605public:\
1606 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1607 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Ted Kremenekf64d8032010-11-18 00:02:32 +00001608 DATA *get() const { return static_cast<DATA*>(data[0]); }\
Ted Kremenek035dc412010-11-13 00:36:50 +00001609};
1610
1611DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1612DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001613DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001614DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001615DEF_JOB(ExplicitTemplateArgsVisit, ASTTemplateArgumentListInfo,
Ted Kremenek60608ec2010-11-17 00:50:47 +00001616 ExplicitTemplateArgsVisitKind)
Douglas Gregor94d96292011-01-19 20:34:17 +00001617DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001618#undef DEF_JOB
1619
1620class DeclVisit : public VisitorJob {
1621public:
1622 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1623 VisitorJob(parent, VisitorJob::DeclVisitKind,
1624 d, isFirst ? (void*) 1 : (void*) 0) {}
1625 static bool classof(const VisitorJob *VJ) {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001626 return VJ->getKind() == DeclVisitKind;
Ted Kremenek035dc412010-11-13 00:36:50 +00001627 }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001628 Decl *get() const { return static_cast<Decl*>(data[0]); }
1629 bool isFirst() const { return data[1] ? true : false; }
Ted Kremenek035dc412010-11-13 00:36:50 +00001630};
Ted Kremenek035dc412010-11-13 00:36:50 +00001631class TypeLocVisit : public VisitorJob {
1632public:
1633 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1634 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1635 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1636
1637 static bool classof(const VisitorJob *VJ) {
1638 return VJ->getKind() == TypeLocVisitKind;
1639 }
1640
Ted Kremenek82f3c502010-11-15 22:23:26 +00001641 TypeLoc get() const {
Ted Kremenekf64d8032010-11-18 00:02:32 +00001642 QualType T = QualType::getFromOpaquePtr(data[0]);
1643 return TypeLoc(T, data[1]);
Ted Kremenek035dc412010-11-13 00:36:50 +00001644 }
1645};
1646
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001647class LabelRefVisit : public VisitorJob {
1648public:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001649 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1650 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001651 labelLoc.getPtrEncoding()) {}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001652
1653 static bool classof(const VisitorJob *VJ) {
1654 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1655 }
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001656 LabelDecl *get() const { return static_cast<LabelDecl*>(data[0]); }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001657 SourceLocation getLoc() const {
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001658 return SourceLocation::getFromPtrEncoding(data[1]); }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001659};
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001660
1661class NestedNameSpecifierLocVisit : public VisitorJob {
1662public:
1663 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1664 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1665 Qualifier.getNestedNameSpecifier(),
1666 Qualifier.getOpaqueData()) { }
1667
1668 static bool classof(const VisitorJob *VJ) {
1669 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1670 }
1671
1672 NestedNameSpecifierLoc get() const {
1673 return NestedNameSpecifierLoc(static_cast<NestedNameSpecifier*>(data[0]),
1674 data[1]);
1675 }
1676};
1677
Ted Kremenekf64d8032010-11-18 00:02:32 +00001678class DeclarationNameInfoVisit : public VisitorJob {
1679public:
1680 DeclarationNameInfoVisit(Stmt *S, CXCursor parent)
1681 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
1682 static bool classof(const VisitorJob *VJ) {
1683 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1684 }
1685 DeclarationNameInfo get() const {
1686 Stmt *S = static_cast<Stmt*>(data[0]);
1687 switch (S->getStmtClass()) {
1688 default:
1689 llvm_unreachable("Unhandled Stmt");
Douglas Gregorba0513d2011-10-25 01:33:02 +00001690 case clang::Stmt::MSDependentExistsStmtClass:
1691 return cast<MSDependentExistsStmt>(S)->getNameInfo();
Ted Kremenekf64d8032010-11-18 00:02:32 +00001692 case Stmt::CXXDependentScopeMemberExprClass:
1693 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1694 case Stmt::DependentScopeDeclRefExprClass:
1695 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
1696 }
1697 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001698};
Ted Kremenekcdba6592010-11-18 00:42:18 +00001699class MemberRefVisit : public VisitorJob {
1700public:
1701 MemberRefVisit(FieldDecl *D, SourceLocation L, CXCursor parent)
1702 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001703 L.getPtrEncoding()) {}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001704 static bool classof(const VisitorJob *VJ) {
1705 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1706 }
1707 FieldDecl *get() const {
1708 return static_cast<FieldDecl*>(data[0]);
1709 }
1710 SourceLocation getLoc() const {
1711 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1712 }
1713};
Ted Kremenek28a71942010-11-13 00:36:47 +00001714class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1715 VisitorWorkList &WL;
1716 CXCursor Parent;
1717public:
1718 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1719 : WL(wl), Parent(parent) {}
1720
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001721 void VisitAddrLabelExpr(AddrLabelExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001722 void VisitBlockExpr(BlockExpr *B);
Ted Kremenek28a71942010-11-13 00:36:47 +00001723 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek083c7e22010-11-13 05:38:03 +00001724 void VisitCompoundStmt(CompoundStmt *S);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001725 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
Douglas Gregorba0513d2011-10-25 01:33:02 +00001726 void VisitMSDependentExistsStmt(MSDependentExistsStmt *S);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001727 void VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001728 void VisitCXXNewExpr(CXXNewExpr *E);
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001729 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001730 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001731 void VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001732 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001733 void VisitCXXTypeidExpr(CXXTypeidExpr *E);
Ted Kremenek55b933a2010-11-17 00:50:36 +00001734 void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001735 void VisitCXXUuidofExpr(CXXUuidofExpr *E);
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001736 void VisitDeclRefExpr(DeclRefExpr *D);
Ted Kremenek035dc412010-11-13 00:36:50 +00001737 void VisitDeclStmt(DeclStmt *S);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001738 void VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001739 void VisitDesignatedInitExpr(DesignatedInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001740 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1741 void VisitForStmt(ForStmt *FS);
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001742 void VisitGotoStmt(GotoStmt *GS);
Ted Kremenek28a71942010-11-13 00:36:47 +00001743 void VisitIfStmt(IfStmt *If);
1744 void VisitInitListExpr(InitListExpr *IE);
1745 void VisitMemberExpr(MemberExpr *M);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001746 void VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001747 void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001748 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1749 void VisitOverloadExpr(OverloadExpr *E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001750 void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001751 void VisitStmt(Stmt *S);
1752 void VisitSwitchStmt(SwitchStmt *S);
1753 void VisitWhileStmt(WhileStmt *W);
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001754 void VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Francois Pichet6ad6f282010-12-07 00:08:36 +00001755 void VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E);
John Wiegley21ff2e52011-04-28 00:16:57 +00001756 void VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E);
John Wiegley55262202011-04-25 06:54:41 +00001757 void VisitExpressionTraitExpr(ExpressionTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001758 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001759 void VisitVAArgExpr(VAArgExpr *E);
Douglas Gregor94d96292011-01-19 20:34:17 +00001760 void VisitSizeOfPackExpr(SizeOfPackExpr *E);
John McCall4b9c2d22011-11-06 09:01:30 +00001761 void VisitPseudoObjectExpr(PseudoObjectExpr *E);
1762 void VisitOpaqueValueExpr(OpaqueValueExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00001763
Ted Kremenek28a71942010-11-13 00:36:47 +00001764private:
Ted Kremenekf64d8032010-11-18 00:02:32 +00001765 void AddDeclarationNameInfo(Stmt *S);
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001766 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001767 void AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001768 void AddMemberRef(FieldDecl *D, SourceLocation L);
Ted Kremenek28a71942010-11-13 00:36:47 +00001769 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001770 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001771 void AddTypeLoc(TypeSourceInfo *TI);
1772 void EnqueueChildren(Stmt *S);
1773};
1774} // end anonyous namespace
1775
Ted Kremenekf64d8032010-11-18 00:02:32 +00001776void EnqueueVisitor::AddDeclarationNameInfo(Stmt *S) {
1777 // 'S' should always be non-null, since it comes from the
1778 // statement we are visiting.
1779 WL.push_back(DeclarationNameInfoVisit(S, Parent));
1780}
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001781
1782void
1783EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1784 if (Qualifier)
1785 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
1786}
1787
Ted Kremenek28a71942010-11-13 00:36:47 +00001788void EnqueueVisitor::AddStmt(Stmt *S) {
1789 if (S)
1790 WL.push_back(StmtVisit(S, Parent));
1791}
Ted Kremenek035dc412010-11-13 00:36:50 +00001792void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001793 if (D)
Ted Kremenek035dc412010-11-13 00:36:50 +00001794 WL.push_back(DeclVisit(D, Parent, isFirst));
Ted Kremenek28a71942010-11-13 00:36:47 +00001795}
Ted Kremenek60608ec2010-11-17 00:50:47 +00001796void EnqueueVisitor::
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001797 AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001798 if (A)
1799 WL.push_back(ExplicitTemplateArgsVisit(
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001800 const_cast<ASTTemplateArgumentListInfo*>(A), Parent));
Ted Kremenek60608ec2010-11-17 00:50:47 +00001801}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001802void EnqueueVisitor::AddMemberRef(FieldDecl *D, SourceLocation L) {
1803 if (D)
1804 WL.push_back(MemberRefVisit(D, L, Parent));
1805}
Ted Kremenek28a71942010-11-13 00:36:47 +00001806void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1807 if (TI)
1808 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1809 }
1810void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001811 unsigned size = WL.size();
John McCall7502c1d2011-02-13 04:07:26 +00001812 for (Stmt::child_range Child = S->children(); Child; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001813 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001814 }
1815 if (size == WL.size())
1816 return;
1817 // Now reverse the entries we just added. This will match the DFS
1818 // ordering performed by the worklist.
1819 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1820 std::reverse(I, E);
1821}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001822void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1823 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
1824}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001825void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1826 AddDecl(B->getBlockDecl());
1827}
Ted Kremenek28a71942010-11-13 00:36:47 +00001828void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1829 EnqueueChildren(E);
1830 AddTypeLoc(E->getTypeSourceInfo());
1831}
Ted Kremenek083c7e22010-11-13 05:38:03 +00001832void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1833 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1834 E = S->body_rend(); I != E; ++I) {
1835 AddStmt(*I);
1836 }
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001837}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001838void EnqueueVisitor::
Douglas Gregorba0513d2011-10-25 01:33:02 +00001839VisitMSDependentExistsStmt(MSDependentExistsStmt *S) {
1840 AddStmt(S->getSubStmt());
1841 AddDeclarationNameInfo(S);
1842 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
1843 AddNestedNameSpecifierLoc(QualifierLoc);
1844}
1845
1846void EnqueueVisitor::
Ted Kremenekf64d8032010-11-18 00:02:32 +00001847VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
1848 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1849 AddDeclarationNameInfo(E);
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001850 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1851 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001852 if (!E->isImplicitAccess())
1853 AddStmt(E->getBase());
1854}
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001855void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1856 // Enqueue the initializer or constructor arguments.
1857 for (unsigned I = E->getNumConstructorArgs(); I > 0; --I)
1858 AddStmt(E->getConstructorArg(I-1));
1859 // Enqueue the array size, if any.
1860 AddStmt(E->getArraySize());
1861 // Enqueue the allocated type.
1862 AddTypeLoc(E->getAllocatedTypeSourceInfo());
1863 // Enqueue the placement arguments.
1864 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1865 AddStmt(E->getPlacementArg(I-1));
1866}
Ted Kremenek28a71942010-11-13 00:36:47 +00001867void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
Ted Kremenek8b8d8c92010-11-13 05:55:56 +00001868 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1869 AddStmt(CE->getArg(I-1));
Ted Kremenek28a71942010-11-13 00:36:47 +00001870 AddStmt(CE->getCallee());
1871 AddStmt(CE->getArg(0));
1872}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001873void EnqueueVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1874 // Visit the name of the type being destroyed.
1875 AddTypeLoc(E->getDestroyedTypeInfo());
1876 // Visit the scope type that looks disturbingly like the nested-name-specifier
1877 // but isn't.
1878 AddTypeLoc(E->getScopeTypeInfo());
1879 // Visit the nested-name-specifier.
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001880 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1881 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001882 // Visit base expression.
1883 AddStmt(E->getBase());
1884}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001885void EnqueueVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1886 AddTypeLoc(E->getTypeSourceInfo());
1887}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001888void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1889 EnqueueChildren(E);
1890 AddTypeLoc(E->getTypeSourceInfo());
1891}
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001892void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1893 EnqueueChildren(E);
1894 if (E->isTypeOperand())
1895 AddTypeLoc(E->getTypeOperandSourceInfo());
1896}
Ted Kremenek55b933a2010-11-17 00:50:36 +00001897
1898void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
1899 *E) {
1900 EnqueueChildren(E);
1901 AddTypeLoc(E->getTypeSourceInfo());
1902}
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001903void EnqueueVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1904 EnqueueChildren(E);
1905 if (E->isTypeOperand())
1906 AddTypeLoc(E->getTypeOperandSourceInfo());
1907}
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001908void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001909 if (DR->hasExplicitTemplateArgs()) {
1910 AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
1911 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001912 WL.push_back(DeclRefExprParts(DR, Parent));
1913}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001914void EnqueueVisitor::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
1915 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1916 AddDeclarationNameInfo(E);
Douglas Gregor00cf3cc2011-02-25 20:49:16 +00001917 AddNestedNameSpecifierLoc(E->getQualifierLoc());
Ted Kremenekf64d8032010-11-18 00:02:32 +00001918}
Ted Kremenek035dc412010-11-13 00:36:50 +00001919void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1920 unsigned size = WL.size();
1921 bool isFirst = true;
1922 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1923 D != DEnd; ++D) {
1924 AddDecl(*D, isFirst);
1925 isFirst = false;
1926 }
1927 if (size == WL.size())
1928 return;
1929 // Now reverse the entries we just added. This will match the DFS
1930 // ordering performed by the worklist.
1931 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1932 std::reverse(I, E);
1933}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001934void EnqueueVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1935 AddStmt(E->getInit());
1936 typedef DesignatedInitExpr::Designator Designator;
1937 for (DesignatedInitExpr::reverse_designators_iterator
1938 D = E->designators_rbegin(), DEnd = E->designators_rend();
1939 D != DEnd; ++D) {
1940 if (D->isFieldDesignator()) {
1941 if (FieldDecl *Field = D->getField())
1942 AddMemberRef(Field, D->getFieldLoc());
1943 continue;
1944 }
1945 if (D->isArrayDesignator()) {
1946 AddStmt(E->getArrayIndex(*D));
1947 continue;
1948 }
1949 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1950 AddStmt(E->getArrayRangeEnd(*D));
1951 AddStmt(E->getArrayRangeStart(*D));
1952 }
1953}
Ted Kremenek28a71942010-11-13 00:36:47 +00001954void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1955 EnqueueChildren(E);
1956 AddTypeLoc(E->getTypeInfoAsWritten());
1957}
1958void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1959 AddStmt(FS->getBody());
1960 AddStmt(FS->getInc());
1961 AddStmt(FS->getCond());
1962 AddDecl(FS->getConditionVariable());
1963 AddStmt(FS->getInit());
1964}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001965void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) {
1966 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
1967}
Ted Kremenek28a71942010-11-13 00:36:47 +00001968void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
1969 AddStmt(If->getElse());
1970 AddStmt(If->getThen());
1971 AddStmt(If->getCond());
1972 AddDecl(If->getConditionVariable());
1973}
1974void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
1975 // We care about the syntactic form of the initializer list, only.
1976 if (InitListExpr *Syntactic = IE->getSyntacticForm())
1977 IE = Syntactic;
1978 EnqueueChildren(IE);
1979}
1980void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
Douglas Gregor89629a72010-11-17 17:15:08 +00001981 WL.push_back(MemberExprParts(M, Parent));
1982
1983 // If the base of the member access expression is an implicit 'this', don't
1984 // visit it.
1985 // FIXME: If we ever want to show these implicit accesses, this will be
1986 // unfortunate. However, clang_getCursor() relies on this behavior.
Douglas Gregor75e85042011-03-02 21:06:53 +00001987 if (!M->isImplicitAccess())
1988 AddStmt(M->getBase());
Ted Kremenek28a71942010-11-13 00:36:47 +00001989}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001990void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1991 AddTypeLoc(E->getEncodedTypeSourceInfo());
1992}
Ted Kremenek28a71942010-11-13 00:36:47 +00001993void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
1994 EnqueueChildren(M);
1995 AddTypeLoc(M->getClassReceiverTypeInfo());
1996}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001997void EnqueueVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
1998 // Visit the components of the offsetof expression.
1999 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
2000 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
2001 const OffsetOfNode &Node = E->getComponent(I-1);
2002 switch (Node.getKind()) {
2003 case OffsetOfNode::Array:
2004 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2005 break;
2006 case OffsetOfNode::Field:
Abramo Bagnara06dec892011-03-12 09:45:03 +00002007 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
Ted Kremenekcdba6592010-11-18 00:42:18 +00002008 break;
2009 case OffsetOfNode::Identifier:
2010 case OffsetOfNode::Base:
2011 continue;
2012 }
2013 }
2014 // Visit the type into which we're computing the offset.
2015 AddTypeLoc(E->getTypeSourceInfo());
2016}
Ted Kremenek28a71942010-11-13 00:36:47 +00002017void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00002018 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
Ted Kremenek60458782010-11-12 21:34:16 +00002019 WL.push_back(OverloadExprParts(E, Parent));
2020}
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002021void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
2022 UnaryExprOrTypeTraitExpr *E) {
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00002023 EnqueueChildren(E);
2024 if (E->isArgumentType())
2025 AddTypeLoc(E->getArgumentTypeInfo());
2026}
Ted Kremenek28a71942010-11-13 00:36:47 +00002027void EnqueueVisitor::VisitStmt(Stmt *S) {
2028 EnqueueChildren(S);
2029}
2030void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
2031 AddStmt(S->getBody());
2032 AddStmt(S->getCond());
2033 AddDecl(S->getConditionVariable());
2034}
Ted Kremenekfafa75a2010-11-17 00:50:39 +00002035
Ted Kremenek28a71942010-11-13 00:36:47 +00002036void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
2037 AddStmt(W->getBody());
2038 AddStmt(W->getCond());
2039 AddDecl(W->getConditionVariable());
2040}
John Wiegley21ff2e52011-04-28 00:16:57 +00002041
Ted Kremenek2939b6f2010-11-17 00:50:50 +00002042void EnqueueVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
2043 AddTypeLoc(E->getQueriedTypeSourceInfo());
2044}
Francois Pichet6ad6f282010-12-07 00:08:36 +00002045
2046void EnqueueVisitor::VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
Francois Pichet6ad6f282010-12-07 00:08:36 +00002047 AddTypeLoc(E->getRhsTypeSourceInfo());
Francois Pichet0a03a3f2010-12-08 09:11:05 +00002048 AddTypeLoc(E->getLhsTypeSourceInfo());
Francois Pichet6ad6f282010-12-07 00:08:36 +00002049}
2050
John Wiegley21ff2e52011-04-28 00:16:57 +00002051void EnqueueVisitor::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
2052 AddTypeLoc(E->getQueriedTypeSourceInfo());
2053}
2054
John Wiegley55262202011-04-25 06:54:41 +00002055void EnqueueVisitor::VisitExpressionTraitExpr(ExpressionTraitExpr *E) {
2056 EnqueueChildren(E);
2057}
2058
Ted Kremenek28a71942010-11-13 00:36:47 +00002059void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
2060 VisitOverloadExpr(U);
2061 if (!U->isImplicitAccess())
2062 AddStmt(U->getBase());
2063}
Ted Kremenek9d3bf792010-11-17 00:50:43 +00002064void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) {
2065 AddStmt(E->getSubExpr());
2066 AddTypeLoc(E->getWrittenTypeInfo());
2067}
Douglas Gregor94d96292011-01-19 20:34:17 +00002068void EnqueueVisitor::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
2069 WL.push_back(SizeOfPackExprParts(E, Parent));
2070}
John McCall4b9c2d22011-11-06 09:01:30 +00002071void EnqueueVisitor::VisitOpaqueValueExpr(OpaqueValueExpr *E) {
2072 // If the opaque value has a source expression, just transparently
2073 // visit that. This is useful for (e.g.) pseudo-object expressions.
2074 if (Expr *SourceExpr = E->getSourceExpr())
2075 return Visit(SourceExpr);
2076 AddStmt(E);
2077}
2078void EnqueueVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *E) {
2079 // Treat the expression like its syntactic form.
2080 Visit(E->getSyntacticForm());
2081}
Ted Kremenek60458782010-11-12 21:34:16 +00002082
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002083void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002084 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002085}
2086
2087bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2088 if (RegionOfInterest.isValid()) {
2089 SourceRange Range = getRawCursorExtent(C);
2090 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2091 return false;
2092 }
2093 return true;
2094}
2095
2096bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2097 while (!WL.empty()) {
2098 // Dequeue the worklist item.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002099 VisitorJob LI = WL.back();
2100 WL.pop_back();
2101
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002102 // Set the Parent field, then back to its old value once we're done.
2103 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2104
2105 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00002106 case VisitorJob::DeclVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002107 Decl *D = cast<DeclVisit>(&LI)->get();
Ted Kremenekf1107452010-11-12 18:26:56 +00002108 if (!D)
2109 continue;
2110
2111 // For now, perform default visitation for Decls.
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002112 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2113 cast<DeclVisit>(&LI)->isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00002114 return true;
2115
2116 continue;
2117 }
Ted Kremenek60608ec2010-11-17 00:50:47 +00002118 case VisitorJob::ExplicitTemplateArgsVisitKind: {
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00002119 const ASTTemplateArgumentListInfo *ArgList =
Ted Kremenek60608ec2010-11-17 00:50:47 +00002120 cast<ExplicitTemplateArgsVisit>(&LI)->get();
2121 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2122 *ArgEnd = Arg + ArgList->NumTemplateArgs;
2123 Arg != ArgEnd; ++Arg) {
2124 if (VisitTemplateArgumentLoc(*Arg))
2125 return true;
2126 }
2127 continue;
2128 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002129 case VisitorJob::TypeLocVisitKind: {
2130 // Perform default visitation for TypeLocs.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002131 if (Visit(cast<TypeLocVisit>(&LI)->get()))
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002132 return true;
2133 continue;
2134 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002135 case VisitorJob::LabelRefVisitKind: {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002136 LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Ted Kremeneke7455012011-02-23 04:54:51 +00002137 if (LabelStmt *stmt = LS->getStmt()) {
2138 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2139 TU))) {
2140 return true;
2141 }
2142 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002143 continue;
2144 }
Ted Kremenek47695c82011-08-18 22:25:21 +00002145
Douglas Gregorf3db29f2011-02-25 18:19:59 +00002146 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2147 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2148 if (VisitNestedNameSpecifierLoc(V->get()))
2149 return true;
2150 continue;
2151 }
2152
Ted Kremenekf64d8032010-11-18 00:02:32 +00002153 case VisitorJob::DeclarationNameInfoVisitKind: {
2154 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2155 ->get()))
2156 return true;
2157 continue;
2158 }
Ted Kremenekcdba6592010-11-18 00:42:18 +00002159 case VisitorJob::MemberRefVisitKind: {
2160 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2161 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2162 return true;
2163 continue;
2164 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002165 case VisitorJob::StmtVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002166 Stmt *S = cast<StmtVisit>(&LI)->get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00002167 if (!S)
2168 continue;
2169
Ted Kremenekf1107452010-11-12 18:26:56 +00002170 // Update the current cursor.
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002171 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
Ted Kremenekcdba6592010-11-18 00:42:18 +00002172 if (!IsInRegionOfInterest(Cursor))
2173 continue;
2174 switch (Visitor(Cursor, Parent, ClientData)) {
2175 case CXChildVisit_Break: return true;
2176 case CXChildVisit_Continue: break;
2177 case CXChildVisit_Recurse:
2178 EnqueueWorkList(WL, S);
Ted Kremenek82f3c502010-11-15 22:23:26 +00002179 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002180 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00002181 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002182 }
2183 case VisitorJob::MemberExprPartsKind: {
2184 // Handle the other pieces in the MemberExpr besides the base.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002185 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002186
2187 // Visit the nested-name-specifier
Douglas Gregor40d96a62011-02-28 21:54:11 +00002188 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
2189 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002190 return true;
2191
2192 // Visit the declaration name.
2193 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2194 return true;
2195
2196 // Visit the explicitly-specified template arguments, if any.
2197 if (M->hasExplicitTemplateArgs()) {
2198 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2199 *ArgEnd = Arg + M->getNumTemplateArgs();
2200 Arg != ArgEnd; ++Arg) {
2201 if (VisitTemplateArgumentLoc(*Arg))
2202 return true;
2203 }
2204 }
2205 continue;
2206 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002207 case VisitorJob::DeclRefExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002208 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002209 // Visit nested-name-specifier, if present.
Douglas Gregor40d96a62011-02-28 21:54:11 +00002210 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
2211 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002212 return true;
2213 // Visit declaration name.
2214 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2215 return true;
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002216 continue;
2217 }
Ted Kremenek60458782010-11-12 21:34:16 +00002218 case VisitorJob::OverloadExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002219 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Ted Kremenek60458782010-11-12 21:34:16 +00002220 // Visit the nested-name-specifier.
Douglas Gregor4c9be892011-02-28 20:01:57 +00002221 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
2222 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenek60458782010-11-12 21:34:16 +00002223 return true;
2224 // Visit the declaration name.
2225 if (VisitDeclarationNameInfo(O->getNameInfo()))
2226 return true;
2227 // Visit the overloaded declaration reference.
2228 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2229 return true;
Ted Kremenek60458782010-11-12 21:34:16 +00002230 continue;
2231 }
Douglas Gregor94d96292011-01-19 20:34:17 +00002232 case VisitorJob::SizeOfPackExprPartsKind: {
2233 SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
2234 NamedDecl *Pack = E->getPack();
2235 if (isa<TemplateTypeParmDecl>(Pack)) {
2236 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
2237 E->getPackLoc(), TU)))
2238 return true;
2239
2240 continue;
2241 }
2242
2243 if (isa<TemplateTemplateParmDecl>(Pack)) {
2244 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
2245 E->getPackLoc(), TU)))
2246 return true;
2247
2248 continue;
2249 }
2250
2251 // Non-type template parameter packs and function parameter packs are
2252 // treated like DeclRefExpr cursors.
2253 continue;
2254 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002255 }
2256 }
2257 return false;
2258}
2259
Ted Kremenekcdba6592010-11-18 00:42:18 +00002260bool CursorVisitor::Visit(Stmt *S) {
Ted Kremenekd1ded662010-11-15 23:31:32 +00002261 VisitorWorkList *WL = 0;
2262 if (!WorkListFreeList.empty()) {
2263 WL = WorkListFreeList.back();
2264 WL->clear();
2265 WorkListFreeList.pop_back();
2266 }
2267 else {
2268 WL = new VisitorWorkList();
2269 WorkListCache.push_back(WL);
2270 }
2271 EnqueueWorkList(*WL, S);
2272 bool result = RunVisitorWorkList(*WL);
2273 WorkListFreeList.push_back(WL);
2274 return result;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002275}
2276
Francois Pichet48a8d142011-07-25 22:00:44 +00002277namespace {
2278typedef llvm::SmallVector<SourceRange, 4> RefNamePieces;
2279RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
2280 const DeclarationNameInfo &NI,
2281 const SourceRange &QLoc,
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00002282 const ASTTemplateArgumentListInfo *TemplateArgs = 0){
Francois Pichet48a8d142011-07-25 22:00:44 +00002283 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
2284 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
2285 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
2286
2287 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
2288
2289 RefNamePieces Pieces;
2290
2291 if (WantQualifier && QLoc.isValid())
2292 Pieces.push_back(QLoc);
2293
2294 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
2295 Pieces.push_back(NI.getLoc());
2296
2297 if (WantTemplateArgs && TemplateArgs)
2298 Pieces.push_back(SourceRange(TemplateArgs->LAngleLoc,
2299 TemplateArgs->RAngleLoc));
2300
2301 if (Kind == DeclarationName::CXXOperatorName) {
2302 Pieces.push_back(SourceLocation::getFromRawEncoding(
2303 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
2304 Pieces.push_back(SourceLocation::getFromRawEncoding(
2305 NI.getInfo().CXXOperatorName.EndOpNameLoc));
2306 }
2307
2308 if (WantSinglePiece) {
2309 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
2310 Pieces.clear();
2311 Pieces.push_back(R);
2312 }
2313
2314 return Pieces;
2315}
2316}
2317
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002318//===----------------------------------------------------------------------===//
2319// Misc. API hooks.
2320//===----------------------------------------------------------------------===//
2321
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002322static llvm::sys::Mutex EnableMultithreadingMutex;
2323static bool EnabledMultithreading;
2324
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002325extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002326CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2327 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002328 // Disable pretty stack trace functionality, which will otherwise be a very
2329 // poor citizen of the world and set up all sorts of signal handlers.
2330 llvm::DisablePrettyStackTrace = true;
2331
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002332 // We use crash recovery to make some of our APIs more reliable, implicitly
2333 // enable it.
2334 llvm::CrashRecoveryContext::Enable();
2335
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002336 // Enable support for multithreading in LLVM.
2337 {
2338 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2339 if (!EnabledMultithreading) {
2340 llvm::llvm_start_multithreaded();
2341 EnabledMultithreading = true;
2342 }
2343 }
2344
Douglas Gregora030b7c2010-01-22 20:35:53 +00002345 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002346 if (excludeDeclarationsFromPCH)
2347 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002348 if (displayDiagnostics)
2349 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002350 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002351}
2352
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002353void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002354 if (CIdx)
2355 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002356}
2357
Ted Kremenekd2427dd2011-03-18 23:05:39 +00002358void clang_toggleCrashRecovery(unsigned isEnabled) {
2359 if (isEnabled)
2360 llvm::CrashRecoveryContext::Enable();
2361 else
2362 llvm::CrashRecoveryContext::Disable();
2363}
2364
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002365CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002366 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002367 if (!CIdx)
2368 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002369
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002370 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002371 FileSystemOptions FileSystemOpts;
2372 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002373
David Blaikied6471f72011-09-25 23:23:43 +00002374 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002375 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002376 CXXIdx->getOnlyLocalDecls(),
2377 0, 0, true);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002378 return MakeCXTranslationUnit(TU);
Steve Naroff600866c2009-08-27 19:51:58 +00002379}
2380
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002381unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002382 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregorb5af8432011-08-25 22:54:01 +00002383 CXTranslationUnit_CacheCompletionResults;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002384}
2385
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002386CXTranslationUnit
2387clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2388 const char *source_filename,
2389 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002390 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002391 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002392 struct CXUnsavedFile *unsaved_files) {
Douglas Gregordca8ee82011-05-06 16:33:08 +00002393 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord |
Chandler Carruthba7537f2011-07-14 09:02:10 +00002394 CXTranslationUnit_NestedMacroExpansions;
Douglas Gregor5a430212010-07-21 18:52:53 +00002395 return clang_parseTranslationUnit(CIdx, source_filename,
2396 command_line_args, num_command_line_args,
2397 unsaved_files, num_unsaved_files,
Douglas Gregordca8ee82011-05-06 16:33:08 +00002398 Options);
Douglas Gregor5a430212010-07-21 18:52:53 +00002399}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002400
2401struct ParseTranslationUnitInfo {
2402 CXIndex CIdx;
2403 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002404 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002405 int num_command_line_args;
2406 struct CXUnsavedFile *unsaved_files;
2407 unsigned num_unsaved_files;
2408 unsigned options;
2409 CXTranslationUnit result;
2410};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002411static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002412 ParseTranslationUnitInfo *PTUI =
2413 static_cast<ParseTranslationUnitInfo*>(UserData);
2414 CXIndex CIdx = PTUI->CIdx;
2415 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002416 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002417 int num_command_line_args = PTUI->num_command_line_args;
2418 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2419 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2420 unsigned options = PTUI->options;
2421 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002422
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002423 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002424 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002425
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002426 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2427
Douglas Gregor44c181a2010-07-23 00:33:23 +00002428 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregor467dc882011-08-25 22:30:56 +00002429 // FIXME: Add a flag for modules.
2430 TranslationUnitKind TUKind
2431 = (options & CXTranslationUnit_Incomplete)? TU_Prefix : TU_Complete;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002432 bool CacheCodeCompetionResults
2433 = options & CXTranslationUnit_CacheCompletionResults;
2434
Douglas Gregor5352ac02010-01-28 00:27:43 +00002435 // Configure the diagnostics.
2436 DiagnosticOptions DiagOpts;
David Blaikied6471f72011-09-25 23:23:43 +00002437 llvm::IntrusiveRefCntPtr<DiagnosticsEngine>
Ted Kremenek25a11e12011-03-22 01:15:24 +00002438 Diags(CompilerInstance::createDiagnostics(DiagOpts, num_command_line_args,
2439 command_line_args));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002440
Ted Kremenek25a11e12011-03-22 01:15:24 +00002441 // Recover resources if we crash before exiting this function.
David Blaikied6471f72011-09-25 23:23:43 +00002442 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
2443 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00002444 DiagCleanup(Diags.getPtr());
2445
2446 llvm::OwningPtr<std::vector<ASTUnit::RemappedFile> >
2447 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2448
2449 // Recover resources if we crash before exiting this function.
2450 llvm::CrashRecoveryContextCleanupRegistrar<
2451 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2452
Douglas Gregor4db64a42010-01-23 00:14:00 +00002453 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002454 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002455 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002456 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002457 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2458 Buffer));
Douglas Gregor4db64a42010-01-23 00:14:00 +00002459 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002460
Ted Kremenek25a11e12011-03-22 01:15:24 +00002461 llvm::OwningPtr<std::vector<const char *> >
2462 Args(new std::vector<const char*>());
2463
2464 // Recover resources if we crash before exiting this method.
2465 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
2466 ArgsCleanup(Args.get());
2467
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002468 // Since the Clang C library is primarily used by batch tools dealing with
2469 // (often very broken) source code, where spell-checking can have a
2470 // significant negative impact on performance (particularly when
2471 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002472 // Only do this if we haven't found a spell-checking-related argument.
2473 bool FoundSpellCheckingArgument = false;
2474 for (int I = 0; I != num_command_line_args; ++I) {
2475 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2476 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2477 FoundSpellCheckingArgument = true;
2478 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002479 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002480 }
2481 if (!FoundSpellCheckingArgument)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002482 Args->push_back("-fno-spell-checking");
Douglas Gregorb10daed2010-10-11 16:52:23 +00002483
Ted Kremenek25a11e12011-03-22 01:15:24 +00002484 Args->insert(Args->end(), command_line_args,
2485 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002486
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002487 // The 'source_filename' argument is optional. If the caller does not
2488 // specify it then it is assumed that the source file is specified
2489 // in the actual argument list.
2490 // Put the source file after command_line_args otherwise if '-x' flag is
2491 // present it will be unused.
2492 if (source_filename)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002493 Args->push_back(source_filename);
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002494
Douglas Gregor44c181a2010-07-23 00:33:23 +00002495 // Do we need the detailed preprocessing record?
Chandler Carruthba7537f2011-07-14 09:02:10 +00002496 bool NestedMacroExpansions = false;
Douglas Gregor44c181a2010-07-23 00:33:23 +00002497 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Ted Kremenek25a11e12011-03-22 01:15:24 +00002498 Args->push_back("-Xclang");
2499 Args->push_back("-detailed-preprocessing-record");
Chandler Carruthba7537f2011-07-14 09:02:10 +00002500 NestedMacroExpansions
2501 = (options & CXTranslationUnit_NestedMacroExpansions);
Douglas Gregor44c181a2010-07-23 00:33:23 +00002502 }
2503
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002504 unsigned NumErrors = Diags->getClient()->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002505 llvm::OwningPtr<ASTUnit> Unit(
Ted Kremenek4ee99262011-03-22 20:16:19 +00002506 ASTUnit::LoadFromCommandLine(Args->size() ? &(*Args)[0] : 0
2507 /* vector::data() not portable */,
2508 Args->size() ? (&(*Args)[0] + Args->size()) :0,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002509 Diags,
2510 CXXIdx->getClangResourcesPath(),
2511 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002512 /*CaptureDiagnostics=*/true,
Ted Kremenek4ee99262011-03-22 20:16:19 +00002513 RemappedFiles->size() ? &(*RemappedFiles)[0]:0,
Ted Kremenek25a11e12011-03-22 01:15:24 +00002514 RemappedFiles->size(),
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00002515 /*RemappedFilesKeepOriginalName=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002516 PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00002517 TUKind,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002518 CacheCodeCompetionResults,
Chandler Carruthba7537f2011-07-14 09:02:10 +00002519 NestedMacroExpansions));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002520
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002521 if (NumErrors != Diags->getClient()->getNumErrors()) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002522 // Make sure to check that 'Unit' is non-NULL.
2523 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2524 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2525 DEnd = Unit->stored_diag_end();
2526 D != DEnd; ++D) {
2527 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2528 CXString Msg = clang_formatDiagnostic(&Diag,
2529 clang_defaultDiagnosticDisplayOptions());
2530 fprintf(stderr, "%s\n", clang_getCString(Msg));
2531 clang_disposeString(Msg);
2532 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002533#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002534 // On Windows, force a flush, since there may be multiple copies of
2535 // stderr and stdout in the file system, all with different buffers
2536 // but writing to the same device.
2537 fflush(stderr);
2538#endif
2539 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002540 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002541
Ted Kremeneka60ed472010-11-16 08:15:36 +00002542 PTUI->result = MakeCXTranslationUnit(Unit.take());
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002543}
2544CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2545 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002546 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002547 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002548 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002549 unsigned num_unsaved_files,
2550 unsigned options) {
2551 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002552 num_command_line_args, unsaved_files,
2553 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002554 llvm::CrashRecoveryContext CRC;
2555
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002556 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002557 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2558 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2559 fprintf(stderr, " 'command_line_args' : [");
2560 for (int i = 0; i != num_command_line_args; ++i) {
2561 if (i)
2562 fprintf(stderr, ", ");
2563 fprintf(stderr, "'%s'", command_line_args[i]);
2564 }
2565 fprintf(stderr, "],\n");
2566 fprintf(stderr, " 'unsaved_files' : [");
2567 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2568 if (i)
2569 fprintf(stderr, ", ");
2570 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2571 unsaved_files[i].Length);
2572 }
2573 fprintf(stderr, "],\n");
2574 fprintf(stderr, " 'options' : %d,\n", options);
2575 fprintf(stderr, "}\n");
2576
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002577 return 0;
Douglas Gregor6df78732011-05-05 20:27:22 +00002578 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
2579 PrintLibclangResourceUsage(PTUI.result);
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002580 }
Douglas Gregor6df78732011-05-05 20:27:22 +00002581
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002582 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002583}
2584
Douglas Gregor19998442010-08-13 15:35:05 +00002585unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2586 return CXSaveTranslationUnit_None;
2587}
2588
2589int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2590 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002591 if (!TU)
Douglas Gregor39c411f2011-07-06 16:43:36 +00002592 return CXSaveError_InvalidTU;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002593
Douglas Gregor39c411f2011-07-06 16:43:36 +00002594 CXSaveError result = static_cast<ASTUnit *>(TU->TUData)->Save(FileName);
Douglas Gregor6df78732011-05-05 20:27:22 +00002595 if (getenv("LIBCLANG_RESOURCE_USAGE"))
2596 PrintLibclangResourceUsage(TU);
2597 return result;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002598}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002599
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002600void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002601 if (CTUnit) {
2602 // If the translation unit has been marked as unsafe to free, just discard
2603 // it.
Ted Kremeneka60ed472010-11-16 08:15:36 +00002604 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002605 return;
2606
Ted Kremeneka60ed472010-11-16 08:15:36 +00002607 delete static_cast<ASTUnit *>(CTUnit->TUData);
2608 disposeCXStringPool(CTUnit->StringPool);
Ted Kremenek15322172011-11-10 08:43:12 +00002609 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002610 delete CTUnit;
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002611 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002612}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002613
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002614unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2615 return CXReparse_None;
2616}
2617
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002618struct ReparseTranslationUnitInfo {
2619 CXTranslationUnit TU;
2620 unsigned num_unsaved_files;
2621 struct CXUnsavedFile *unsaved_files;
2622 unsigned options;
2623 int result;
2624};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002625
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002626static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002627 ReparseTranslationUnitInfo *RTUI =
2628 static_cast<ReparseTranslationUnitInfo*>(UserData);
2629 CXTranslationUnit TU = RTUI->TU;
Ted Kremenek15322172011-11-10 08:43:12 +00002630
2631 // Reset the associated diagnostics.
2632 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
2633 TU->Diagnostics = 0;
2634
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002635 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2636 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2637 unsigned options = RTUI->options;
2638 (void) options;
2639 RTUI->result = 1;
2640
Douglas Gregorabc563f2010-07-19 21:46:24 +00002641 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002642 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002643
Ted Kremeneka60ed472010-11-16 08:15:36 +00002644 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor593b0c12010-09-23 18:47:53 +00002645 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002646
Ted Kremenek25a11e12011-03-22 01:15:24 +00002647 llvm::OwningPtr<std::vector<ASTUnit::RemappedFile> >
2648 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2649
2650 // Recover resources if we crash before exiting this function.
2651 llvm::CrashRecoveryContextCleanupRegistrar<
2652 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2653
Douglas Gregorabc563f2010-07-19 21:46:24 +00002654 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002655 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002656 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002657 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002658 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2659 Buffer));
Douglas Gregorabc563f2010-07-19 21:46:24 +00002660 }
2661
Ted Kremenek4ee99262011-03-22 20:16:19 +00002662 if (!CXXUnit->Reparse(RemappedFiles->size() ? &(*RemappedFiles)[0] : 0,
2663 RemappedFiles->size()))
Douglas Gregor593b0c12010-09-23 18:47:53 +00002664 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002665}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002666
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002667int clang_reparseTranslationUnit(CXTranslationUnit TU,
2668 unsigned num_unsaved_files,
2669 struct CXUnsavedFile *unsaved_files,
2670 unsigned options) {
2671 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2672 options, 0 };
Argyrios Kyrtzidis8c4b47e2011-10-28 22:54:33 +00002673
Argyrios Kyrtzidise7de9b42011-10-29 19:32:39 +00002674 if (getenv("LIBCLANG_NOTHREADS")) {
Argyrios Kyrtzidis8c4b47e2011-10-28 22:54:33 +00002675 clang_reparseTranslationUnit_Impl(&RTUI);
2676 return RTUI.result;
2677 }
2678
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002679 llvm::CrashRecoveryContext CRC;
2680
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002681 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002682 fprintf(stderr, "libclang: crash detected during reparsing\n");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002683 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002684 return 1;
Douglas Gregor6df78732011-05-05 20:27:22 +00002685 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
2686 PrintLibclangResourceUsage(TU);
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002687
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002688 return RTUI.result;
2689}
2690
Douglas Gregordf95a132010-08-09 20:45:32 +00002691
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002692CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002693 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002694 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002695
Ted Kremeneka60ed472010-11-16 08:15:36 +00002696 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002697 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002698}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002699
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002700CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002701 CXCursor Result = { CXCursor_TranslationUnit, 0, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002702 return Result;
2703}
2704
Ted Kremenekfb480492010-01-13 21:46:36 +00002705} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002706
Ted Kremenekfb480492010-01-13 21:46:36 +00002707//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002708// CXFile Operations.
2709//===----------------------------------------------------------------------===//
2710
2711extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002712CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002713 if (!SFile)
Ted Kremeneka60ed472010-11-16 08:15:36 +00002714 return createCXString((const char*)NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002715
Steve Naroff88145032009-10-27 14:35:18 +00002716 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002717 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002718}
2719
2720time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002721 if (!SFile)
2722 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002723
Steve Naroff88145032009-10-27 14:35:18 +00002724 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2725 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002726}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002727
Douglas Gregorb9790342010-01-22 21:44:22 +00002728CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2729 if (!tu)
2730 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002731
Ted Kremeneka60ed472010-11-16 08:15:36 +00002732 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002733
Douglas Gregorb9790342010-01-22 21:44:22 +00002734 FileManager &FMgr = CXXUnit->getFileManager();
Chris Lattner39b49bc2010-11-23 08:35:12 +00002735 return const_cast<FileEntry *>(FMgr.getFile(file_name));
Douglas Gregorb9790342010-01-22 21:44:22 +00002736}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002737
Douglas Gregordd3e5542011-05-04 00:14:37 +00002738unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit tu, CXFile file) {
2739 if (!tu || !file)
2740 return 0;
2741
2742 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
2743 FileEntry *FEnt = static_cast<FileEntry *>(file);
2744 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
2745 .isFileMultipleIncludeGuarded(FEnt);
2746}
2747
Ted Kremenekfb480492010-01-13 21:46:36 +00002748} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002749
Ted Kremenekfb480492010-01-13 21:46:36 +00002750//===----------------------------------------------------------------------===//
2751// CXCursor Operations.
2752//===----------------------------------------------------------------------===//
2753
Ted Kremenekfb480492010-01-13 21:46:36 +00002754static Decl *getDeclFromExpr(Stmt *E) {
Argyrios Kyrtzidisc2954612011-09-12 22:17:26 +00002755 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Douglas Gregordb1314e2010-10-01 21:11:22 +00002756 return getDeclFromExpr(CE->getSubExpr());
2757
Ted Kremenekfb480492010-01-13 21:46:36 +00002758 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2759 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002760 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2761 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002762 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2763 return ME->getMemberDecl();
2764 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2765 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002766 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
John McCall12f78a62010-12-02 01:19:52 +00002767 return PRE->isExplicitProperty() ? PRE->getExplicitProperty() : 0;
John McCall4b9c2d22011-11-06 09:01:30 +00002768 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
2769 return getDeclFromExpr(POE->getSyntacticForm());
2770 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
2771 if (Expr *Src = OVE->getSourceExpr())
2772 return getDeclFromExpr(Src);
Douglas Gregordb1314e2010-10-01 21:11:22 +00002773
Ted Kremenekfb480492010-01-13 21:46:36 +00002774 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2775 return getDeclFromExpr(CE->getCallee());
Chris Lattner5f9e2722011-07-23 10:55:15 +00002776 if (CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Douglas Gregor93798e22010-11-05 21:11:19 +00002777 if (!CE->isElidable())
2778 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002779 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2780 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002781
Douglas Gregordb1314e2010-10-01 21:11:22 +00002782 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2783 return PE->getProtocol();
Douglas Gregorc7793c72011-01-15 01:15:58 +00002784 if (SubstNonTypeTemplateParmPackExpr *NTTP
2785 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
2786 return NTTP->getParameterPack();
Douglas Gregor94d96292011-01-19 20:34:17 +00002787 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2788 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
2789 isa<ParmVarDecl>(SizeOfPack->getPack()))
2790 return SizeOfPack->getPack();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002791
Ted Kremenekfb480492010-01-13 21:46:36 +00002792 return 0;
2793}
2794
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002795static SourceLocation getLocationFromExpr(Expr *E) {
Argyrios Kyrtzidisc2954612011-09-12 22:17:26 +00002796 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
2797 return getLocationFromExpr(CE->getSubExpr());
2798
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002799 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2800 return /*FIXME:*/Msg->getLeftLoc();
2801 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2802 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002803 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2804 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002805 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2806 return Member->getMemberLoc();
2807 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2808 return Ivar->getLocation();
Douglas Gregor94d96292011-01-19 20:34:17 +00002809 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2810 return SizeOfPack->getPackLoc();
2811
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002812 return E->getLocStart();
2813}
2814
Ted Kremenekfb480492010-01-13 21:46:36 +00002815extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002816
2817unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002818 CXCursorVisitor visitor,
2819 CXClientData client_data) {
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00002820 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
2821 /*VisitPreprocessorLast=*/false);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002822 return CursorVis.VisitChildren(parent);
2823}
2824
David Chisnall3387c652010-11-03 14:12:26 +00002825#ifndef __has_feature
2826#define __has_feature(x) 0
2827#endif
2828#if __has_feature(blocks)
2829typedef enum CXChildVisitResult
2830 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2831
2832static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2833 CXClientData client_data) {
2834 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2835 return block(cursor, parent);
2836}
2837#else
2838// If we are compiled with a compiler that doesn't have native blocks support,
2839// define and call the block manually, so the
2840typedef struct _CXChildVisitResult
2841{
2842 void *isa;
2843 int flags;
2844 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002845 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2846 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00002847} *CXCursorVisitorBlock;
2848
2849static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2850 CXClientData client_data) {
2851 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2852 return block->invoke(block, cursor, parent);
2853}
2854#endif
2855
2856
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002857unsigned clang_visitChildrenWithBlock(CXCursor parent,
2858 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00002859 return clang_visitChildren(parent, visitWithBlock, block);
2860}
2861
Douglas Gregor78205d42010-01-20 21:45:58 +00002862static CXString getDeclSpelling(Decl *D) {
2863 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
Douglas Gregore3c60a72010-11-17 00:13:31 +00002864 if (!ND) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002865 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00002866 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
2867 return createCXString(Property->getIdentifier()->getName());
2868
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002869 return createCXString("");
Douglas Gregore3c60a72010-11-17 00:13:31 +00002870 }
2871
Douglas Gregor78205d42010-01-20 21:45:58 +00002872 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002873 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002874
Douglas Gregor78205d42010-01-20 21:45:58 +00002875 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2876 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2877 // and returns different names. NamedDecl returns the class name and
2878 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002879 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002880
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002881 if (isa<UsingDirectiveDecl>(D))
2882 return createCXString("");
2883
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002884 llvm::SmallString<1024> S;
2885 llvm::raw_svector_ostream os(S);
2886 ND->printName(os);
2887
2888 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002889}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002890
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002891CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002892 if (clang_isTranslationUnit(C.kind))
Ted Kremeneka60ed472010-11-16 08:15:36 +00002893 return clang_getTranslationUnitSpelling(
2894 static_cast<CXTranslationUnit>(C.data[2]));
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002895
Steve Narofff334b4e2009-09-02 18:26:48 +00002896 if (clang_isReference(C.kind)) {
2897 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002898 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002899 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002900 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002901 }
2902 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002903 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002904 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002905 }
2906 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002907 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002908 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002909 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002910 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002911 case CXCursor_CXXBaseSpecifier: {
2912 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2913 return createCXString(B->getType().getAsString());
2914 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002915 case CXCursor_TypeRef: {
2916 TypeDecl *Type = getCursorTypeRef(C).first;
2917 assert(Type && "Missing type decl");
2918
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002919 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2920 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002921 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002922 case CXCursor_TemplateRef: {
2923 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002924 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002925
2926 return createCXString(Template->getNameAsString());
2927 }
Douglas Gregor69319002010-08-31 23:48:11 +00002928
2929 case CXCursor_NamespaceRef: {
2930 NamedDecl *NS = getCursorNamespaceRef(C).first;
2931 assert(NS && "Missing namespace decl");
2932
2933 return createCXString(NS->getNameAsString());
2934 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002935
Douglas Gregora67e03f2010-09-09 21:42:20 +00002936 case CXCursor_MemberRef: {
2937 FieldDecl *Field = getCursorMemberRef(C).first;
2938 assert(Field && "Missing member decl");
2939
2940 return createCXString(Field->getNameAsString());
2941 }
2942
Douglas Gregor36897b02010-09-10 00:22:18 +00002943 case CXCursor_LabelRef: {
2944 LabelStmt *Label = getCursorLabelRef(C).first;
2945 assert(Label && "Missing label");
2946
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002947 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00002948 }
2949
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002950 case CXCursor_OverloadedDeclRef: {
2951 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2952 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2953 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2954 return createCXString(ND->getNameAsString());
2955 return createCXString("");
2956 }
2957 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2958 return createCXString(E->getName().getAsString());
2959 OverloadedTemplateStorage *Ovl
2960 = Storage.get<OverloadedTemplateStorage*>();
2961 if (Ovl->size() == 0)
2962 return createCXString("");
2963 return createCXString((*Ovl->begin())->getNameAsString());
2964 }
2965
Daniel Dunbaracca7252009-11-30 20:42:49 +00002966 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002967 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002968 }
2969 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002970
2971 if (clang_isExpression(C.kind)) {
2972 Decl *D = getDeclFromExpr(getCursorExpr(C));
2973 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002974 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002975 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002976 }
2977
Douglas Gregor36897b02010-09-10 00:22:18 +00002978 if (clang_isStatement(C.kind)) {
2979 Stmt *S = getCursorStmt(C);
2980 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002981 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00002982
2983 return createCXString("");
2984 }
2985
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00002986 if (C.kind == CXCursor_MacroExpansion)
Chandler Carruth9e5bb852011-07-14 08:20:46 +00002987 return createCXString(getCursorMacroExpansion(C)->getName()
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002988 ->getNameStart());
2989
Douglas Gregor572feb22010-03-18 18:04:21 +00002990 if (C.kind == CXCursor_MacroDefinition)
2991 return createCXString(getCursorMacroDefinition(C)->getName()
2992 ->getNameStart());
2993
Douglas Gregorecdcb882010-10-20 22:00:55 +00002994 if (C.kind == CXCursor_InclusionDirective)
2995 return createCXString(getCursorInclusionDirective(C)->getFileName());
2996
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002997 if (clang_isDeclaration(C.kind))
2998 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002999
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00003000 if (C.kind == CXCursor_AnnotateAttr) {
3001 AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
3002 return createCXString(AA->getAnnotation());
3003 }
3004
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003005 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00003006}
3007
Douglas Gregor358559d2010-10-02 22:49:11 +00003008CXString clang_getCursorDisplayName(CXCursor C) {
3009 if (!clang_isDeclaration(C.kind))
3010 return clang_getCursorSpelling(C);
3011
3012 Decl *D = getCursorDecl(C);
3013 if (!D)
3014 return createCXString("");
3015
Douglas Gregor30c42402011-09-27 22:38:19 +00003016 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
Douglas Gregor358559d2010-10-02 22:49:11 +00003017 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
3018 D = FunTmpl->getTemplatedDecl();
3019
3020 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
3021 llvm::SmallString<64> Str;
3022 llvm::raw_svector_ostream OS(Str);
3023 OS << Function->getNameAsString();
3024 if (Function->getPrimaryTemplate())
3025 OS << "<>";
3026 OS << "(";
3027 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
3028 if (I)
3029 OS << ", ";
3030 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
3031 }
3032
3033 if (Function->isVariadic()) {
3034 if (Function->getNumParams())
3035 OS << ", ";
3036 OS << "...";
3037 }
3038 OS << ")";
3039 return createCXString(OS.str());
3040 }
3041
3042 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
3043 llvm::SmallString<64> Str;
3044 llvm::raw_svector_ostream OS(Str);
3045 OS << ClassTemplate->getNameAsString();
3046 OS << "<";
3047 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
3048 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3049 if (I)
3050 OS << ", ";
3051
3052 NamedDecl *Param = Params->getParam(I);
3053 if (Param->getIdentifier()) {
3054 OS << Param->getIdentifier()->getName();
3055 continue;
3056 }
3057
3058 // There is no parameter name, which makes this tricky. Try to come up
3059 // with something useful that isn't too long.
3060 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3061 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
3062 else if (NonTypeTemplateParmDecl *NTTP
3063 = dyn_cast<NonTypeTemplateParmDecl>(Param))
3064 OS << NTTP->getType().getAsString(Policy);
3065 else
3066 OS << "template<...> class";
3067 }
3068
3069 OS << ">";
3070 return createCXString(OS.str());
3071 }
3072
3073 if (ClassTemplateSpecializationDecl *ClassSpec
3074 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
3075 // If the type was explicitly written, use that.
3076 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
3077 return createCXString(TSInfo->getType().getAsString(Policy));
3078
3079 llvm::SmallString<64> Str;
3080 llvm::raw_svector_ostream OS(Str);
3081 OS << ClassSpec->getNameAsString();
3082 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00003083 ClassSpec->getTemplateArgs().data(),
3084 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00003085 Policy);
3086 return createCXString(OS.str());
3087 }
3088
3089 return clang_getCursorSpelling(C);
3090}
3091
Ted Kremeneke68fff62010-02-17 00:41:32 +00003092CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00003093 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00003094 case CXCursor_FunctionDecl:
3095 return createCXString("FunctionDecl");
3096 case CXCursor_TypedefDecl:
3097 return createCXString("TypedefDecl");
3098 case CXCursor_EnumDecl:
3099 return createCXString("EnumDecl");
3100 case CXCursor_EnumConstantDecl:
3101 return createCXString("EnumConstantDecl");
3102 case CXCursor_StructDecl:
3103 return createCXString("StructDecl");
3104 case CXCursor_UnionDecl:
3105 return createCXString("UnionDecl");
3106 case CXCursor_ClassDecl:
3107 return createCXString("ClassDecl");
3108 case CXCursor_FieldDecl:
3109 return createCXString("FieldDecl");
3110 case CXCursor_VarDecl:
3111 return createCXString("VarDecl");
3112 case CXCursor_ParmDecl:
3113 return createCXString("ParmDecl");
3114 case CXCursor_ObjCInterfaceDecl:
3115 return createCXString("ObjCInterfaceDecl");
3116 case CXCursor_ObjCCategoryDecl:
3117 return createCXString("ObjCCategoryDecl");
3118 case CXCursor_ObjCProtocolDecl:
3119 return createCXString("ObjCProtocolDecl");
3120 case CXCursor_ObjCPropertyDecl:
3121 return createCXString("ObjCPropertyDecl");
3122 case CXCursor_ObjCIvarDecl:
3123 return createCXString("ObjCIvarDecl");
3124 case CXCursor_ObjCInstanceMethodDecl:
3125 return createCXString("ObjCInstanceMethodDecl");
3126 case CXCursor_ObjCClassMethodDecl:
3127 return createCXString("ObjCClassMethodDecl");
3128 case CXCursor_ObjCImplementationDecl:
3129 return createCXString("ObjCImplementationDecl");
3130 case CXCursor_ObjCCategoryImplDecl:
3131 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00003132 case CXCursor_CXXMethod:
3133 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003134 case CXCursor_UnexposedDecl:
3135 return createCXString("UnexposedDecl");
3136 case CXCursor_ObjCSuperClassRef:
3137 return createCXString("ObjCSuperClassRef");
3138 case CXCursor_ObjCProtocolRef:
3139 return createCXString("ObjCProtocolRef");
3140 case CXCursor_ObjCClassRef:
3141 return createCXString("ObjCClassRef");
3142 case CXCursor_TypeRef:
3143 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003144 case CXCursor_TemplateRef:
3145 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00003146 case CXCursor_NamespaceRef:
3147 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00003148 case CXCursor_MemberRef:
3149 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00003150 case CXCursor_LabelRef:
3151 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003152 case CXCursor_OverloadedDeclRef:
3153 return createCXString("OverloadedDeclRef");
Douglas Gregor42b29842011-10-05 19:00:14 +00003154 case CXCursor_IntegerLiteral:
3155 return createCXString("IntegerLiteral");
3156 case CXCursor_FloatingLiteral:
3157 return createCXString("FloatingLiteral");
3158 case CXCursor_ImaginaryLiteral:
3159 return createCXString("ImaginaryLiteral");
3160 case CXCursor_StringLiteral:
3161 return createCXString("StringLiteral");
3162 case CXCursor_CharacterLiteral:
3163 return createCXString("CharacterLiteral");
3164 case CXCursor_ParenExpr:
3165 return createCXString("ParenExpr");
3166 case CXCursor_UnaryOperator:
3167 return createCXString("UnaryOperator");
3168 case CXCursor_ArraySubscriptExpr:
3169 return createCXString("ArraySubscriptExpr");
3170 case CXCursor_BinaryOperator:
3171 return createCXString("BinaryOperator");
3172 case CXCursor_CompoundAssignOperator:
3173 return createCXString("CompoundAssignOperator");
3174 case CXCursor_ConditionalOperator:
3175 return createCXString("ConditionalOperator");
3176 case CXCursor_CStyleCastExpr:
3177 return createCXString("CStyleCastExpr");
3178 case CXCursor_CompoundLiteralExpr:
3179 return createCXString("CompoundLiteralExpr");
3180 case CXCursor_InitListExpr:
3181 return createCXString("InitListExpr");
3182 case CXCursor_AddrLabelExpr:
3183 return createCXString("AddrLabelExpr");
3184 case CXCursor_StmtExpr:
3185 return createCXString("StmtExpr");
3186 case CXCursor_GenericSelectionExpr:
3187 return createCXString("GenericSelectionExpr");
3188 case CXCursor_GNUNullExpr:
3189 return createCXString("GNUNullExpr");
3190 case CXCursor_CXXStaticCastExpr:
3191 return createCXString("CXXStaticCastExpr");
3192 case CXCursor_CXXDynamicCastExpr:
3193 return createCXString("CXXDynamicCastExpr");
3194 case CXCursor_CXXReinterpretCastExpr:
3195 return createCXString("CXXReinterpretCastExpr");
3196 case CXCursor_CXXConstCastExpr:
3197 return createCXString("CXXConstCastExpr");
3198 case CXCursor_CXXFunctionalCastExpr:
3199 return createCXString("CXXFunctionalCastExpr");
3200 case CXCursor_CXXTypeidExpr:
3201 return createCXString("CXXTypeidExpr");
3202 case CXCursor_CXXBoolLiteralExpr:
3203 return createCXString("CXXBoolLiteralExpr");
3204 case CXCursor_CXXNullPtrLiteralExpr:
3205 return createCXString("CXXNullPtrLiteralExpr");
3206 case CXCursor_CXXThisExpr:
3207 return createCXString("CXXThisExpr");
3208 case CXCursor_CXXThrowExpr:
3209 return createCXString("CXXThrowExpr");
3210 case CXCursor_CXXNewExpr:
3211 return createCXString("CXXNewExpr");
3212 case CXCursor_CXXDeleteExpr:
3213 return createCXString("CXXDeleteExpr");
3214 case CXCursor_UnaryExpr:
3215 return createCXString("UnaryExpr");
3216 case CXCursor_ObjCStringLiteral:
3217 return createCXString("ObjCStringLiteral");
3218 case CXCursor_ObjCEncodeExpr:
3219 return createCXString("ObjCEncodeExpr");
3220 case CXCursor_ObjCSelectorExpr:
3221 return createCXString("ObjCSelectorExpr");
3222 case CXCursor_ObjCProtocolExpr:
3223 return createCXString("ObjCProtocolExpr");
3224 case CXCursor_ObjCBridgedCastExpr:
3225 return createCXString("ObjCBridgedCastExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00003226 case CXCursor_BlockExpr:
3227 return createCXString("BlockExpr");
Douglas Gregor42b29842011-10-05 19:00:14 +00003228 case CXCursor_PackExpansionExpr:
3229 return createCXString("PackExpansionExpr");
3230 case CXCursor_SizeOfPackExpr:
3231 return createCXString("SizeOfPackExpr");
3232 case CXCursor_UnexposedExpr:
3233 return createCXString("UnexposedExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003234 case CXCursor_DeclRefExpr:
3235 return createCXString("DeclRefExpr");
3236 case CXCursor_MemberRefExpr:
3237 return createCXString("MemberRefExpr");
3238 case CXCursor_CallExpr:
3239 return createCXString("CallExpr");
3240 case CXCursor_ObjCMessageExpr:
3241 return createCXString("ObjCMessageExpr");
3242 case CXCursor_UnexposedStmt:
3243 return createCXString("UnexposedStmt");
Douglas Gregor42b29842011-10-05 19:00:14 +00003244 case CXCursor_DeclStmt:
3245 return createCXString("DeclStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00003246 case CXCursor_LabelStmt:
3247 return createCXString("LabelStmt");
Douglas Gregor42b29842011-10-05 19:00:14 +00003248 case CXCursor_CompoundStmt:
3249 return createCXString("CompoundStmt");
3250 case CXCursor_CaseStmt:
3251 return createCXString("CaseStmt");
3252 case CXCursor_DefaultStmt:
3253 return createCXString("DefaultStmt");
3254 case CXCursor_IfStmt:
3255 return createCXString("IfStmt");
3256 case CXCursor_SwitchStmt:
3257 return createCXString("SwitchStmt");
3258 case CXCursor_WhileStmt:
3259 return createCXString("WhileStmt");
3260 case CXCursor_DoStmt:
3261 return createCXString("DoStmt");
3262 case CXCursor_ForStmt:
3263 return createCXString("ForStmt");
3264 case CXCursor_GotoStmt:
3265 return createCXString("GotoStmt");
3266 case CXCursor_IndirectGotoStmt:
3267 return createCXString("IndirectGotoStmt");
3268 case CXCursor_ContinueStmt:
3269 return createCXString("ContinueStmt");
3270 case CXCursor_BreakStmt:
3271 return createCXString("BreakStmt");
3272 case CXCursor_ReturnStmt:
3273 return createCXString("ReturnStmt");
3274 case CXCursor_AsmStmt:
3275 return createCXString("AsmStmt");
3276 case CXCursor_ObjCAtTryStmt:
3277 return createCXString("ObjCAtTryStmt");
3278 case CXCursor_ObjCAtCatchStmt:
3279 return createCXString("ObjCAtCatchStmt");
3280 case CXCursor_ObjCAtFinallyStmt:
3281 return createCXString("ObjCAtFinallyStmt");
3282 case CXCursor_ObjCAtThrowStmt:
3283 return createCXString("ObjCAtThrowStmt");
3284 case CXCursor_ObjCAtSynchronizedStmt:
3285 return createCXString("ObjCAtSynchronizedStmt");
3286 case CXCursor_ObjCAutoreleasePoolStmt:
3287 return createCXString("ObjCAutoreleasePoolStmt");
3288 case CXCursor_ObjCForCollectionStmt:
3289 return createCXString("ObjCForCollectionStmt");
3290 case CXCursor_CXXCatchStmt:
3291 return createCXString("CXXCatchStmt");
3292 case CXCursor_CXXTryStmt:
3293 return createCXString("CXXTryStmt");
3294 case CXCursor_CXXForRangeStmt:
3295 return createCXString("CXXForRangeStmt");
3296 case CXCursor_SEHTryStmt:
3297 return createCXString("SEHTryStmt");
3298 case CXCursor_SEHExceptStmt:
3299 return createCXString("SEHExceptStmt");
3300 case CXCursor_SEHFinallyStmt:
3301 return createCXString("SEHFinallyStmt");
3302 case CXCursor_NullStmt:
3303 return createCXString("NullStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003304 case CXCursor_InvalidFile:
3305 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00003306 case CXCursor_InvalidCode:
3307 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003308 case CXCursor_NoDeclFound:
3309 return createCXString("NoDeclFound");
3310 case CXCursor_NotImplemented:
3311 return createCXString("NotImplemented");
3312 case CXCursor_TranslationUnit:
3313 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00003314 case CXCursor_UnexposedAttr:
3315 return createCXString("UnexposedAttr");
3316 case CXCursor_IBActionAttr:
3317 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003318 case CXCursor_IBOutletAttr:
3319 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003320 case CXCursor_IBOutletCollectionAttr:
3321 return createCXString("attribute(iboutletcollection)");
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00003322 case CXCursor_CXXFinalAttr:
3323 return createCXString("attribute(final)");
3324 case CXCursor_CXXOverrideAttr:
3325 return createCXString("attribute(override)");
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00003326 case CXCursor_AnnotateAttr:
3327 return createCXString("attribute(annotate)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003328 case CXCursor_PreprocessingDirective:
3329 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003330 case CXCursor_MacroDefinition:
3331 return createCXString("macro definition");
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003332 case CXCursor_MacroExpansion:
3333 return createCXString("macro expansion");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003334 case CXCursor_InclusionDirective:
3335 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003336 case CXCursor_Namespace:
3337 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003338 case CXCursor_LinkageSpec:
3339 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003340 case CXCursor_CXXBaseSpecifier:
3341 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003342 case CXCursor_Constructor:
3343 return createCXString("CXXConstructor");
3344 case CXCursor_Destructor:
3345 return createCXString("CXXDestructor");
3346 case CXCursor_ConversionFunction:
3347 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003348 case CXCursor_TemplateTypeParameter:
3349 return createCXString("TemplateTypeParameter");
3350 case CXCursor_NonTypeTemplateParameter:
3351 return createCXString("NonTypeTemplateParameter");
3352 case CXCursor_TemplateTemplateParameter:
3353 return createCXString("TemplateTemplateParameter");
3354 case CXCursor_FunctionTemplate:
3355 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003356 case CXCursor_ClassTemplate:
3357 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003358 case CXCursor_ClassTemplatePartialSpecialization:
3359 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003360 case CXCursor_NamespaceAlias:
3361 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003362 case CXCursor_UsingDirective:
3363 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003364 case CXCursor_UsingDeclaration:
3365 return createCXString("UsingDeclaration");
Richard Smith162e1c12011-04-15 14:24:37 +00003366 case CXCursor_TypeAliasDecl:
Douglas Gregor352697a2011-06-03 23:08:58 +00003367 return createCXString("TypeAliasDecl");
3368 case CXCursor_ObjCSynthesizeDecl:
3369 return createCXString("ObjCSynthesizeDecl");
3370 case CXCursor_ObjCDynamicDecl:
3371 return createCXString("ObjCDynamicDecl");
Argyrios Kyrtzidis2dfdb942011-09-30 17:58:23 +00003372 case CXCursor_CXXAccessSpecifier:
3373 return createCXString("CXXAccessSpecifier");
Steve Naroff89922f82009-08-31 00:59:03 +00003374 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003375
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003376 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneka60ed472010-11-16 08:15:36 +00003377 return createCXString((const char*) 0);
Steve Naroff600866c2009-08-27 19:51:58 +00003378}
Steve Naroff89922f82009-08-31 00:59:03 +00003379
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003380struct GetCursorData {
3381 SourceLocation TokenBeginLoc;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003382 bool PointsAtMacroArgExpansion;
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003383 CXCursor &BestCursor;
3384
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003385 GetCursorData(SourceManager &SM,
3386 SourceLocation tokenBegin, CXCursor &outputCursor)
3387 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
3388 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
3389 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003390};
3391
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003392static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3393 CXCursor parent,
3394 CXClientData client_data) {
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003395 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
3396 CXCursor *BestCursor = &Data->BestCursor;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003397
3398 // If we point inside a macro argument we should provide info of what the
3399 // token is so use the actual cursor, don't replace it with a macro expansion
3400 // cursor.
3401 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
3402 return CXChildVisit_Recurse;
Argyrios Kyrtzidis65ab9072011-09-26 19:05:37 +00003403
3404 if (clang_isDeclaration(cursor.kind)) {
3405 // Avoid having the implicit methods override the property decls.
3406 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(getCursorDecl(cursor)))
3407 if (MD->isImplicit())
3408 return CXChildVisit_Break;
3409 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003410
3411 if (clang_isExpression(cursor.kind) &&
3412 clang_isDeclaration(BestCursor->kind)) {
3413 Decl *D = getCursorDecl(*BestCursor);
3414
3415 // Avoid having the cursor of an expression replace the declaration cursor
3416 // when the expression source range overlaps the declaration range.
3417 // This can happen for C++ constructor expressions whose range generally
3418 // include the variable declaration, e.g.:
3419 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
3420 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
3421 D->getLocation() == Data->TokenBeginLoc)
3422 return CXChildVisit_Break;
3423 }
3424
Douglas Gregor93798e22010-11-05 21:11:19 +00003425 // If our current best cursor is the construction of a temporary object,
3426 // don't replace that cursor with a type reference, because we want
3427 // clang_getCursor() to point at the constructor.
3428 if (clang_isExpression(BestCursor->kind) &&
3429 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003430 cursor.kind == CXCursor_TypeRef) {
3431 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
3432 // as having the actual point on the type reference.
3433 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
Douglas Gregor93798e22010-11-05 21:11:19 +00003434 return CXChildVisit_Recurse;
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003435 }
Douglas Gregor93798e22010-11-05 21:11:19 +00003436
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003437 *BestCursor = cursor;
3438 return CXChildVisit_Recurse;
3439}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003440
Douglas Gregorb9790342010-01-22 21:44:22 +00003441CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3442 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003443 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003444
Ted Kremeneka60ed472010-11-16 08:15:36 +00003445 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003446 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3447
Ted Kremeneka297de22010-01-25 22:34:44 +00003448 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003449 CXCursor Result = cxcursor::getCursor(TU, SLoc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003450
Douglas Gregor40749ee2010-11-03 00:35:38 +00003451 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregor40749ee2010-11-03 00:35:38 +00003452 if (Logging) {
3453 CXFile SearchFile;
3454 unsigned SearchLine, SearchColumn;
3455 CXFile ResultFile;
3456 unsigned ResultLine, ResultColumn;
Douglas Gregor66537982010-11-17 17:14:07 +00003457 CXString SearchFileName, ResultFileName, KindSpelling, USR;
3458 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
Douglas Gregor40749ee2010-11-03 00:35:38 +00003459 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3460
Chandler Carruth20174222011-08-31 16:53:37 +00003461 clang_getExpansionLocation(Loc, &SearchFile, &SearchLine, &SearchColumn, 0);
3462 clang_getExpansionLocation(ResultLoc, &ResultFile, &ResultLine,
3463 &ResultColumn, 0);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003464 SearchFileName = clang_getFileName(SearchFile);
3465 ResultFileName = clang_getFileName(ResultFile);
3466 KindSpelling = clang_getCursorKindSpelling(Result.kind);
Douglas Gregor66537982010-11-17 17:14:07 +00003467 USR = clang_getCursorUSR(Result);
3468 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n",
Douglas Gregor40749ee2010-11-03 00:35:38 +00003469 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3470 clang_getCString(KindSpelling),
Douglas Gregor66537982010-11-17 17:14:07 +00003471 clang_getCString(ResultFileName), ResultLine, ResultColumn,
3472 clang_getCString(USR), IsDef);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003473 clang_disposeString(SearchFileName);
3474 clang_disposeString(ResultFileName);
3475 clang_disposeString(KindSpelling);
Douglas Gregor66537982010-11-17 17:14:07 +00003476 clang_disposeString(USR);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003477
3478 CXCursor Definition = clang_getCursorDefinition(Result);
3479 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
3480 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
3481 CXString DefinitionKindSpelling
3482 = clang_getCursorKindSpelling(Definition.kind);
3483 CXFile DefinitionFile;
3484 unsigned DefinitionLine, DefinitionColumn;
Chandler Carruth20174222011-08-31 16:53:37 +00003485 clang_getExpansionLocation(DefinitionLoc, &DefinitionFile,
3486 &DefinitionLine, &DefinitionColumn, 0);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003487 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
3488 fprintf(stderr, " -> %s(%s:%d:%d)\n",
3489 clang_getCString(DefinitionKindSpelling),
3490 clang_getCString(DefinitionFileName),
3491 DefinitionLine, DefinitionColumn);
3492 clang_disposeString(DefinitionFileName);
3493 clang_disposeString(DefinitionKindSpelling);
3494 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003495 }
3496
Ted Kremeneke68fff62010-02-17 00:41:32 +00003497 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003498}
3499
Ted Kremenek73885552009-11-17 19:28:59 +00003500CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003501 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003502}
3503
3504unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003505 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003506}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003507
Douglas Gregor9ce55842010-11-20 00:09:34 +00003508unsigned clang_hashCursor(CXCursor C) {
3509 unsigned Index = 0;
3510 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
3511 Index = 1;
3512
3513 return llvm::DenseMapInfo<std::pair<unsigned, void*> >::getHashValue(
3514 std::make_pair(C.kind, C.data[Index]));
3515}
3516
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003517unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003518 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3519}
3520
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003521unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003522 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3523}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003524
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003525unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003526 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3527}
3528
Douglas Gregor97b98722010-01-19 23:20:36 +00003529unsigned clang_isExpression(enum CXCursorKind K) {
3530 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3531}
3532
3533unsigned clang_isStatement(enum CXCursorKind K) {
3534 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3535}
3536
Douglas Gregor8be80e12011-07-06 03:00:34 +00003537unsigned clang_isAttribute(enum CXCursorKind K) {
3538 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
3539}
3540
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003541unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3542 return K == CXCursor_TranslationUnit;
3543}
3544
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003545unsigned clang_isPreprocessing(enum CXCursorKind K) {
3546 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3547}
3548
Ted Kremenekad6eff62010-03-08 21:17:29 +00003549unsigned clang_isUnexposed(enum CXCursorKind K) {
3550 switch (K) {
3551 case CXCursor_UnexposedDecl:
3552 case CXCursor_UnexposedExpr:
3553 case CXCursor_UnexposedStmt:
3554 case CXCursor_UnexposedAttr:
3555 return true;
3556 default:
3557 return false;
3558 }
3559}
3560
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003561CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003562 return C.kind;
3563}
3564
Douglas Gregor98258af2010-01-18 22:46:11 +00003565CXSourceLocation clang_getCursorLocation(CXCursor C) {
3566 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003567 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003568 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003569 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3570 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003571 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003572 }
3573
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003574 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003575 std::pair<ObjCProtocolDecl *, SourceLocation> P
3576 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003577 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003578 }
3579
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003580 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003581 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3582 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003583 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003584 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003585
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003586 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003587 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003588 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003589 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003590
3591 case CXCursor_TemplateRef: {
3592 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3593 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3594 }
3595
Douglas Gregor69319002010-08-31 23:48:11 +00003596 case CXCursor_NamespaceRef: {
3597 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3598 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3599 }
3600
Douglas Gregora67e03f2010-09-09 21:42:20 +00003601 case CXCursor_MemberRef: {
3602 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3603 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3604 }
3605
Ted Kremenek3064ef92010-08-27 21:34:58 +00003606 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003607 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3608 if (!BaseSpec)
3609 return clang_getNullLocation();
3610
3611 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3612 return cxloc::translateSourceLocation(getCursorContext(C),
3613 TSInfo->getTypeLoc().getBeginLoc());
3614
3615 return cxloc::translateSourceLocation(getCursorContext(C),
3616 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003617 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003618
Douglas Gregor36897b02010-09-10 00:22:18 +00003619 case CXCursor_LabelRef: {
3620 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3621 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3622 }
3623
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003624 case CXCursor_OverloadedDeclRef:
3625 return cxloc::translateSourceLocation(getCursorContext(C),
3626 getCursorOverloadedDeclRef(C).second);
3627
Douglas Gregorf46034a2010-01-18 23:41:10 +00003628 default:
3629 // FIXME: Need a way to enumerate all non-reference cases.
3630 llvm_unreachable("Missed a reference kind");
3631 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003632 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003633
3634 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003635 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003636 getLocationFromExpr(getCursorExpr(C)));
3637
Douglas Gregor36897b02010-09-10 00:22:18 +00003638 if (clang_isStatement(C.kind))
3639 return cxloc::translateSourceLocation(getCursorContext(C),
3640 getCursorStmt(C)->getLocStart());
3641
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003642 if (C.kind == CXCursor_PreprocessingDirective) {
3643 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3644 return cxloc::translateSourceLocation(getCursorContext(C), L);
3645 }
Douglas Gregor48072312010-03-18 15:23:44 +00003646
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003647 if (C.kind == CXCursor_MacroExpansion) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003648 SourceLocation L
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003649 = cxcursor::getCursorMacroExpansion(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003650 return cxloc::translateSourceLocation(getCursorContext(C), L);
3651 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003652
3653 if (C.kind == CXCursor_MacroDefinition) {
3654 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3655 return cxloc::translateSourceLocation(getCursorContext(C), L);
3656 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003657
3658 if (C.kind == CXCursor_InclusionDirective) {
3659 SourceLocation L
3660 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3661 return cxloc::translateSourceLocation(getCursorContext(C), L);
3662 }
3663
Ted Kremenek9a700d22010-05-12 06:16:13 +00003664 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003665 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003666
Douglas Gregorf46034a2010-01-18 23:41:10 +00003667 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003668 SourceLocation Loc = D->getLocation();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003669 // FIXME: Multiple variables declared in a single declaration
3670 // currently lack the information needed to correctly determine their
3671 // ranges when accounting for the type-specifier. We use context
3672 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3673 // and if so, whether it is the first decl.
3674 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3675 if (!cxcursor::isFirstInDeclGroup(C))
3676 Loc = VD->getLocation();
3677 }
3678
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003679 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003680}
Douglas Gregora7bde202010-01-19 00:34:46 +00003681
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003682} // end extern "C"
3683
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003684CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
3685 assert(TU);
3686
3687 // Guard against an invalid SourceLocation, or we may assert in one
3688 // of the following calls.
3689 if (SLoc.isInvalid())
3690 return clang_getNullCursor();
3691
3692 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
3693
3694 // Translate the given source location to make it point at the beginning of
3695 // the token under the cursor.
3696 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3697 CXXUnit->getASTContext().getLangOptions());
3698
3699 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3700 if (SLoc.isValid()) {
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003701 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003702 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
3703 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00003704 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003705 SourceLocation(SLoc));
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00003706 CursorVis.visitFileRegion();
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003707 }
3708
3709 return Result;
3710}
3711
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003712static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003713 if (clang_isReference(C.kind)) {
3714 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003715 case CXCursor_ObjCSuperClassRef:
3716 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003717
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003718 case CXCursor_ObjCProtocolRef:
3719 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003720
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003721 case CXCursor_ObjCClassRef:
3722 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003723
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003724 case CXCursor_TypeRef:
3725 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003726
3727 case CXCursor_TemplateRef:
3728 return getCursorTemplateRef(C).second;
3729
Douglas Gregor69319002010-08-31 23:48:11 +00003730 case CXCursor_NamespaceRef:
3731 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003732
3733 case CXCursor_MemberRef:
3734 return getCursorMemberRef(C).second;
3735
Ted Kremenek3064ef92010-08-27 21:34:58 +00003736 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003737 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003738
Douglas Gregor36897b02010-09-10 00:22:18 +00003739 case CXCursor_LabelRef:
3740 return getCursorLabelRef(C).second;
3741
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003742 case CXCursor_OverloadedDeclRef:
3743 return getCursorOverloadedDeclRef(C).second;
3744
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003745 default:
3746 // FIXME: Need a way to enumerate all non-reference cases.
3747 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003748 }
3749 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003750
3751 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003752 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003753
3754 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003755 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003756
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00003757 if (clang_isAttribute(C.kind))
3758 return getCursorAttr(C)->getRange();
3759
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003760 if (C.kind == CXCursor_PreprocessingDirective)
3761 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003762
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00003763 if (C.kind == CXCursor_MacroExpansion) {
3764 ASTUnit *TU = getCursorASTUnit(C);
3765 SourceRange Range = cxcursor::getCursorMacroExpansion(C)->getSourceRange();
3766 return TU->mapRangeFromPreamble(Range);
3767 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003768
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00003769 if (C.kind == CXCursor_MacroDefinition) {
3770 ASTUnit *TU = getCursorASTUnit(C);
3771 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
3772 return TU->mapRangeFromPreamble(Range);
3773 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003774
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00003775 if (C.kind == CXCursor_InclusionDirective) {
3776 ASTUnit *TU = getCursorASTUnit(C);
3777 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3778 return TU->mapRangeFromPreamble(Range);
3779 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003780
Ted Kremenek007a7c92010-11-01 23:26:51 +00003781 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3782 Decl *D = cxcursor::getCursorDecl(C);
3783 SourceRange R = D->getSourceRange();
3784 // FIXME: Multiple variables declared in a single declaration
3785 // currently lack the information needed to correctly determine their
3786 // ranges when accounting for the type-specifier. We use context
3787 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3788 // and if so, whether it is the first decl.
3789 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3790 if (!cxcursor::isFirstInDeclGroup(C))
3791 R.setBegin(VD->getLocation());
3792 }
3793 return R;
3794 }
Douglas Gregor66537982010-11-17 17:14:07 +00003795 return SourceRange();
3796}
3797
3798/// \brief Retrieves the "raw" cursor extent, which is then extended to include
3799/// the decl-specifier-seq for declarations.
3800static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
3801 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3802 Decl *D = cxcursor::getCursorDecl(C);
3803 SourceRange R = D->getSourceRange();
Douglas Gregor66537982010-11-17 17:14:07 +00003804
Douglas Gregor2494dd02011-03-01 01:34:45 +00003805 // Adjust the start of the location for declarations preceded by
3806 // declaration specifiers.
3807 SourceLocation StartLoc;
3808 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
3809 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
3810 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
3811 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
3812 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
3813 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
3814 }
3815
3816 if (StartLoc.isValid() && R.getBegin().isValid() &&
3817 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
3818 R.setBegin(StartLoc);
3819
3820 // FIXME: Multiple variables declared in a single declaration
3821 // currently lack the information needed to correctly determine their
3822 // ranges when accounting for the type-specifier. We use context
3823 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3824 // and if so, whether it is the first decl.
3825 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3826 if (!cxcursor::isFirstInDeclGroup(C))
3827 R.setBegin(VD->getLocation());
Douglas Gregor66537982010-11-17 17:14:07 +00003828 }
3829
3830 return R;
3831 }
3832
3833 return getRawCursorExtent(C);
3834}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003835
3836extern "C" {
3837
3838CXSourceRange clang_getCursorExtent(CXCursor C) {
3839 SourceRange R = getRawCursorExtent(C);
3840 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003841 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003842
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003843 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003844}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003845
3846CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003847 if (clang_isInvalid(C.kind))
3848 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003849
Ted Kremeneka60ed472010-11-16 08:15:36 +00003850 CXTranslationUnit tu = getCursorTU(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003851 if (clang_isDeclaration(C.kind)) {
3852 Decl *D = getCursorDecl(C);
3853 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003854 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003855 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003856 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003857 if (ObjCForwardProtocolDecl *Protocols
3858 = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003859 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), tu);
Chris Lattner5f9e2722011-07-23 10:55:15 +00003860 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00003861 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3862 return MakeCXCursor(Property, tu);
3863
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003864 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003865 }
3866
Douglas Gregor97b98722010-01-19 23:20:36 +00003867 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003868 Expr *E = getCursorExpr(C);
3869 Decl *D = getDeclFromExpr(E);
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003870 if (D) {
3871 CXCursor declCursor = MakeCXCursor(D, tu);
3872 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
3873 declCursor);
3874 return declCursor;
3875 }
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003876
3877 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003878 return MakeCursorOverloadedDeclRef(Ovl, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003879
Douglas Gregor97b98722010-01-19 23:20:36 +00003880 return clang_getNullCursor();
3881 }
3882
Douglas Gregor36897b02010-09-10 00:22:18 +00003883 if (clang_isStatement(C.kind)) {
3884 Stmt *S = getCursorStmt(C);
3885 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Ted Kremenek37c2e962011-03-15 23:47:49 +00003886 if (LabelDecl *label = Goto->getLabel())
3887 if (LabelStmt *labelS = label->getStmt())
3888 return MakeCXCursor(labelS, getCursorDecl(C), tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003889
3890 return clang_getNullCursor();
3891 }
3892
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003893 if (C.kind == CXCursor_MacroExpansion) {
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003894 if (MacroDefinition *Def = getCursorMacroExpansion(C)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003895 return MakeMacroDefinitionCursor(Def, tu);
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003896 }
3897
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003898 if (!clang_isReference(C.kind))
3899 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003900
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003901 switch (C.kind) {
3902 case CXCursor_ObjCSuperClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003903 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003904
3905 case CXCursor_ObjCProtocolRef: {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003906 return MakeCXCursor(getCursorObjCProtocolRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003907
3908 case CXCursor_ObjCClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003909 return MakeCXCursor(getCursorObjCClassRef(C).first, tu );
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003910
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003911 case CXCursor_TypeRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003912 return MakeCXCursor(getCursorTypeRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003913
3914 case CXCursor_TemplateRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003915 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003916
Douglas Gregor69319002010-08-31 23:48:11 +00003917 case CXCursor_NamespaceRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003918 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
Douglas Gregor69319002010-08-31 23:48:11 +00003919
Douglas Gregora67e03f2010-09-09 21:42:20 +00003920 case CXCursor_MemberRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003921 return MakeCXCursor(getCursorMemberRef(C).first, tu );
Douglas Gregora67e03f2010-09-09 21:42:20 +00003922
Ted Kremenek3064ef92010-08-27 21:34:58 +00003923 case CXCursor_CXXBaseSpecifier: {
3924 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3925 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003926 tu ));
Ted Kremenek3064ef92010-08-27 21:34:58 +00003927 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003928
Douglas Gregor36897b02010-09-10 00:22:18 +00003929 case CXCursor_LabelRef:
3930 // FIXME: We end up faking the "parent" declaration here because we
3931 // don't want to make CXCursor larger.
3932 return MakeCXCursor(getCursorLabelRef(C).first,
Ted Kremeneka60ed472010-11-16 08:15:36 +00003933 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
3934 .getTranslationUnitDecl(),
3935 tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003936
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003937 case CXCursor_OverloadedDeclRef:
3938 return C;
3939
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003940 default:
3941 // We would prefer to enumerate all non-reference cursor kinds here.
3942 llvm_unreachable("Unhandled reference cursor kind");
3943 break;
3944 }
3945 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003946
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003947 return clang_getNullCursor();
3948}
3949
Douglas Gregorb6998662010-01-19 19:34:47 +00003950CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003951 if (clang_isInvalid(C.kind))
3952 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003953
Ted Kremeneka60ed472010-11-16 08:15:36 +00003954 CXTranslationUnit TU = getCursorTU(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003955
Douglas Gregorb6998662010-01-19 19:34:47 +00003956 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003957 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003958 C = clang_getCursorReferenced(C);
3959 WasReference = true;
3960 }
3961
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003962 if (C.kind == CXCursor_MacroExpansion)
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003963 return clang_getCursorReferenced(C);
3964
Douglas Gregorb6998662010-01-19 19:34:47 +00003965 if (!clang_isDeclaration(C.kind))
3966 return clang_getNullCursor();
3967
3968 Decl *D = getCursorDecl(C);
3969 if (!D)
3970 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003971
Douglas Gregorb6998662010-01-19 19:34:47 +00003972 switch (D->getKind()) {
3973 // Declaration kinds that don't really separate the notions of
3974 // declaration and definition.
3975 case Decl::Namespace:
3976 case Decl::Typedef:
Richard Smith162e1c12011-04-15 14:24:37 +00003977 case Decl::TypeAlias:
Richard Smith3e4c6c42011-05-05 21:57:07 +00003978 case Decl::TypeAliasTemplate:
Douglas Gregorb6998662010-01-19 19:34:47 +00003979 case Decl::TemplateTypeParm:
3980 case Decl::EnumConstant:
3981 case Decl::Field:
Benjamin Kramerd9811462010-11-21 14:11:41 +00003982 case Decl::IndirectField:
Douglas Gregorb6998662010-01-19 19:34:47 +00003983 case Decl::ObjCIvar:
3984 case Decl::ObjCAtDefsField:
3985 case Decl::ImplicitParam:
3986 case Decl::ParmVar:
3987 case Decl::NonTypeTemplateParm:
3988 case Decl::TemplateTemplateParm:
3989 case Decl::ObjCCategoryImpl:
3990 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00003991 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00003992 case Decl::LinkageSpec:
3993 case Decl::ObjCPropertyImpl:
3994 case Decl::FileScopeAsm:
3995 case Decl::StaticAssert:
3996 case Decl::Block:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003997 case Decl::Label: // FIXME: Is this right??
Francois Pichetaf0f4d02011-08-14 03:52:19 +00003998 case Decl::ClassScopeFunctionSpecialization:
Douglas Gregorb6998662010-01-19 19:34:47 +00003999 return C;
4000
4001 // Declaration kinds that don't make any sense here, but are
4002 // nonetheless harmless.
4003 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00004004 break;
4005
4006 // Declaration kinds for which the definition is not resolvable.
4007 case Decl::UnresolvedUsingTypename:
4008 case Decl::UnresolvedUsingValue:
4009 break;
4010
4011 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00004012 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004013 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004014
4015 case Decl::NamespaceAlias:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004016 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004017
4018 case Decl::Enum:
4019 case Decl::Record:
4020 case Decl::CXXRecord:
4021 case Decl::ClassTemplateSpecialization:
4022 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00004023 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004024 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004025 return clang_getNullCursor();
4026
4027 case Decl::Function:
4028 case Decl::CXXMethod:
4029 case Decl::CXXConstructor:
4030 case Decl::CXXDestructor:
4031 case Decl::CXXConversion: {
4032 const FunctionDecl *Def = 0;
4033 if (cast<FunctionDecl>(D)->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004034 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004035 return clang_getNullCursor();
4036 }
4037
4038 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00004039 // Ask the variable if it has a definition.
4040 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004041 return MakeCXCursor(Def, TU);
Sebastian Redl31310a22010-02-01 20:16:42 +00004042 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00004043 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004044
Douglas Gregorb6998662010-01-19 19:34:47 +00004045 case Decl::FunctionTemplate: {
4046 const FunctionDecl *Def = 0;
4047 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004048 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004049 return clang_getNullCursor();
4050 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004051
Douglas Gregorb6998662010-01-19 19:34:47 +00004052 case Decl::ClassTemplate: {
4053 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00004054 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00004055 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004056 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004057 return clang_getNullCursor();
4058 }
4059
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004060 case Decl::Using:
4061 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004062 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004063
4064 case Decl::UsingShadow:
4065 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004066 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004067 TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004068
4069 case Decl::ObjCMethod: {
4070 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
4071 if (Method->isThisDeclarationADefinition())
4072 return C;
4073
4074 // Dig out the method definition in the associated
4075 // @implementation, if we have it.
4076 // FIXME: The ASTs should make finding the definition easier.
4077 if (ObjCInterfaceDecl *Class
4078 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
4079 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
4080 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
4081 Method->isInstanceMethod()))
4082 if (Def->isThisDeclarationADefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004083 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004084
4085 return clang_getNullCursor();
4086 }
4087
4088 case Decl::ObjCCategory:
4089 if (ObjCCategoryImplDecl *Impl
4090 = cast<ObjCCategoryDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004091 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004092 return clang_getNullCursor();
4093
4094 case Decl::ObjCProtocol:
4095 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
4096 return C;
4097 return clang_getNullCursor();
4098
4099 case Decl::ObjCInterface:
4100 // There are two notions of a "definition" for an Objective-C
4101 // class: the interface and its implementation. When we resolved a
4102 // reference to an Objective-C class, produce the @interface as
4103 // the definition; when we were provided with the interface,
4104 // produce the @implementation as the definition.
4105 if (WasReference) {
4106 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
4107 return C;
4108 } else if (ObjCImplementationDecl *Impl
4109 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004110 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004111 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004112
Douglas Gregorb6998662010-01-19 19:34:47 +00004113 case Decl::ObjCProperty:
4114 // FIXME: We don't really know where to find the
4115 // ObjCPropertyImplDecls that implement this property.
4116 return clang_getNullCursor();
4117
4118 case Decl::ObjCCompatibleAlias:
4119 if (ObjCInterfaceDecl *Class
4120 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
4121 if (!Class->isForwardDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004122 return MakeCXCursor(Class, TU);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004123
Douglas Gregorb6998662010-01-19 19:34:47 +00004124 return clang_getNullCursor();
4125
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004126 case Decl::ObjCForwardProtocol:
4127 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004128 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004129
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004130 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004131 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004132 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004133
4134 case Decl::Friend:
4135 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004136 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004137 return clang_getNullCursor();
4138
4139 case Decl::FriendTemplate:
4140 if (NamedDecl *Friend = cast<FriendTemplateDecl>(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
4145 return clang_getNullCursor();
4146}
4147
4148unsigned clang_isCursorDefinition(CXCursor C) {
4149 if (!clang_isDeclaration(C.kind))
4150 return 0;
4151
4152 return clang_getCursorDefinition(C) == C;
4153}
4154
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004155CXCursor clang_getCanonicalCursor(CXCursor C) {
4156 if (!clang_isDeclaration(C.kind))
4157 return C;
4158
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004159 if (Decl *D = getCursorDecl(C)) {
Argyrios Kyrtzidisdebb00f2011-07-15 22:37:58 +00004160 if (ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
4161 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
4162 return MakeCXCursor(CatD, getCursorTU(C));
4163
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004164 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
4165 if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
4166 return MakeCXCursor(IFD, getCursorTU(C));
4167
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004168 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004169 }
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004170
4171 return C;
4172}
4173
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004174unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004175 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004176 return 0;
4177
4178 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
4179 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
4180 return E->getNumDecls();
4181
4182 if (OverloadedTemplateStorage *S
4183 = Storage.dyn_cast<OverloadedTemplateStorage*>())
4184 return S->size();
4185
4186 Decl *D = Storage.get<Decl*>();
4187 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00004188 return Using->shadow_size();
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00004189 if (isa<ObjCClassDecl>(D))
4190 return 1;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004191 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
4192 return Protocols->protocol_size();
4193
4194 return 0;
4195}
4196
4197CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004198 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004199 return clang_getNullCursor();
4200
4201 if (index >= clang_getNumOverloadedDecls(cursor))
4202 return clang_getNullCursor();
4203
Ted Kremeneka60ed472010-11-16 08:15:36 +00004204 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004205 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
4206 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004207 return MakeCXCursor(E->decls_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004208
4209 if (OverloadedTemplateStorage *S
4210 = Storage.dyn_cast<OverloadedTemplateStorage*>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004211 return MakeCXCursor(S->begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004212
4213 Decl *D = Storage.get<Decl*>();
4214 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
4215 // FIXME: This is, unfortunately, linear time.
4216 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
4217 std::advance(Pos, index);
Ted Kremeneka60ed472010-11-16 08:15:36 +00004218 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004219 }
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004220 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00004221 return MakeCXCursor(Classes->getForwardInterfaceDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004222 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004223 return MakeCXCursor(Protocols->protocol_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004224
4225 return clang_getNullCursor();
4226}
4227
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00004228void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00004229 const char **startBuf,
4230 const char **endBuf,
4231 unsigned *startLine,
4232 unsigned *startColumn,
4233 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00004234 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00004235 assert(getCursorDecl(C) && "CXCursor has null decl");
4236 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00004237 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
4238 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004239
Steve Naroff4ade6d62009-09-23 17:52:52 +00004240 SourceManager &SM = FD->getASTContext().getSourceManager();
4241 *startBuf = SM.getCharacterData(Body->getLBracLoc());
4242 *endBuf = SM.getCharacterData(Body->getRBracLoc());
4243 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
4244 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
4245 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
4246 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
4247}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004248
Douglas Gregor430d7a12011-07-25 17:48:11 +00004249
4250CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
4251 unsigned PieceIndex) {
4252 RefNamePieces Pieces;
4253
4254 switch (C.kind) {
4255 case CXCursor_MemberRefExpr:
4256 if (MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
4257 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
4258 E->getQualifierLoc().getSourceRange());
4259 break;
4260
4261 case CXCursor_DeclRefExpr:
4262 if (DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C)))
4263 Pieces = buildPieces(NameFlags, false, E->getNameInfo(),
4264 E->getQualifierLoc().getSourceRange(),
4265 E->getExplicitTemplateArgsOpt());
4266 break;
4267
4268 case CXCursor_CallExpr:
4269 if (CXXOperatorCallExpr *OCE =
4270 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
4271 Expr *Callee = OCE->getCallee();
4272 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
4273 Callee = ICE->getSubExpr();
4274
4275 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
4276 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
4277 DRE->getQualifierLoc().getSourceRange());
4278 }
4279 break;
4280
4281 default:
4282 break;
4283 }
4284
4285 if (Pieces.empty()) {
4286 if (PieceIndex == 0)
4287 return clang_getCursorExtent(C);
4288 } else if (PieceIndex < Pieces.size()) {
4289 SourceRange R = Pieces[PieceIndex];
4290 if (R.isValid())
4291 return cxloc::translateSourceRange(getCursorContext(C), R);
4292 }
4293
4294 return clang_getNullRange();
4295}
4296
Douglas Gregor0a812cf2010-02-18 23:07:20 +00004297void clang_enableStackTraces(void) {
4298 llvm::sys::PrintStackTraceOnErrorSignal();
4299}
4300
Daniel Dunbar995aaf92010-11-04 01:26:29 +00004301void clang_executeOnThread(void (*fn)(void*), void *user_data,
4302 unsigned stack_size) {
4303 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
4304}
4305
Ted Kremenekfb480492010-01-13 21:46:36 +00004306} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00004307
Ted Kremenekfb480492010-01-13 21:46:36 +00004308//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004309// Token-based Operations.
4310//===----------------------------------------------------------------------===//
4311
4312/* CXToken layout:
4313 * int_data[0]: a CXTokenKind
4314 * int_data[1]: starting token location
4315 * int_data[2]: token length
4316 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004317 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004318 * otherwise unused.
4319 */
4320extern "C" {
4321
4322CXTokenKind clang_getTokenKind(CXToken CXTok) {
4323 return static_cast<CXTokenKind>(CXTok.int_data[0]);
4324}
4325
4326CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
4327 switch (clang_getTokenKind(CXTok)) {
4328 case CXToken_Identifier:
4329 case CXToken_Keyword:
4330 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004331 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
4332 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004333
4334 case CXToken_Literal: {
4335 // We have stashed the starting pointer in the ptr_data field. Use it.
4336 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Chris Lattner5f9e2722011-07-23 10:55:15 +00004337 return createCXString(StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004338 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004339
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004340 case CXToken_Punctuation:
4341 case CXToken_Comment:
4342 break;
4343 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004344
4345 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004346 // deconstructing the source location.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004347 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004348 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004349 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004350
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004351 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
4352 std::pair<FileID, unsigned> LocInfo
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004353 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00004354 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004355 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004356 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
4357 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00004358 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004359
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004360 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004361}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004362
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004363CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004364 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004365 if (!CXXUnit)
4366 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004367
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004368 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
4369 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4370}
4371
4372CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004373 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor5352ac02010-01-28 00:27:43 +00004374 if (!CXXUnit)
4375 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004376
4377 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004378 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4379}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004380
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004381static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
4382 SmallVectorImpl<CXToken> &CXTokens) {
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004383 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4384 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004385 = SourceMgr.getDecomposedLoc(Range.getBegin());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004386 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004387 = SourceMgr.getDecomposedLoc(Range.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004388
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004389 // Cannot tokenize across files.
4390 if (BeginLocInfo.first != EndLocInfo.first)
4391 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004392
4393 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004394 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004395 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004396 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00004397 if (Invalid)
4398 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00004399
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004400 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4401 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004402 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004403 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004404
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004405 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004406 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004407 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00004408 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004409 do {
4410 // Lex the next token
4411 Lex.LexFromRawLexer(Tok);
4412 if (Tok.is(tok::eof))
4413 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004414
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004415 // Initialize the CXToken.
4416 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004417
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004418 // - Common fields
4419 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
4420 CXTok.int_data[2] = Tok.getLength();
4421 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004422
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004423 // - Kind-specific fields
4424 if (Tok.isLiteral()) {
4425 CXTok.int_data[0] = CXToken_Literal;
4426 CXTok.ptr_data = (void *)Tok.getLiteralData();
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004427 } else if (Tok.is(tok::raw_identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00004428 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004429 IdentifierInfo *II
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004430 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004431
David Chisnall096428b2010-10-13 21:44:48 +00004432 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004433 CXTok.int_data[0] = CXToken_Keyword;
4434 }
4435 else {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004436 CXTok.int_data[0] = Tok.is(tok::identifier)
4437 ? CXToken_Identifier
4438 : CXToken_Keyword;
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004439 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004440 CXTok.ptr_data = II;
4441 } else if (Tok.is(tok::comment)) {
4442 CXTok.int_data[0] = CXToken_Comment;
4443 CXTok.ptr_data = 0;
4444 } else {
4445 CXTok.int_data[0] = CXToken_Punctuation;
4446 CXTok.ptr_data = 0;
4447 }
4448 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00004449 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004450 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004451}
4452
4453void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
4454 CXToken **Tokens, unsigned *NumTokens) {
4455 if (Tokens)
4456 *Tokens = 0;
4457 if (NumTokens)
4458 *NumTokens = 0;
4459
4460 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4461 if (!CXXUnit || !Tokens || !NumTokens)
4462 return;
4463
4464 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4465
4466 SourceRange R = cxloc::translateCXSourceRange(Range);
4467 if (R.isInvalid())
4468 return;
4469
4470 SmallVector<CXToken, 32> CXTokens;
4471 getTokens(CXXUnit, R, CXTokens);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004472
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004473 if (CXTokens.empty())
4474 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004475
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004476 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
4477 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
4478 *NumTokens = CXTokens.size();
4479}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004480
Ted Kremenek6db61092010-05-05 00:55:15 +00004481void clang_disposeTokens(CXTranslationUnit TU,
4482 CXToken *Tokens, unsigned NumTokens) {
4483 free(Tokens);
4484}
4485
4486} // end: extern "C"
4487
4488//===----------------------------------------------------------------------===//
4489// Token annotation APIs.
4490//===----------------------------------------------------------------------===//
4491
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004492typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004493static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4494 CXCursor parent,
4495 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00004496namespace {
4497class AnnotateTokensWorker {
4498 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004499 CXToken *Tokens;
4500 CXCursor *Cursors;
4501 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004502 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00004503 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004504 CursorVisitor AnnotateVis;
4505 SourceManager &SrcMgr;
Douglas Gregorf5251602011-03-08 17:10:18 +00004506 bool HasContextSensitiveKeywords;
4507
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004508 bool MoreTokens() const { return TokIdx < NumTokens; }
4509 unsigned NextToken() const { return TokIdx; }
4510 void AdvanceToken() { ++TokIdx; }
4511 SourceLocation GetTokenLoc(unsigned tokI) {
4512 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4513 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004514 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004515 return Tokens[tokI].int_data[3] != 0;
4516 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004517 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004518 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[3]);
4519 }
4520
4521 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004522 void annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
4523 SourceRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004524
Ted Kremenek6db61092010-05-05 00:55:15 +00004525public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00004526 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004527 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004528 CXTranslationUnit tu, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00004529 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00004530 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004531 AnnotateVis(tu,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00004532 AnnotateTokensVisitor, this,
4533 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00004534 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00004535 RegionOfInterest),
Douglas Gregorf5251602011-03-08 17:10:18 +00004536 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()),
4537 HasContextSensitiveKeywords(false) { }
Ted Kremenek11949cb2010-05-05 00:55:17 +00004538
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004539 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00004540 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004541 void AnnotateTokens();
Douglas Gregorf5251602011-03-08 17:10:18 +00004542
4543 /// \brief Determine whether the annotator saw any cursors that have
4544 /// context-sensitive keywords.
4545 bool hasContextSensitiveKeywords() const {
4546 return HasContextSensitiveKeywords;
4547 }
Ted Kremenek6db61092010-05-05 00:55:15 +00004548};
4549}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004550
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004551void AnnotateTokensWorker::AnnotateTokens() {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004552 // Walk the AST within the region of interest, annotating tokens
4553 // along the way.
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004554 AnnotateVis.visitFileRegion();
Ted Kremenek11949cb2010-05-05 00:55:17 +00004555
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004556 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4557 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004558 if (Pos != Annotated.end() &&
4559 (clang_isInvalid(Cursors[I].kind) ||
4560 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004561 Cursors[I] = Pos->second;
4562 }
4563
4564 // Finish up annotating any tokens left.
4565 if (!MoreTokens())
4566 return;
4567
4568 const CXCursor &C = clang_getNullCursor();
4569 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004570 if (I < PreprocessingTokIdx && clang_isPreprocessing(Cursors[I].kind))
4571 continue;
4572
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004573 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4574 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004575 }
4576}
4577
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004578/// \brief It annotates and advances tokens with a cursor until the comparison
4579//// between the cursor location and the source range is the same as
4580/// \arg compResult.
4581///
4582/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
4583/// Pass RangeOverlap to annotate tokens inside a range.
4584void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
4585 RangeComparisonResult compResult,
4586 SourceRange range) {
4587 while (MoreTokens()) {
4588 const unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004589 if (isFunctionMacroToken(I))
4590 return annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004591
4592 SourceLocation TokLoc = GetTokenLoc(I);
4593 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4594 Cursors[I] = updateC;
4595 AdvanceToken();
4596 continue;
4597 }
4598 break;
4599 }
4600}
4601
4602/// \brief Special annotation handling for macro argument tokens.
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004603void AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
4604 CXCursor updateC,
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004605 RangeComparisonResult compResult,
4606 SourceRange range) {
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004607 assert(MoreTokens());
4608 assert(isFunctionMacroToken(NextToken()) &&
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004609 "Should be called only for macro arg tokens");
4610
4611 // This works differently than annotateAndAdvanceTokens; because expanded
4612 // macro arguments can have arbitrary translation-unit source order, we do not
4613 // advance the token index one by one until a token fails the range test.
4614 // We only advance once past all of the macro arg tokens if all of them
4615 // pass the range test. If one of them fails we keep the token index pointing
4616 // at the start of the macro arg tokens so that the failing token will be
4617 // annotated by a subsequent annotation try.
4618
4619 bool atLeastOneCompFail = false;
4620
4621 unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004622 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
4623 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004624 if (TokLoc.isFileID())
4625 continue; // not macro arg token, it's parens or comma.
4626 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4627 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
4628 Cursors[I] = updateC;
4629 } else
4630 atLeastOneCompFail = true;
4631 }
4632
4633 if (!atLeastOneCompFail)
4634 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
4635}
4636
Ted Kremenek6db61092010-05-05 00:55:15 +00004637enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004638AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004639 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004640 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004641 if (cursorRange.isInvalid())
4642 return CXChildVisit_Recurse;
Douglas Gregorf5251602011-03-08 17:10:18 +00004643
4644 if (!HasContextSensitiveKeywords) {
4645 // Objective-C properties can have context-sensitive keywords.
4646 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
4647 if (ObjCPropertyDecl *Property
4648 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
4649 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
4650 }
4651 // Objective-C methods can have context-sensitive keywords.
4652 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
4653 cursor.kind == CXCursor_ObjCClassMethodDecl) {
4654 if (ObjCMethodDecl *Method
4655 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
4656 if (Method->getObjCDeclQualifier())
4657 HasContextSensitiveKeywords = true;
4658 else {
4659 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
4660 PEnd = Method->param_end();
4661 P != PEnd; ++P) {
4662 if ((*P)->getObjCDeclQualifier()) {
4663 HasContextSensitiveKeywords = true;
4664 break;
4665 }
4666 }
4667 }
4668 }
4669 }
4670 // C++ methods can have context-sensitive keywords.
4671 else if (cursor.kind == CXCursor_CXXMethod) {
4672 if (CXXMethodDecl *Method
4673 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
4674 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
4675 HasContextSensitiveKeywords = true;
4676 }
4677 }
4678 // C++ classes can have context-sensitive keywords.
4679 else if (cursor.kind == CXCursor_StructDecl ||
4680 cursor.kind == CXCursor_ClassDecl ||
4681 cursor.kind == CXCursor_ClassTemplate ||
4682 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
4683 if (Decl *D = getCursorDecl(cursor))
4684 if (D->hasAttr<FinalAttr>())
4685 HasContextSensitiveKeywords = true;
4686 }
4687 }
4688
Douglas Gregor4419b672010-10-21 06:10:04 +00004689 if (clang_isPreprocessing(cursor.kind)) {
Chandler Carruthcea731a2011-07-14 16:07:57 +00004690 // For macro expansions, just note where the beginning of the macro
4691 // expansion occurs.
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004692 if (cursor.kind == CXCursor_MacroExpansion) {
Douglas Gregor4419b672010-10-21 06:10:04 +00004693 Annotated[Loc.int_data] = cursor;
4694 return CXChildVisit_Recurse;
4695 }
4696
Douglas Gregor4419b672010-10-21 06:10:04 +00004697 // Items in the preprocessing record are kept separate from items in
4698 // declarations, so we keep a separate token index.
4699 unsigned SavedTokIdx = TokIdx;
4700 TokIdx = PreprocessingTokIdx;
4701
4702 // Skip tokens up until we catch up to the beginning of the preprocessing
4703 // entry.
4704 while (MoreTokens()) {
4705 const unsigned I = NextToken();
4706 SourceLocation TokLoc = GetTokenLoc(I);
4707 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4708 case RangeBefore:
4709 AdvanceToken();
4710 continue;
4711 case RangeAfter:
4712 case RangeOverlap:
4713 break;
4714 }
4715 break;
4716 }
4717
4718 // Look at all of the tokens within this range.
4719 while (MoreTokens()) {
4720 const unsigned I = NextToken();
4721 SourceLocation TokLoc = GetTokenLoc(I);
4722 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4723 case RangeBefore:
David Blaikieb219cfc2011-09-23 05:06:16 +00004724 llvm_unreachable("Infeasible");
Douglas Gregor4419b672010-10-21 06:10:04 +00004725 case RangeAfter:
4726 break;
4727 case RangeOverlap:
4728 Cursors[I] = cursor;
4729 AdvanceToken();
4730 continue;
4731 }
4732 break;
4733 }
4734
4735 // Save the preprocessing token index; restore the non-preprocessing
4736 // token index.
4737 PreprocessingTokIdx = TokIdx;
4738 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004739 return CXChildVisit_Recurse;
4740 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004741
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004742 if (cursorRange.isInvalid())
4743 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004744
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004745 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4746
Ted Kremeneka333c662010-05-12 05:29:33 +00004747 // Adjust the annotated range based specific declarations.
4748 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4749 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004750 Decl *D = cxcursor::getCursorDecl(cursor);
Douglas Gregor2494dd02011-03-01 01:34:45 +00004751
4752 SourceLocation StartLoc;
Ted Kremenek23173d72010-05-18 21:09:07 +00004753 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00004754 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
4755 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
4756 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
4757 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
4758 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
Ted Kremeneka333c662010-05-12 05:29:33 +00004759 }
Douglas Gregor2494dd02011-03-01 01:34:45 +00004760
4761 if (StartLoc.isValid() && L.isValid() &&
4762 SrcMgr.isBeforeInTranslationUnit(StartLoc, L))
4763 cursorRange.setBegin(StartLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004764 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004765
Ted Kremenek3f404602010-08-14 01:14:06 +00004766 // If the location of the cursor occurs within a macro instantiation, record
4767 // the spelling location of the cursor in our annotation map. We can then
4768 // paper over the token labelings during a post-processing step to try and
4769 // get cursor mappings for tokens that are the *arguments* of a macro
4770 // instantiation.
4771 if (L.isMacroID()) {
4772 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4773 // Only invalidate the old annotation if it isn't part of a preprocessing
4774 // directive. Here we assume that the default construction of CXCursor
4775 // results in CXCursor.kind being an initialized value (i.e., 0). If
4776 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004777
Ted Kremenek3f404602010-08-14 01:14:06 +00004778 CXCursor &oldC = Annotated[rawEncoding];
4779 if (!clang_isPreprocessing(oldC.kind))
4780 oldC = cursor;
4781 }
4782
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004783 const enum CXCursorKind K = clang_getCursorKind(parent);
4784 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004785 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4786 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004787
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004788 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004789
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00004790 // Avoid having the cursor of an expression "overwrite" the annotation of the
4791 // variable declaration that it belongs to.
4792 // This can happen for C++ constructor expressions whose range generally
4793 // include the variable declaration, e.g.:
4794 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
4795 if (clang_isExpression(cursorK)) {
4796 Expr *E = getCursorExpr(cursor);
Argyrios Kyrtzidis8ccac3d2011-06-29 22:20:07 +00004797 if (Decl *D = getCursorParentDecl(cursor)) {
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00004798 const unsigned I = NextToken();
4799 if (E->getLocStart().isValid() && D->getLocation().isValid() &&
4800 E->getLocStart() == D->getLocation() &&
4801 E->getLocStart() == GetTokenLoc(I)) {
4802 Cursors[I] = updateC;
4803 AdvanceToken();
4804 }
4805 }
4806 }
4807
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004808 // Visit children to get their cursor information.
4809 const unsigned BeforeChildren = NextToken();
4810 VisitChildren(cursor);
4811 const unsigned AfterChildren = NextToken();
4812
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004813 // Scan the tokens that are at the end of the cursor, but are not captured
4814 // but the child cursors.
4815 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
Ted Kremenek6db61092010-05-05 00:55:15 +00004816
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004817 // Scan the tokens that are at the beginning of the cursor, but are not
4818 // capture by the child cursors.
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004819 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4820 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4821 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004822
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004823 Cursors[I] = cursor;
4824 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004825
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004826 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004827}
4828
Ted Kremenek6db61092010-05-05 00:55:15 +00004829static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4830 CXCursor parent,
4831 CXClientData client_data) {
4832 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4833}
4834
Ted Kremenek6628a612011-03-18 22:51:30 +00004835namespace {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004836
4837/// \brief Uses the macro expansions in the preprocessing record to find
4838/// and mark tokens that are macro arguments. This info is used by the
4839/// AnnotateTokensWorker.
4840class MarkMacroArgTokensVisitor {
4841 SourceManager &SM;
4842 CXToken *Tokens;
4843 unsigned NumTokens;
4844 unsigned CurIdx;
4845
4846public:
4847 MarkMacroArgTokensVisitor(SourceManager &SM,
4848 CXToken *tokens, unsigned numTokens)
4849 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
4850
4851 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
4852 if (cursor.kind != CXCursor_MacroExpansion)
4853 return CXChildVisit_Continue;
4854
4855 SourceRange macroRange = getCursorMacroExpansion(cursor)->getSourceRange();
4856 if (macroRange.getBegin() == macroRange.getEnd())
4857 return CXChildVisit_Continue; // it's not a function macro.
4858
4859 for (; CurIdx < NumTokens; ++CurIdx) {
4860 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
4861 macroRange.getBegin()))
4862 break;
4863 }
4864
4865 if (CurIdx == NumTokens)
4866 return CXChildVisit_Break;
4867
4868 for (; CurIdx < NumTokens; ++CurIdx) {
4869 SourceLocation tokLoc = getTokenLoc(CurIdx);
4870 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
4871 break;
4872
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004873 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004874 }
4875
4876 if (CurIdx == NumTokens)
4877 return CXChildVisit_Break;
4878
4879 return CXChildVisit_Continue;
4880 }
4881
4882private:
4883 SourceLocation getTokenLoc(unsigned tokI) {
4884 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4885 }
4886
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004887 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004888 // The third field is reserved and currently not used. Use it here
4889 // to mark macro arg expanded tokens with their expanded locations.
4890 Tokens[tokI].int_data[3] = loc.getRawEncoding();
4891 }
4892};
4893
4894} // end anonymous namespace
4895
4896static CXChildVisitResult
4897MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
4898 CXClientData client_data) {
4899 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
4900 parent);
4901}
4902
4903namespace {
Ted Kremenek6628a612011-03-18 22:51:30 +00004904 struct clang_annotateTokens_Data {
4905 CXTranslationUnit TU;
4906 ASTUnit *CXXUnit;
4907 CXToken *Tokens;
4908 unsigned NumTokens;
4909 CXCursor *Cursors;
4910 };
4911}
4912
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004913static void annotatePreprocessorTokens(CXTranslationUnit TU,
4914 SourceRange RegionOfInterest,
4915 AnnotateTokensData &Annotated) {
4916 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4917
4918 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4919 std::pair<FileID, unsigned> BeginLocInfo
4920 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4921 std::pair<FileID, unsigned> EndLocInfo
4922 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
4923
4924 if (BeginLocInfo.first != EndLocInfo.first)
4925 return;
4926
4927 StringRef Buffer;
4928 bool Invalid = false;
4929 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
4930 if (Buffer.empty() || Invalid)
4931 return;
4932
4933 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4934 CXXUnit->getASTContext().getLangOptions(),
4935 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
4936 Buffer.end());
4937 Lex.SetCommentRetentionState(true);
4938
4939 // Lex tokens in raw mode until we hit the end of the range, to avoid
4940 // entering #includes or expanding macros.
4941 while (true) {
4942 Token Tok;
4943 Lex.LexFromRawLexer(Tok);
4944
4945 reprocess:
4946 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4947 // We have found a preprocessing directive. Gobble it up so that we
4948 // don't see it while preprocessing these tokens later, but keep track
4949 // of all of the token locations inside this preprocessing directive so
4950 // that we can annotate them appropriately.
4951 //
4952 // FIXME: Some simple tests here could identify macro definitions and
4953 // #undefs, to provide specific cursor kinds for those.
4954 SmallVector<SourceLocation, 32> Locations;
4955 do {
4956 Locations.push_back(Tok.getLocation());
4957 Lex.LexFromRawLexer(Tok);
4958 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
4959
4960 using namespace cxcursor;
4961 CXCursor Cursor
4962 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4963 Locations.back()),
4964 TU);
4965 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4966 Annotated[Locations[I].getRawEncoding()] = Cursor;
4967 }
4968
4969 if (Tok.isAtStartOfLine())
4970 goto reprocess;
4971
4972 continue;
4973 }
4974
4975 if (Tok.is(tok::eof))
4976 break;
4977 }
4978}
4979
Ted Kremenekab979612010-11-11 08:05:23 +00004980// This gets run a separate thread to avoid stack blowout.
Ted Kremenek6628a612011-03-18 22:51:30 +00004981static void clang_annotateTokensImpl(void *UserData) {
4982 CXTranslationUnit TU = ((clang_annotateTokens_Data*)UserData)->TU;
4983 ASTUnit *CXXUnit = ((clang_annotateTokens_Data*)UserData)->CXXUnit;
4984 CXToken *Tokens = ((clang_annotateTokens_Data*)UserData)->Tokens;
4985 const unsigned NumTokens = ((clang_annotateTokens_Data*)UserData)->NumTokens;
4986 CXCursor *Cursors = ((clang_annotateTokens_Data*)UserData)->Cursors;
4987
4988 // Determine the region of interest, which contains all of the tokens.
4989 SourceRange RegionOfInterest;
4990 RegionOfInterest.setBegin(
4991 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
4992 RegionOfInterest.setEnd(
4993 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
4994 Tokens[NumTokens-1])));
4995
4996 // A mapping from the source locations found when re-lexing or traversing the
4997 // region of interest to the corresponding cursors.
4998 AnnotateTokensData Annotated;
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004999
Ted Kremenek6628a612011-03-18 22:51:30 +00005000 // Relex the tokens within the source range to look for preprocessing
5001 // directives.
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005002 annotatePreprocessorTokens(TU, RegionOfInterest, Annotated);
Ted Kremenek6628a612011-03-18 22:51:30 +00005003
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005004 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
5005 // Search and mark tokens that are macro argument expansions.
5006 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
5007 Tokens, NumTokens);
5008 CursorVisitor MacroArgMarker(TU,
5009 MarkMacroArgTokensVisitorDelegate, &Visitor,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00005010 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00005011 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00005012 RegionOfInterest);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005013 MacroArgMarker.visitPreprocessedEntitiesInRegion();
5014 }
5015
Ted Kremenek6628a612011-03-18 22:51:30 +00005016 // Annotate all of the source locations in the region of interest that map to
5017 // a specific cursor.
5018 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
5019 TU, RegionOfInterest);
5020
5021 // FIXME: We use a ridiculous stack size here because the data-recursion
5022 // algorithm uses a large stack frame than the non-data recursive version,
5023 // and AnnotationTokensWorker currently transforms the data-recursion
5024 // algorithm back into a traditional recursion by explicitly calling
5025 // VisitChildren(). We will need to remove this explicit recursive call.
5026 W.AnnotateTokens();
5027
5028 // If we ran into any entities that involve context-sensitive keywords,
5029 // take another pass through the tokens to mark them as such.
5030 if (W.hasContextSensitiveKeywords()) {
5031 for (unsigned I = 0; I != NumTokens; ++I) {
5032 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
5033 continue;
5034
5035 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
5036 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5037 if (ObjCPropertyDecl *Property
5038 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
5039 if (Property->getPropertyAttributesAsWritten() != 0 &&
5040 llvm::StringSwitch<bool>(II->getName())
5041 .Case("readonly", true)
5042 .Case("assign", true)
John McCallf85e1932011-06-15 23:02:42 +00005043 .Case("unsafe_unretained", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00005044 .Case("readwrite", true)
5045 .Case("retain", true)
5046 .Case("copy", true)
5047 .Case("nonatomic", true)
5048 .Case("atomic", true)
5049 .Case("getter", true)
5050 .Case("setter", true)
John McCallf85e1932011-06-15 23:02:42 +00005051 .Case("strong", true)
5052 .Case("weak", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00005053 .Default(false))
5054 Tokens[I].int_data[0] = CXToken_Keyword;
5055 }
5056 continue;
5057 }
5058
5059 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
5060 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
5061 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5062 if (llvm::StringSwitch<bool>(II->getName())
5063 .Case("in", true)
5064 .Case("out", true)
5065 .Case("inout", true)
5066 .Case("oneway", true)
5067 .Case("bycopy", true)
5068 .Case("byref", true)
5069 .Default(false))
5070 Tokens[I].int_data[0] = CXToken_Keyword;
5071 continue;
5072 }
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00005073
5074 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
5075 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
5076 Tokens[I].int_data[0] = CXToken_Keyword;
Ted Kremenek6628a612011-03-18 22:51:30 +00005077 continue;
5078 }
5079 }
5080 }
Ted Kremenekab979612010-11-11 08:05:23 +00005081}
5082
Ted Kremenek6db61092010-05-05 00:55:15 +00005083extern "C" {
5084
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005085void clang_annotateTokens(CXTranslationUnit TU,
5086 CXToken *Tokens, unsigned NumTokens,
5087 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005088
5089 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005090 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005091
Douglas Gregor4419b672010-10-21 06:10:04 +00005092 // Any token we don't specifically annotate will have a NULL cursor.
5093 CXCursor C = clang_getNullCursor();
5094 for (unsigned I = 0; I != NumTokens; ++I)
5095 Cursors[I] = C;
5096
Ted Kremeneka60ed472010-11-16 08:15:36 +00005097 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor4419b672010-10-21 06:10:04 +00005098 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005099 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005100
Douglas Gregorbdf60622010-03-05 21:16:25 +00005101 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenek6628a612011-03-18 22:51:30 +00005102
5103 clang_annotateTokens_Data data = { TU, CXXUnit, Tokens, NumTokens, Cursors };
Ted Kremenekab979612010-11-11 08:05:23 +00005104 llvm::CrashRecoveryContext CRC;
Ted Kremenek6628a612011-03-18 22:51:30 +00005105 if (!RunSafely(CRC, clang_annotateTokensImpl, &data,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005106 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00005107 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
5108 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005109}
Ted Kremenek6628a612011-03-18 22:51:30 +00005110
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005111} // end: extern "C"
5112
5113//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00005114// Operations for querying linkage of a cursor.
5115//===----------------------------------------------------------------------===//
5116
5117extern "C" {
5118CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00005119 if (!clang_isDeclaration(cursor.kind))
5120 return CXLinkage_Invalid;
5121
Ted Kremenek16b42592010-03-03 06:36:57 +00005122 Decl *D = cxcursor::getCursorDecl(cursor);
5123 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
5124 switch (ND->getLinkage()) {
5125 case NoLinkage: return CXLinkage_NoLinkage;
5126 case InternalLinkage: return CXLinkage_Internal;
5127 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
5128 case ExternalLinkage: return CXLinkage_External;
5129 };
5130
5131 return CXLinkage_Invalid;
5132}
5133} // end: extern "C"
5134
5135//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005136// Operations for querying language of a cursor.
5137//===----------------------------------------------------------------------===//
5138
5139static CXLanguageKind getDeclLanguage(const Decl *D) {
5140 switch (D->getKind()) {
5141 default:
5142 break;
5143 case Decl::ImplicitParam:
5144 case Decl::ObjCAtDefsField:
5145 case Decl::ObjCCategory:
5146 case Decl::ObjCCategoryImpl:
5147 case Decl::ObjCClass:
5148 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005149 case Decl::ObjCForwardProtocol:
5150 case Decl::ObjCImplementation:
5151 case Decl::ObjCInterface:
5152 case Decl::ObjCIvar:
5153 case Decl::ObjCMethod:
5154 case Decl::ObjCProperty:
5155 case Decl::ObjCPropertyImpl:
5156 case Decl::ObjCProtocol:
5157 return CXLanguage_ObjC;
5158 case Decl::CXXConstructor:
5159 case Decl::CXXConversion:
5160 case Decl::CXXDestructor:
5161 case Decl::CXXMethod:
5162 case Decl::CXXRecord:
5163 case Decl::ClassTemplate:
5164 case Decl::ClassTemplatePartialSpecialization:
5165 case Decl::ClassTemplateSpecialization:
5166 case Decl::Friend:
5167 case Decl::FriendTemplate:
5168 case Decl::FunctionTemplate:
5169 case Decl::LinkageSpec:
5170 case Decl::Namespace:
5171 case Decl::NamespaceAlias:
5172 case Decl::NonTypeTemplateParm:
5173 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005174 case Decl::TemplateTemplateParm:
5175 case Decl::TemplateTypeParm:
5176 case Decl::UnresolvedUsingTypename:
5177 case Decl::UnresolvedUsingValue:
5178 case Decl::Using:
5179 case Decl::UsingDirective:
5180 case Decl::UsingShadow:
5181 return CXLanguage_CPlusPlus;
5182 }
5183
5184 return CXLanguage_C;
5185}
5186
5187extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00005188
5189enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
5190 if (clang_isDeclaration(cursor.kind))
5191 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005192 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Douglas Gregor58ddb602010-08-23 23:00:57 +00005193 return CXAvailability_Available;
5194
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005195 switch (D->getAvailability()) {
5196 case AR_Available:
5197 case AR_NotYetIntroduced:
5198 return CXAvailability_Available;
5199
5200 case AR_Deprecated:
Douglas Gregor58ddb602010-08-23 23:00:57 +00005201 return CXAvailability_Deprecated;
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005202
5203 case AR_Unavailable:
5204 return CXAvailability_NotAvailable;
5205 }
Douglas Gregor58ddb602010-08-23 23:00:57 +00005206 }
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005207
Douglas Gregor58ddb602010-08-23 23:00:57 +00005208 return CXAvailability_Available;
5209}
5210
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005211CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
5212 if (clang_isDeclaration(cursor.kind))
5213 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
5214
5215 return CXLanguage_Invalid;
5216}
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005217
5218 /// \brief If the given cursor is the "templated" declaration
5219 /// descibing a class or function template, return the class or
5220 /// function template.
5221static Decl *maybeGetTemplateCursor(Decl *D) {
5222 if (!D)
5223 return 0;
5224
5225 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
5226 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
5227 return FunTmpl;
5228
5229 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
5230 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
5231 return ClassTmpl;
5232
5233 return D;
5234}
5235
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005236CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
5237 if (clang_isDeclaration(cursor.kind)) {
5238 if (Decl *D = getCursorDecl(cursor)) {
5239 DeclContext *DC = D->getDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005240 if (!DC)
5241 return clang_getNullCursor();
5242
5243 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5244 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005245 }
5246 }
5247
5248 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
5249 if (Decl *D = getCursorDecl(cursor))
Ted Kremeneka60ed472010-11-16 08:15:36 +00005250 return MakeCXCursor(D, getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005251 }
5252
5253 return clang_getNullCursor();
5254}
5255
5256CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
5257 if (clang_isDeclaration(cursor.kind)) {
5258 if (Decl *D = getCursorDecl(cursor)) {
5259 DeclContext *DC = D->getLexicalDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005260 if (!DC)
5261 return clang_getNullCursor();
5262
5263 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5264 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005265 }
5266 }
5267
5268 // FIXME: Note that we can't easily compute the lexical context of a
5269 // statement or expression, so we return nothing.
5270 return clang_getNullCursor();
5271}
5272
Douglas Gregor9f592342010-10-01 20:25:15 +00005273void clang_getOverriddenCursors(CXCursor cursor,
5274 CXCursor **overridden,
5275 unsigned *num_overridden) {
5276 if (overridden)
5277 *overridden = 0;
5278 if (num_overridden)
5279 *num_overridden = 0;
5280 if (!overridden || !num_overridden)
5281 return;
5282
Argyrios Kyrtzidisb11be042011-10-06 07:00:46 +00005283 SmallVector<CXCursor, 8> Overridden;
5284 cxcursor::getOverriddenCursors(cursor, Overridden);
Douglas Gregor9f592342010-10-01 20:25:15 +00005285
Ted Kremenek24077122011-11-14 23:51:37 +00005286 // Don't allocate memory if we have no overriden cursors.
5287 if (Overridden.size() == 0)
5288 return;
5289
Argyrios Kyrtzidisb11be042011-10-06 07:00:46 +00005290 *num_overridden = Overridden.size();
5291 *overridden = new CXCursor [Overridden.size()];
5292 std::copy(Overridden.begin(), Overridden.end(), *overridden);
Douglas Gregor9f592342010-10-01 20:25:15 +00005293}
5294
5295void clang_disposeOverriddenCursors(CXCursor *overridden) {
5296 delete [] overridden;
5297}
5298
Douglas Gregorecdcb882010-10-20 22:00:55 +00005299CXFile clang_getIncludedFile(CXCursor cursor) {
5300 if (cursor.kind != CXCursor_InclusionDirective)
5301 return 0;
5302
5303 InclusionDirective *ID = getCursorInclusionDirective(cursor);
5304 return (void *)ID->getFile();
5305}
5306
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005307} // end: extern "C"
5308
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005309
5310//===----------------------------------------------------------------------===//
5311// C++ AST instrospection.
5312//===----------------------------------------------------------------------===//
5313
5314extern "C" {
5315unsigned clang_CXXMethod_isStatic(CXCursor C) {
5316 if (!clang_isDeclaration(C.kind))
5317 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00005318
5319 CXXMethodDecl *Method = 0;
5320 Decl *D = cxcursor::getCursorDecl(C);
5321 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5322 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5323 else
5324 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5325 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00005326}
Ted Kremenekb12903e2010-05-18 22:32:15 +00005327
Douglas Gregor211924b2011-05-12 15:17:24 +00005328unsigned clang_CXXMethod_isVirtual(CXCursor C) {
5329 if (!clang_isDeclaration(C.kind))
5330 return 0;
5331
5332 CXXMethodDecl *Method = 0;
5333 Decl *D = cxcursor::getCursorDecl(C);
5334 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5335 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5336 else
5337 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5338 return (Method && Method->isVirtual()) ? 1 : 0;
5339}
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005340} // end: extern "C"
5341
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005342//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00005343// Attribute introspection.
5344//===----------------------------------------------------------------------===//
5345
5346extern "C" {
5347CXType clang_getIBOutletCollectionType(CXCursor C) {
5348 if (C.kind != CXCursor_IBOutletCollectionAttr)
Ted Kremeneka60ed472010-11-16 08:15:36 +00005349 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005350
5351 IBOutletCollectionAttr *A =
5352 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
5353
Argyrios Kyrtzidis18aa2ff2011-09-13 18:49:52 +00005354 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005355}
5356} // end: extern "C"
5357
5358//===----------------------------------------------------------------------===//
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005359// Inspecting memory usage.
5360//===----------------------------------------------------------------------===//
5361
Ted Kremenekf7870022011-04-20 16:41:07 +00005362typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005363
Ted Kremenekf7870022011-04-20 16:41:07 +00005364static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
5365 enum CXTUResourceUsageKind k,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005366 unsigned long amount) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005367 CXTUResourceUsageEntry entry = { k, amount };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005368 entries.push_back(entry);
5369}
5370
5371extern "C" {
5372
Ted Kremenekf7870022011-04-20 16:41:07 +00005373const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005374 const char *str = "";
5375 switch (kind) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005376 case CXTUResourceUsage_AST:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005377 str = "ASTContext: expressions, declarations, and types";
5378 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005379 case CXTUResourceUsage_Identifiers:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005380 str = "ASTContext: identifiers";
5381 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005382 case CXTUResourceUsage_Selectors:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005383 str = "ASTContext: selectors";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005384 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005385 case CXTUResourceUsage_GlobalCompletionResults:
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005386 str = "Code completion: cached global results";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005387 break;
Ted Kremenek457aaf02011-04-28 04:10:31 +00005388 case CXTUResourceUsage_SourceManagerContentCache:
5389 str = "SourceManager: content cache allocator";
5390 break;
Ted Kremenekba29bd22011-04-28 04:53:38 +00005391 case CXTUResourceUsage_AST_SideTables:
5392 str = "ASTContext: side tables";
5393 break;
Ted Kremenekf61b8312011-04-28 20:36:42 +00005394 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
5395 str = "SourceManager: malloc'ed memory buffers";
5396 break;
5397 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
5398 str = "SourceManager: mmap'ed memory buffers";
5399 break;
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005400 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
5401 str = "ExternalASTSource: malloc'ed memory buffers";
5402 break;
5403 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
5404 str = "ExternalASTSource: mmap'ed memory buffers";
5405 break;
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005406 case CXTUResourceUsage_Preprocessor:
5407 str = "Preprocessor: malloc'ed memory";
5408 break;
5409 case CXTUResourceUsage_PreprocessingRecord:
5410 str = "Preprocessor: PreprocessingRecord";
5411 break;
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005412 case CXTUResourceUsage_SourceManager_DataStructures:
5413 str = "SourceManager: data structures and tables";
5414 break;
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005415 case CXTUResourceUsage_Preprocessor_HeaderSearch:
5416 str = "Preprocessor: header search tables";
5417 break;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005418 }
5419 return str;
5420}
5421
Ted Kremenekf7870022011-04-20 16:41:07 +00005422CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005423 if (!TU) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005424 CXTUResourceUsage usage = { (void*) 0, 0, 0 };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005425 return usage;
5426 }
5427
5428 ASTUnit *astUnit = static_cast<ASTUnit*>(TU->TUData);
5429 llvm::OwningPtr<MemUsageEntries> entries(new MemUsageEntries());
5430 ASTContext &astContext = astUnit->getASTContext();
5431
5432 // How much memory is used by AST nodes and types?
Ted Kremenekf7870022011-04-20 16:41:07 +00005433 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005434 (unsigned long) astContext.getASTAllocatedMemory());
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005435
5436 // How much memory is used by identifiers?
Ted Kremenekf7870022011-04-20 16:41:07 +00005437 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005438 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
5439
5440 // How much memory is used for selectors?
Ted Kremenekf7870022011-04-20 16:41:07 +00005441 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005442 (unsigned long) astContext.Selectors.getTotalMemory());
5443
Ted Kremenekba29bd22011-04-28 04:53:38 +00005444 // How much memory is used by ASTContext's side tables?
5445 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
5446 (unsigned long) astContext.getSideTableAllocatedMemory());
5447
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005448 // How much memory is used for caching global code completion results?
5449 unsigned long completionBytes = 0;
5450 if (GlobalCodeCompletionAllocator *completionAllocator =
5451 astUnit->getCachedCompletionAllocator().getPtr()) {
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005452 completionBytes = completionAllocator->getTotalMemory();
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005453 }
Ted Kremenek457aaf02011-04-28 04:10:31 +00005454 createCXTUResourceUsageEntry(*entries,
5455 CXTUResourceUsage_GlobalCompletionResults,
5456 completionBytes);
5457
5458 // How much memory is being used by SourceManager's content cache?
5459 createCXTUResourceUsageEntry(*entries,
5460 CXTUResourceUsage_SourceManagerContentCache,
5461 (unsigned long) astContext.getSourceManager().getContentCacheSize());
Ted Kremenekf61b8312011-04-28 20:36:42 +00005462
5463 // How much memory is being used by the MemoryBuffer's in SourceManager?
5464 const SourceManager::MemoryBufferSizes &srcBufs =
5465 astUnit->getSourceManager().getMemoryBufferSizes();
5466
5467 createCXTUResourceUsageEntry(*entries,
5468 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
5469 (unsigned long) srcBufs.malloc_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005470 createCXTUResourceUsageEntry(*entries,
Ted Kremenekf61b8312011-04-28 20:36:42 +00005471 CXTUResourceUsage_SourceManager_Membuffer_MMap,
5472 (unsigned long) srcBufs.mmap_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005473 createCXTUResourceUsageEntry(*entries,
5474 CXTUResourceUsage_SourceManager_DataStructures,
5475 (unsigned long) astContext.getSourceManager()
5476 .getDataStructureSizes());
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005477
5478 // How much memory is being used by the ExternalASTSource?
5479 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
5480 const ExternalASTSource::MemoryBufferSizes &sizes =
5481 esrc->getMemoryBufferSizes();
5482
5483 createCXTUResourceUsageEntry(*entries,
5484 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
5485 (unsigned long) sizes.malloc_bytes);
5486 createCXTUResourceUsageEntry(*entries,
5487 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
5488 (unsigned long) sizes.mmap_bytes);
5489 }
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005490
5491 // How much memory is being used by the Preprocessor?
5492 Preprocessor &pp = astUnit->getPreprocessor();
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005493 createCXTUResourceUsageEntry(*entries,
5494 CXTUResourceUsage_Preprocessor,
Argyrios Kyrtzidisc5c5e922011-06-29 22:20:04 +00005495 pp.getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005496
5497 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
5498 createCXTUResourceUsageEntry(*entries,
5499 CXTUResourceUsage_PreprocessingRecord,
5500 pRec->getTotalMemory());
5501 }
5502
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005503 createCXTUResourceUsageEntry(*entries,
5504 CXTUResourceUsage_Preprocessor_HeaderSearch,
5505 pp.getHeaderSearchInfo().getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005506
Ted Kremenekf7870022011-04-20 16:41:07 +00005507 CXTUResourceUsage usage = { (void*) entries.get(),
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005508 (unsigned) entries->size(),
5509 entries->size() ? &(*entries)[0] : 0 };
5510 entries.take();
5511 return usage;
5512}
5513
Ted Kremenekf7870022011-04-20 16:41:07 +00005514void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005515 if (usage.data)
5516 delete (MemUsageEntries*) usage.data;
5517}
5518
5519} // end extern "C"
5520
Douglas Gregor6df78732011-05-05 20:27:22 +00005521void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
5522 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
5523 for (unsigned I = 0; I != Usage.numEntries; ++I)
5524 fprintf(stderr, " %s: %lu\n",
5525 clang_getTUResourceUsageName(Usage.entries[I].kind),
5526 Usage.entries[I].amount);
5527
5528 clang_disposeCXTUResourceUsage(Usage);
5529}
5530
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005531//===----------------------------------------------------------------------===//
Ted Kremenek04bb7162010-01-22 22:44:15 +00005532// Misc. utility functions.
5533//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00005534
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00005535/// Default to using an 8 MB stack size on "safety" threads.
5536static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005537
5538namespace clang {
5539
5540bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005541 void (*Fn)(void*), void *UserData,
5542 unsigned Size) {
5543 if (!Size)
5544 Size = GetSafetyThreadStackSize();
5545 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005546 return CRC.RunSafelyOnThread(Fn, UserData, Size);
5547 return CRC.RunSafely(Fn, UserData);
5548}
5549
5550unsigned GetSafetyThreadStackSize() {
5551 return SafetyStackThreadSize;
5552}
5553
5554void SetSafetyThreadStackSize(unsigned Value) {
5555 SafetyStackThreadSize = Value;
5556}
5557
5558}
5559
Ted Kremenek04bb7162010-01-22 22:44:15 +00005560extern "C" {
5561
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00005562CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00005563 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00005564}
5565
5566} // end: extern "C"
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005567