blob: b1e4bad14d6be193d847130d8224069680b1d3fc [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"
Dmitri Gribenkoae99b752012-07-20 21:34:34 +000016#include "CXComment.h"
Ted Kremenek16c440a2010-01-15 20:35:54 +000017#include "CXCursor.h"
Ted Kremenek0a90d322010-11-17 23:24:11 +000018#include "CXTranslationUnit.h"
Ted Kremeneked122732010-11-16 01:56:27 +000019#include "CXString.h"
Ted Kremenek95f33552010-08-26 01:42:22 +000020#include "CXType.h"
Ted Kremeneka297de22010-01-25 22:34:44 +000021#include "CXSourceLocation.h"
Douglas Gregor5352ac02010-01-28 00:27:43 +000022#include "CIndexDiagnostic.h"
Argyrios Kyrtzidise397bf12011-11-03 19:02:34 +000023#include "CursorVisitor.h"
Ted Kremenekab188932010-01-05 19:32:54 +000024
Ted Kremenek04bb7162010-01-22 22:44:15 +000025#include "clang/Basic/Version.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000026
Steve Narofffb570422009-09-22 19:25:29 +000027#include "clang/AST/StmtVisitor.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000028#include "clang/Basic/Diagnostic.h"
29#include "clang/Frontend/ASTUnit.h"
30#include "clang/Frontend/CompilerInstance.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000031#include "clang/Frontend/FrontendDiagnostic.h"
Ted Kremenekd8210652010-01-06 23:43:31 +000032#include "clang/Lex/Lexer.h"
Douglas Gregordd3e5542011-05-04 00:14:37 +000033#include "clang/Lex/HeaderSearch.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000034#include "clang/Lex/PreprocessingRecord.h"
Douglas Gregor33e9abd2010-01-22 19:49:59 +000035#include "clang/Lex/Preprocessor.h"
Douglas Gregora67e03f2010-09-09 21:42:20 +000036#include "llvm/ADT/STLExtras.h"
Ted Kremenekd8c370c2010-11-02 23:10:24 +000037#include "llvm/ADT/Optional.h"
Douglas Gregorf5251602011-03-08 17:10:18 +000038#include "llvm/ADT/StringSwitch.h"
Argyrios Kyrtzidisb2c60b02012-03-01 19:45:56 +000039#include "llvm/Support/SaveAndRestore.h"
Daniel Dunbarc7df4f32010-08-18 18:43:14 +000040#include "llvm/Support/CrashRecoveryContext.h"
Daniel Dunbar48615ff2010-10-08 19:30:33 +000041#include "llvm/Support/PrettyStackTrace.h"
Douglas Gregor02465752009-10-16 21:24:31 +000042#include "llvm/Support/MemoryBuffer.h"
Douglas Gregor358559d2010-10-02 22:49:11 +000043#include "llvm/Support/raw_ostream.h"
Douglas Gregor7a07fcb2010-08-09 21:00:09 +000044#include "llvm/Support/Timer.h"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000045#include "llvm/Support/Mutex.h"
46#include "llvm/Support/Program.h"
47#include "llvm/Support/Signals.h"
48#include "llvm/Support/Threading.h"
Ted Kremenek37f1ea02010-11-15 23:11:54 +000049#include "llvm/Support/Compiler.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000050
Steve Naroff50398192009-08-28 15:28:48 +000051using namespace clang;
Ted Kremenek16c440a2010-01-15 20:35:54 +000052using namespace clang::cxcursor;
Ted Kremenekee4db4f2010-02-17 00:41:08 +000053using namespace clang::cxstring;
Argyrios Kyrtzidis9049cf62011-10-12 07:07:33 +000054using namespace clang::cxtu;
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +000055using namespace clang::cxindex;
Steve Naroff50398192009-08-28 15:28:48 +000056
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +000057CXTranslationUnit cxtu::MakeCXTranslationUnit(CIndexer *CIdx, ASTUnit *TU) {
Ted Kremeneka60ed472010-11-16 08:15:36 +000058 if (!TU)
59 return 0;
60 CXTranslationUnit D = new CXTranslationUnitImpl();
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +000061 D->CIdx = CIdx;
Ted Kremeneka60ed472010-11-16 08:15:36 +000062 D->TUData = TU;
63 D->StringPool = createCXStringPool();
Ted Kremenek15322172011-11-10 08:43:12 +000064 D->Diagnostics = 0;
Ted Kremenekbbf66ca2012-04-30 19:06:49 +000065 D->OverridenCursorsPool = createOverridenCXCursorsPool();
Ted Kremeneka60ed472010-11-16 08:15:36 +000066 return D;
67}
68
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +000069cxtu::CXTUOwner::~CXTUOwner() {
70 if (TU)
71 clang_disposeTranslationUnit(TU);
72}
73
Ted Kremenekf0e23e82010-02-17 00:41:40 +000074/// \brief Compare two source ranges to determine their relative position in
Douglas Gregor33e9abd2010-01-22 19:49:59 +000075/// the translation unit.
Ted Kremenekf0e23e82010-02-17 00:41:40 +000076static RangeComparisonResult RangeCompare(SourceManager &SM,
77 SourceRange R1,
Douglas Gregor33e9abd2010-01-22 19:49:59 +000078 SourceRange R2) {
79 assert(R1.isValid() && "First range is invalid?");
80 assert(R2.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000081 if (R1.getEnd() != R2.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000082 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000083 return RangeBefore;
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000084 if (R2.getEnd() != R1.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000085 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000086 return RangeAfter;
87 return RangeOverlap;
88}
89
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000090/// \brief Determine if a source location falls within, before, or after a
91/// a given source range.
92static RangeComparisonResult LocationCompare(SourceManager &SM,
93 SourceLocation L, SourceRange R) {
94 assert(R.isValid() && "First range is invalid?");
95 assert(L.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000096 if (L == R.getBegin() || L == R.getEnd())
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000097 return RangeOverlap;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000098 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
99 return RangeBefore;
100 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
101 return RangeAfter;
102 return RangeOverlap;
103}
104
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000105/// \brief Translate a Clang source range into a CIndex source range.
106///
107/// Clang internally represents ranges where the end location points to the
108/// start of the token at the end. However, for external clients it is more
109/// useful to have a CXSourceRange be a proper half-open interval. This routine
110/// does the appropriate translation.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000111CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000112 const LangOptions &LangOpts,
Chris Lattner0a76aae2010-06-18 22:45:06 +0000113 const CharSourceRange &R) {
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000114 // We want the last character in this location, so we will adjust the
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000115 // location accordingly.
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000116 SourceLocation EndLoc = R.getEnd();
Argyrios Kyrtzidiseba8cd52012-04-11 18:15:01 +0000117 if (EndLoc.isValid() && EndLoc.isMacroID() && !SM.isMacroArgExpansion(EndLoc))
Chandler Carruthedc3dcc2011-07-25 16:56:02 +0000118 EndLoc = SM.getExpansionRange(EndLoc).second;
Argyrios Kyrtzidiseba8cd52012-04-11 18:15:01 +0000119 if (R.isTokenRange() && !EndLoc.isInvalid()) {
120 unsigned Length = Lexer::MeasureTokenLength(SM.getSpellingLoc(EndLoc),
121 SM, LangOpts);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000122 EndLoc = EndLoc.getLocWithOffset(Length);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000123 }
124
125 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
126 R.getBegin().getRawEncoding(),
127 EndLoc.getRawEncoding() };
128 return Result;
129}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000130
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000131//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000132// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000133//===----------------------------------------------------------------------===//
134
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000135static SourceRange getRawCursorExtent(CXCursor C);
Douglas Gregor66537982010-11-17 17:14:07 +0000136static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
137
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000138
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000139RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000140 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000141}
142
Douglas Gregorb1373d02010-01-20 20:59:29 +0000143/// \brief Visit the given cursor and, if requested by the visitor,
144/// its children.
145///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000146/// \param Cursor the cursor to visit.
147///
148/// \param CheckRegionOfInterest if true, then the caller already checked that
149/// this cursor is within the region of interest.
150///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000151/// \returns true if the visitation should be aborted, false if it
152/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000153bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000154 if (clang_isInvalid(Cursor.kind))
155 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000156
Douglas Gregorb1373d02010-01-20 20:59:29 +0000157 if (clang_isDeclaration(Cursor.kind)) {
158 Decl *D = getCursorDecl(Cursor);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +0000159 if (!D) {
160 assert(0 && "Invalid declaration cursor");
161 return true; // abort.
162 }
163
Argyrios Kyrtzidis65ab9072011-09-26 19:05:37 +0000164 // Ignore implicit declarations, unless it's an objc method because
165 // currently we should report implicit methods for properties when indexing.
166 if (D->isImplicit() && !isa<ObjCMethodDecl>(D))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000167 return false;
168 }
169
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000170 // If we have a range of interest, and this cursor doesn't intersect with it,
171 // we're done.
172 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000173 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000174 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000175 return false;
176 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000177
Douglas Gregorb1373d02010-01-20 20:59:29 +0000178 switch (Visitor(Cursor, Parent, ClientData)) {
179 case CXChildVisit_Break:
180 return true;
181
182 case CXChildVisit_Continue:
183 return false;
184
185 case CXChildVisit_Recurse:
186 return VisitChildren(Cursor);
187 }
188
David Blaikie7530c032012-01-17 06:56:22 +0000189 llvm_unreachable("Invalid CXChildVisitResult!");
Douglas Gregorb1373d02010-01-20 20:59:29 +0000190}
191
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000192static bool visitPreprocessedEntitiesInRange(SourceRange R,
193 PreprocessingRecord &PPRec,
194 CursorVisitor &Visitor) {
195 SourceManager &SM = Visitor.getASTUnit()->getSourceManager();
196 FileID FID;
197
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +0000198 if (!Visitor.shouldVisitIncludedEntities()) {
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000199 // If the begin/end of the range lie in the same FileID, do the optimization
200 // where we skip preprocessed entities that do not come from the same FileID.
Argyrios Kyrtzidisacca4112011-12-21 16:56:38 +0000201 FID = SM.getFileID(SM.getFileLoc(R.getBegin()));
202 if (FID != SM.getFileID(SM.getFileLoc(R.getEnd())))
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000203 FID = FileID();
204 }
205
206 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
207 Entities = PPRec.getPreprocessedEntitiesInRange(R);
208 return Visitor.visitPreprocessedEntities(Entities.first, Entities.second,
209 PPRec, FID);
210}
211
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000212void CursorVisitor::visitFileRegion() {
213 if (RegionOfInterest.isInvalid())
214 return;
215
216 ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData);
217 SourceManager &SM = Unit->getSourceManager();
218
219 std::pair<FileID, unsigned>
220 Begin = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getBegin())),
221 End = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getEnd()));
222
223 if (End.first != Begin.first) {
224 // If the end does not reside in the same file, try to recover by
225 // picking the end of the file of begin location.
226 End.first = Begin.first;
227 End.second = SM.getFileIDSize(Begin.first);
228 }
229
230 assert(Begin.first == End.first);
231 if (Begin.second > End.second)
232 return;
233
234 FileID File = Begin.first;
235 unsigned Offset = Begin.second;
236 unsigned Length = End.second - Begin.second;
237
Argyrios Kyrtzidisb49e7282011-11-29 03:14:11 +0000238 if (!VisitDeclsOnly && !VisitPreprocessorLast)
239 if (visitPreprocessedEntitiesInRegion())
240 return; // visitation break.
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000241
242 visitDeclsFromFileRegion(File, Offset, Length);
243
Argyrios Kyrtzidisb49e7282011-11-29 03:14:11 +0000244 if (!VisitDeclsOnly && VisitPreprocessorLast)
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000245 visitPreprocessedEntitiesInRegion();
246}
247
Argyrios Kyrtzidise2079cf2011-11-16 08:58:54 +0000248static bool isInLexicalContext(Decl *D, DeclContext *DC) {
249 if (!DC)
250 return false;
251
252 for (DeclContext *DeclDC = D->getLexicalDeclContext();
253 DeclDC; DeclDC = DeclDC->getLexicalParent()) {
254 if (DeclDC == DC)
255 return true;
256 }
257 return false;
258}
259
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000260void CursorVisitor::visitDeclsFromFileRegion(FileID File,
261 unsigned Offset, unsigned Length) {
262 ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData);
263 SourceManager &SM = Unit->getSourceManager();
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000264 SourceRange Range = RegionOfInterest;
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000265
266 SmallVector<Decl *, 16> Decls;
267 Unit->findFileRegionDecls(File, Offset, Length, Decls);
268
269 // If we didn't find any file level decls for the file, try looking at the
270 // file that it was included from.
Argyrios Kyrtzidisc14a03d2011-11-23 20:27:36 +0000271 while (Decls.empty() || Decls.front()->isTopLevelDeclInObjCContainer()) {
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000272 bool Invalid = false;
273 const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid);
274 if (Invalid)
275 return;
276
277 SourceLocation Outer;
278 if (SLEntry.isFile())
279 Outer = SLEntry.getFile().getIncludeLoc();
280 else
281 Outer = SLEntry.getExpansion().getExpansionLocStart();
282 if (Outer.isInvalid())
283 return;
284
285 llvm::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer);
286 Length = 0;
287 Unit->findFileRegionDecls(File, Offset, Length, Decls);
288 }
289
290 assert(!Decls.empty());
291
292 bool VisitedAtLeastOnce = false;
Argyrios Kyrtzidise2079cf2011-11-16 08:58:54 +0000293 DeclContext *CurDC = 0;
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000294 SmallVector<Decl *, 16>::iterator DIt = Decls.begin();
295 for (SmallVector<Decl *, 16>::iterator DE = Decls.end(); DIt != DE; ++DIt) {
296 Decl *D = *DIt;
Argyrios Kyrtzidised8bef42011-11-28 22:38:07 +0000297 if (D->getSourceRange().isInvalid())
298 continue;
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000299
Argyrios Kyrtzidise2079cf2011-11-16 08:58:54 +0000300 if (isInLexicalContext(D, CurDC))
301 continue;
302
303 CurDC = dyn_cast<DeclContext>(D);
304
Argyrios Kyrtzidise2079cf2011-11-16 08:58:54 +0000305 if (TagDecl *TD = dyn_cast<TagDecl>(D))
306 if (!TD->isFreeStanding())
307 continue;
308
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000309 RangeComparisonResult CompRes = RangeCompare(SM, D->getSourceRange(),Range);
310 if (CompRes == RangeBefore)
311 continue;
312 if (CompRes == RangeAfter)
313 break;
314
315 assert(CompRes == RangeOverlap);
316 VisitedAtLeastOnce = true;
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +0000317
318 if (isa<ObjCContainerDecl>(D)) {
319 FileDI_current = &DIt;
320 FileDE_current = DE;
321 } else {
322 FileDI_current = 0;
323 }
324
Argyrios Kyrtzidisba986172011-11-03 19:02:28 +0000325 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000326 break;
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000327 }
328
329 if (VisitedAtLeastOnce)
330 return;
331
332 // No Decls overlapped with the range. Move up the lexical context until there
333 // is a context that contains the range or we reach the translation unit
334 // level.
335 DeclContext *DC = DIt == Decls.begin() ? (*DIt)->getLexicalDeclContext()
336 : (*(DIt-1))->getLexicalDeclContext();
337
338 while (DC && !DC->isTranslationUnit()) {
339 Decl *D = cast<Decl>(DC);
340 SourceRange CurDeclRange = D->getSourceRange();
341 if (CurDeclRange.isInvalid())
342 break;
343
344 if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) {
Argyrios Kyrtzidisba986172011-11-03 19:02:28 +0000345 Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true);
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000346 break;
347 }
348
349 DC = D->getLexicalDeclContext();
350 }
351}
352
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000353bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
Argyrios Kyrtzidisb49e7282011-11-29 03:14:11 +0000354 if (!AU->getPreprocessor().getPreprocessingRecord())
355 return false;
356
Douglas Gregor788f5a12010-03-20 00:41:21 +0000357 PreprocessingRecord &PPRec
Ted Kremeneka60ed472010-11-16 08:15:36 +0000358 = *AU->getPreprocessor().getPreprocessingRecord();
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000359 SourceManager &SM = AU->getSourceManager();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000360
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000361 if (RegionOfInterest.isValid()) {
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +0000362 SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000363 SourceLocation B = MappedRange.getBegin();
364 SourceLocation E = MappedRange.getEnd();
365
366 if (AU->isInPreambleFileID(B)) {
367 if (SM.isLoadedSourceLocation(E))
368 return visitPreprocessedEntitiesInRange(SourceRange(B, E),
369 PPRec, *this);
370
371 // Beginning of range lies in the preamble but it also extends beyond
372 // it into the main file. Split the range into 2 parts, one covering
373 // the preamble and another covering the main file. This allows subsequent
374 // calls to visitPreprocessedEntitiesInRange to accept a source range that
375 // lies in the same FileID, allowing it to skip preprocessed entities that
376 // do not come from the same FileID.
377 bool breaked =
378 visitPreprocessedEntitiesInRange(
379 SourceRange(B, AU->getEndOfPreambleFileID()),
380 PPRec, *this);
381 if (breaked) return true;
382 return visitPreprocessedEntitiesInRange(
383 SourceRange(AU->getStartOfMainFileID(), E),
384 PPRec, *this);
385 }
386
387 return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this);
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000388 }
389
Douglas Gregor788f5a12010-03-20 00:41:21 +0000390 bool OnlyLocalDecls
Douglas Gregor32038bb2010-12-21 19:07:48 +0000391 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
392
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000393 if (OnlyLocalDecls)
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000394 return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(),
395 PPRec);
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000396
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000397 return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec);
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000398}
399
400template<typename InputIterator>
401bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000402 InputIterator Last,
403 PreprocessingRecord &PPRec,
404 FileID FID) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000405 for (; First != Last; ++First) {
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000406 if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID))
407 continue;
408
409 PreprocessedEntity *PPE = *First;
410 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000411 if (Visit(MakeMacroExpansionCursor(ME, TU)))
412 return true;
413
414 continue;
415 }
416
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000417 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(PPE)) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000418 if (Visit(MakeMacroDefinitionCursor(MD, TU)))
419 return true;
420
421 continue;
422 }
423
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000424 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000425 if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
426 return true;
427
428 continue;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000429 }
430 }
431
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000432 return false;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000433}
434
Douglas Gregorb1373d02010-01-20 20:59:29 +0000435/// \brief Visit the children of the given cursor.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000436///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000437/// \returns true if the visitation should be aborted, false if it
438/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000439bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregorc314aa42011-03-02 19:17:03 +0000440 if (clang_isReference(Cursor.kind) &&
441 Cursor.kind != CXCursor_CXXBaseSpecifier) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000442 // By definition, references have no children.
443 return false;
444 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000445
446 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000447 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000448 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000449
Douglas Gregorb1373d02010-01-20 20:59:29 +0000450 if (clang_isDeclaration(Cursor.kind)) {
451 Decl *D = getCursorDecl(Cursor);
Douglas Gregor06d9b1a2011-04-14 21:41:34 +0000452 if (!D)
453 return false;
454
Ted Kremenek539311e2010-02-18 18:47:01 +0000455 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000456 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000457
Douglas Gregor06d9b1a2011-04-14 21:41:34 +0000458 if (clang_isStatement(Cursor.kind)) {
459 if (Stmt *S = getCursorStmt(Cursor))
460 return Visit(S);
461
462 return false;
463 }
464
465 if (clang_isExpression(Cursor.kind)) {
466 if (Expr *E = getCursorExpr(Cursor))
467 return Visit(E);
468
469 return false;
470 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000471
Douglas Gregorb1373d02010-01-20 20:59:29 +0000472 if (clang_isTranslationUnit(Cursor.kind)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000473 CXTranslationUnit tu = getCursorTU(Cursor);
474 ASTUnit *CXXUnit = static_cast<ASTUnit*>(tu->TUData);
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000475
476 int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
477 for (unsigned I = 0; I != 2; ++I) {
478 if (VisitOrder[I]) {
479 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
480 RegionOfInterest.isInvalid()) {
481 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
482 TLEnd = CXXUnit->top_level_end();
483 TL != TLEnd; ++TL) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000484 if (Visit(MakeCXCursor(*TL, tu, RegionOfInterest), true))
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000485 return true;
486 }
487 } else if (VisitDeclContext(
488 CXXUnit->getASTContext().getTranslationUnitDecl()))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000489 return true;
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000490 continue;
Douglas Gregor7b691f332010-01-20 21:13:59 +0000491 }
Bob Wilson3178cb62010-03-19 03:57:57 +0000492
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000493 // Walk the preprocessing record.
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000494 if (CXXUnit->getPreprocessor().getPreprocessingRecord())
495 visitPreprocessedEntitiesInRegion();
Douglas Gregor0396f462010-03-19 05:22:59 +0000496 }
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000497
Douglas Gregor7b691f332010-01-20 21:13:59 +0000498 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000499 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000500
Douglas Gregorc314aa42011-03-02 19:17:03 +0000501 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
502 if (CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
503 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
504 return Visit(BaseTSInfo->getTypeLoc());
505 }
506 }
507 }
Argyrios Kyrtzidis221d5a52011-09-13 18:49:56 +0000508
509 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
510 IBOutletCollectionAttr *A =
511 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
512 if (const ObjCInterfaceType *InterT = A->getInterface()->getAs<ObjCInterfaceType>())
513 return Visit(cxcursor::MakeCursorObjCClassRef(InterT->getInterface(),
514 A->getInterfaceLoc(), TU));
515 }
516
Douglas Gregorb1373d02010-01-20 20:59:29 +0000517 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000518 return false;
519}
520
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000521bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
Douglas Gregor13c8ccb2011-04-22 23:49:24 +0000522 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
523 if (Visit(TSInfo->getTypeLoc()))
524 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000525
Ted Kremenek664cffd2010-07-22 11:30:19 +0000526 if (Stmt *Body = B->getBody())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000527 return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest));
Ted Kremenek664cffd2010-07-22 11:30:19 +0000528
529 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000530}
531
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000532llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
533 if (RegionOfInterest.isValid()) {
Douglas Gregor66537982010-11-17 17:14:07 +0000534 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000535 if (Range.isInvalid())
536 return llvm::Optional<bool>();
Douglas Gregor66537982010-11-17 17:14:07 +0000537
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000538 switch (CompareRegionOfInterest(Range)) {
539 case RangeBefore:
540 // This declaration comes before the region of interest; skip it.
541 return llvm::Optional<bool>();
542
543 case RangeAfter:
544 // This declaration comes after the region of interest; we're done.
545 return false;
546
547 case RangeOverlap:
548 // This declaration overlaps the region of interest; visit it.
549 break;
550 }
551 }
552 return true;
553}
554
555bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
556 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
557
558 // FIXME: Eventually remove. This part of a hack to support proper
559 // iteration over all Decls contained lexically within an ObjC container.
560 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
561 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
562
563 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000564 Decl *D = *I;
565 if (D->getLexicalDeclContext() != DC)
566 continue;
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000567 CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
Argyrios Kyrtzidis1836db02012-02-04 01:04:58 +0000568
569 // FIXME: ObjCClassRef/ObjCProtocolRef for forward class/protocol
570 // declarations is a mismatch with the compiler semantics.
571 if (Cursor.kind == CXCursor_ObjCInterfaceDecl) {
572 ObjCInterfaceDecl *ID = cast<ObjCInterfaceDecl>(D);
573 if (!ID->isThisDeclarationADefinition())
574 Cursor = MakeCursorObjCClassRef(ID, ID->getLocation(), TU);
575
576 } else if (Cursor.kind == CXCursor_ObjCProtocolDecl) {
577 ObjCProtocolDecl *PD = cast<ObjCProtocolDecl>(D);
578 if (!PD->isThisDeclarationADefinition())
579 Cursor = MakeCursorObjCProtocolRef(PD, PD->getLocation(), TU);
580 }
581
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000582 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
583 if (!V.hasValue())
584 continue;
585 if (!V.getValue())
586 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000587 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000588 return true;
589 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000590 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000591}
592
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000593bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
594 llvm_unreachable("Translation units are visited directly by Visit()");
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000595}
596
Richard Smith162e1c12011-04-15 14:24:37 +0000597bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
598 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
599 return Visit(TSInfo->getTypeLoc());
600
601 return false;
602}
603
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000604bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
605 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
606 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000607
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000608 return false;
609}
610
611bool CursorVisitor::VisitTagDecl(TagDecl *D) {
612 return VisitDeclContext(D);
613}
614
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000615bool CursorVisitor::VisitClassTemplateSpecializationDecl(
616 ClassTemplateSpecializationDecl *D) {
617 bool ShouldVisitBody = false;
618 switch (D->getSpecializationKind()) {
619 case TSK_Undeclared:
620 case TSK_ImplicitInstantiation:
621 // Nothing to visit
622 return false;
623
624 case TSK_ExplicitInstantiationDeclaration:
625 case TSK_ExplicitInstantiationDefinition:
626 break;
627
628 case TSK_ExplicitSpecialization:
629 ShouldVisitBody = true;
630 break;
631 }
632
633 // Visit the template arguments used in the specialization.
634 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
635 TypeLoc TL = SpecType->getTypeLoc();
636 if (TemplateSpecializationTypeLoc *TSTLoc
637 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
638 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
639 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
640 return true;
641 }
642 }
643
644 if (ShouldVisitBody && VisitCXXRecordDecl(D))
645 return true;
646
647 return false;
648}
649
Douglas Gregor74dbe642010-08-31 19:31:58 +0000650bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
651 ClassTemplatePartialSpecializationDecl *D) {
652 // FIXME: Visit the "outer" template parameter lists on the TagDecl
653 // before visiting these template parameters.
654 if (VisitTemplateParameters(D->getTemplateParameters()))
655 return true;
656
657 // Visit the partial specialization arguments.
658 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
659 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
660 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
661 return true;
662
663 return VisitCXXRecordDecl(D);
664}
665
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000666bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000667 // Visit the default argument.
668 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
669 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
670 if (Visit(DefArg->getTypeLoc()))
671 return true;
672
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000673 return false;
674}
675
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000676bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
677 if (Expr *Init = D->getInitExpr())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000678 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000679 return false;
680}
681
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000682bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
683 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
684 if (Visit(TSInfo->getTypeLoc()))
685 return true;
686
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000687 // Visit the nested-name-specifier, if present.
688 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
689 if (VisitNestedNameSpecifierLoc(QualifierLoc))
690 return true;
691
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000692 return false;
693}
694
Douglas Gregora67e03f2010-09-09 21:42:20 +0000695/// \brief Compare two base or member initializers based on their source order.
Sean Huntcbb67482011-01-08 20:30:50 +0000696static int CompareCXXCtorInitializers(const void* Xp, const void *Yp) {
697 CXXCtorInitializer const * const *X
698 = static_cast<CXXCtorInitializer const * const *>(Xp);
699 CXXCtorInitializer const * const *Y
700 = static_cast<CXXCtorInitializer const * const *>(Yp);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000701
702 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
703 return -1;
704 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
705 return 1;
706 else
707 return 0;
708}
709
Douglas Gregorb1373d02010-01-20 20:59:29 +0000710bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000711 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
712 // Visit the function declaration's syntactic components in the order
713 // written. This requires a bit of work.
Abramo Bagnara723df242010-12-14 22:11:44 +0000714 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
Douglas Gregor01829d32010-08-31 14:41:23 +0000715 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
716
717 // If we have a function declared directly (without the use of a typedef),
718 // visit just the return type. Otherwise, just visit the function's type
719 // now.
720 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
721 (!FTL && Visit(TL)))
722 return true;
723
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000724 // Visit the nested-name-specifier, if present.
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000725 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
726 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000727 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000728
729 // Visit the declaration name.
730 if (VisitDeclarationNameInfo(ND->getNameInfo()))
731 return true;
732
733 // FIXME: Visit explicitly-specified template arguments!
734
735 // Visit the function parameters, if we have a function type.
736 if (FTL && VisitFunctionTypeLoc(*FTL, true))
737 return true;
738
739 // FIXME: Attributes?
740 }
741
Sean Hunt10620eb2011-05-06 20:44:56 +0000742 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
Douglas Gregora67e03f2010-09-09 21:42:20 +0000743 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
744 // Find the initializers that were written in the source.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000745 SmallVector<CXXCtorInitializer *, 4> WrittenInits;
Douglas Gregora67e03f2010-09-09 21:42:20 +0000746 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
747 IEnd = Constructor->init_end();
748 I != IEnd; ++I) {
749 if (!(*I)->isWritten())
750 continue;
751
752 WrittenInits.push_back(*I);
753 }
754
755 // Sort the initializers in source order
756 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
Sean Huntcbb67482011-01-08 20:30:50 +0000757 &CompareCXXCtorInitializers);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000758
759 // Visit the initializers in source order
760 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
Sean Huntcbb67482011-01-08 20:30:50 +0000761 CXXCtorInitializer *Init = WrittenInits[I];
Francois Pichet00eb3f92010-12-04 09:14:42 +0000762 if (Init->isAnyMemberInitializer()) {
763 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
Douglas Gregora67e03f2010-09-09 21:42:20 +0000764 Init->getMemberLocation(), TU)))
765 return true;
Douglas Gregor76852c22011-11-01 01:16:03 +0000766 } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) {
767 if (Visit(TInfo->getTypeLoc()))
Douglas Gregora67e03f2010-09-09 21:42:20 +0000768 return true;
769 }
770
771 // Visit the initializer value.
772 if (Expr *Initializer = Init->getInit())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000773 if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
Douglas Gregora67e03f2010-09-09 21:42:20 +0000774 return true;
775 }
776 }
777
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000778 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
Douglas Gregora67e03f2010-09-09 21:42:20 +0000779 return true;
780 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000781
Douglas Gregorb1373d02010-01-20 20:59:29 +0000782 return false;
783}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000784
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000785bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
786 if (VisitDeclaratorDecl(D))
787 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000788
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000789 if (Expr *BitWidth = D->getBitWidth())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000790 return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000791
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000792 return false;
793}
794
795bool CursorVisitor::VisitVarDecl(VarDecl *D) {
796 if (VisitDeclaratorDecl(D))
797 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000798
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000799 if (Expr *Init = D->getInit())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000800 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000801
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000802 return false;
803}
804
Douglas Gregor84b51d72010-09-01 20:16:53 +0000805bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
806 if (VisitDeclaratorDecl(D))
807 return true;
808
809 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
810 if (Expr *DefArg = D->getDefaultArgument())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000811 return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
Douglas Gregor84b51d72010-09-01 20:16:53 +0000812
813 return false;
814}
815
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000816bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
817 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
818 // before visiting these template parameters.
819 if (VisitTemplateParameters(D->getTemplateParameters()))
820 return true;
821
822 return VisitFunctionDecl(D->getTemplatedDecl());
823}
824
Douglas Gregor39d6f072010-08-31 19:02:00 +0000825bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
826 // FIXME: Visit the "outer" template parameter lists on the TagDecl
827 // before visiting these template parameters.
828 if (VisitTemplateParameters(D->getTemplateParameters()))
829 return true;
830
831 return VisitCXXRecordDecl(D->getTemplatedDecl());
832}
833
Douglas Gregor84b51d72010-09-01 20:16:53 +0000834bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
835 if (VisitTemplateParameters(D->getTemplateParameters()))
836 return true;
837
838 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
839 VisitTemplateArgumentLoc(D->getDefaultArgument()))
840 return true;
841
842 return false;
843}
844
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000845bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000846 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
847 if (Visit(TSInfo->getTypeLoc()))
848 return true;
849
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000850 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000851 PEnd = ND->param_end();
852 P != PEnd; ++P) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000853 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000854 return true;
855 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000856
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000857 if (ND->isThisDeclarationADefinition() &&
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000858 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000859 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000860
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000861 return false;
862}
863
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +0000864template <typename DeclIt>
865static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current,
866 SourceManager &SM, SourceLocation EndLoc,
867 SmallVectorImpl<Decl *> &Decls) {
868 DeclIt next = *DI_current;
869 while (++next != DE_current) {
870 Decl *D_next = *next;
871 if (!D_next)
872 break;
873 SourceLocation L = D_next->getLocStart();
874 if (!L.isValid())
875 break;
876 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
877 *DI_current = next;
878 Decls.push_back(D_next);
879 continue;
880 }
881 break;
882 }
883}
884
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000885namespace {
886 struct ContainerDeclsSort {
887 SourceManager &SM;
888 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
889 bool operator()(Decl *A, Decl *B) {
890 SourceLocation L_A = A->getLocStart();
891 SourceLocation L_B = B->getLocStart();
892 assert(L_A.isValid() && L_B.isValid());
893 return SM.isBeforeInTranslationUnit(L_A, L_B);
894 }
895 };
896}
897
Douglas Gregora59e3902010-01-21 23:27:09 +0000898bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000899 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
900 // an @implementation can lexically contain Decls that are not properly
901 // nested in the AST. When we identify such cases, we need to retrofit
902 // this nesting here.
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +0000903 if (!DI_current && !FileDI_current)
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000904 return VisitDeclContext(D);
905
906 // Scan the Decls that immediately come after the container
907 // in the current DeclContext. If any fall within the
908 // container's lexical region, stash them into a vector
909 // for later processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000910 SmallVector<Decl *, 24> DeclsInContainer;
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000911 SourceLocation EndLoc = D->getSourceRange().getEnd();
Ted Kremeneka60ed472010-11-16 08:15:36 +0000912 SourceManager &SM = AU->getSourceManager();
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000913 if (EndLoc.isValid()) {
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +0000914 if (DI_current) {
915 addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc,
916 DeclsInContainer);
917 } else {
918 addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc,
919 DeclsInContainer);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000920 }
921 }
922
923 // The common case.
924 if (DeclsInContainer.empty())
925 return VisitDeclContext(D);
926
927 // Get all the Decls in the DeclContext, and sort them with the
928 // additional ones we've collected. Then visit them.
929 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
930 I!=E; ++I) {
931 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000932 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
933 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000934 continue;
935 DeclsInContainer.push_back(subDecl);
936 }
937
938 // Now sort the Decls so that they appear in lexical order.
939 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
940 ContainerDeclsSort(SM));
941
942 // Now visit the decls.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000943 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000944 E = DeclsInContainer.end(); I != E; ++I) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000945 CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000946 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
947 if (!V.hasValue())
948 continue;
949 if (!V.getValue())
950 return false;
951 if (Visit(Cursor, true))
952 return true;
953 }
954 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000955}
956
Douglas Gregorb1373d02010-01-20 20:59:29 +0000957bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000958 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
959 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000960 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000961
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000962 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
963 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
964 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000965 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000966 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000967
Douglas Gregora59e3902010-01-21 23:27:09 +0000968 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000969}
970
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000971bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000972 if (!PID->isThisDeclarationADefinition())
973 return Visit(MakeCursorObjCProtocolRef(PID, PID->getLocation(), TU));
974
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000975 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
976 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
977 E = PID->protocol_end(); I != E; ++I, ++PL)
978 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
979 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000980
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000981 return VisitObjCContainerDecl(PID);
982}
983
Ted Kremenek23173d72010-05-18 21:09:07 +0000984bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000985 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000986 return true;
987
Ted Kremenek23173d72010-05-18 21:09:07 +0000988 // FIXME: This implements a workaround with @property declarations also being
989 // installed in the DeclContext for the @interface. Eventually this code
990 // should be removed.
991 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
992 if (!CDecl || !CDecl->IsClassExtension())
993 return false;
994
995 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
996 if (!ID)
997 return false;
998
999 IdentifierInfo *PropertyId = PD->getIdentifier();
1000 ObjCPropertyDecl *prevDecl =
1001 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
1002
1003 if (!prevDecl)
1004 return false;
1005
1006 // Visit synthesized methods since they will be skipped when visiting
1007 // the @interface.
1008 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +00001009 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001010 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
Ted Kremenek23173d72010-05-18 21:09:07 +00001011 return true;
1012
1013 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +00001014 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001015 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
Ted Kremenek23173d72010-05-18 21:09:07 +00001016 return true;
1017
1018 return false;
1019}
1020
Douglas Gregorb1373d02010-01-20 20:59:29 +00001021bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Douglas Gregor375bb142011-12-27 22:43:10 +00001022 if (!D->isThisDeclarationADefinition()) {
1023 // Forward declaration is treated like a reference.
1024 return Visit(MakeCursorObjCClassRef(D, D->getLocation(), TU));
1025 }
1026
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001027 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +00001028 if (D->getSuperClass() &&
1029 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001030 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001031 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001032 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001033
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001034 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1035 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1036 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001037 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001038 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001039
Douglas Gregora59e3902010-01-21 23:27:09 +00001040 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001041}
1042
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001043bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1044 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001045}
1046
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001047bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +00001048 // 'ID' could be null when dealing with invalid code.
1049 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1050 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1051 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001052
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001053 return VisitObjCImplDecl(D);
1054}
1055
1056bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1057#if 0
1058 // Issue callbacks for super class.
1059 // FIXME: No source location information!
1060 if (D->getSuperClass() &&
1061 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001062 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001063 TU)))
1064 return true;
1065#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001066
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001067 return VisitObjCImplDecl(D);
1068}
1069
Douglas Gregora4ffd852010-11-17 01:03:52 +00001070bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1071 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
Argyrios Kyrtzidis135bf8e2012-06-09 03:03:02 +00001072 if (PD->isIvarNameSpecified())
1073 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
Douglas Gregora4ffd852010-11-17 01:03:52 +00001074
1075 return false;
1076}
1077
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001078bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1079 return VisitDeclContext(D);
1080}
1081
Douglas Gregor69319002010-08-31 23:48:11 +00001082bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001083 // Visit nested-name-specifier.
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00001084 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1085 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001086 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001087
1088 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1089 D->getTargetNameLoc(), TU));
1090}
1091
Douglas Gregor7e242562010-09-01 19:52:22 +00001092bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001093 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001094 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1095 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001096 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001097 }
Douglas Gregor7e242562010-09-01 19:52:22 +00001098
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001099 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1100 return true;
1101
Douglas Gregor7e242562010-09-01 19:52:22 +00001102 return VisitDeclarationNameInfo(D->getNameInfo());
1103}
1104
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001105bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001106 // Visit nested-name-specifier.
Douglas Gregordb992412011-02-25 16:33:46 +00001107 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1108 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001109 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001110
1111 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1112 D->getIdentLocation(), TU));
1113}
1114
Douglas Gregor7e242562010-09-01 19:52:22 +00001115bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001116 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001117 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1118 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001119 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001120 }
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001121
Douglas Gregor7e242562010-09-01 19:52:22 +00001122 return VisitDeclarationNameInfo(D->getNameInfo());
1123}
1124
1125bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1126 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001127 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001128 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1129 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001130 return true;
1131
Douglas Gregor7e242562010-09-01 19:52:22 +00001132 return false;
1133}
1134
Douglas Gregor01829d32010-08-31 14:41:23 +00001135bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1136 switch (Name.getName().getNameKind()) {
1137 case clang::DeclarationName::Identifier:
1138 case clang::DeclarationName::CXXLiteralOperatorName:
1139 case clang::DeclarationName::CXXOperatorName:
1140 case clang::DeclarationName::CXXUsingDirective:
1141 return false;
1142
1143 case clang::DeclarationName::CXXConstructorName:
1144 case clang::DeclarationName::CXXDestructorName:
1145 case clang::DeclarationName::CXXConversionFunctionName:
1146 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1147 return Visit(TSInfo->getTypeLoc());
1148 return false;
1149
1150 case clang::DeclarationName::ObjCZeroArgSelector:
1151 case clang::DeclarationName::ObjCOneArgSelector:
1152 case clang::DeclarationName::ObjCMultiArgSelector:
1153 // FIXME: Per-identifier location info?
1154 return false;
1155 }
David Blaikie7530c032012-01-17 06:56:22 +00001156
1157 llvm_unreachable("Invalid DeclarationName::Kind!");
Douglas Gregor01829d32010-08-31 14:41:23 +00001158}
1159
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001160bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1161 SourceRange Range) {
1162 // FIXME: This whole routine is a hack to work around the lack of proper
1163 // source information in nested-name-specifiers (PR5791). Since we do have
1164 // a beginning source location, we can visit the first component of the
1165 // nested-name-specifier, if it's a single-token component.
1166 if (!NNS)
1167 return false;
1168
1169 // Get the first component in the nested-name-specifier.
1170 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1171 NNS = Prefix;
1172
1173 switch (NNS->getKind()) {
1174 case NestedNameSpecifier::Namespace:
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001175 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1176 TU));
1177
Douglas Gregor14aba762011-02-24 02:36:08 +00001178 case NestedNameSpecifier::NamespaceAlias:
1179 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1180 Range.getBegin(), TU));
1181
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001182 case NestedNameSpecifier::TypeSpec: {
1183 // If the type has a form where we know that the beginning of the source
1184 // range matches up with a reference cursor. Visit the appropriate reference
1185 // cursor.
John McCallf4c73712011-01-19 06:33:43 +00001186 const Type *T = NNS->getAsType();
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001187 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1188 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1189 if (const TagType *Tag = dyn_cast<TagType>(T))
1190 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1191 if (const TemplateSpecializationType *TST
1192 = dyn_cast<TemplateSpecializationType>(T))
1193 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1194 break;
1195 }
1196
1197 case NestedNameSpecifier::TypeSpecWithTemplate:
1198 case NestedNameSpecifier::Global:
1199 case NestedNameSpecifier::Identifier:
1200 break;
1201 }
1202
1203 return false;
1204}
1205
Douglas Gregordc355712011-02-25 00:36:19 +00001206bool
1207CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001208 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
Douglas Gregordc355712011-02-25 00:36:19 +00001209 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1210 Qualifiers.push_back(Qualifier);
1211
1212 while (!Qualifiers.empty()) {
1213 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1214 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1215 switch (NNS->getKind()) {
1216 case NestedNameSpecifier::Namespace:
1217 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001218 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001219 TU)))
1220 return true;
1221
1222 break;
1223
1224 case NestedNameSpecifier::NamespaceAlias:
1225 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001226 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001227 TU)))
1228 return true;
1229
1230 break;
1231
1232 case NestedNameSpecifier::TypeSpec:
1233 case NestedNameSpecifier::TypeSpecWithTemplate:
1234 if (Visit(Q.getTypeLoc()))
1235 return true;
1236
1237 break;
1238
1239 case NestedNameSpecifier::Global:
1240 case NestedNameSpecifier::Identifier:
1241 break;
1242 }
1243 }
1244
1245 return false;
1246}
1247
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001248bool CursorVisitor::VisitTemplateParameters(
1249 const TemplateParameterList *Params) {
1250 if (!Params)
1251 return false;
1252
1253 for (TemplateParameterList::const_iterator P = Params->begin(),
1254 PEnd = Params->end();
1255 P != PEnd; ++P) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001256 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001257 return true;
1258 }
1259
1260 return false;
1261}
1262
Douglas Gregor0b36e612010-08-31 20:37:03 +00001263bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1264 switch (Name.getKind()) {
1265 case TemplateName::Template:
1266 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1267
1268 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001269 // Visit the overloaded template set.
1270 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1271 return true;
1272
Douglas Gregor0b36e612010-08-31 20:37:03 +00001273 return false;
1274
1275 case TemplateName::DependentTemplate:
1276 // FIXME: Visit nested-name-specifier.
1277 return false;
1278
1279 case TemplateName::QualifiedTemplate:
1280 // FIXME: Visit nested-name-specifier.
1281 return Visit(MakeCursorTemplateRef(
1282 Name.getAsQualifiedTemplateName()->getDecl(),
1283 Loc, TU));
John McCall14606042011-06-30 08:33:18 +00001284
1285 case TemplateName::SubstTemplateTemplateParm:
1286 return Visit(MakeCursorTemplateRef(
1287 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1288 Loc, TU));
Douglas Gregor1aee05d2011-01-15 06:45:20 +00001289
1290 case TemplateName::SubstTemplateTemplateParmPack:
1291 return Visit(MakeCursorTemplateRef(
1292 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1293 Loc, TU));
Douglas Gregor0b36e612010-08-31 20:37:03 +00001294 }
David Blaikie7530c032012-01-17 06:56:22 +00001295
1296 llvm_unreachable("Invalid TemplateName::Kind!");
Douglas Gregor0b36e612010-08-31 20:37:03 +00001297}
1298
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001299bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1300 switch (TAL.getArgument().getKind()) {
1301 case TemplateArgument::Null:
1302 case TemplateArgument::Integral:
Douglas Gregor87dd6972010-12-20 16:52:59 +00001303 case TemplateArgument::Pack:
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001304 return false;
1305
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001306 case TemplateArgument::Type:
1307 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1308 return Visit(TSInfo->getTypeLoc());
1309 return false;
1310
1311 case TemplateArgument::Declaration:
1312 if (Expr *E = TAL.getSourceDeclExpression())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001313 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001314 return false;
1315
1316 case TemplateArgument::Expression:
1317 if (Expr *E = TAL.getSourceExpression())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001318 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001319 return false;
1320
1321 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001322 case TemplateArgument::TemplateExpansion:
Douglas Gregorb6744ef2011-03-02 17:09:35 +00001323 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1324 return true;
1325
Douglas Gregora7fc9012011-01-05 18:58:31 +00001326 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
Douglas Gregor0b36e612010-08-31 20:37:03 +00001327 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001328 }
David Blaikie7530c032012-01-17 06:56:22 +00001329
1330 llvm_unreachable("Invalid TemplateArgument::Kind!");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001331}
1332
Ted Kremeneka0536d82010-05-07 01:04:29 +00001333bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1334 return VisitDeclContext(D);
1335}
1336
Douglas Gregor01829d32010-08-31 14:41:23 +00001337bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1338 return Visit(TL.getUnqualifiedLoc());
1339}
1340
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001341bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00001342 ASTContext &Context = AU->getASTContext();
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001343
1344 // Some builtin types (such as Objective-C's "id", "sel", and
1345 // "Class") have associated declarations. Create cursors for those.
1346 QualType VisitType;
John McCalle0a22d02011-10-18 21:02:43 +00001347 switch (TL.getTypePtr()->getKind()) {
John McCall2dde35b2011-10-18 22:28:37 +00001348
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001349 case BuiltinType::Void:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001350 case BuiltinType::NullPtr:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001351 case BuiltinType::Dependent:
John McCall2dde35b2011-10-18 22:28:37 +00001352#define BUILTIN_TYPE(Id, SingletonId)
1353#define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1354#define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1355#define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
1356#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
1357#include "clang/AST/BuiltinTypes.def"
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001358 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001359
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001360 case BuiltinType::ObjCId:
1361 VisitType = Context.getObjCIdType();
1362 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001363
1364 case BuiltinType::ObjCClass:
1365 VisitType = Context.getObjCClassType();
1366 break;
1367
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001368 case BuiltinType::ObjCSel:
1369 VisitType = Context.getObjCSelType();
1370 break;
1371 }
1372
1373 if (!VisitType.isNull()) {
1374 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001375 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001376 TU));
1377 }
1378
1379 return false;
1380}
1381
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001382bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
Richard Smith162e1c12011-04-15 14:24:37 +00001383 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001384}
1385
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001386bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1387 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1388}
1389
1390bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
Argyrios Kyrtzidis6f155de2011-08-25 22:24:47 +00001391 if (TL.isDefinition())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001392 return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
Argyrios Kyrtzidis6f155de2011-08-25 22:24:47 +00001393
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001394 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1395}
1396
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001397bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Chandler Carruth960d13d2011-05-01 09:53:37 +00001398 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001399}
1400
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001401bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1402 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1403 return true;
1404
John McCallc12c5bb2010-05-15 11:32:37 +00001405 return false;
1406}
1407
1408bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1409 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1410 return true;
1411
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001412 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1413 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1414 TU)))
1415 return true;
1416 }
1417
1418 return false;
1419}
1420
1421bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001422 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001423}
1424
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001425bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1426 return Visit(TL.getInnerLoc());
1427}
1428
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001429bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1430 return Visit(TL.getPointeeLoc());
1431}
1432
1433bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1434 return Visit(TL.getPointeeLoc());
1435}
1436
1437bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1438 return Visit(TL.getPointeeLoc());
1439}
1440
1441bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001442 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001443}
1444
1445bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001446 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001447}
1448
Argyrios Kyrtzidis3422fbc2011-08-15 18:44:43 +00001449bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1450 return Visit(TL.getModifiedLoc());
1451}
1452
Douglas Gregor01829d32010-08-31 14:41:23 +00001453bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1454 bool SkipResultType) {
1455 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001456 return true;
1457
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001458 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001459 if (Decl *D = TL.getArg(I))
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001460 if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001461 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001462
1463 return false;
1464}
1465
1466bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1467 if (Visit(TL.getElementLoc()))
1468 return true;
1469
1470 if (Expr *Size = TL.getSizeExpr())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001471 return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001472
1473 return false;
1474}
1475
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001476bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1477 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001478 // Visit the template name.
1479 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1480 TL.getTemplateNameLoc()))
1481 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001482
1483 // Visit the template arguments.
1484 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1485 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1486 return true;
1487
1488 return false;
1489}
1490
Douglas Gregor2332c112010-01-21 20:48:56 +00001491bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1492 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1493}
1494
1495bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1496 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1497 return Visit(TSInfo->getTypeLoc());
1498
1499 return false;
1500}
1501
Sean Huntca63c202011-05-24 22:41:36 +00001502bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1503 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1504 return Visit(TSInfo->getTypeLoc());
1505
1506 return false;
1507}
1508
Douglas Gregor2494dd02011-03-01 01:34:45 +00001509bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
1510 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1511 return true;
1512
1513 return false;
1514}
1515
Douglas Gregor94fdffa2011-03-01 20:11:18 +00001516bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1517 DependentTemplateSpecializationTypeLoc TL) {
1518 // Visit the nested-name-specifier, if there is one.
1519 if (TL.getQualifierLoc() &&
1520 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1521 return true;
1522
1523 // Visit the template arguments.
1524 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1525 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1526 return true;
1527
1528 return false;
1529}
1530
Douglas Gregor9e876872011-03-01 18:12:44 +00001531bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1532 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1533 return true;
1534
1535 return Visit(TL.getNamedTypeLoc());
1536}
1537
Douglas Gregor7536dd52010-12-20 02:24:11 +00001538bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1539 return Visit(TL.getPatternLoc());
1540}
1541
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +00001542bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1543 if (Expr *E = TL.getUnderlyingExpr())
1544 return Visit(MakeCXCursor(E, StmtParent, TU));
1545
1546 return false;
1547}
1548
1549bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1550 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1551}
1552
Eli Friedmanb001de72011-10-06 23:00:33 +00001553bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1554 return Visit(TL.getValueLoc());
1555}
1556
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +00001557#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1558bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1559 return Visit##PARENT##Loc(TL); \
1560}
1561
1562DEFAULT_TYPELOC_IMPL(Complex, Type)
1563DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1564DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1565DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1566DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
1567DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1568DEFAULT_TYPELOC_IMPL(Vector, Type)
1569DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1570DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1571DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1572DEFAULT_TYPELOC_IMPL(Record, TagType)
1573DEFAULT_TYPELOC_IMPL(Enum, TagType)
1574DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1575DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1576DEFAULT_TYPELOC_IMPL(Auto, Type)
1577
Ted Kremenek3064ef92010-08-27 21:34:58 +00001578bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001579 // Visit the nested-name-specifier, if present.
1580 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1581 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1582 return true;
1583
John McCall5e1cdac2011-10-07 06:10:15 +00001584 if (D->isCompleteDefinition()) {
Ted Kremenek3064ef92010-08-27 21:34:58 +00001585 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1586 E = D->bases_end(); I != E; ++I) {
1587 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1588 return true;
1589 }
1590 }
1591
1592 return VisitTagDecl(D);
1593}
1594
Ted Kremenek09dfa372010-02-18 05:46:33 +00001595bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001596 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1597 i != e; ++i)
1598 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001599 return true;
1600
1601 return false;
1602}
1603
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001604//===----------------------------------------------------------------------===//
1605// Data-recursive visitor methods.
1606//===----------------------------------------------------------------------===//
1607
Ted Kremenek28a71942010-11-13 00:36:47 +00001608namespace {
Ted Kremenek035dc412010-11-13 00:36:50 +00001609#define DEF_JOB(NAME, DATA, KIND)\
1610class NAME : public VisitorJob {\
1611public:\
1612 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1613 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Ted Kremenekf64d8032010-11-18 00:02:32 +00001614 DATA *get() const { return static_cast<DATA*>(data[0]); }\
Ted Kremenek035dc412010-11-13 00:36:50 +00001615};
1616
1617DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1618DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001619DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001620DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001621DEF_JOB(ExplicitTemplateArgsVisit, ASTTemplateArgumentListInfo,
Ted Kremenek60608ec2010-11-17 00:50:47 +00001622 ExplicitTemplateArgsVisitKind)
Douglas Gregor94d96292011-01-19 20:34:17 +00001623DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
Douglas Gregor011d8b92012-02-15 00:54:55 +00001624DEF_JOB(LambdaExprParts, LambdaExpr, LambdaExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001625#undef DEF_JOB
1626
1627class DeclVisit : public VisitorJob {
1628public:
1629 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1630 VisitorJob(parent, VisitorJob::DeclVisitKind,
1631 d, isFirst ? (void*) 1 : (void*) 0) {}
1632 static bool classof(const VisitorJob *VJ) {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001633 return VJ->getKind() == DeclVisitKind;
Ted Kremenek035dc412010-11-13 00:36:50 +00001634 }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001635 Decl *get() const { return static_cast<Decl*>(data[0]); }
1636 bool isFirst() const { return data[1] ? true : false; }
Ted Kremenek035dc412010-11-13 00:36:50 +00001637};
Ted Kremenek035dc412010-11-13 00:36:50 +00001638class TypeLocVisit : public VisitorJob {
1639public:
1640 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1641 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1642 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1643
1644 static bool classof(const VisitorJob *VJ) {
1645 return VJ->getKind() == TypeLocVisitKind;
1646 }
1647
Ted Kremenek82f3c502010-11-15 22:23:26 +00001648 TypeLoc get() const {
Ted Kremenekf64d8032010-11-18 00:02:32 +00001649 QualType T = QualType::getFromOpaquePtr(data[0]);
1650 return TypeLoc(T, data[1]);
Ted Kremenek035dc412010-11-13 00:36:50 +00001651 }
1652};
1653
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001654class LabelRefVisit : public VisitorJob {
1655public:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001656 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1657 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001658 labelLoc.getPtrEncoding()) {}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001659
1660 static bool classof(const VisitorJob *VJ) {
1661 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1662 }
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001663 LabelDecl *get() const { return static_cast<LabelDecl*>(data[0]); }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001664 SourceLocation getLoc() const {
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001665 return SourceLocation::getFromPtrEncoding(data[1]); }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001666};
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001667
1668class NestedNameSpecifierLocVisit : public VisitorJob {
1669public:
1670 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1671 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1672 Qualifier.getNestedNameSpecifier(),
1673 Qualifier.getOpaqueData()) { }
1674
1675 static bool classof(const VisitorJob *VJ) {
1676 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1677 }
1678
1679 NestedNameSpecifierLoc get() const {
1680 return NestedNameSpecifierLoc(static_cast<NestedNameSpecifier*>(data[0]),
1681 data[1]);
1682 }
1683};
1684
Ted Kremenekf64d8032010-11-18 00:02:32 +00001685class DeclarationNameInfoVisit : public VisitorJob {
1686public:
1687 DeclarationNameInfoVisit(Stmt *S, CXCursor parent)
1688 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
1689 static bool classof(const VisitorJob *VJ) {
1690 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1691 }
1692 DeclarationNameInfo get() const {
1693 Stmt *S = static_cast<Stmt*>(data[0]);
1694 switch (S->getStmtClass()) {
1695 default:
1696 llvm_unreachable("Unhandled Stmt");
Douglas Gregorba0513d2011-10-25 01:33:02 +00001697 case clang::Stmt::MSDependentExistsStmtClass:
1698 return cast<MSDependentExistsStmt>(S)->getNameInfo();
Ted Kremenekf64d8032010-11-18 00:02:32 +00001699 case Stmt::CXXDependentScopeMemberExprClass:
1700 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1701 case Stmt::DependentScopeDeclRefExprClass:
1702 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
1703 }
1704 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001705};
Ted Kremenekcdba6592010-11-18 00:42:18 +00001706class MemberRefVisit : public VisitorJob {
1707public:
1708 MemberRefVisit(FieldDecl *D, SourceLocation L, CXCursor parent)
1709 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001710 L.getPtrEncoding()) {}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001711 static bool classof(const VisitorJob *VJ) {
1712 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1713 }
1714 FieldDecl *get() const {
1715 return static_cast<FieldDecl*>(data[0]);
1716 }
1717 SourceLocation getLoc() const {
1718 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1719 }
1720};
Ted Kremenek28a71942010-11-13 00:36:47 +00001721class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1722 VisitorWorkList &WL;
1723 CXCursor Parent;
1724public:
1725 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1726 : WL(wl), Parent(parent) {}
1727
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001728 void VisitAddrLabelExpr(AddrLabelExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001729 void VisitBlockExpr(BlockExpr *B);
Ted Kremenek28a71942010-11-13 00:36:47 +00001730 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek083c7e22010-11-13 05:38:03 +00001731 void VisitCompoundStmt(CompoundStmt *S);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001732 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
Douglas Gregorba0513d2011-10-25 01:33:02 +00001733 void VisitMSDependentExistsStmt(MSDependentExistsStmt *S);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001734 void VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001735 void VisitCXXNewExpr(CXXNewExpr *E);
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001736 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001737 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001738 void VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001739 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001740 void VisitCXXTypeidExpr(CXXTypeidExpr *E);
Ted Kremenek55b933a2010-11-17 00:50:36 +00001741 void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001742 void VisitCXXUuidofExpr(CXXUuidofExpr *E);
Argyrios Kyrtzidisdcbb2fb2011-12-03 03:49:44 +00001743 void VisitCXXCatchStmt(CXXCatchStmt *S);
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001744 void VisitDeclRefExpr(DeclRefExpr *D);
Ted Kremenek035dc412010-11-13 00:36:50 +00001745 void VisitDeclStmt(DeclStmt *S);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001746 void VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001747 void VisitDesignatedInitExpr(DesignatedInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001748 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1749 void VisitForStmt(ForStmt *FS);
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001750 void VisitGotoStmt(GotoStmt *GS);
Ted Kremenek28a71942010-11-13 00:36:47 +00001751 void VisitIfStmt(IfStmt *If);
1752 void VisitInitListExpr(InitListExpr *IE);
1753 void VisitMemberExpr(MemberExpr *M);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001754 void VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001755 void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001756 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1757 void VisitOverloadExpr(OverloadExpr *E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001758 void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001759 void VisitStmt(Stmt *S);
1760 void VisitSwitchStmt(SwitchStmt *S);
1761 void VisitWhileStmt(WhileStmt *W);
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001762 void VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Francois Pichet6ad6f282010-12-07 00:08:36 +00001763 void VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E);
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00001764 void VisitTypeTraitExpr(TypeTraitExpr *E);
John Wiegley21ff2e52011-04-28 00:16:57 +00001765 void VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E);
John Wiegley55262202011-04-25 06:54:41 +00001766 void VisitExpressionTraitExpr(ExpressionTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001767 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001768 void VisitVAArgExpr(VAArgExpr *E);
Douglas Gregor94d96292011-01-19 20:34:17 +00001769 void VisitSizeOfPackExpr(SizeOfPackExpr *E);
John McCall4b9c2d22011-11-06 09:01:30 +00001770 void VisitPseudoObjectExpr(PseudoObjectExpr *E);
1771 void VisitOpaqueValueExpr(OpaqueValueExpr *E);
Douglas Gregor011d8b92012-02-15 00:54:55 +00001772 void VisitLambdaExpr(LambdaExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00001773
Ted Kremenek28a71942010-11-13 00:36:47 +00001774private:
Ted Kremenekf64d8032010-11-18 00:02:32 +00001775 void AddDeclarationNameInfo(Stmt *S);
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001776 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001777 void AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001778 void AddMemberRef(FieldDecl *D, SourceLocation L);
Ted Kremenek28a71942010-11-13 00:36:47 +00001779 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001780 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001781 void AddTypeLoc(TypeSourceInfo *TI);
1782 void EnqueueChildren(Stmt *S);
1783};
1784} // end anonyous namespace
1785
Ted Kremenekf64d8032010-11-18 00:02:32 +00001786void EnqueueVisitor::AddDeclarationNameInfo(Stmt *S) {
1787 // 'S' should always be non-null, since it comes from the
1788 // statement we are visiting.
1789 WL.push_back(DeclarationNameInfoVisit(S, Parent));
1790}
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001791
1792void
1793EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1794 if (Qualifier)
1795 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
1796}
1797
Ted Kremenek28a71942010-11-13 00:36:47 +00001798void EnqueueVisitor::AddStmt(Stmt *S) {
1799 if (S)
1800 WL.push_back(StmtVisit(S, Parent));
1801}
Ted Kremenek035dc412010-11-13 00:36:50 +00001802void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001803 if (D)
Ted Kremenek035dc412010-11-13 00:36:50 +00001804 WL.push_back(DeclVisit(D, Parent, isFirst));
Ted Kremenek28a71942010-11-13 00:36:47 +00001805}
Ted Kremenek60608ec2010-11-17 00:50:47 +00001806void EnqueueVisitor::
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001807 AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001808 if (A)
1809 WL.push_back(ExplicitTemplateArgsVisit(
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001810 const_cast<ASTTemplateArgumentListInfo*>(A), Parent));
Ted Kremenek60608ec2010-11-17 00:50:47 +00001811}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001812void EnqueueVisitor::AddMemberRef(FieldDecl *D, SourceLocation L) {
1813 if (D)
1814 WL.push_back(MemberRefVisit(D, L, Parent));
1815}
Ted Kremenek28a71942010-11-13 00:36:47 +00001816void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1817 if (TI)
1818 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1819 }
1820void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001821 unsigned size = WL.size();
John McCall7502c1d2011-02-13 04:07:26 +00001822 for (Stmt::child_range Child = S->children(); Child; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001823 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001824 }
1825 if (size == WL.size())
1826 return;
1827 // Now reverse the entries we just added. This will match the DFS
1828 // ordering performed by the worklist.
1829 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1830 std::reverse(I, E);
1831}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001832void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1833 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
1834}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001835void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1836 AddDecl(B->getBlockDecl());
1837}
Ted Kremenek28a71942010-11-13 00:36:47 +00001838void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1839 EnqueueChildren(E);
1840 AddTypeLoc(E->getTypeSourceInfo());
1841}
Ted Kremenek083c7e22010-11-13 05:38:03 +00001842void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1843 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1844 E = S->body_rend(); I != E; ++I) {
1845 AddStmt(*I);
1846 }
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001847}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001848void EnqueueVisitor::
Douglas Gregorba0513d2011-10-25 01:33:02 +00001849VisitMSDependentExistsStmt(MSDependentExistsStmt *S) {
1850 AddStmt(S->getSubStmt());
1851 AddDeclarationNameInfo(S);
1852 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
1853 AddNestedNameSpecifierLoc(QualifierLoc);
1854}
1855
1856void EnqueueVisitor::
Ted Kremenekf64d8032010-11-18 00:02:32 +00001857VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
1858 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1859 AddDeclarationNameInfo(E);
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001860 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1861 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001862 if (!E->isImplicitAccess())
1863 AddStmt(E->getBase());
1864}
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001865void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001866 // Enqueue the initializer , if any.
1867 AddStmt(E->getInitializer());
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001868 // Enqueue the array size, if any.
1869 AddStmt(E->getArraySize());
1870 // Enqueue the allocated type.
1871 AddTypeLoc(E->getAllocatedTypeSourceInfo());
1872 // Enqueue the placement arguments.
1873 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1874 AddStmt(E->getPlacementArg(I-1));
1875}
Ted Kremenek28a71942010-11-13 00:36:47 +00001876void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
Ted Kremenek8b8d8c92010-11-13 05:55:56 +00001877 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1878 AddStmt(CE->getArg(I-1));
Ted Kremenek28a71942010-11-13 00:36:47 +00001879 AddStmt(CE->getCallee());
1880 AddStmt(CE->getArg(0));
1881}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001882void EnqueueVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1883 // Visit the name of the type being destroyed.
1884 AddTypeLoc(E->getDestroyedTypeInfo());
1885 // Visit the scope type that looks disturbingly like the nested-name-specifier
1886 // but isn't.
1887 AddTypeLoc(E->getScopeTypeInfo());
1888 // Visit the nested-name-specifier.
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001889 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1890 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001891 // Visit base expression.
1892 AddStmt(E->getBase());
1893}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001894void EnqueueVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1895 AddTypeLoc(E->getTypeSourceInfo());
1896}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001897void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1898 EnqueueChildren(E);
1899 AddTypeLoc(E->getTypeSourceInfo());
1900}
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001901void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1902 EnqueueChildren(E);
1903 if (E->isTypeOperand())
1904 AddTypeLoc(E->getTypeOperandSourceInfo());
1905}
Ted Kremenek55b933a2010-11-17 00:50:36 +00001906
1907void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
1908 *E) {
1909 EnqueueChildren(E);
1910 AddTypeLoc(E->getTypeSourceInfo());
1911}
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001912void EnqueueVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1913 EnqueueChildren(E);
1914 if (E->isTypeOperand())
1915 AddTypeLoc(E->getTypeOperandSourceInfo());
1916}
Argyrios Kyrtzidisdcbb2fb2011-12-03 03:49:44 +00001917
1918void EnqueueVisitor::VisitCXXCatchStmt(CXXCatchStmt *S) {
1919 EnqueueChildren(S);
1920 AddDecl(S->getExceptionDecl());
1921}
1922
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001923void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001924 if (DR->hasExplicitTemplateArgs()) {
1925 AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
1926 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001927 WL.push_back(DeclRefExprParts(DR, Parent));
1928}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001929void EnqueueVisitor::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
1930 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1931 AddDeclarationNameInfo(E);
Douglas Gregor00cf3cc2011-02-25 20:49:16 +00001932 AddNestedNameSpecifierLoc(E->getQualifierLoc());
Ted Kremenekf64d8032010-11-18 00:02:32 +00001933}
Ted Kremenek035dc412010-11-13 00:36:50 +00001934void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1935 unsigned size = WL.size();
1936 bool isFirst = true;
1937 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1938 D != DEnd; ++D) {
1939 AddDecl(*D, isFirst);
1940 isFirst = false;
1941 }
1942 if (size == WL.size())
1943 return;
1944 // Now reverse the entries we just added. This will match the DFS
1945 // ordering performed by the worklist.
1946 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1947 std::reverse(I, E);
1948}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001949void EnqueueVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1950 AddStmt(E->getInit());
1951 typedef DesignatedInitExpr::Designator Designator;
1952 for (DesignatedInitExpr::reverse_designators_iterator
1953 D = E->designators_rbegin(), DEnd = E->designators_rend();
1954 D != DEnd; ++D) {
1955 if (D->isFieldDesignator()) {
1956 if (FieldDecl *Field = D->getField())
1957 AddMemberRef(Field, D->getFieldLoc());
1958 continue;
1959 }
1960 if (D->isArrayDesignator()) {
1961 AddStmt(E->getArrayIndex(*D));
1962 continue;
1963 }
1964 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1965 AddStmt(E->getArrayRangeEnd(*D));
1966 AddStmt(E->getArrayRangeStart(*D));
1967 }
1968}
Ted Kremenek28a71942010-11-13 00:36:47 +00001969void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1970 EnqueueChildren(E);
1971 AddTypeLoc(E->getTypeInfoAsWritten());
1972}
1973void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1974 AddStmt(FS->getBody());
1975 AddStmt(FS->getInc());
1976 AddStmt(FS->getCond());
1977 AddDecl(FS->getConditionVariable());
1978 AddStmt(FS->getInit());
1979}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001980void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) {
1981 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
1982}
Ted Kremenek28a71942010-11-13 00:36:47 +00001983void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
1984 AddStmt(If->getElse());
1985 AddStmt(If->getThen());
1986 AddStmt(If->getCond());
1987 AddDecl(If->getConditionVariable());
1988}
1989void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
1990 // We care about the syntactic form of the initializer list, only.
1991 if (InitListExpr *Syntactic = IE->getSyntacticForm())
1992 IE = Syntactic;
1993 EnqueueChildren(IE);
1994}
1995void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
Douglas Gregor89629a72010-11-17 17:15:08 +00001996 WL.push_back(MemberExprParts(M, Parent));
1997
1998 // If the base of the member access expression is an implicit 'this', don't
1999 // visit it.
2000 // FIXME: If we ever want to show these implicit accesses, this will be
2001 // unfortunate. However, clang_getCursor() relies on this behavior.
Douglas Gregor75e85042011-03-02 21:06:53 +00002002 if (!M->isImplicitAccess())
2003 AddStmt(M->getBase());
Ted Kremenek28a71942010-11-13 00:36:47 +00002004}
Ted Kremenek73d15c42010-11-13 01:09:29 +00002005void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
2006 AddTypeLoc(E->getEncodedTypeSourceInfo());
2007}
Ted Kremenek28a71942010-11-13 00:36:47 +00002008void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
2009 EnqueueChildren(M);
2010 AddTypeLoc(M->getClassReceiverTypeInfo());
2011}
Ted Kremenekcdba6592010-11-18 00:42:18 +00002012void EnqueueVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
2013 // Visit the components of the offsetof expression.
2014 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
2015 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
2016 const OffsetOfNode &Node = E->getComponent(I-1);
2017 switch (Node.getKind()) {
2018 case OffsetOfNode::Array:
2019 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2020 break;
2021 case OffsetOfNode::Field:
Abramo Bagnara06dec892011-03-12 09:45:03 +00002022 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
Ted Kremenekcdba6592010-11-18 00:42:18 +00002023 break;
2024 case OffsetOfNode::Identifier:
2025 case OffsetOfNode::Base:
2026 continue;
2027 }
2028 }
2029 // Visit the type into which we're computing the offset.
2030 AddTypeLoc(E->getTypeSourceInfo());
2031}
Ted Kremenek28a71942010-11-13 00:36:47 +00002032void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00002033 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
Ted Kremenek60458782010-11-12 21:34:16 +00002034 WL.push_back(OverloadExprParts(E, Parent));
2035}
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002036void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
2037 UnaryExprOrTypeTraitExpr *E) {
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00002038 EnqueueChildren(E);
2039 if (E->isArgumentType())
2040 AddTypeLoc(E->getArgumentTypeInfo());
2041}
Ted Kremenek28a71942010-11-13 00:36:47 +00002042void EnqueueVisitor::VisitStmt(Stmt *S) {
2043 EnqueueChildren(S);
2044}
2045void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
2046 AddStmt(S->getBody());
2047 AddStmt(S->getCond());
2048 AddDecl(S->getConditionVariable());
2049}
Ted Kremenekfafa75a2010-11-17 00:50:39 +00002050
Ted Kremenek28a71942010-11-13 00:36:47 +00002051void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
2052 AddStmt(W->getBody());
2053 AddStmt(W->getCond());
2054 AddDecl(W->getConditionVariable());
2055}
John Wiegley21ff2e52011-04-28 00:16:57 +00002056
Ted Kremenek2939b6f2010-11-17 00:50:50 +00002057void EnqueueVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
2058 AddTypeLoc(E->getQueriedTypeSourceInfo());
2059}
Francois Pichet6ad6f282010-12-07 00:08:36 +00002060
2061void EnqueueVisitor::VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
Francois Pichet6ad6f282010-12-07 00:08:36 +00002062 AddTypeLoc(E->getRhsTypeSourceInfo());
Francois Pichet0a03a3f2010-12-08 09:11:05 +00002063 AddTypeLoc(E->getLhsTypeSourceInfo());
Francois Pichet6ad6f282010-12-07 00:08:36 +00002064}
2065
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00002066void EnqueueVisitor::VisitTypeTraitExpr(TypeTraitExpr *E) {
2067 for (unsigned I = E->getNumArgs(); I > 0; --I)
2068 AddTypeLoc(E->getArg(I-1));
2069}
2070
John Wiegley21ff2e52011-04-28 00:16:57 +00002071void EnqueueVisitor::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
2072 AddTypeLoc(E->getQueriedTypeSourceInfo());
2073}
2074
John Wiegley55262202011-04-25 06:54:41 +00002075void EnqueueVisitor::VisitExpressionTraitExpr(ExpressionTraitExpr *E) {
2076 EnqueueChildren(E);
2077}
2078
Ted Kremenek28a71942010-11-13 00:36:47 +00002079void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
2080 VisitOverloadExpr(U);
2081 if (!U->isImplicitAccess())
2082 AddStmt(U->getBase());
2083}
Ted Kremenek9d3bf792010-11-17 00:50:43 +00002084void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) {
2085 AddStmt(E->getSubExpr());
2086 AddTypeLoc(E->getWrittenTypeInfo());
2087}
Douglas Gregor94d96292011-01-19 20:34:17 +00002088void EnqueueVisitor::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
2089 WL.push_back(SizeOfPackExprParts(E, Parent));
2090}
John McCall4b9c2d22011-11-06 09:01:30 +00002091void EnqueueVisitor::VisitOpaqueValueExpr(OpaqueValueExpr *E) {
2092 // If the opaque value has a source expression, just transparently
2093 // visit that. This is useful for (e.g.) pseudo-object expressions.
2094 if (Expr *SourceExpr = E->getSourceExpr())
2095 return Visit(SourceExpr);
John McCall4b9c2d22011-11-06 09:01:30 +00002096}
Douglas Gregor011d8b92012-02-15 00:54:55 +00002097void EnqueueVisitor::VisitLambdaExpr(LambdaExpr *E) {
2098 AddStmt(E->getBody());
2099 WL.push_back(LambdaExprParts(E, Parent));
2100}
John McCall4b9c2d22011-11-06 09:01:30 +00002101void EnqueueVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *E) {
2102 // Treat the expression like its syntactic form.
2103 Visit(E->getSyntacticForm());
2104}
Ted Kremenek60458782010-11-12 21:34:16 +00002105
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002106void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002107 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002108}
2109
2110bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2111 if (RegionOfInterest.isValid()) {
2112 SourceRange Range = getRawCursorExtent(C);
2113 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2114 return false;
2115 }
2116 return true;
2117}
2118
2119bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2120 while (!WL.empty()) {
2121 // Dequeue the worklist item.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002122 VisitorJob LI = WL.back();
2123 WL.pop_back();
2124
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002125 // Set the Parent field, then back to its old value once we're done.
2126 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2127
2128 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00002129 case VisitorJob::DeclVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002130 Decl *D = cast<DeclVisit>(&LI)->get();
Ted Kremenekf1107452010-11-12 18:26:56 +00002131 if (!D)
2132 continue;
2133
2134 // For now, perform default visitation for Decls.
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002135 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2136 cast<DeclVisit>(&LI)->isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00002137 return true;
2138
2139 continue;
2140 }
Ted Kremenek60608ec2010-11-17 00:50:47 +00002141 case VisitorJob::ExplicitTemplateArgsVisitKind: {
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00002142 const ASTTemplateArgumentListInfo *ArgList =
Ted Kremenek60608ec2010-11-17 00:50:47 +00002143 cast<ExplicitTemplateArgsVisit>(&LI)->get();
2144 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2145 *ArgEnd = Arg + ArgList->NumTemplateArgs;
2146 Arg != ArgEnd; ++Arg) {
2147 if (VisitTemplateArgumentLoc(*Arg))
2148 return true;
2149 }
2150 continue;
2151 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002152 case VisitorJob::TypeLocVisitKind: {
2153 // Perform default visitation for TypeLocs.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002154 if (Visit(cast<TypeLocVisit>(&LI)->get()))
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002155 return true;
2156 continue;
2157 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002158 case VisitorJob::LabelRefVisitKind: {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002159 LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Ted Kremeneke7455012011-02-23 04:54:51 +00002160 if (LabelStmt *stmt = LS->getStmt()) {
2161 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2162 TU))) {
2163 return true;
2164 }
2165 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002166 continue;
2167 }
Ted Kremenek47695c82011-08-18 22:25:21 +00002168
Douglas Gregorf3db29f2011-02-25 18:19:59 +00002169 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2170 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2171 if (VisitNestedNameSpecifierLoc(V->get()))
2172 return true;
2173 continue;
2174 }
2175
Ted Kremenekf64d8032010-11-18 00:02:32 +00002176 case VisitorJob::DeclarationNameInfoVisitKind: {
2177 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2178 ->get()))
2179 return true;
2180 continue;
2181 }
Ted Kremenekcdba6592010-11-18 00:42:18 +00002182 case VisitorJob::MemberRefVisitKind: {
2183 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2184 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2185 return true;
2186 continue;
2187 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002188 case VisitorJob::StmtVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002189 Stmt *S = cast<StmtVisit>(&LI)->get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00002190 if (!S)
2191 continue;
2192
Ted Kremenekf1107452010-11-12 18:26:56 +00002193 // Update the current cursor.
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002194 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
Ted Kremenekcdba6592010-11-18 00:42:18 +00002195 if (!IsInRegionOfInterest(Cursor))
2196 continue;
2197 switch (Visitor(Cursor, Parent, ClientData)) {
2198 case CXChildVisit_Break: return true;
2199 case CXChildVisit_Continue: break;
2200 case CXChildVisit_Recurse:
2201 EnqueueWorkList(WL, S);
Ted Kremenek82f3c502010-11-15 22:23:26 +00002202 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002203 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00002204 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002205 }
2206 case VisitorJob::MemberExprPartsKind: {
2207 // Handle the other pieces in the MemberExpr besides the base.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002208 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002209
2210 // Visit the nested-name-specifier
Douglas Gregor40d96a62011-02-28 21:54:11 +00002211 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
2212 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002213 return true;
2214
2215 // Visit the declaration name.
2216 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2217 return true;
2218
2219 // Visit the explicitly-specified template arguments, if any.
2220 if (M->hasExplicitTemplateArgs()) {
2221 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2222 *ArgEnd = Arg + M->getNumTemplateArgs();
2223 Arg != ArgEnd; ++Arg) {
2224 if (VisitTemplateArgumentLoc(*Arg))
2225 return true;
2226 }
2227 }
2228 continue;
2229 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002230 case VisitorJob::DeclRefExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002231 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002232 // Visit nested-name-specifier, if present.
Douglas Gregor40d96a62011-02-28 21:54:11 +00002233 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
2234 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002235 return true;
2236 // Visit declaration name.
2237 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2238 return true;
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002239 continue;
2240 }
Ted Kremenek60458782010-11-12 21:34:16 +00002241 case VisitorJob::OverloadExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002242 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Ted Kremenek60458782010-11-12 21:34:16 +00002243 // Visit the nested-name-specifier.
Douglas Gregor4c9be892011-02-28 20:01:57 +00002244 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
2245 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenek60458782010-11-12 21:34:16 +00002246 return true;
2247 // Visit the declaration name.
2248 if (VisitDeclarationNameInfo(O->getNameInfo()))
2249 return true;
2250 // Visit the overloaded declaration reference.
2251 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2252 return true;
Ted Kremenek60458782010-11-12 21:34:16 +00002253 continue;
2254 }
Douglas Gregor94d96292011-01-19 20:34:17 +00002255 case VisitorJob::SizeOfPackExprPartsKind: {
2256 SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
2257 NamedDecl *Pack = E->getPack();
2258 if (isa<TemplateTypeParmDecl>(Pack)) {
2259 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
2260 E->getPackLoc(), TU)))
2261 return true;
2262
2263 continue;
2264 }
2265
2266 if (isa<TemplateTemplateParmDecl>(Pack)) {
2267 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
2268 E->getPackLoc(), TU)))
2269 return true;
2270
2271 continue;
2272 }
2273
2274 // Non-type template parameter packs and function parameter packs are
2275 // treated like DeclRefExpr cursors.
2276 continue;
2277 }
Douglas Gregor011d8b92012-02-15 00:54:55 +00002278
2279 case VisitorJob::LambdaExprPartsKind: {
2280 // Visit captures.
2281 LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
2282 for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
2283 CEnd = E->explicit_capture_end();
2284 C != CEnd; ++C) {
2285 if (C->capturesThis())
2286 continue;
2287
2288 if (Visit(MakeCursorVariableRef(C->getCapturedVar(),
2289 C->getLocation(),
2290 TU)))
2291 return true;
2292 }
2293
2294 // Visit parameters and return type, if present.
2295 if (E->hasExplicitParameters() || E->hasExplicitResultType()) {
2296 TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
2297 if (E->hasExplicitParameters() && E->hasExplicitResultType()) {
2298 // Visit the whole type.
2299 if (Visit(TL))
2300 return true;
2301 } else if (isa<FunctionProtoTypeLoc>(TL)) {
2302 FunctionProtoTypeLoc Proto = cast<FunctionProtoTypeLoc>(TL);
2303 if (E->hasExplicitParameters()) {
2304 // Visit parameters.
2305 for (unsigned I = 0, N = Proto.getNumArgs(); I != N; ++I)
2306 if (Visit(MakeCXCursor(Proto.getArg(I), TU)))
2307 return true;
2308 } else {
2309 // Visit result type.
2310 if (Visit(Proto.getResultLoc()))
2311 return true;
2312 }
2313 }
2314 }
2315 break;
2316 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002317 }
2318 }
2319 return false;
2320}
2321
Ted Kremenekcdba6592010-11-18 00:42:18 +00002322bool CursorVisitor::Visit(Stmt *S) {
Ted Kremenekd1ded662010-11-15 23:31:32 +00002323 VisitorWorkList *WL = 0;
2324 if (!WorkListFreeList.empty()) {
2325 WL = WorkListFreeList.back();
2326 WL->clear();
2327 WorkListFreeList.pop_back();
2328 }
2329 else {
2330 WL = new VisitorWorkList();
2331 WorkListCache.push_back(WL);
2332 }
2333 EnqueueWorkList(*WL, S);
2334 bool result = RunVisitorWorkList(*WL);
2335 WorkListFreeList.push_back(WL);
2336 return result;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002337}
2338
Francois Pichet48a8d142011-07-25 22:00:44 +00002339namespace {
2340typedef llvm::SmallVector<SourceRange, 4> RefNamePieces;
2341RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
2342 const DeclarationNameInfo &NI,
2343 const SourceRange &QLoc,
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00002344 const ASTTemplateArgumentListInfo *TemplateArgs = 0){
Francois Pichet48a8d142011-07-25 22:00:44 +00002345 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
2346 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
2347 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
2348
2349 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
2350
2351 RefNamePieces Pieces;
2352
2353 if (WantQualifier && QLoc.isValid())
2354 Pieces.push_back(QLoc);
2355
2356 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
2357 Pieces.push_back(NI.getLoc());
2358
2359 if (WantTemplateArgs && TemplateArgs)
2360 Pieces.push_back(SourceRange(TemplateArgs->LAngleLoc,
2361 TemplateArgs->RAngleLoc));
2362
2363 if (Kind == DeclarationName::CXXOperatorName) {
2364 Pieces.push_back(SourceLocation::getFromRawEncoding(
2365 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
2366 Pieces.push_back(SourceLocation::getFromRawEncoding(
2367 NI.getInfo().CXXOperatorName.EndOpNameLoc));
2368 }
2369
2370 if (WantSinglePiece) {
2371 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
2372 Pieces.clear();
2373 Pieces.push_back(R);
2374 }
2375
2376 return Pieces;
2377}
2378}
2379
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002380//===----------------------------------------------------------------------===//
2381// Misc. API hooks.
2382//===----------------------------------------------------------------------===//
2383
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002384static llvm::sys::Mutex EnableMultithreadingMutex;
2385static bool EnabledMultithreading;
2386
Argyrios Kyrtzidisfa39f5b2011-12-15 04:52:41 +00002387static void fatal_error_handler(void *user_data, const std::string& reason) {
Argyrios Kyrtzidisfa39f5b2011-12-15 04:52:41 +00002388 // Write the result out to stderr avoiding errs() because raw_ostreams can
2389 // call report_fatal_error.
Argyrios Kyrtzidisdb7a8002011-12-15 06:51:30 +00002390 fprintf(stderr, "LIBCLANG FATAL ERROR: %s\n", reason.c_str());
Argyrios Kyrtzidisfa39f5b2011-12-15 04:52:41 +00002391 ::abort();
2392}
2393
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002394extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002395CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2396 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002397 // Disable pretty stack trace functionality, which will otherwise be a very
2398 // poor citizen of the world and set up all sorts of signal handlers.
2399 llvm::DisablePrettyStackTrace = true;
2400
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002401 // We use crash recovery to make some of our APIs more reliable, implicitly
2402 // enable it.
2403 llvm::CrashRecoveryContext::Enable();
2404
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002405 // Enable support for multithreading in LLVM.
2406 {
2407 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2408 if (!EnabledMultithreading) {
Argyrios Kyrtzidisfa39f5b2011-12-15 04:52:41 +00002409 llvm::install_fatal_error_handler(fatal_error_handler, 0);
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002410 llvm::llvm_start_multithreaded();
2411 EnabledMultithreading = true;
2412 }
2413 }
2414
Douglas Gregora030b7c2010-01-22 20:35:53 +00002415 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002416 if (excludeDeclarationsFromPCH)
2417 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002418 if (displayDiagnostics)
2419 CIdxr->setDisplayDiagnostics();
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002420
2421 if (getenv("LIBCLANG_BGPRIO_INDEX"))
2422 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
2423 CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
2424 if (getenv("LIBCLANG_BGPRIO_EDIT"))
2425 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
2426 CXGlobalOpt_ThreadBackgroundPriorityForEditing);
2427
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002428 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002429}
2430
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002431void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002432 if (CIdx)
2433 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002434}
2435
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002436void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
2437 if (CIdx)
2438 static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
2439}
2440
2441unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
2442 if (CIdx)
2443 return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
2444 return 0;
2445}
2446
Ted Kremenekd2427dd2011-03-18 23:05:39 +00002447void clang_toggleCrashRecovery(unsigned isEnabled) {
2448 if (isEnabled)
2449 llvm::CrashRecoveryContext::Enable();
2450 else
2451 llvm::CrashRecoveryContext::Disable();
2452}
2453
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002454CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002455 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002456 if (!CIdx)
2457 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002458
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002459 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002460 FileSystemOptions FileSystemOpts;
2461 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002462
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00002463 IntrusiveRefCntPtr<DiagnosticsEngine> Diags;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002464 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002465 CXXIdx->getOnlyLocalDecls(),
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00002466 0, 0,
2467 /*CaptureDiagnostics=*/true,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00002468 /*AllowPCHWithCompilerErrors=*/true,
2469 /*UserFilesAreVolatile=*/true);
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002470 return MakeCXTranslationUnit(CXXIdx, TU);
Steve Naroff600866c2009-08-27 19:51:58 +00002471}
2472
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002473unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002474 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregorb5af8432011-08-25 22:54:01 +00002475 CXTranslationUnit_CacheCompletionResults;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002476}
2477
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002478CXTranslationUnit
2479clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2480 const char *source_filename,
2481 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002482 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002483 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002484 struct CXUnsavedFile *unsaved_files) {
Argyrios Kyrtzidise1d43302012-02-25 02:41:16 +00002485 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
Douglas Gregor5a430212010-07-21 18:52:53 +00002486 return clang_parseTranslationUnit(CIdx, source_filename,
2487 command_line_args, num_command_line_args,
2488 unsaved_files, num_unsaved_files,
Douglas Gregordca8ee82011-05-06 16:33:08 +00002489 Options);
Douglas Gregor5a430212010-07-21 18:52:53 +00002490}
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00002491
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002492struct ParseTranslationUnitInfo {
2493 CXIndex CIdx;
2494 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002495 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002496 int num_command_line_args;
2497 struct CXUnsavedFile *unsaved_files;
2498 unsigned num_unsaved_files;
2499 unsigned options;
2500 CXTranslationUnit result;
2501};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002502static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002503 ParseTranslationUnitInfo *PTUI =
2504 static_cast<ParseTranslationUnitInfo*>(UserData);
2505 CXIndex CIdx = PTUI->CIdx;
2506 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002507 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002508 int num_command_line_args = PTUI->num_command_line_args;
2509 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2510 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2511 unsigned options = PTUI->options;
2512 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002513
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002514 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002515 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002516
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002517 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2518
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002519 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
Argyrios Kyrtzidis81b5ac32012-03-28 02:49:54 +00002520 setThreadBackgroundPriority();
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002521
Douglas Gregor44c181a2010-07-23 00:33:23 +00002522 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregor467dc882011-08-25 22:30:56 +00002523 // FIXME: Add a flag for modules.
2524 TranslationUnitKind TUKind
2525 = (options & CXTranslationUnit_Incomplete)? TU_Prefix : TU_Complete;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002526 bool CacheCodeCompetionResults
2527 = options & CXTranslationUnit_CacheCompletionResults;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002528 bool IncludeBriefCommentsInCodeCompletion
2529 = options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
Erik Verbruggen6a91d382012-04-12 10:11:59 +00002530 bool SkipFunctionBodies = options & CXTranslationUnit_SkipFunctionBodies;
2531
Douglas Gregor5352ac02010-01-28 00:27:43 +00002532 // Configure the diagnostics.
2533 DiagnosticOptions DiagOpts;
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00002534 IntrusiveRefCntPtr<DiagnosticsEngine>
Ted Kremenek25a11e12011-03-22 01:15:24 +00002535 Diags(CompilerInstance::createDiagnostics(DiagOpts, num_command_line_args,
2536 command_line_args));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002537
Ted Kremenek25a11e12011-03-22 01:15:24 +00002538 // Recover resources if we crash before exiting this function.
David Blaikied6471f72011-09-25 23:23:43 +00002539 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
2540 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00002541 DiagCleanup(Diags.getPtr());
2542
Dylan Noblesmith1e4c01b2012-02-13 12:32:21 +00002543 OwningPtr<std::vector<ASTUnit::RemappedFile> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00002544 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2545
2546 // Recover resources if we crash before exiting this function.
2547 llvm::CrashRecoveryContextCleanupRegistrar<
2548 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2549
Douglas Gregor4db64a42010-01-23 00:14:00 +00002550 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002551 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002552 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002553 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002554 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2555 Buffer));
Douglas Gregor4db64a42010-01-23 00:14:00 +00002556 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002557
Dylan Noblesmith1e4c01b2012-02-13 12:32:21 +00002558 OwningPtr<std::vector<const char *> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00002559 Args(new std::vector<const char*>());
2560
2561 // Recover resources if we crash before exiting this method.
2562 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
2563 ArgsCleanup(Args.get());
2564
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002565 // Since the Clang C library is primarily used by batch tools dealing with
2566 // (often very broken) source code, where spell-checking can have a
2567 // significant negative impact on performance (particularly when
2568 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002569 // Only do this if we haven't found a spell-checking-related argument.
2570 bool FoundSpellCheckingArgument = false;
2571 for (int I = 0; I != num_command_line_args; ++I) {
2572 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2573 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2574 FoundSpellCheckingArgument = true;
2575 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002576 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002577 }
2578 if (!FoundSpellCheckingArgument)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002579 Args->push_back("-fno-spell-checking");
Douglas Gregorb10daed2010-10-11 16:52:23 +00002580
Ted Kremenek25a11e12011-03-22 01:15:24 +00002581 Args->insert(Args->end(), command_line_args,
2582 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002583
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002584 // The 'source_filename' argument is optional. If the caller does not
2585 // specify it then it is assumed that the source file is specified
2586 // in the actual argument list.
2587 // Put the source file after command_line_args otherwise if '-x' flag is
2588 // present it will be unused.
2589 if (source_filename)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002590 Args->push_back(source_filename);
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002591
Douglas Gregor44c181a2010-07-23 00:33:23 +00002592 // Do we need the detailed preprocessing record?
2593 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Ted Kremenek25a11e12011-03-22 01:15:24 +00002594 Args->push_back("-Xclang");
2595 Args->push_back("-detailed-preprocessing-record");
Douglas Gregor44c181a2010-07-23 00:33:23 +00002596 }
2597
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002598 unsigned NumErrors = Diags->getClient()->getNumErrors();
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00002599 OwningPtr<ASTUnit> ErrUnit;
Dylan Noblesmith1e4c01b2012-02-13 12:32:21 +00002600 OwningPtr<ASTUnit> Unit(
Ted Kremenek4ee99262011-03-22 20:16:19 +00002601 ASTUnit::LoadFromCommandLine(Args->size() ? &(*Args)[0] : 0
2602 /* vector::data() not portable */,
2603 Args->size() ? (&(*Args)[0] + Args->size()) :0,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002604 Diags,
2605 CXXIdx->getClangResourcesPath(),
2606 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002607 /*CaptureDiagnostics=*/true,
Ted Kremenek4ee99262011-03-22 20:16:19 +00002608 RemappedFiles->size() ? &(*RemappedFiles)[0]:0,
Ted Kremenek25a11e12011-03-22 01:15:24 +00002609 RemappedFiles->size(),
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00002610 /*RemappedFilesKeepOriginalName=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002611 PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00002612 TUKind,
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00002613 CacheCodeCompetionResults,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002614 IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00002615 /*AllowPCHWithCompilerErrors=*/true,
Erik Verbruggen6a91d382012-04-12 10:11:59 +00002616 SkipFunctionBodies,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00002617 /*UserFilesAreVolatile=*/true,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00002618 &ErrUnit));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002619
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002620 if (NumErrors != Diags->getClient()->getNumErrors()) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002621 // Make sure to check that 'Unit' is non-NULL.
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00002622 if (CXXIdx->getDisplayDiagnostics())
2623 printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
Douglas Gregora88084b2010-02-18 18:08:43 +00002624 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002625
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002626 PTUI->result = MakeCXTranslationUnit(CXXIdx, Unit.take());
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002627}
2628CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2629 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002630 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002631 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002632 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002633 unsigned num_unsaved_files,
2634 unsigned options) {
2635 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002636 num_command_line_args, unsaved_files,
2637 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002638 llvm::CrashRecoveryContext CRC;
2639
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002640 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002641 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2642 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2643 fprintf(stderr, " 'command_line_args' : [");
2644 for (int i = 0; i != num_command_line_args; ++i) {
2645 if (i)
2646 fprintf(stderr, ", ");
2647 fprintf(stderr, "'%s'", command_line_args[i]);
2648 }
2649 fprintf(stderr, "],\n");
2650 fprintf(stderr, " 'unsaved_files' : [");
2651 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2652 if (i)
2653 fprintf(stderr, ", ");
2654 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2655 unsaved_files[i].Length);
2656 }
2657 fprintf(stderr, "],\n");
2658 fprintf(stderr, " 'options' : %d,\n", options);
2659 fprintf(stderr, "}\n");
2660
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002661 return 0;
Douglas Gregor6df78732011-05-05 20:27:22 +00002662 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
2663 PrintLibclangResourceUsage(PTUI.result);
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002664 }
Douglas Gregor6df78732011-05-05 20:27:22 +00002665
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002666 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002667}
2668
Douglas Gregor19998442010-08-13 15:35:05 +00002669unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2670 return CXSaveTranslationUnit_None;
2671}
Argyrios Kyrtzidis142bcb52012-03-28 02:17:59 +00002672
2673namespace {
2674
2675struct SaveTranslationUnitInfo {
2676 CXTranslationUnit TU;
2677 const char *FileName;
2678 unsigned options;
2679 CXSaveError result;
2680};
2681
2682}
2683
2684static void clang_saveTranslationUnit_Impl(void *UserData) {
2685 SaveTranslationUnitInfo *STUI =
2686 static_cast<SaveTranslationUnitInfo*>(UserData);
2687
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002688 CIndexer *CXXIdx = (CIndexer*)STUI->TU->CIdx;
2689 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
Argyrios Kyrtzidis81b5ac32012-03-28 02:49:54 +00002690 setThreadBackgroundPriority();
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002691
Argyrios Kyrtzidis142bcb52012-03-28 02:17:59 +00002692 STUI->result = static_cast<ASTUnit *>(STUI->TU->TUData)->Save(STUI->FileName);
2693}
2694
Douglas Gregor19998442010-08-13 15:35:05 +00002695int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2696 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002697 if (!TU)
Douglas Gregor39c411f2011-07-06 16:43:36 +00002698 return CXSaveError_InvalidTU;
Argyrios Kyrtzidis142bcb52012-03-28 02:17:59 +00002699
2700 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
2701 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Argyrios Kyrtzidis374a00b2012-06-08 05:48:06 +00002702 if (!CXXUnit->hasSema())
2703 return CXSaveError_InvalidTU;
Argyrios Kyrtzidis142bcb52012-03-28 02:17:59 +00002704
2705 SaveTranslationUnitInfo STUI = { TU, FileName, options, CXSaveError_None };
2706
2707 if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred() ||
2708 getenv("LIBCLANG_NOTHREADS")) {
2709 clang_saveTranslationUnit_Impl(&STUI);
2710
2711 if (getenv("LIBCLANG_RESOURCE_USAGE"))
2712 PrintLibclangResourceUsage(TU);
2713
2714 return STUI.result;
2715 }
2716
2717 // We have an AST that has invalid nodes due to compiler errors.
2718 // Use a crash recovery thread for protection.
2719
2720 llvm::CrashRecoveryContext CRC;
2721
2722 if (!RunSafely(CRC, clang_saveTranslationUnit_Impl, &STUI)) {
2723 fprintf(stderr, "libclang: crash detected during AST saving: {\n");
2724 fprintf(stderr, " 'filename' : '%s'\n", FileName);
2725 fprintf(stderr, " 'options' : %d,\n", options);
2726 fprintf(stderr, "}\n");
2727
2728 return CXSaveError_Unknown;
2729
2730 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
Douglas Gregor6df78732011-05-05 20:27:22 +00002731 PrintLibclangResourceUsage(TU);
Argyrios Kyrtzidis142bcb52012-03-28 02:17:59 +00002732 }
2733
2734 return STUI.result;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002735}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002736
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002737void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002738 if (CTUnit) {
2739 // If the translation unit has been marked as unsafe to free, just discard
2740 // it.
Ted Kremeneka60ed472010-11-16 08:15:36 +00002741 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002742 return;
2743
Ted Kremeneka60ed472010-11-16 08:15:36 +00002744 delete static_cast<ASTUnit *>(CTUnit->TUData);
2745 disposeCXStringPool(CTUnit->StringPool);
Ted Kremenek15322172011-11-10 08:43:12 +00002746 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
Ted Kremenekbbf66ca2012-04-30 19:06:49 +00002747 disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002748 delete CTUnit;
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002749 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002750}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002751
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002752unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2753 return CXReparse_None;
2754}
2755
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002756struct ReparseTranslationUnitInfo {
2757 CXTranslationUnit TU;
2758 unsigned num_unsaved_files;
2759 struct CXUnsavedFile *unsaved_files;
2760 unsigned options;
2761 int result;
2762};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002763
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002764static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002765 ReparseTranslationUnitInfo *RTUI =
2766 static_cast<ReparseTranslationUnitInfo*>(UserData);
2767 CXTranslationUnit TU = RTUI->TU;
Ted Kremenek15322172011-11-10 08:43:12 +00002768
2769 // Reset the associated diagnostics.
2770 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
2771 TU->Diagnostics = 0;
2772
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002773 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2774 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2775 unsigned options = RTUI->options;
2776 (void) options;
2777 RTUI->result = 1;
2778
Douglas Gregorabc563f2010-07-19 21:46:24 +00002779 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002780 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002781
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002782 CIndexer *CXXIdx = (CIndexer*)TU->CIdx;
2783 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
Argyrios Kyrtzidis81b5ac32012-03-28 02:49:54 +00002784 setThreadBackgroundPriority();
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002785
Ted Kremeneka60ed472010-11-16 08:15:36 +00002786 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor593b0c12010-09-23 18:47:53 +00002787 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002788
Dylan Noblesmith1e4c01b2012-02-13 12:32:21 +00002789 OwningPtr<std::vector<ASTUnit::RemappedFile> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00002790 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2791
2792 // Recover resources if we crash before exiting this function.
2793 llvm::CrashRecoveryContextCleanupRegistrar<
2794 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2795
Douglas Gregorabc563f2010-07-19 21:46:24 +00002796 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002797 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002798 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002799 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002800 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2801 Buffer));
Douglas Gregorabc563f2010-07-19 21:46:24 +00002802 }
2803
Ted Kremenek4ee99262011-03-22 20:16:19 +00002804 if (!CXXUnit->Reparse(RemappedFiles->size() ? &(*RemappedFiles)[0] : 0,
2805 RemappedFiles->size()))
Douglas Gregor593b0c12010-09-23 18:47:53 +00002806 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002807}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002808
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002809int clang_reparseTranslationUnit(CXTranslationUnit TU,
2810 unsigned num_unsaved_files,
2811 struct CXUnsavedFile *unsaved_files,
2812 unsigned options) {
2813 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2814 options, 0 };
Argyrios Kyrtzidis8c4b47e2011-10-28 22:54:33 +00002815
Argyrios Kyrtzidise7de9b42011-10-29 19:32:39 +00002816 if (getenv("LIBCLANG_NOTHREADS")) {
Argyrios Kyrtzidis8c4b47e2011-10-28 22:54:33 +00002817 clang_reparseTranslationUnit_Impl(&RTUI);
2818 return RTUI.result;
2819 }
2820
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002821 llvm::CrashRecoveryContext CRC;
2822
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002823 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002824 fprintf(stderr, "libclang: crash detected during reparsing\n");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002825 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002826 return 1;
Douglas Gregor6df78732011-05-05 20:27:22 +00002827 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
2828 PrintLibclangResourceUsage(TU);
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002829
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002830 return RTUI.result;
2831}
2832
Douglas Gregordf95a132010-08-09 20:45:32 +00002833
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002834CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002835 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002836 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002837
Ted Kremeneka60ed472010-11-16 08:15:36 +00002838 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002839 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002840}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002841
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002842CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregor8e5900c2012-04-30 23:41:16 +00002843 ASTUnit *CXXUnit = static_cast<ASTUnit*>(TU->TUData);
2844 return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002845}
2846
Ted Kremenekfb480492010-01-13 21:46:36 +00002847} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002848
Ted Kremenekfb480492010-01-13 21:46:36 +00002849//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002850// CXFile Operations.
2851//===----------------------------------------------------------------------===//
2852
2853extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002854CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002855 if (!SFile)
Ted Kremeneka60ed472010-11-16 08:15:36 +00002856 return createCXString((const char*)NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002857
Steve Naroff88145032009-10-27 14:35:18 +00002858 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002859 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002860}
2861
2862time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002863 if (!SFile)
2864 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002865
Steve Naroff88145032009-10-27 14:35:18 +00002866 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2867 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002868}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002869
Douglas Gregorb9790342010-01-22 21:44:22 +00002870CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2871 if (!tu)
2872 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002873
Ted Kremeneka60ed472010-11-16 08:15:36 +00002874 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002875
Douglas Gregorb9790342010-01-22 21:44:22 +00002876 FileManager &FMgr = CXXUnit->getFileManager();
Chris Lattner39b49bc2010-11-23 08:35:12 +00002877 return const_cast<FileEntry *>(FMgr.getFile(file_name));
Douglas Gregorb9790342010-01-22 21:44:22 +00002878}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002879
Douglas Gregordd3e5542011-05-04 00:14:37 +00002880unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit tu, CXFile file) {
2881 if (!tu || !file)
2882 return 0;
2883
2884 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
2885 FileEntry *FEnt = static_cast<FileEntry *>(file);
2886 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
2887 .isFileMultipleIncludeGuarded(FEnt);
2888}
2889
Ted Kremenekfb480492010-01-13 21:46:36 +00002890} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002891
Ted Kremenekfb480492010-01-13 21:46:36 +00002892//===----------------------------------------------------------------------===//
2893// CXCursor Operations.
2894//===----------------------------------------------------------------------===//
2895
Ted Kremenekfb480492010-01-13 21:46:36 +00002896static Decl *getDeclFromExpr(Stmt *E) {
Argyrios Kyrtzidisc2954612011-09-12 22:17:26 +00002897 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Douglas Gregordb1314e2010-10-01 21:11:22 +00002898 return getDeclFromExpr(CE->getSubExpr());
2899
Ted Kremenekfb480492010-01-13 21:46:36 +00002900 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2901 return RefExpr->getDecl();
2902 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2903 return ME->getMemberDecl();
2904 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2905 return RE->getDecl();
Argyrios Kyrtzidisb085d892012-03-30 00:19:18 +00002906 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
2907 if (PRE->isExplicitProperty())
2908 return PRE->getExplicitProperty();
2909 // It could be messaging both getter and setter as in:
2910 // ++myobj.myprop;
2911 // in which case prefer to associate the setter since it is less obvious
2912 // from inspecting the source that the setter is going to get called.
2913 if (PRE->isMessagingSetter())
2914 return PRE->getImplicitPropertySetter();
2915 return PRE->getImplicitPropertyGetter();
2916 }
John McCall4b9c2d22011-11-06 09:01:30 +00002917 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
2918 return getDeclFromExpr(POE->getSyntacticForm());
2919 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
2920 if (Expr *Src = OVE->getSourceExpr())
2921 return getDeclFromExpr(Src);
Douglas Gregordb1314e2010-10-01 21:11:22 +00002922
Ted Kremenekfb480492010-01-13 21:46:36 +00002923 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2924 return getDeclFromExpr(CE->getCallee());
Chris Lattner5f9e2722011-07-23 10:55:15 +00002925 if (CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Douglas Gregor93798e22010-11-05 21:11:19 +00002926 if (!CE->isElidable())
2927 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002928 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2929 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002930
Douglas Gregordb1314e2010-10-01 21:11:22 +00002931 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2932 return PE->getProtocol();
Douglas Gregorc7793c72011-01-15 01:15:58 +00002933 if (SubstNonTypeTemplateParmPackExpr *NTTP
2934 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
2935 return NTTP->getParameterPack();
Douglas Gregor94d96292011-01-19 20:34:17 +00002936 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2937 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
2938 isa<ParmVarDecl>(SizeOfPack->getPack()))
2939 return SizeOfPack->getPack();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002940
Ted Kremenekfb480492010-01-13 21:46:36 +00002941 return 0;
2942}
2943
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002944static SourceLocation getLocationFromExpr(Expr *E) {
Argyrios Kyrtzidisc2954612011-09-12 22:17:26 +00002945 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
2946 return getLocationFromExpr(CE->getSubExpr());
2947
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002948 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2949 return /*FIXME:*/Msg->getLeftLoc();
2950 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2951 return DRE->getLocation();
2952 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2953 return Member->getMemberLoc();
2954 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2955 return Ivar->getLocation();
Douglas Gregor94d96292011-01-19 20:34:17 +00002956 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2957 return SizeOfPack->getPackLoc();
Argyrios Kyrtzidisd0469522012-03-30 00:19:13 +00002958 if (ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
2959 return PropRef->getLocation();
Douglas Gregor94d96292011-01-19 20:34:17 +00002960
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002961 return E->getLocStart();
2962}
2963
Ted Kremenekfb480492010-01-13 21:46:36 +00002964extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002965
2966unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002967 CXCursorVisitor visitor,
2968 CXClientData client_data) {
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00002969 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
2970 /*VisitPreprocessorLast=*/false);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002971 return CursorVis.VisitChildren(parent);
2972}
2973
David Chisnall3387c652010-11-03 14:12:26 +00002974#ifndef __has_feature
2975#define __has_feature(x) 0
2976#endif
2977#if __has_feature(blocks)
2978typedef enum CXChildVisitResult
2979 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2980
2981static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2982 CXClientData client_data) {
2983 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2984 return block(cursor, parent);
2985}
2986#else
2987// If we are compiled with a compiler that doesn't have native blocks support,
2988// define and call the block manually, so the
2989typedef struct _CXChildVisitResult
2990{
2991 void *isa;
2992 int flags;
2993 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002994 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2995 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00002996} *CXCursorVisitorBlock;
2997
2998static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2999 CXClientData client_data) {
3000 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
3001 return block->invoke(block, cursor, parent);
3002}
3003#endif
3004
3005
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003006unsigned clang_visitChildrenWithBlock(CXCursor parent,
3007 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00003008 return clang_visitChildren(parent, visitWithBlock, block);
3009}
3010
Douglas Gregor78205d42010-01-20 21:45:58 +00003011static CXString getDeclSpelling(Decl *D) {
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00003012 if (!D)
3013 return createCXString("");
3014
3015 NamedDecl *ND = dyn_cast<NamedDecl>(D);
Douglas Gregore3c60a72010-11-17 00:13:31 +00003016 if (!ND) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003017 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00003018 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3019 return createCXString(Property->getIdentifier()->getName());
3020
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003021 return createCXString("");
Douglas Gregore3c60a72010-11-17 00:13:31 +00003022 }
3023
Douglas Gregor78205d42010-01-20 21:45:58 +00003024 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003025 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003026
Douglas Gregor78205d42010-01-20 21:45:58 +00003027 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
3028 // No, this isn't the same as the code below. getIdentifier() is non-virtual
3029 // and returns different names. NamedDecl returns the class name and
3030 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003031 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003032
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003033 if (isa<UsingDirectiveDecl>(D))
3034 return createCXString("");
3035
Dylan Noblesmith36d59272012-02-13 12:32:26 +00003036 SmallString<1024> S;
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00003037 llvm::raw_svector_ostream os(S);
3038 ND->printName(os);
3039
3040 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00003041}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003042
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003043CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003044 if (clang_isTranslationUnit(C.kind))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003045 return clang_getTranslationUnitSpelling(
3046 static_cast<CXTranslationUnit>(C.data[2]));
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003047
Steve Narofff334b4e2009-09-02 18:26:48 +00003048 if (clang_isReference(C.kind)) {
3049 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00003050 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00003051 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003052 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003053 }
3054 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00003055 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003056 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003057 }
3058 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00003059 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00003060 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003061 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003062 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00003063 case CXCursor_CXXBaseSpecifier: {
3064 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
3065 return createCXString(B->getType().getAsString());
3066 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003067 case CXCursor_TypeRef: {
3068 TypeDecl *Type = getCursorTypeRef(C).first;
3069 assert(Type && "Missing type decl");
3070
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003071 return createCXString(getCursorContext(C).getTypeDeclType(Type).
3072 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003073 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003074 case CXCursor_TemplateRef: {
3075 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00003076 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003077
3078 return createCXString(Template->getNameAsString());
3079 }
Douglas Gregor69319002010-08-31 23:48:11 +00003080
3081 case CXCursor_NamespaceRef: {
3082 NamedDecl *NS = getCursorNamespaceRef(C).first;
3083 assert(NS && "Missing namespace decl");
3084
3085 return createCXString(NS->getNameAsString());
3086 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003087
Douglas Gregora67e03f2010-09-09 21:42:20 +00003088 case CXCursor_MemberRef: {
3089 FieldDecl *Field = getCursorMemberRef(C).first;
3090 assert(Field && "Missing member decl");
3091
3092 return createCXString(Field->getNameAsString());
3093 }
3094
Douglas Gregor36897b02010-09-10 00:22:18 +00003095 case CXCursor_LabelRef: {
3096 LabelStmt *Label = getCursorLabelRef(C).first;
3097 assert(Label && "Missing label");
3098
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003099 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00003100 }
3101
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003102 case CXCursor_OverloadedDeclRef: {
3103 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3104 if (Decl *D = Storage.dyn_cast<Decl *>()) {
3105 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
3106 return createCXString(ND->getNameAsString());
3107 return createCXString("");
3108 }
3109 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3110 return createCXString(E->getName().getAsString());
3111 OverloadedTemplateStorage *Ovl
3112 = Storage.get<OverloadedTemplateStorage*>();
3113 if (Ovl->size() == 0)
3114 return createCXString("");
3115 return createCXString((*Ovl->begin())->getNameAsString());
3116 }
3117
Douglas Gregor011d8b92012-02-15 00:54:55 +00003118 case CXCursor_VariableRef: {
3119 VarDecl *Var = getCursorVariableRef(C).first;
3120 assert(Var && "Missing variable decl");
3121
3122 return createCXString(Var->getNameAsString());
3123 }
3124
Daniel Dunbaracca7252009-11-30 20:42:49 +00003125 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003126 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00003127 }
3128 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003129
3130 if (clang_isExpression(C.kind)) {
3131 Decl *D = getDeclFromExpr(getCursorExpr(C));
3132 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00003133 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003134 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00003135 }
3136
Douglas Gregor36897b02010-09-10 00:22:18 +00003137 if (clang_isStatement(C.kind)) {
3138 Stmt *S = getCursorStmt(C);
3139 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003140 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00003141
3142 return createCXString("");
3143 }
3144
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003145 if (C.kind == CXCursor_MacroExpansion)
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003146 return createCXString(getCursorMacroExpansion(C)->getName()
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003147 ->getNameStart());
3148
Douglas Gregor572feb22010-03-18 18:04:21 +00003149 if (C.kind == CXCursor_MacroDefinition)
3150 return createCXString(getCursorMacroDefinition(C)->getName()
3151 ->getNameStart());
3152
Douglas Gregorecdcb882010-10-20 22:00:55 +00003153 if (C.kind == CXCursor_InclusionDirective)
3154 return createCXString(getCursorInclusionDirective(C)->getFileName());
3155
Douglas Gregor60cbfac2010-01-25 16:56:17 +00003156 if (clang_isDeclaration(C.kind))
3157 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00003158
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00003159 if (C.kind == CXCursor_AnnotateAttr) {
3160 AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
3161 return createCXString(AA->getAnnotation());
3162 }
3163
Argyrios Kyrtzidis84b79642011-12-06 22:05:01 +00003164 if (C.kind == CXCursor_AsmLabelAttr) {
3165 AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
3166 return createCXString(AA->getLabel());
3167 }
3168
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003169 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00003170}
3171
Argyrios Kyrtzidisba1da142012-03-30 20:58:35 +00003172CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C,
3173 unsigned pieceIndex,
3174 unsigned options) {
3175 if (clang_Cursor_isNull(C))
3176 return clang_getNullRange();
3177
3178 ASTContext &Ctx = getCursorContext(C);
3179
3180 if (clang_isStatement(C.kind)) {
3181 Stmt *S = getCursorStmt(C);
3182 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
3183 if (pieceIndex > 0)
3184 return clang_getNullRange();
3185 return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
3186 }
3187
3188 return clang_getNullRange();
3189 }
3190
3191 if (C.kind == CXCursor_ObjCMessageExpr) {
3192 if (ObjCMessageExpr *
3193 ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
3194 if (pieceIndex >= ME->getNumSelectorLocs())
3195 return clang_getNullRange();
3196 return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
3197 }
3198 }
3199
3200 if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
3201 C.kind == CXCursor_ObjCClassMethodDecl) {
3202 if (ObjCMethodDecl *
3203 MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
3204 if (pieceIndex >= MD->getNumSelectorLocs())
3205 return clang_getNullRange();
3206 return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
3207 }
3208 }
3209
Argyrios Kyrtzidis9482a182012-04-16 20:01:28 +00003210 if (C.kind == CXCursor_ObjCCategoryDecl ||
3211 C.kind == CXCursor_ObjCCategoryImplDecl) {
3212 if (pieceIndex > 0)
3213 return clang_getNullRange();
3214 if (ObjCCategoryDecl *
3215 CD = dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
3216 return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
3217 if (ObjCCategoryImplDecl *
3218 CID = dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
3219 return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
3220 }
3221
Argyrios Kyrtzidisba1da142012-03-30 20:58:35 +00003222 // FIXME: A CXCursor_InclusionDirective should give the location of the
3223 // filename, but we don't keep track of this.
3224
3225 // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
3226 // but we don't keep track of this.
3227
3228 // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
3229 // but we don't keep track of this.
3230
3231 // Default handling, give the location of the cursor.
3232
3233 if (pieceIndex > 0)
3234 return clang_getNullRange();
3235
3236 CXSourceLocation CXLoc = clang_getCursorLocation(C);
3237 SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
3238 return cxloc::translateSourceRange(Ctx, Loc);
3239}
3240
Douglas Gregor358559d2010-10-02 22:49:11 +00003241CXString clang_getCursorDisplayName(CXCursor C) {
3242 if (!clang_isDeclaration(C.kind))
3243 return clang_getCursorSpelling(C);
3244
3245 Decl *D = getCursorDecl(C);
3246 if (!D)
3247 return createCXString("");
3248
Douglas Gregor30c42402011-09-27 22:38:19 +00003249 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
Douglas Gregor358559d2010-10-02 22:49:11 +00003250 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
3251 D = FunTmpl->getTemplatedDecl();
3252
3253 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Dylan Noblesmith36d59272012-02-13 12:32:26 +00003254 SmallString<64> Str;
Douglas Gregor358559d2010-10-02 22:49:11 +00003255 llvm::raw_svector_ostream OS(Str);
Benjamin Kramera59d20b2012-02-07 11:57:57 +00003256 OS << *Function;
Douglas Gregor358559d2010-10-02 22:49:11 +00003257 if (Function->getPrimaryTemplate())
3258 OS << "<>";
3259 OS << "(";
3260 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
3261 if (I)
3262 OS << ", ";
3263 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
3264 }
3265
3266 if (Function->isVariadic()) {
3267 if (Function->getNumParams())
3268 OS << ", ";
3269 OS << "...";
3270 }
3271 OS << ")";
3272 return createCXString(OS.str());
3273 }
3274
3275 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
Dylan Noblesmith36d59272012-02-13 12:32:26 +00003276 SmallString<64> Str;
Douglas Gregor358559d2010-10-02 22:49:11 +00003277 llvm::raw_svector_ostream OS(Str);
Benjamin Kramera59d20b2012-02-07 11:57:57 +00003278 OS << *ClassTemplate;
Douglas Gregor358559d2010-10-02 22:49:11 +00003279 OS << "<";
3280 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
3281 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3282 if (I)
3283 OS << ", ";
3284
3285 NamedDecl *Param = Params->getParam(I);
3286 if (Param->getIdentifier()) {
3287 OS << Param->getIdentifier()->getName();
3288 continue;
3289 }
3290
3291 // There is no parameter name, which makes this tricky. Try to come up
3292 // with something useful that isn't too long.
3293 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3294 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
3295 else if (NonTypeTemplateParmDecl *NTTP
3296 = dyn_cast<NonTypeTemplateParmDecl>(Param))
3297 OS << NTTP->getType().getAsString(Policy);
3298 else
3299 OS << "template<...> class";
3300 }
3301
3302 OS << ">";
3303 return createCXString(OS.str());
3304 }
3305
3306 if (ClassTemplateSpecializationDecl *ClassSpec
3307 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
3308 // If the type was explicitly written, use that.
3309 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
3310 return createCXString(TSInfo->getType().getAsString(Policy));
3311
Dylan Noblesmith36d59272012-02-13 12:32:26 +00003312 SmallString<64> Str;
Douglas Gregor358559d2010-10-02 22:49:11 +00003313 llvm::raw_svector_ostream OS(Str);
Benjamin Kramera59d20b2012-02-07 11:57:57 +00003314 OS << *ClassSpec;
Douglas Gregor358559d2010-10-02 22:49:11 +00003315 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00003316 ClassSpec->getTemplateArgs().data(),
3317 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00003318 Policy);
3319 return createCXString(OS.str());
3320 }
3321
3322 return clang_getCursorSpelling(C);
3323}
3324
Ted Kremeneke68fff62010-02-17 00:41:32 +00003325CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00003326 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00003327 case CXCursor_FunctionDecl:
3328 return createCXString("FunctionDecl");
3329 case CXCursor_TypedefDecl:
3330 return createCXString("TypedefDecl");
3331 case CXCursor_EnumDecl:
3332 return createCXString("EnumDecl");
3333 case CXCursor_EnumConstantDecl:
3334 return createCXString("EnumConstantDecl");
3335 case CXCursor_StructDecl:
3336 return createCXString("StructDecl");
3337 case CXCursor_UnionDecl:
3338 return createCXString("UnionDecl");
3339 case CXCursor_ClassDecl:
3340 return createCXString("ClassDecl");
3341 case CXCursor_FieldDecl:
3342 return createCXString("FieldDecl");
3343 case CXCursor_VarDecl:
3344 return createCXString("VarDecl");
3345 case CXCursor_ParmDecl:
3346 return createCXString("ParmDecl");
3347 case CXCursor_ObjCInterfaceDecl:
3348 return createCXString("ObjCInterfaceDecl");
3349 case CXCursor_ObjCCategoryDecl:
3350 return createCXString("ObjCCategoryDecl");
3351 case CXCursor_ObjCProtocolDecl:
3352 return createCXString("ObjCProtocolDecl");
3353 case CXCursor_ObjCPropertyDecl:
3354 return createCXString("ObjCPropertyDecl");
3355 case CXCursor_ObjCIvarDecl:
3356 return createCXString("ObjCIvarDecl");
3357 case CXCursor_ObjCInstanceMethodDecl:
3358 return createCXString("ObjCInstanceMethodDecl");
3359 case CXCursor_ObjCClassMethodDecl:
3360 return createCXString("ObjCClassMethodDecl");
3361 case CXCursor_ObjCImplementationDecl:
3362 return createCXString("ObjCImplementationDecl");
3363 case CXCursor_ObjCCategoryImplDecl:
3364 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00003365 case CXCursor_CXXMethod:
3366 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003367 case CXCursor_UnexposedDecl:
3368 return createCXString("UnexposedDecl");
3369 case CXCursor_ObjCSuperClassRef:
3370 return createCXString("ObjCSuperClassRef");
3371 case CXCursor_ObjCProtocolRef:
3372 return createCXString("ObjCProtocolRef");
3373 case CXCursor_ObjCClassRef:
3374 return createCXString("ObjCClassRef");
3375 case CXCursor_TypeRef:
3376 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003377 case CXCursor_TemplateRef:
3378 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00003379 case CXCursor_NamespaceRef:
3380 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00003381 case CXCursor_MemberRef:
3382 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00003383 case CXCursor_LabelRef:
3384 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003385 case CXCursor_OverloadedDeclRef:
3386 return createCXString("OverloadedDeclRef");
Douglas Gregor011d8b92012-02-15 00:54:55 +00003387 case CXCursor_VariableRef:
3388 return createCXString("VariableRef");
Douglas Gregor42b29842011-10-05 19:00:14 +00003389 case CXCursor_IntegerLiteral:
3390 return createCXString("IntegerLiteral");
3391 case CXCursor_FloatingLiteral:
3392 return createCXString("FloatingLiteral");
3393 case CXCursor_ImaginaryLiteral:
3394 return createCXString("ImaginaryLiteral");
3395 case CXCursor_StringLiteral:
3396 return createCXString("StringLiteral");
3397 case CXCursor_CharacterLiteral:
3398 return createCXString("CharacterLiteral");
3399 case CXCursor_ParenExpr:
3400 return createCXString("ParenExpr");
3401 case CXCursor_UnaryOperator:
3402 return createCXString("UnaryOperator");
3403 case CXCursor_ArraySubscriptExpr:
3404 return createCXString("ArraySubscriptExpr");
3405 case CXCursor_BinaryOperator:
3406 return createCXString("BinaryOperator");
3407 case CXCursor_CompoundAssignOperator:
3408 return createCXString("CompoundAssignOperator");
3409 case CXCursor_ConditionalOperator:
3410 return createCXString("ConditionalOperator");
3411 case CXCursor_CStyleCastExpr:
3412 return createCXString("CStyleCastExpr");
3413 case CXCursor_CompoundLiteralExpr:
3414 return createCXString("CompoundLiteralExpr");
3415 case CXCursor_InitListExpr:
3416 return createCXString("InitListExpr");
3417 case CXCursor_AddrLabelExpr:
3418 return createCXString("AddrLabelExpr");
3419 case CXCursor_StmtExpr:
3420 return createCXString("StmtExpr");
3421 case CXCursor_GenericSelectionExpr:
3422 return createCXString("GenericSelectionExpr");
3423 case CXCursor_GNUNullExpr:
3424 return createCXString("GNUNullExpr");
3425 case CXCursor_CXXStaticCastExpr:
3426 return createCXString("CXXStaticCastExpr");
3427 case CXCursor_CXXDynamicCastExpr:
3428 return createCXString("CXXDynamicCastExpr");
3429 case CXCursor_CXXReinterpretCastExpr:
3430 return createCXString("CXXReinterpretCastExpr");
3431 case CXCursor_CXXConstCastExpr:
3432 return createCXString("CXXConstCastExpr");
3433 case CXCursor_CXXFunctionalCastExpr:
3434 return createCXString("CXXFunctionalCastExpr");
3435 case CXCursor_CXXTypeidExpr:
3436 return createCXString("CXXTypeidExpr");
3437 case CXCursor_CXXBoolLiteralExpr:
3438 return createCXString("CXXBoolLiteralExpr");
3439 case CXCursor_CXXNullPtrLiteralExpr:
3440 return createCXString("CXXNullPtrLiteralExpr");
3441 case CXCursor_CXXThisExpr:
3442 return createCXString("CXXThisExpr");
3443 case CXCursor_CXXThrowExpr:
3444 return createCXString("CXXThrowExpr");
3445 case CXCursor_CXXNewExpr:
3446 return createCXString("CXXNewExpr");
3447 case CXCursor_CXXDeleteExpr:
3448 return createCXString("CXXDeleteExpr");
3449 case CXCursor_UnaryExpr:
3450 return createCXString("UnaryExpr");
3451 case CXCursor_ObjCStringLiteral:
3452 return createCXString("ObjCStringLiteral");
Ted Kremenekb3f75422012-03-06 20:06:06 +00003453 case CXCursor_ObjCBoolLiteralExpr:
3454 return createCXString("ObjCBoolLiteralExpr");
Douglas Gregor42b29842011-10-05 19:00:14 +00003455 case CXCursor_ObjCEncodeExpr:
3456 return createCXString("ObjCEncodeExpr");
3457 case CXCursor_ObjCSelectorExpr:
3458 return createCXString("ObjCSelectorExpr");
3459 case CXCursor_ObjCProtocolExpr:
3460 return createCXString("ObjCProtocolExpr");
3461 case CXCursor_ObjCBridgedCastExpr:
3462 return createCXString("ObjCBridgedCastExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00003463 case CXCursor_BlockExpr:
3464 return createCXString("BlockExpr");
Douglas Gregor42b29842011-10-05 19:00:14 +00003465 case CXCursor_PackExpansionExpr:
3466 return createCXString("PackExpansionExpr");
3467 case CXCursor_SizeOfPackExpr:
3468 return createCXString("SizeOfPackExpr");
Douglas Gregor011d8b92012-02-15 00:54:55 +00003469 case CXCursor_LambdaExpr:
3470 return createCXString("LambdaExpr");
Douglas Gregor42b29842011-10-05 19:00:14 +00003471 case CXCursor_UnexposedExpr:
3472 return createCXString("UnexposedExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003473 case CXCursor_DeclRefExpr:
3474 return createCXString("DeclRefExpr");
3475 case CXCursor_MemberRefExpr:
3476 return createCXString("MemberRefExpr");
3477 case CXCursor_CallExpr:
3478 return createCXString("CallExpr");
3479 case CXCursor_ObjCMessageExpr:
3480 return createCXString("ObjCMessageExpr");
3481 case CXCursor_UnexposedStmt:
3482 return createCXString("UnexposedStmt");
Douglas Gregor42b29842011-10-05 19:00:14 +00003483 case CXCursor_DeclStmt:
3484 return createCXString("DeclStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00003485 case CXCursor_LabelStmt:
3486 return createCXString("LabelStmt");
Douglas Gregor42b29842011-10-05 19:00:14 +00003487 case CXCursor_CompoundStmt:
3488 return createCXString("CompoundStmt");
3489 case CXCursor_CaseStmt:
3490 return createCXString("CaseStmt");
3491 case CXCursor_DefaultStmt:
3492 return createCXString("DefaultStmt");
3493 case CXCursor_IfStmt:
3494 return createCXString("IfStmt");
3495 case CXCursor_SwitchStmt:
3496 return createCXString("SwitchStmt");
3497 case CXCursor_WhileStmt:
3498 return createCXString("WhileStmt");
3499 case CXCursor_DoStmt:
3500 return createCXString("DoStmt");
3501 case CXCursor_ForStmt:
3502 return createCXString("ForStmt");
3503 case CXCursor_GotoStmt:
3504 return createCXString("GotoStmt");
3505 case CXCursor_IndirectGotoStmt:
3506 return createCXString("IndirectGotoStmt");
3507 case CXCursor_ContinueStmt:
3508 return createCXString("ContinueStmt");
3509 case CXCursor_BreakStmt:
3510 return createCXString("BreakStmt");
3511 case CXCursor_ReturnStmt:
3512 return createCXString("ReturnStmt");
3513 case CXCursor_AsmStmt:
3514 return createCXString("AsmStmt");
Chad Rosier8cd64b42012-06-11 20:47:18 +00003515 case CXCursor_MSAsmStmt:
3516 return createCXString("MSAsmStmt");
Douglas Gregor42b29842011-10-05 19:00:14 +00003517 case CXCursor_ObjCAtTryStmt:
3518 return createCXString("ObjCAtTryStmt");
3519 case CXCursor_ObjCAtCatchStmt:
3520 return createCXString("ObjCAtCatchStmt");
3521 case CXCursor_ObjCAtFinallyStmt:
3522 return createCXString("ObjCAtFinallyStmt");
3523 case CXCursor_ObjCAtThrowStmt:
3524 return createCXString("ObjCAtThrowStmt");
3525 case CXCursor_ObjCAtSynchronizedStmt:
3526 return createCXString("ObjCAtSynchronizedStmt");
3527 case CXCursor_ObjCAutoreleasePoolStmt:
3528 return createCXString("ObjCAutoreleasePoolStmt");
3529 case CXCursor_ObjCForCollectionStmt:
3530 return createCXString("ObjCForCollectionStmt");
3531 case CXCursor_CXXCatchStmt:
3532 return createCXString("CXXCatchStmt");
3533 case CXCursor_CXXTryStmt:
3534 return createCXString("CXXTryStmt");
3535 case CXCursor_CXXForRangeStmt:
3536 return createCXString("CXXForRangeStmt");
3537 case CXCursor_SEHTryStmt:
3538 return createCXString("SEHTryStmt");
3539 case CXCursor_SEHExceptStmt:
3540 return createCXString("SEHExceptStmt");
3541 case CXCursor_SEHFinallyStmt:
3542 return createCXString("SEHFinallyStmt");
3543 case CXCursor_NullStmt:
3544 return createCXString("NullStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003545 case CXCursor_InvalidFile:
3546 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00003547 case CXCursor_InvalidCode:
3548 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003549 case CXCursor_NoDeclFound:
3550 return createCXString("NoDeclFound");
3551 case CXCursor_NotImplemented:
3552 return createCXString("NotImplemented");
3553 case CXCursor_TranslationUnit:
3554 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00003555 case CXCursor_UnexposedAttr:
3556 return createCXString("UnexposedAttr");
3557 case CXCursor_IBActionAttr:
3558 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003559 case CXCursor_IBOutletAttr:
3560 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003561 case CXCursor_IBOutletCollectionAttr:
3562 return createCXString("attribute(iboutletcollection)");
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00003563 case CXCursor_CXXFinalAttr:
3564 return createCXString("attribute(final)");
3565 case CXCursor_CXXOverrideAttr:
3566 return createCXString("attribute(override)");
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00003567 case CXCursor_AnnotateAttr:
3568 return createCXString("attribute(annotate)");
Argyrios Kyrtzidis84b79642011-12-06 22:05:01 +00003569 case CXCursor_AsmLabelAttr:
3570 return createCXString("asm label");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003571 case CXCursor_PreprocessingDirective:
3572 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003573 case CXCursor_MacroDefinition:
3574 return createCXString("macro definition");
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003575 case CXCursor_MacroExpansion:
3576 return createCXString("macro expansion");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003577 case CXCursor_InclusionDirective:
3578 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003579 case CXCursor_Namespace:
3580 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003581 case CXCursor_LinkageSpec:
3582 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003583 case CXCursor_CXXBaseSpecifier:
3584 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003585 case CXCursor_Constructor:
3586 return createCXString("CXXConstructor");
3587 case CXCursor_Destructor:
3588 return createCXString("CXXDestructor");
3589 case CXCursor_ConversionFunction:
3590 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003591 case CXCursor_TemplateTypeParameter:
3592 return createCXString("TemplateTypeParameter");
3593 case CXCursor_NonTypeTemplateParameter:
3594 return createCXString("NonTypeTemplateParameter");
3595 case CXCursor_TemplateTemplateParameter:
3596 return createCXString("TemplateTemplateParameter");
3597 case CXCursor_FunctionTemplate:
3598 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003599 case CXCursor_ClassTemplate:
3600 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003601 case CXCursor_ClassTemplatePartialSpecialization:
3602 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003603 case CXCursor_NamespaceAlias:
3604 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003605 case CXCursor_UsingDirective:
3606 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003607 case CXCursor_UsingDeclaration:
3608 return createCXString("UsingDeclaration");
Richard Smith162e1c12011-04-15 14:24:37 +00003609 case CXCursor_TypeAliasDecl:
Douglas Gregor352697a2011-06-03 23:08:58 +00003610 return createCXString("TypeAliasDecl");
3611 case CXCursor_ObjCSynthesizeDecl:
3612 return createCXString("ObjCSynthesizeDecl");
3613 case CXCursor_ObjCDynamicDecl:
3614 return createCXString("ObjCDynamicDecl");
Argyrios Kyrtzidis2dfdb942011-09-30 17:58:23 +00003615 case CXCursor_CXXAccessSpecifier:
3616 return createCXString("CXXAccessSpecifier");
Steve Naroff89922f82009-08-31 00:59:03 +00003617 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003618
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003619 llvm_unreachable("Unhandled CXCursorKind");
Steve Naroff600866c2009-08-27 19:51:58 +00003620}
Steve Naroff89922f82009-08-31 00:59:03 +00003621
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003622struct GetCursorData {
3623 SourceLocation TokenBeginLoc;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003624 bool PointsAtMacroArgExpansion;
Argyrios Kyrtzidis135bf8e2012-06-09 03:03:02 +00003625 bool VisitedObjCPropertyImplDecl;
3626 SourceLocation VisitedDeclaratorDeclStartLoc;
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003627 CXCursor &BestCursor;
3628
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003629 GetCursorData(SourceManager &SM,
3630 SourceLocation tokenBegin, CXCursor &outputCursor)
3631 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
3632 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
Argyrios Kyrtzidis135bf8e2012-06-09 03:03:02 +00003633 VisitedObjCPropertyImplDecl = false;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003634 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003635};
3636
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003637static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3638 CXCursor parent,
3639 CXClientData client_data) {
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003640 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
3641 CXCursor *BestCursor = &Data->BestCursor;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003642
3643 // If we point inside a macro argument we should provide info of what the
3644 // token is so use the actual cursor, don't replace it with a macro expansion
3645 // cursor.
3646 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
3647 return CXChildVisit_Recurse;
Argyrios Kyrtzidis65ab9072011-09-26 19:05:37 +00003648
3649 if (clang_isDeclaration(cursor.kind)) {
3650 // Avoid having the implicit methods override the property decls.
Argyrios Kyrtzidisa9d45a32012-04-16 22:42:01 +00003651 if (ObjCMethodDecl *MD
3652 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
Argyrios Kyrtzidis65ab9072011-09-26 19:05:37 +00003653 if (MD->isImplicit())
3654 return CXChildVisit_Break;
Argyrios Kyrtzidisa9d45a32012-04-16 22:42:01 +00003655
3656 } else if (ObjCInterfaceDecl *ID
3657 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) {
3658 // Check that when we have multiple @class references in the same line,
3659 // that later ones do not override the previous ones.
3660 // If we have:
3661 // @class Foo, Bar;
3662 // source ranges for both start at '@', so 'Bar' will end up overriding
3663 // 'Foo' even though the cursor location was at 'Foo'.
3664 if (BestCursor->kind == CXCursor_ObjCInterfaceDecl ||
3665 BestCursor->kind == CXCursor_ObjCClassRef)
3666 if (ObjCInterfaceDecl *PrevID
3667 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(*BestCursor))){
3668 if (PrevID != ID &&
3669 !PrevID->isThisDeclarationADefinition() &&
3670 !ID->isThisDeclarationADefinition())
3671 return CXChildVisit_Break;
3672 }
Argyrios Kyrtzidis135bf8e2012-06-09 03:03:02 +00003673
3674 } else if (DeclaratorDecl *DD
3675 = dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) {
3676 SourceLocation StartLoc = DD->getSourceRange().getBegin();
3677 // Check that when we have multiple declarators in the same line,
3678 // that later ones do not override the previous ones.
3679 // If we have:
3680 // int Foo, Bar;
3681 // source ranges for both start at 'int', so 'Bar' will end up overriding
3682 // 'Foo' even though the cursor location was at 'Foo'.
3683 if (Data->VisitedDeclaratorDeclStartLoc == StartLoc)
3684 return CXChildVisit_Break;
3685 Data->VisitedDeclaratorDeclStartLoc = StartLoc;
3686
3687 } else if (ObjCPropertyImplDecl *PropImp
3688 = dyn_cast_or_null<ObjCPropertyImplDecl>(getCursorDecl(cursor))) {
3689 (void)PropImp;
3690 // Check that when we have multiple @synthesize in the same line,
3691 // that later ones do not override the previous ones.
3692 // If we have:
3693 // @synthesize Foo, Bar;
3694 // source ranges for both start at '@', so 'Bar' will end up overriding
3695 // 'Foo' even though the cursor location was at 'Foo'.
3696 if (Data->VisitedObjCPropertyImplDecl)
3697 return CXChildVisit_Break;
3698 Data->VisitedObjCPropertyImplDecl = true;
Argyrios Kyrtzidisa9d45a32012-04-16 22:42:01 +00003699 }
Argyrios Kyrtzidis65ab9072011-09-26 19:05:37 +00003700 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003701
3702 if (clang_isExpression(cursor.kind) &&
3703 clang_isDeclaration(BestCursor->kind)) {
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00003704 if (Decl *D = getCursorDecl(*BestCursor)) {
3705 // Avoid having the cursor of an expression replace the declaration cursor
3706 // when the expression source range overlaps the declaration range.
3707 // This can happen for C++ constructor expressions whose range generally
3708 // include the variable declaration, e.g.:
3709 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
3710 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
3711 D->getLocation() == Data->TokenBeginLoc)
3712 return CXChildVisit_Break;
3713 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003714 }
3715
Douglas Gregor93798e22010-11-05 21:11:19 +00003716 // If our current best cursor is the construction of a temporary object,
3717 // don't replace that cursor with a type reference, because we want
3718 // clang_getCursor() to point at the constructor.
3719 if (clang_isExpression(BestCursor->kind) &&
3720 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003721 cursor.kind == CXCursor_TypeRef) {
3722 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
3723 // as having the actual point on the type reference.
3724 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
Douglas Gregor93798e22010-11-05 21:11:19 +00003725 return CXChildVisit_Recurse;
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003726 }
Douglas Gregor93798e22010-11-05 21:11:19 +00003727
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003728 *BestCursor = cursor;
3729 return CXChildVisit_Recurse;
3730}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003731
Douglas Gregorb9790342010-01-22 21:44:22 +00003732CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3733 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003734 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003735
Ted Kremeneka60ed472010-11-16 08:15:36 +00003736 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003737 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3738
Ted Kremeneka297de22010-01-25 22:34:44 +00003739 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003740 CXCursor Result = cxcursor::getCursor(TU, SLoc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003741
Douglas Gregor40749ee2010-11-03 00:35:38 +00003742 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregor40749ee2010-11-03 00:35:38 +00003743 if (Logging) {
3744 CXFile SearchFile;
3745 unsigned SearchLine, SearchColumn;
3746 CXFile ResultFile;
3747 unsigned ResultLine, ResultColumn;
Douglas Gregor66537982010-11-17 17:14:07 +00003748 CXString SearchFileName, ResultFileName, KindSpelling, USR;
3749 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
Douglas Gregor40749ee2010-11-03 00:35:38 +00003750 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3751
Chandler Carruth20174222011-08-31 16:53:37 +00003752 clang_getExpansionLocation(Loc, &SearchFile, &SearchLine, &SearchColumn, 0);
3753 clang_getExpansionLocation(ResultLoc, &ResultFile, &ResultLine,
3754 &ResultColumn, 0);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003755 SearchFileName = clang_getFileName(SearchFile);
3756 ResultFileName = clang_getFileName(ResultFile);
3757 KindSpelling = clang_getCursorKindSpelling(Result.kind);
Douglas Gregor66537982010-11-17 17:14:07 +00003758 USR = clang_getCursorUSR(Result);
3759 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n",
Douglas Gregor40749ee2010-11-03 00:35:38 +00003760 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3761 clang_getCString(KindSpelling),
Douglas Gregor66537982010-11-17 17:14:07 +00003762 clang_getCString(ResultFileName), ResultLine, ResultColumn,
3763 clang_getCString(USR), IsDef);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003764 clang_disposeString(SearchFileName);
3765 clang_disposeString(ResultFileName);
3766 clang_disposeString(KindSpelling);
Douglas Gregor66537982010-11-17 17:14:07 +00003767 clang_disposeString(USR);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003768
3769 CXCursor Definition = clang_getCursorDefinition(Result);
3770 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
3771 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
3772 CXString DefinitionKindSpelling
3773 = clang_getCursorKindSpelling(Definition.kind);
3774 CXFile DefinitionFile;
3775 unsigned DefinitionLine, DefinitionColumn;
Chandler Carruth20174222011-08-31 16:53:37 +00003776 clang_getExpansionLocation(DefinitionLoc, &DefinitionFile,
3777 &DefinitionLine, &DefinitionColumn, 0);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003778 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
3779 fprintf(stderr, " -> %s(%s:%d:%d)\n",
3780 clang_getCString(DefinitionKindSpelling),
3781 clang_getCString(DefinitionFileName),
3782 DefinitionLine, DefinitionColumn);
3783 clang_disposeString(DefinitionFileName);
3784 clang_disposeString(DefinitionKindSpelling);
3785 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003786 }
3787
Ted Kremeneke68fff62010-02-17 00:41:32 +00003788 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003789}
3790
Ted Kremenek73885552009-11-17 19:28:59 +00003791CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003792 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003793}
3794
3795unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003796 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003797}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003798
Douglas Gregor9ce55842010-11-20 00:09:34 +00003799unsigned clang_hashCursor(CXCursor C) {
3800 unsigned Index = 0;
3801 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
3802 Index = 1;
3803
3804 return llvm::DenseMapInfo<std::pair<unsigned, void*> >::getHashValue(
3805 std::make_pair(C.kind, C.data[Index]));
3806}
3807
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003808unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003809 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3810}
3811
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003812unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003813 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3814}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003815
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003816unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003817 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3818}
3819
Douglas Gregor97b98722010-01-19 23:20:36 +00003820unsigned clang_isExpression(enum CXCursorKind K) {
3821 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3822}
3823
3824unsigned clang_isStatement(enum CXCursorKind K) {
3825 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3826}
3827
Douglas Gregor8be80e12011-07-06 03:00:34 +00003828unsigned clang_isAttribute(enum CXCursorKind K) {
3829 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
3830}
3831
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003832unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3833 return K == CXCursor_TranslationUnit;
3834}
3835
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003836unsigned clang_isPreprocessing(enum CXCursorKind K) {
3837 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3838}
3839
Ted Kremenekad6eff62010-03-08 21:17:29 +00003840unsigned clang_isUnexposed(enum CXCursorKind K) {
3841 switch (K) {
3842 case CXCursor_UnexposedDecl:
3843 case CXCursor_UnexposedExpr:
3844 case CXCursor_UnexposedStmt:
3845 case CXCursor_UnexposedAttr:
3846 return true;
3847 default:
3848 return false;
3849 }
3850}
3851
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003852CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003853 return C.kind;
3854}
3855
Douglas Gregor98258af2010-01-18 22:46:11 +00003856CXSourceLocation clang_getCursorLocation(CXCursor C) {
3857 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003858 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003859 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003860 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3861 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003862 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003863 }
3864
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003865 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003866 std::pair<ObjCProtocolDecl *, SourceLocation> P
3867 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003868 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003869 }
3870
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003871 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003872 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3873 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003874 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003875 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003876
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003877 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003878 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003879 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003880 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003881
3882 case CXCursor_TemplateRef: {
3883 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3884 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3885 }
3886
Douglas Gregor69319002010-08-31 23:48:11 +00003887 case CXCursor_NamespaceRef: {
3888 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3889 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3890 }
3891
Douglas Gregora67e03f2010-09-09 21:42:20 +00003892 case CXCursor_MemberRef: {
3893 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3894 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3895 }
3896
Douglas Gregor011d8b92012-02-15 00:54:55 +00003897 case CXCursor_VariableRef: {
3898 std::pair<VarDecl *, SourceLocation> P = getCursorVariableRef(C);
3899 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3900 }
3901
Ted Kremenek3064ef92010-08-27 21:34:58 +00003902 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003903 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3904 if (!BaseSpec)
3905 return clang_getNullLocation();
3906
3907 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3908 return cxloc::translateSourceLocation(getCursorContext(C),
3909 TSInfo->getTypeLoc().getBeginLoc());
3910
3911 return cxloc::translateSourceLocation(getCursorContext(C),
Daniel Dunbar96a00142012-03-09 18:35:03 +00003912 BaseSpec->getLocStart());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003913 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003914
Douglas Gregor36897b02010-09-10 00:22:18 +00003915 case CXCursor_LabelRef: {
3916 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3917 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3918 }
3919
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003920 case CXCursor_OverloadedDeclRef:
3921 return cxloc::translateSourceLocation(getCursorContext(C),
3922 getCursorOverloadedDeclRef(C).second);
3923
Douglas Gregorf46034a2010-01-18 23:41:10 +00003924 default:
3925 // FIXME: Need a way to enumerate all non-reference cases.
3926 llvm_unreachable("Missed a reference kind");
3927 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003928 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003929
3930 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003931 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003932 getLocationFromExpr(getCursorExpr(C)));
3933
Douglas Gregor36897b02010-09-10 00:22:18 +00003934 if (clang_isStatement(C.kind))
3935 return cxloc::translateSourceLocation(getCursorContext(C),
3936 getCursorStmt(C)->getLocStart());
3937
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003938 if (C.kind == CXCursor_PreprocessingDirective) {
3939 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3940 return cxloc::translateSourceLocation(getCursorContext(C), L);
3941 }
Douglas Gregor48072312010-03-18 15:23:44 +00003942
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003943 if (C.kind == CXCursor_MacroExpansion) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003944 SourceLocation L
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003945 = cxcursor::getCursorMacroExpansion(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003946 return cxloc::translateSourceLocation(getCursorContext(C), L);
3947 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003948
3949 if (C.kind == CXCursor_MacroDefinition) {
3950 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3951 return cxloc::translateSourceLocation(getCursorContext(C), L);
3952 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003953
3954 if (C.kind == CXCursor_InclusionDirective) {
3955 SourceLocation L
3956 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3957 return cxloc::translateSourceLocation(getCursorContext(C), L);
3958 }
3959
Ted Kremenek9a700d22010-05-12 06:16:13 +00003960 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003961 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003962
Douglas Gregorf46034a2010-01-18 23:41:10 +00003963 Decl *D = getCursorDecl(C);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00003964 if (!D)
3965 return clang_getNullLocation();
3966
Douglas Gregorf46034a2010-01-18 23:41:10 +00003967 SourceLocation Loc = D->getLocation();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003968 // FIXME: Multiple variables declared in a single declaration
3969 // currently lack the information needed to correctly determine their
3970 // ranges when accounting for the type-specifier. We use context
3971 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3972 // and if so, whether it is the first decl.
3973 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3974 if (!cxcursor::isFirstInDeclGroup(C))
3975 Loc = VD->getLocation();
3976 }
3977
Argyrios Kyrtzidisccc6f362012-03-23 03:33:19 +00003978 // For ObjC methods, give the start location of the method name.
3979 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
3980 Loc = MD->getSelectorStartLoc();
3981
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003982 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003983}
Douglas Gregora7bde202010-01-19 00:34:46 +00003984
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003985} // end extern "C"
3986
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003987CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
3988 assert(TU);
3989
3990 // Guard against an invalid SourceLocation, or we may assert in one
3991 // of the following calls.
3992 if (SLoc.isInvalid())
3993 return clang_getNullCursor();
3994
3995 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
3996
3997 // Translate the given source location to make it point at the beginning of
3998 // the token under the cursor.
3999 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +00004000 CXXUnit->getASTContext().getLangOpts());
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00004001
4002 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
4003 if (SLoc.isValid()) {
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00004004 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00004005 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
4006 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00004007 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00004008 SourceLocation(SLoc));
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00004009 CursorVis.visitFileRegion();
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00004010 }
4011
4012 return Result;
4013}
4014
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004015static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00004016 if (clang_isReference(C.kind)) {
4017 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004018 case CXCursor_ObjCSuperClassRef:
4019 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004020
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004021 case CXCursor_ObjCProtocolRef:
4022 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004023
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004024 case CXCursor_ObjCClassRef:
4025 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004026
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004027 case CXCursor_TypeRef:
4028 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00004029
4030 case CXCursor_TemplateRef:
4031 return getCursorTemplateRef(C).second;
4032
Douglas Gregor69319002010-08-31 23:48:11 +00004033 case CXCursor_NamespaceRef:
4034 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00004035
4036 case CXCursor_MemberRef:
4037 return getCursorMemberRef(C).second;
4038
Ted Kremenek3064ef92010-08-27 21:34:58 +00004039 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00004040 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00004041
Douglas Gregor36897b02010-09-10 00:22:18 +00004042 case CXCursor_LabelRef:
4043 return getCursorLabelRef(C).second;
4044
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004045 case CXCursor_OverloadedDeclRef:
4046 return getCursorOverloadedDeclRef(C).second;
4047
Douglas Gregor011d8b92012-02-15 00:54:55 +00004048 case CXCursor_VariableRef:
4049 return getCursorVariableRef(C).second;
4050
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004051 default:
4052 // FIXME: Need a way to enumerate all non-reference cases.
4053 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00004054 }
4055 }
Douglas Gregor97b98722010-01-19 23:20:36 +00004056
4057 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004058 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00004059
4060 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004061 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004062
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00004063 if (clang_isAttribute(C.kind))
4064 return getCursorAttr(C)->getRange();
4065
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004066 if (C.kind == CXCursor_PreprocessingDirective)
4067 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00004068
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004069 if (C.kind == CXCursor_MacroExpansion) {
4070 ASTUnit *TU = getCursorASTUnit(C);
4071 SourceRange Range = cxcursor::getCursorMacroExpansion(C)->getSourceRange();
4072 return TU->mapRangeFromPreamble(Range);
4073 }
Douglas Gregor572feb22010-03-18 18:04:21 +00004074
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004075 if (C.kind == CXCursor_MacroDefinition) {
4076 ASTUnit *TU = getCursorASTUnit(C);
4077 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
4078 return TU->mapRangeFromPreamble(Range);
4079 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00004080
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004081 if (C.kind == CXCursor_InclusionDirective) {
4082 ASTUnit *TU = getCursorASTUnit(C);
4083 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
4084 return TU->mapRangeFromPreamble(Range);
4085 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00004086
Argyrios Kyrtzidis0822c5f2012-03-19 23:17:58 +00004087 if (C.kind == CXCursor_TranslationUnit) {
4088 ASTUnit *TU = getCursorASTUnit(C);
4089 FileID MainID = TU->getSourceManager().getMainFileID();
4090 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
4091 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
4092 return SourceRange(Start, End);
4093 }
4094
Ted Kremenek007a7c92010-11-01 23:26:51 +00004095 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
4096 Decl *D = cxcursor::getCursorDecl(C);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00004097 if (!D)
4098 return SourceRange();
4099
Ted Kremenek007a7c92010-11-01 23:26:51 +00004100 SourceRange R = D->getSourceRange();
4101 // FIXME: Multiple variables declared in a single declaration
4102 // currently lack the information needed to correctly determine their
4103 // ranges when accounting for the type-specifier. We use context
4104 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
4105 // and if so, whether it is the first decl.
4106 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4107 if (!cxcursor::isFirstInDeclGroup(C))
4108 R.setBegin(VD->getLocation());
4109 }
4110 return R;
4111 }
Douglas Gregor66537982010-11-17 17:14:07 +00004112 return SourceRange();
4113}
4114
4115/// \brief Retrieves the "raw" cursor extent, which is then extended to include
4116/// the decl-specifier-seq for declarations.
4117static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
4118 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
4119 Decl *D = cxcursor::getCursorDecl(C);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00004120 if (!D)
4121 return SourceRange();
4122
Douglas Gregor66537982010-11-17 17:14:07 +00004123 SourceRange R = D->getSourceRange();
Douglas Gregor66537982010-11-17 17:14:07 +00004124
Douglas Gregor2494dd02011-03-01 01:34:45 +00004125 // Adjust the start of the location for declarations preceded by
4126 // declaration specifiers.
4127 SourceLocation StartLoc;
4128 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
4129 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
Daniel Dunbar96a00142012-03-09 18:35:03 +00004130 StartLoc = TI->getTypeLoc().getLocStart();
Douglas Gregor2494dd02011-03-01 01:34:45 +00004131 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
4132 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
Daniel Dunbar96a00142012-03-09 18:35:03 +00004133 StartLoc = TI->getTypeLoc().getLocStart();
Douglas Gregor2494dd02011-03-01 01:34:45 +00004134 }
4135
4136 if (StartLoc.isValid() && R.getBegin().isValid() &&
4137 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
4138 R.setBegin(StartLoc);
4139
4140 // FIXME: Multiple variables declared in a single declaration
4141 // currently lack the information needed to correctly determine their
4142 // ranges when accounting for the type-specifier. We use context
4143 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
4144 // and if so, whether it is the first decl.
4145 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4146 if (!cxcursor::isFirstInDeclGroup(C))
4147 R.setBegin(VD->getLocation());
Douglas Gregor66537982010-11-17 17:14:07 +00004148 }
4149
4150 return R;
4151 }
4152
4153 return getRawCursorExtent(C);
4154}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004155
4156extern "C" {
4157
4158CXSourceRange clang_getCursorExtent(CXCursor C) {
4159 SourceRange R = getRawCursorExtent(C);
4160 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00004161 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004162
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004163 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00004164}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004165
4166CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00004167 if (clang_isInvalid(C.kind))
4168 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004169
Ted Kremeneka60ed472010-11-16 08:15:36 +00004170 CXTranslationUnit tu = getCursorTU(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004171 if (clang_isDeclaration(C.kind)) {
4172 Decl *D = getCursorDecl(C);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00004173 if (!D)
4174 return clang_getNullCursor();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004175 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004176 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Chris Lattner5f9e2722011-07-23 10:55:15 +00004177 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00004178 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
4179 return MakeCXCursor(Property, tu);
4180
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004181 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004182 }
4183
Douglas Gregor97b98722010-01-19 23:20:36 +00004184 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004185 Expr *E = getCursorExpr(C);
4186 Decl *D = getDeclFromExpr(E);
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00004187 if (D) {
4188 CXCursor declCursor = MakeCXCursor(D, tu);
4189 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
4190 declCursor);
4191 return declCursor;
4192 }
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004193
4194 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004195 return MakeCursorOverloadedDeclRef(Ovl, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004196
Douglas Gregor97b98722010-01-19 23:20:36 +00004197 return clang_getNullCursor();
4198 }
4199
Douglas Gregor36897b02010-09-10 00:22:18 +00004200 if (clang_isStatement(C.kind)) {
4201 Stmt *S = getCursorStmt(C);
4202 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Ted Kremenek37c2e962011-03-15 23:47:49 +00004203 if (LabelDecl *label = Goto->getLabel())
4204 if (LabelStmt *labelS = label->getStmt())
4205 return MakeCXCursor(labelS, getCursorDecl(C), tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00004206
4207 return clang_getNullCursor();
4208 }
4209
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004210 if (C.kind == CXCursor_MacroExpansion) {
Chandler Carruth9e5bb852011-07-14 08:20:46 +00004211 if (MacroDefinition *Def = getCursorMacroExpansion(C)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004212 return MakeMacroDefinitionCursor(Def, tu);
Douglas Gregorbf7efa22010-03-18 18:23:03 +00004213 }
4214
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004215 if (!clang_isReference(C.kind))
4216 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004217
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004218 switch (C.kind) {
4219 case CXCursor_ObjCSuperClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004220 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004221
4222 case CXCursor_ObjCProtocolRef: {
Argyrios Kyrtzidis98c16b82012-01-24 19:40:15 +00004223 ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
4224 if (ObjCProtocolDecl *Def = Prot->getDefinition())
4225 return MakeCXCursor(Def, tu);
4226
Argyrios Kyrtzidisc15707d2012-01-24 21:39:26 +00004227 return MakeCXCursor(Prot, tu);
Argyrios Kyrtzidis98c16b82012-01-24 19:40:15 +00004228 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004229
Douglas Gregor7723fec2011-12-15 20:29:51 +00004230 case CXCursor_ObjCClassRef: {
4231 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
4232 if (ObjCInterfaceDecl *Def = Class->getDefinition())
4233 return MakeCXCursor(Def, tu);
4234
Argyrios Kyrtzidisc15707d2012-01-24 21:39:26 +00004235 return MakeCXCursor(Class, tu);
Douglas Gregor7723fec2011-12-15 20:29:51 +00004236 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00004237
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004238 case CXCursor_TypeRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004239 return MakeCXCursor(getCursorTypeRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00004240
4241 case CXCursor_TemplateRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004242 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00004243
Douglas Gregor69319002010-08-31 23:48:11 +00004244 case CXCursor_NamespaceRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004245 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
Douglas Gregor69319002010-08-31 23:48:11 +00004246
Douglas Gregora67e03f2010-09-09 21:42:20 +00004247 case CXCursor_MemberRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004248 return MakeCXCursor(getCursorMemberRef(C).first, tu );
Douglas Gregora67e03f2010-09-09 21:42:20 +00004249
Ted Kremenek3064ef92010-08-27 21:34:58 +00004250 case CXCursor_CXXBaseSpecifier: {
4251 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
4252 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004253 tu ));
Ted Kremenek3064ef92010-08-27 21:34:58 +00004254 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004255
Douglas Gregor36897b02010-09-10 00:22:18 +00004256 case CXCursor_LabelRef:
4257 // FIXME: We end up faking the "parent" declaration here because we
4258 // don't want to make CXCursor larger.
4259 return MakeCXCursor(getCursorLabelRef(C).first,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004260 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
4261 .getTranslationUnitDecl(),
4262 tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00004263
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004264 case CXCursor_OverloadedDeclRef:
4265 return C;
Douglas Gregor011d8b92012-02-15 00:54:55 +00004266
4267 case CXCursor_VariableRef:
4268 return MakeCXCursor(getCursorVariableRef(C).first, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004269
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004270 default:
4271 // We would prefer to enumerate all non-reference cursor kinds here.
4272 llvm_unreachable("Unhandled reference cursor kind");
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004273 }
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004274}
4275
Douglas Gregorb6998662010-01-19 19:34:47 +00004276CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00004277 if (clang_isInvalid(C.kind))
4278 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004279
Ted Kremeneka60ed472010-11-16 08:15:36 +00004280 CXTranslationUnit TU = getCursorTU(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004281
Douglas Gregorb6998662010-01-19 19:34:47 +00004282 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00004283 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00004284 C = clang_getCursorReferenced(C);
4285 WasReference = true;
4286 }
4287
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004288 if (C.kind == CXCursor_MacroExpansion)
Douglas Gregorbf7efa22010-03-18 18:23:03 +00004289 return clang_getCursorReferenced(C);
4290
Douglas Gregorb6998662010-01-19 19:34:47 +00004291 if (!clang_isDeclaration(C.kind))
4292 return clang_getNullCursor();
4293
4294 Decl *D = getCursorDecl(C);
4295 if (!D)
4296 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004297
Douglas Gregorb6998662010-01-19 19:34:47 +00004298 switch (D->getKind()) {
4299 // Declaration kinds that don't really separate the notions of
4300 // declaration and definition.
4301 case Decl::Namespace:
4302 case Decl::Typedef:
Richard Smith162e1c12011-04-15 14:24:37 +00004303 case Decl::TypeAlias:
Richard Smith3e4c6c42011-05-05 21:57:07 +00004304 case Decl::TypeAliasTemplate:
Douglas Gregorb6998662010-01-19 19:34:47 +00004305 case Decl::TemplateTypeParm:
4306 case Decl::EnumConstant:
4307 case Decl::Field:
Benjamin Kramerd9811462010-11-21 14:11:41 +00004308 case Decl::IndirectField:
Douglas Gregorb6998662010-01-19 19:34:47 +00004309 case Decl::ObjCIvar:
4310 case Decl::ObjCAtDefsField:
4311 case Decl::ImplicitParam:
4312 case Decl::ParmVar:
4313 case Decl::NonTypeTemplateParm:
4314 case Decl::TemplateTemplateParm:
4315 case Decl::ObjCCategoryImpl:
4316 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00004317 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00004318 case Decl::LinkageSpec:
4319 case Decl::ObjCPropertyImpl:
4320 case Decl::FileScopeAsm:
4321 case Decl::StaticAssert:
4322 case Decl::Block:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00004323 case Decl::Label: // FIXME: Is this right??
Francois Pichetaf0f4d02011-08-14 03:52:19 +00004324 case Decl::ClassScopeFunctionSpecialization:
Douglas Gregor15de72c2011-12-02 23:23:56 +00004325 case Decl::Import:
Douglas Gregorb6998662010-01-19 19:34:47 +00004326 return C;
4327
4328 // Declaration kinds that don't make any sense here, but are
4329 // nonetheless harmless.
4330 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00004331 break;
4332
4333 // Declaration kinds for which the definition is not resolvable.
4334 case Decl::UnresolvedUsingTypename:
4335 case Decl::UnresolvedUsingValue:
4336 break;
4337
4338 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00004339 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004340 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004341
4342 case Decl::NamespaceAlias:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004343 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004344
4345 case Decl::Enum:
4346 case Decl::Record:
4347 case Decl::CXXRecord:
4348 case Decl::ClassTemplateSpecialization:
4349 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00004350 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004351 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004352 return clang_getNullCursor();
4353
4354 case Decl::Function:
4355 case Decl::CXXMethod:
4356 case Decl::CXXConstructor:
4357 case Decl::CXXDestructor:
4358 case Decl::CXXConversion: {
4359 const FunctionDecl *Def = 0;
4360 if (cast<FunctionDecl>(D)->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004361 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004362 return clang_getNullCursor();
4363 }
4364
4365 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00004366 // Ask the variable if it has a definition.
4367 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004368 return MakeCXCursor(Def, TU);
Sebastian Redl31310a22010-02-01 20:16:42 +00004369 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00004370 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004371
Douglas Gregorb6998662010-01-19 19:34:47 +00004372 case Decl::FunctionTemplate: {
4373 const FunctionDecl *Def = 0;
4374 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004375 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004376 return clang_getNullCursor();
4377 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004378
Douglas Gregorb6998662010-01-19 19:34:47 +00004379 case Decl::ClassTemplate: {
4380 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00004381 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00004382 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004383 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004384 return clang_getNullCursor();
4385 }
4386
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004387 case Decl::Using:
4388 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004389 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004390
4391 case Decl::UsingShadow:
4392 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004393 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004394 TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004395
4396 case Decl::ObjCMethod: {
4397 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
4398 if (Method->isThisDeclarationADefinition())
4399 return C;
4400
4401 // Dig out the method definition in the associated
4402 // @implementation, if we have it.
4403 // FIXME: The ASTs should make finding the definition easier.
4404 if (ObjCInterfaceDecl *Class
4405 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
4406 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
4407 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
4408 Method->isInstanceMethod()))
4409 if (Def->isThisDeclarationADefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004410 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004411
4412 return clang_getNullCursor();
4413 }
4414
4415 case Decl::ObjCCategory:
4416 if (ObjCCategoryImplDecl *Impl
4417 = cast<ObjCCategoryDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004418 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004419 return clang_getNullCursor();
4420
4421 case Decl::ObjCProtocol:
Douglas Gregor5e2a1ff2012-01-01 19:29:29 +00004422 if (ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
4423 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004424 return clang_getNullCursor();
4425
Douglas Gregor375bb142011-12-27 22:43:10 +00004426 case Decl::ObjCInterface: {
Douglas Gregorb6998662010-01-19 19:34:47 +00004427 // There are two notions of a "definition" for an Objective-C
4428 // class: the interface and its implementation. When we resolved a
4429 // reference to an Objective-C class, produce the @interface as
4430 // the definition; when we were provided with the interface,
4431 // produce the @implementation as the definition.
Douglas Gregor375bb142011-12-27 22:43:10 +00004432 ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
Douglas Gregorb6998662010-01-19 19:34:47 +00004433 if (WasReference) {
Douglas Gregor375bb142011-12-27 22:43:10 +00004434 if (ObjCInterfaceDecl *Def = IFace->getDefinition())
Douglas Gregor7723fec2011-12-15 20:29:51 +00004435 return MakeCXCursor(Def, TU);
Douglas Gregor375bb142011-12-27 22:43:10 +00004436 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004437 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004438 return clang_getNullCursor();
Douglas Gregor375bb142011-12-27 22:43:10 +00004439 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004440
Douglas Gregorb6998662010-01-19 19:34:47 +00004441 case Decl::ObjCProperty:
4442 // FIXME: We don't really know where to find the
4443 // ObjCPropertyImplDecls that implement this property.
4444 return clang_getNullCursor();
4445
4446 case Decl::ObjCCompatibleAlias:
4447 if (ObjCInterfaceDecl *Class
4448 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
Douglas Gregor7723fec2011-12-15 20:29:51 +00004449 if (ObjCInterfaceDecl *Def = Class->getDefinition())
4450 return MakeCXCursor(Def, TU);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004451
Douglas Gregorb6998662010-01-19 19:34:47 +00004452 return clang_getNullCursor();
4453
Douglas Gregorb6998662010-01-19 19:34:47 +00004454 case Decl::Friend:
4455 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004456 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004457 return clang_getNullCursor();
4458
4459 case Decl::FriendTemplate:
4460 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004461 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004462 return clang_getNullCursor();
4463 }
4464
4465 return clang_getNullCursor();
4466}
4467
4468unsigned clang_isCursorDefinition(CXCursor C) {
4469 if (!clang_isDeclaration(C.kind))
4470 return 0;
4471
4472 return clang_getCursorDefinition(C) == C;
4473}
4474
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004475CXCursor clang_getCanonicalCursor(CXCursor C) {
4476 if (!clang_isDeclaration(C.kind))
4477 return C;
4478
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004479 if (Decl *D = getCursorDecl(C)) {
Argyrios Kyrtzidisdebb00f2011-07-15 22:37:58 +00004480 if (ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
4481 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
4482 return MakeCXCursor(CatD, getCursorTU(C));
4483
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004484 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
4485 if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
4486 return MakeCXCursor(IFD, getCursorTU(C));
4487
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004488 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004489 }
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004490
4491 return C;
4492}
Argyrios Kyrtzidis34ebe1e2012-03-30 22:15:48 +00004493
4494int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) {
4495 return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first;
4496}
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004497
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004498unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004499 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004500 return 0;
4501
4502 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
4503 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
4504 return E->getNumDecls();
4505
4506 if (OverloadedTemplateStorage *S
4507 = Storage.dyn_cast<OverloadedTemplateStorage*>())
4508 return S->size();
4509
4510 Decl *D = Storage.get<Decl*>();
4511 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00004512 return Using->shadow_size();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004513
4514 return 0;
4515}
4516
4517CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004518 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004519 return clang_getNullCursor();
4520
4521 if (index >= clang_getNumOverloadedDecls(cursor))
4522 return clang_getNullCursor();
4523
Ted Kremeneka60ed472010-11-16 08:15:36 +00004524 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004525 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
4526 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004527 return MakeCXCursor(E->decls_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004528
4529 if (OverloadedTemplateStorage *S
4530 = Storage.dyn_cast<OverloadedTemplateStorage*>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004531 return MakeCXCursor(S->begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004532
4533 Decl *D = Storage.get<Decl*>();
4534 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
4535 // FIXME: This is, unfortunately, linear time.
4536 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
4537 std::advance(Pos, index);
Ted Kremeneka60ed472010-11-16 08:15:36 +00004538 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004539 }
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004540
4541 return clang_getNullCursor();
4542}
4543
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00004544void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00004545 const char **startBuf,
4546 const char **endBuf,
4547 unsigned *startLine,
4548 unsigned *startColumn,
4549 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00004550 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00004551 assert(getCursorDecl(C) && "CXCursor has null decl");
4552 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00004553 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
4554 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004555
Steve Naroff4ade6d62009-09-23 17:52:52 +00004556 SourceManager &SM = FD->getASTContext().getSourceManager();
4557 *startBuf = SM.getCharacterData(Body->getLBracLoc());
4558 *endBuf = SM.getCharacterData(Body->getRBracLoc());
4559 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
4560 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
4561 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
4562 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
4563}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004564
Douglas Gregor430d7a12011-07-25 17:48:11 +00004565
4566CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
4567 unsigned PieceIndex) {
4568 RefNamePieces Pieces;
4569
4570 switch (C.kind) {
4571 case CXCursor_MemberRefExpr:
4572 if (MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
4573 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
4574 E->getQualifierLoc().getSourceRange());
4575 break;
4576
4577 case CXCursor_DeclRefExpr:
4578 if (DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C)))
4579 Pieces = buildPieces(NameFlags, false, E->getNameInfo(),
4580 E->getQualifierLoc().getSourceRange(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00004581 E->getOptionalExplicitTemplateArgs());
Douglas Gregor430d7a12011-07-25 17:48:11 +00004582 break;
4583
4584 case CXCursor_CallExpr:
4585 if (CXXOperatorCallExpr *OCE =
4586 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
4587 Expr *Callee = OCE->getCallee();
4588 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
4589 Callee = ICE->getSubExpr();
4590
4591 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
4592 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
4593 DRE->getQualifierLoc().getSourceRange());
4594 }
4595 break;
4596
4597 default:
4598 break;
4599 }
4600
4601 if (Pieces.empty()) {
4602 if (PieceIndex == 0)
4603 return clang_getCursorExtent(C);
4604 } else if (PieceIndex < Pieces.size()) {
4605 SourceRange R = Pieces[PieceIndex];
4606 if (R.isValid())
4607 return cxloc::translateSourceRange(getCursorContext(C), R);
4608 }
4609
4610 return clang_getNullRange();
4611}
4612
Douglas Gregor0a812cf2010-02-18 23:07:20 +00004613void clang_enableStackTraces(void) {
4614 llvm::sys::PrintStackTraceOnErrorSignal();
4615}
4616
Daniel Dunbar995aaf92010-11-04 01:26:29 +00004617void clang_executeOnThread(void (*fn)(void*), void *user_data,
4618 unsigned stack_size) {
4619 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
4620}
4621
Ted Kremenekfb480492010-01-13 21:46:36 +00004622} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00004623
Ted Kremenekfb480492010-01-13 21:46:36 +00004624//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004625// Token-based Operations.
4626//===----------------------------------------------------------------------===//
4627
4628/* CXToken layout:
4629 * int_data[0]: a CXTokenKind
4630 * int_data[1]: starting token location
4631 * int_data[2]: token length
4632 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004633 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004634 * otherwise unused.
4635 */
4636extern "C" {
4637
4638CXTokenKind clang_getTokenKind(CXToken CXTok) {
4639 return static_cast<CXTokenKind>(CXTok.int_data[0]);
4640}
4641
4642CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
4643 switch (clang_getTokenKind(CXTok)) {
4644 case CXToken_Identifier:
4645 case CXToken_Keyword:
4646 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004647 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
4648 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004649
4650 case CXToken_Literal: {
4651 // We have stashed the starting pointer in the ptr_data field. Use it.
4652 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Chris Lattner5f9e2722011-07-23 10:55:15 +00004653 return createCXString(StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004654 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004655
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004656 case CXToken_Punctuation:
4657 case CXToken_Comment:
4658 break;
4659 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004660
4661 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004662 // deconstructing the source location.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004663 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004664 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004665 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004666
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004667 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
4668 std::pair<FileID, unsigned> LocInfo
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004669 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00004670 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004671 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004672 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
4673 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00004674 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004675
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004676 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004677}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004678
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004679CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004680 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004681 if (!CXXUnit)
4682 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004683
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004684 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
4685 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4686}
4687
4688CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004689 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor5352ac02010-01-28 00:27:43 +00004690 if (!CXXUnit)
4691 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004692
4693 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004694 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4695}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004696
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004697static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
4698 SmallVectorImpl<CXToken> &CXTokens) {
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004699 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4700 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004701 = SourceMgr.getDecomposedLoc(Range.getBegin());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004702 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004703 = SourceMgr.getDecomposedLoc(Range.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004704
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004705 // Cannot tokenize across files.
4706 if (BeginLocInfo.first != EndLocInfo.first)
4707 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004708
4709 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004710 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004711 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004712 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00004713 if (Invalid)
4714 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00004715
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004716 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
David Blaikie4e4d0842012-03-11 07:00:24 +00004717 CXXUnit->getASTContext().getLangOpts(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004718 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004719 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004720
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004721 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004722 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004723 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00004724 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004725 do {
4726 // Lex the next token
4727 Lex.LexFromRawLexer(Tok);
4728 if (Tok.is(tok::eof))
4729 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004730
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004731 // Initialize the CXToken.
4732 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004733
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004734 // - Common fields
4735 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
4736 CXTok.int_data[2] = Tok.getLength();
4737 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004738
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004739 // - Kind-specific fields
4740 if (Tok.isLiteral()) {
4741 CXTok.int_data[0] = CXToken_Literal;
4742 CXTok.ptr_data = (void *)Tok.getLiteralData();
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004743 } else if (Tok.is(tok::raw_identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00004744 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004745 IdentifierInfo *II
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004746 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004747
David Chisnall096428b2010-10-13 21:44:48 +00004748 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004749 CXTok.int_data[0] = CXToken_Keyword;
4750 }
4751 else {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004752 CXTok.int_data[0] = Tok.is(tok::identifier)
4753 ? CXToken_Identifier
4754 : CXToken_Keyword;
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004755 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004756 CXTok.ptr_data = II;
4757 } else if (Tok.is(tok::comment)) {
4758 CXTok.int_data[0] = CXToken_Comment;
4759 CXTok.ptr_data = 0;
4760 } else {
4761 CXTok.int_data[0] = CXToken_Punctuation;
4762 CXTok.ptr_data = 0;
4763 }
4764 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00004765 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004766 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004767}
4768
4769void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
4770 CXToken **Tokens, unsigned *NumTokens) {
4771 if (Tokens)
4772 *Tokens = 0;
4773 if (NumTokens)
4774 *NumTokens = 0;
4775
4776 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4777 if (!CXXUnit || !Tokens || !NumTokens)
4778 return;
4779
4780 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4781
4782 SourceRange R = cxloc::translateCXSourceRange(Range);
4783 if (R.isInvalid())
4784 return;
4785
4786 SmallVector<CXToken, 32> CXTokens;
4787 getTokens(CXXUnit, R, CXTokens);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004788
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004789 if (CXTokens.empty())
4790 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004791
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004792 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
4793 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
4794 *NumTokens = CXTokens.size();
4795}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004796
Ted Kremenek6db61092010-05-05 00:55:15 +00004797void clang_disposeTokens(CXTranslationUnit TU,
4798 CXToken *Tokens, unsigned NumTokens) {
4799 free(Tokens);
4800}
4801
4802} // end: extern "C"
4803
4804//===----------------------------------------------------------------------===//
4805// Token annotation APIs.
4806//===----------------------------------------------------------------------===//
4807
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004808typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004809static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4810 CXCursor parent,
4811 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00004812namespace {
4813class AnnotateTokensWorker {
4814 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004815 CXToken *Tokens;
4816 CXCursor *Cursors;
4817 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004818 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00004819 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004820 CursorVisitor AnnotateVis;
4821 SourceManager &SrcMgr;
Douglas Gregorf5251602011-03-08 17:10:18 +00004822 bool HasContextSensitiveKeywords;
4823
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004824 bool MoreTokens() const { return TokIdx < NumTokens; }
4825 unsigned NextToken() const { return TokIdx; }
4826 void AdvanceToken() { ++TokIdx; }
4827 SourceLocation GetTokenLoc(unsigned tokI) {
4828 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4829 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004830 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004831 return Tokens[tokI].int_data[3] != 0;
4832 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004833 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004834 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[3]);
4835 }
4836
4837 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004838 void annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
4839 SourceRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004840
Ted Kremenek6db61092010-05-05 00:55:15 +00004841public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00004842 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004843 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004844 CXTranslationUnit tu, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00004845 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00004846 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004847 AnnotateVis(tu,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00004848 AnnotateTokensVisitor, this,
4849 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00004850 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00004851 RegionOfInterest),
Douglas Gregorf5251602011-03-08 17:10:18 +00004852 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()),
4853 HasContextSensitiveKeywords(false) { }
Ted Kremenek11949cb2010-05-05 00:55:17 +00004854
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004855 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00004856 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004857 void AnnotateTokens();
Douglas Gregorf5251602011-03-08 17:10:18 +00004858
4859 /// \brief Determine whether the annotator saw any cursors that have
4860 /// context-sensitive keywords.
4861 bool hasContextSensitiveKeywords() const {
4862 return HasContextSensitiveKeywords;
4863 }
Ted Kremenek6db61092010-05-05 00:55:15 +00004864};
4865}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004866
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004867void AnnotateTokensWorker::AnnotateTokens() {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004868 // Walk the AST within the region of interest, annotating tokens
4869 // along the way.
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004870 AnnotateVis.visitFileRegion();
Ted Kremenek11949cb2010-05-05 00:55:17 +00004871
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004872 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4873 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004874 if (Pos != Annotated.end() &&
4875 (clang_isInvalid(Cursors[I].kind) ||
4876 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004877 Cursors[I] = Pos->second;
4878 }
4879
4880 // Finish up annotating any tokens left.
4881 if (!MoreTokens())
4882 return;
4883
4884 const CXCursor &C = clang_getNullCursor();
4885 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004886 if (I < PreprocessingTokIdx && clang_isPreprocessing(Cursors[I].kind))
4887 continue;
4888
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004889 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4890 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004891 }
4892}
4893
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004894/// \brief It annotates and advances tokens with a cursor until the comparison
4895//// between the cursor location and the source range is the same as
4896/// \arg compResult.
4897///
4898/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
4899/// Pass RangeOverlap to annotate tokens inside a range.
4900void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
4901 RangeComparisonResult compResult,
4902 SourceRange range) {
4903 while (MoreTokens()) {
4904 const unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004905 if (isFunctionMacroToken(I))
4906 return annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004907
4908 SourceLocation TokLoc = GetTokenLoc(I);
4909 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4910 Cursors[I] = updateC;
4911 AdvanceToken();
4912 continue;
4913 }
4914 break;
4915 }
4916}
4917
4918/// \brief Special annotation handling for macro argument tokens.
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004919void AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
4920 CXCursor updateC,
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004921 RangeComparisonResult compResult,
4922 SourceRange range) {
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004923 assert(MoreTokens());
4924 assert(isFunctionMacroToken(NextToken()) &&
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004925 "Should be called only for macro arg tokens");
4926
4927 // This works differently than annotateAndAdvanceTokens; because expanded
4928 // macro arguments can have arbitrary translation-unit source order, we do not
4929 // advance the token index one by one until a token fails the range test.
4930 // We only advance once past all of the macro arg tokens if all of them
4931 // pass the range test. If one of them fails we keep the token index pointing
4932 // at the start of the macro arg tokens so that the failing token will be
4933 // annotated by a subsequent annotation try.
4934
4935 bool atLeastOneCompFail = false;
4936
4937 unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004938 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
4939 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004940 if (TokLoc.isFileID())
4941 continue; // not macro arg token, it's parens or comma.
4942 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4943 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
4944 Cursors[I] = updateC;
4945 } else
4946 atLeastOneCompFail = true;
4947 }
4948
4949 if (!atLeastOneCompFail)
4950 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
4951}
4952
Ted Kremenek6db61092010-05-05 00:55:15 +00004953enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004954AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004955 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004956 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004957 if (cursorRange.isInvalid())
4958 return CXChildVisit_Recurse;
Douglas Gregorf5251602011-03-08 17:10:18 +00004959
4960 if (!HasContextSensitiveKeywords) {
4961 // Objective-C properties can have context-sensitive keywords.
4962 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
4963 if (ObjCPropertyDecl *Property
4964 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
4965 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
4966 }
4967 // Objective-C methods can have context-sensitive keywords.
4968 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
4969 cursor.kind == CXCursor_ObjCClassMethodDecl) {
4970 if (ObjCMethodDecl *Method
4971 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
4972 if (Method->getObjCDeclQualifier())
4973 HasContextSensitiveKeywords = true;
4974 else {
4975 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
4976 PEnd = Method->param_end();
4977 P != PEnd; ++P) {
4978 if ((*P)->getObjCDeclQualifier()) {
4979 HasContextSensitiveKeywords = true;
4980 break;
4981 }
4982 }
4983 }
4984 }
4985 }
4986 // C++ methods can have context-sensitive keywords.
4987 else if (cursor.kind == CXCursor_CXXMethod) {
4988 if (CXXMethodDecl *Method
4989 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
4990 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
4991 HasContextSensitiveKeywords = true;
4992 }
4993 }
4994 // C++ classes can have context-sensitive keywords.
4995 else if (cursor.kind == CXCursor_StructDecl ||
4996 cursor.kind == CXCursor_ClassDecl ||
4997 cursor.kind == CXCursor_ClassTemplate ||
4998 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
4999 if (Decl *D = getCursorDecl(cursor))
5000 if (D->hasAttr<FinalAttr>())
5001 HasContextSensitiveKeywords = true;
5002 }
5003 }
5004
Douglas Gregor4419b672010-10-21 06:10:04 +00005005 if (clang_isPreprocessing(cursor.kind)) {
Chandler Carruthcea731a2011-07-14 16:07:57 +00005006 // For macro expansions, just note where the beginning of the macro
5007 // expansion occurs.
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00005008 if (cursor.kind == CXCursor_MacroExpansion) {
Douglas Gregor4419b672010-10-21 06:10:04 +00005009 Annotated[Loc.int_data] = cursor;
5010 return CXChildVisit_Recurse;
5011 }
5012
Douglas Gregor4419b672010-10-21 06:10:04 +00005013 // Items in the preprocessing record are kept separate from items in
5014 // declarations, so we keep a separate token index.
5015 unsigned SavedTokIdx = TokIdx;
5016 TokIdx = PreprocessingTokIdx;
5017
5018 // Skip tokens up until we catch up to the beginning of the preprocessing
5019 // entry.
5020 while (MoreTokens()) {
5021 const unsigned I = NextToken();
5022 SourceLocation TokLoc = GetTokenLoc(I);
5023 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
5024 case RangeBefore:
5025 AdvanceToken();
5026 continue;
5027 case RangeAfter:
5028 case RangeOverlap:
5029 break;
5030 }
5031 break;
5032 }
5033
5034 // Look at all of the tokens within this range.
5035 while (MoreTokens()) {
5036 const unsigned I = NextToken();
5037 SourceLocation TokLoc = GetTokenLoc(I);
5038 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
5039 case RangeBefore:
David Blaikieb219cfc2011-09-23 05:06:16 +00005040 llvm_unreachable("Infeasible");
Douglas Gregor4419b672010-10-21 06:10:04 +00005041 case RangeAfter:
5042 break;
5043 case RangeOverlap:
5044 Cursors[I] = cursor;
5045 AdvanceToken();
5046 continue;
5047 }
5048 break;
5049 }
5050
5051 // Save the preprocessing token index; restore the non-preprocessing
5052 // token index.
5053 PreprocessingTokIdx = TokIdx;
5054 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005055 return CXChildVisit_Recurse;
5056 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005057
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005058 if (cursorRange.isInvalid())
5059 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00005060
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005061 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
5062
Ted Kremeneka333c662010-05-12 05:29:33 +00005063 // Adjust the annotated range based specific declarations.
5064 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
5065 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00005066 Decl *D = cxcursor::getCursorDecl(cursor);
Douglas Gregor2494dd02011-03-01 01:34:45 +00005067
5068 SourceLocation StartLoc;
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00005069 if (const DeclaratorDecl *DD = dyn_cast_or_null<DeclaratorDecl>(D)) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00005070 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
Daniel Dunbar96a00142012-03-09 18:35:03 +00005071 StartLoc = TI->getTypeLoc().getLocStart();
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00005072 } else if (TypedefDecl *Typedef = dyn_cast_or_null<TypedefDecl>(D)) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00005073 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
Daniel Dunbar96a00142012-03-09 18:35:03 +00005074 StartLoc = TI->getTypeLoc().getLocStart();
Ted Kremeneka333c662010-05-12 05:29:33 +00005075 }
Douglas Gregor2494dd02011-03-01 01:34:45 +00005076
5077 if (StartLoc.isValid() && L.isValid() &&
5078 SrcMgr.isBeforeInTranslationUnit(StartLoc, L))
5079 cursorRange.setBegin(StartLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00005080 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00005081
Ted Kremenek3f404602010-08-14 01:14:06 +00005082 // If the location of the cursor occurs within a macro instantiation, record
5083 // the spelling location of the cursor in our annotation map. We can then
5084 // paper over the token labelings during a post-processing step to try and
5085 // get cursor mappings for tokens that are the *arguments* of a macro
5086 // instantiation.
5087 if (L.isMacroID()) {
5088 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
5089 // Only invalidate the old annotation if it isn't part of a preprocessing
5090 // directive. Here we assume that the default construction of CXCursor
5091 // results in CXCursor.kind being an initialized value (i.e., 0). If
5092 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00005093
Ted Kremenek3f404602010-08-14 01:14:06 +00005094 CXCursor &oldC = Annotated[rawEncoding];
5095 if (!clang_isPreprocessing(oldC.kind))
5096 oldC = cursor;
5097 }
5098
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005099 const enum CXCursorKind K = clang_getCursorKind(parent);
5100 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00005101 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
5102 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005103
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005104 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005105
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00005106 // Avoid having the cursor of an expression "overwrite" the annotation of the
5107 // variable declaration that it belongs to.
5108 // This can happen for C++ constructor expressions whose range generally
5109 // include the variable declaration, e.g.:
5110 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
5111 if (clang_isExpression(cursorK)) {
5112 Expr *E = getCursorExpr(cursor);
Argyrios Kyrtzidis8ccac3d2011-06-29 22:20:07 +00005113 if (Decl *D = getCursorParentDecl(cursor)) {
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00005114 const unsigned I = NextToken();
5115 if (E->getLocStart().isValid() && D->getLocation().isValid() &&
5116 E->getLocStart() == D->getLocation() &&
5117 E->getLocStart() == GetTokenLoc(I)) {
5118 Cursors[I] = updateC;
5119 AdvanceToken();
5120 }
5121 }
5122 }
5123
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005124 // Visit children to get their cursor information.
5125 const unsigned BeforeChildren = NextToken();
5126 VisitChildren(cursor);
5127 const unsigned AfterChildren = NextToken();
5128
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005129 // Scan the tokens that are at the end of the cursor, but are not captured
5130 // but the child cursors.
5131 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
Ted Kremenek6db61092010-05-05 00:55:15 +00005132
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005133 // Scan the tokens that are at the beginning of the cursor, but are not
5134 // capture by the child cursors.
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005135 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
5136 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
5137 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00005138
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005139 Cursors[I] = cursor;
5140 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005141
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005142 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005143}
5144
Ted Kremenek6db61092010-05-05 00:55:15 +00005145static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
5146 CXCursor parent,
5147 CXClientData client_data) {
5148 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
5149}
5150
Ted Kremenek6628a612011-03-18 22:51:30 +00005151namespace {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005152
5153/// \brief Uses the macro expansions in the preprocessing record to find
5154/// and mark tokens that are macro arguments. This info is used by the
5155/// AnnotateTokensWorker.
5156class MarkMacroArgTokensVisitor {
5157 SourceManager &SM;
5158 CXToken *Tokens;
5159 unsigned NumTokens;
5160 unsigned CurIdx;
5161
5162public:
5163 MarkMacroArgTokensVisitor(SourceManager &SM,
5164 CXToken *tokens, unsigned numTokens)
5165 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
5166
5167 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
5168 if (cursor.kind != CXCursor_MacroExpansion)
5169 return CXChildVisit_Continue;
5170
5171 SourceRange macroRange = getCursorMacroExpansion(cursor)->getSourceRange();
5172 if (macroRange.getBegin() == macroRange.getEnd())
5173 return CXChildVisit_Continue; // it's not a function macro.
5174
5175 for (; CurIdx < NumTokens; ++CurIdx) {
5176 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
5177 macroRange.getBegin()))
5178 break;
5179 }
5180
5181 if (CurIdx == NumTokens)
5182 return CXChildVisit_Break;
5183
5184 for (; CurIdx < NumTokens; ++CurIdx) {
5185 SourceLocation tokLoc = getTokenLoc(CurIdx);
5186 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
5187 break;
5188
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00005189 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005190 }
5191
5192 if (CurIdx == NumTokens)
5193 return CXChildVisit_Break;
5194
5195 return CXChildVisit_Continue;
5196 }
5197
5198private:
5199 SourceLocation getTokenLoc(unsigned tokI) {
5200 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
5201 }
5202
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00005203 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005204 // The third field is reserved and currently not used. Use it here
5205 // to mark macro arg expanded tokens with their expanded locations.
5206 Tokens[tokI].int_data[3] = loc.getRawEncoding();
5207 }
5208};
5209
5210} // end anonymous namespace
5211
5212static CXChildVisitResult
5213MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
5214 CXClientData client_data) {
5215 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
5216 parent);
5217}
5218
5219namespace {
Ted Kremenek6628a612011-03-18 22:51:30 +00005220 struct clang_annotateTokens_Data {
5221 CXTranslationUnit TU;
5222 ASTUnit *CXXUnit;
5223 CXToken *Tokens;
5224 unsigned NumTokens;
5225 CXCursor *Cursors;
5226 };
5227}
5228
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005229static void annotatePreprocessorTokens(CXTranslationUnit TU,
5230 SourceRange RegionOfInterest,
5231 AnnotateTokensData &Annotated) {
5232 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
5233
5234 SourceManager &SourceMgr = CXXUnit->getSourceManager();
5235 std::pair<FileID, unsigned> BeginLocInfo
5236 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
5237 std::pair<FileID, unsigned> EndLocInfo
5238 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
5239
5240 if (BeginLocInfo.first != EndLocInfo.first)
5241 return;
5242
5243 StringRef Buffer;
5244 bool Invalid = false;
5245 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
5246 if (Buffer.empty() || Invalid)
5247 return;
5248
5249 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
David Blaikie4e4d0842012-03-11 07:00:24 +00005250 CXXUnit->getASTContext().getLangOpts(),
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005251 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
5252 Buffer.end());
5253 Lex.SetCommentRetentionState(true);
5254
5255 // Lex tokens in raw mode until we hit the end of the range, to avoid
5256 // entering #includes or expanding macros.
5257 while (true) {
5258 Token Tok;
5259 Lex.LexFromRawLexer(Tok);
5260
5261 reprocess:
5262 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
5263 // We have found a preprocessing directive. Gobble it up so that we
5264 // don't see it while preprocessing these tokens later, but keep track
5265 // of all of the token locations inside this preprocessing directive so
5266 // that we can annotate them appropriately.
5267 //
5268 // FIXME: Some simple tests here could identify macro definitions and
5269 // #undefs, to provide specific cursor kinds for those.
5270 SmallVector<SourceLocation, 32> Locations;
5271 do {
5272 Locations.push_back(Tok.getLocation());
5273 Lex.LexFromRawLexer(Tok);
5274 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
5275
5276 using namespace cxcursor;
5277 CXCursor Cursor
5278 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
5279 Locations.back()),
5280 TU);
5281 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
5282 Annotated[Locations[I].getRawEncoding()] = Cursor;
5283 }
5284
5285 if (Tok.isAtStartOfLine())
5286 goto reprocess;
5287
5288 continue;
5289 }
5290
5291 if (Tok.is(tok::eof))
5292 break;
5293 }
5294}
5295
Ted Kremenekab979612010-11-11 08:05:23 +00005296// This gets run a separate thread to avoid stack blowout.
Ted Kremenek6628a612011-03-18 22:51:30 +00005297static void clang_annotateTokensImpl(void *UserData) {
5298 CXTranslationUnit TU = ((clang_annotateTokens_Data*)UserData)->TU;
5299 ASTUnit *CXXUnit = ((clang_annotateTokens_Data*)UserData)->CXXUnit;
5300 CXToken *Tokens = ((clang_annotateTokens_Data*)UserData)->Tokens;
5301 const unsigned NumTokens = ((clang_annotateTokens_Data*)UserData)->NumTokens;
5302 CXCursor *Cursors = ((clang_annotateTokens_Data*)UserData)->Cursors;
5303
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00005304 CIndexer *CXXIdx = (CIndexer*)TU->CIdx;
5305 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
Argyrios Kyrtzidis81b5ac32012-03-28 02:49:54 +00005306 setThreadBackgroundPriority();
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00005307
Ted Kremenek6628a612011-03-18 22:51:30 +00005308 // Determine the region of interest, which contains all of the tokens.
5309 SourceRange RegionOfInterest;
5310 RegionOfInterest.setBegin(
5311 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
5312 RegionOfInterest.setEnd(
5313 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
5314 Tokens[NumTokens-1])));
5315
5316 // A mapping from the source locations found when re-lexing or traversing the
5317 // region of interest to the corresponding cursors.
5318 AnnotateTokensData Annotated;
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005319
Ted Kremenek6628a612011-03-18 22:51:30 +00005320 // Relex the tokens within the source range to look for preprocessing
5321 // directives.
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005322 annotatePreprocessorTokens(TU, RegionOfInterest, Annotated);
Ted Kremenek6628a612011-03-18 22:51:30 +00005323
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005324 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
5325 // Search and mark tokens that are macro argument expansions.
5326 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
5327 Tokens, NumTokens);
5328 CursorVisitor MacroArgMarker(TU,
5329 MarkMacroArgTokensVisitorDelegate, &Visitor,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00005330 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00005331 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00005332 RegionOfInterest);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005333 MacroArgMarker.visitPreprocessedEntitiesInRegion();
5334 }
5335
Ted Kremenek6628a612011-03-18 22:51:30 +00005336 // Annotate all of the source locations in the region of interest that map to
5337 // a specific cursor.
5338 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
5339 TU, RegionOfInterest);
5340
5341 // FIXME: We use a ridiculous stack size here because the data-recursion
5342 // algorithm uses a large stack frame than the non-data recursive version,
5343 // and AnnotationTokensWorker currently transforms the data-recursion
5344 // algorithm back into a traditional recursion by explicitly calling
5345 // VisitChildren(). We will need to remove this explicit recursive call.
5346 W.AnnotateTokens();
5347
5348 // If we ran into any entities that involve context-sensitive keywords,
5349 // take another pass through the tokens to mark them as such.
5350 if (W.hasContextSensitiveKeywords()) {
5351 for (unsigned I = 0; I != NumTokens; ++I) {
5352 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
5353 continue;
5354
5355 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
5356 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5357 if (ObjCPropertyDecl *Property
5358 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
5359 if (Property->getPropertyAttributesAsWritten() != 0 &&
5360 llvm::StringSwitch<bool>(II->getName())
5361 .Case("readonly", true)
5362 .Case("assign", true)
John McCallf85e1932011-06-15 23:02:42 +00005363 .Case("unsafe_unretained", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00005364 .Case("readwrite", true)
5365 .Case("retain", true)
5366 .Case("copy", true)
5367 .Case("nonatomic", true)
5368 .Case("atomic", true)
5369 .Case("getter", true)
5370 .Case("setter", true)
John McCallf85e1932011-06-15 23:02:42 +00005371 .Case("strong", true)
5372 .Case("weak", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00005373 .Default(false))
5374 Tokens[I].int_data[0] = CXToken_Keyword;
5375 }
5376 continue;
5377 }
5378
5379 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
5380 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
5381 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5382 if (llvm::StringSwitch<bool>(II->getName())
5383 .Case("in", true)
5384 .Case("out", true)
5385 .Case("inout", true)
5386 .Case("oneway", true)
5387 .Case("bycopy", true)
5388 .Case("byref", true)
5389 .Default(false))
5390 Tokens[I].int_data[0] = CXToken_Keyword;
5391 continue;
5392 }
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00005393
5394 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
5395 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
5396 Tokens[I].int_data[0] = CXToken_Keyword;
Ted Kremenek6628a612011-03-18 22:51:30 +00005397 continue;
5398 }
5399 }
5400 }
Ted Kremenekab979612010-11-11 08:05:23 +00005401}
5402
Ted Kremenek6db61092010-05-05 00:55:15 +00005403extern "C" {
5404
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005405void clang_annotateTokens(CXTranslationUnit TU,
5406 CXToken *Tokens, unsigned NumTokens,
5407 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005408
5409 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005410 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005411
Douglas Gregor4419b672010-10-21 06:10:04 +00005412 // Any token we don't specifically annotate will have a NULL cursor.
5413 CXCursor C = clang_getNullCursor();
5414 for (unsigned I = 0; I != NumTokens; ++I)
5415 Cursors[I] = C;
5416
Ted Kremeneka60ed472010-11-16 08:15:36 +00005417 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor4419b672010-10-21 06:10:04 +00005418 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005419 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005420
Douglas Gregorbdf60622010-03-05 21:16:25 +00005421 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenek6628a612011-03-18 22:51:30 +00005422
5423 clang_annotateTokens_Data data = { TU, CXXUnit, Tokens, NumTokens, Cursors };
Ted Kremenekab979612010-11-11 08:05:23 +00005424 llvm::CrashRecoveryContext CRC;
Ted Kremenek6628a612011-03-18 22:51:30 +00005425 if (!RunSafely(CRC, clang_annotateTokensImpl, &data,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005426 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00005427 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
5428 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005429}
Ted Kremenek6628a612011-03-18 22:51:30 +00005430
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005431} // end: extern "C"
5432
5433//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00005434// Operations for querying linkage of a cursor.
5435//===----------------------------------------------------------------------===//
5436
5437extern "C" {
5438CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00005439 if (!clang_isDeclaration(cursor.kind))
5440 return CXLinkage_Invalid;
5441
Ted Kremenek16b42592010-03-03 06:36:57 +00005442 Decl *D = cxcursor::getCursorDecl(cursor);
5443 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
5444 switch (ND->getLinkage()) {
5445 case NoLinkage: return CXLinkage_NoLinkage;
5446 case InternalLinkage: return CXLinkage_Internal;
5447 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
5448 case ExternalLinkage: return CXLinkage_External;
5449 };
5450
5451 return CXLinkage_Invalid;
5452}
5453} // end: extern "C"
5454
5455//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005456// Operations for querying language of a cursor.
5457//===----------------------------------------------------------------------===//
5458
5459static CXLanguageKind getDeclLanguage(const Decl *D) {
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00005460 if (!D)
5461 return CXLanguage_C;
5462
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005463 switch (D->getKind()) {
5464 default:
5465 break;
5466 case Decl::ImplicitParam:
5467 case Decl::ObjCAtDefsField:
5468 case Decl::ObjCCategory:
5469 case Decl::ObjCCategoryImpl:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005470 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005471 case Decl::ObjCImplementation:
5472 case Decl::ObjCInterface:
5473 case Decl::ObjCIvar:
5474 case Decl::ObjCMethod:
5475 case Decl::ObjCProperty:
5476 case Decl::ObjCPropertyImpl:
5477 case Decl::ObjCProtocol:
5478 return CXLanguage_ObjC;
5479 case Decl::CXXConstructor:
5480 case Decl::CXXConversion:
5481 case Decl::CXXDestructor:
5482 case Decl::CXXMethod:
5483 case Decl::CXXRecord:
5484 case Decl::ClassTemplate:
5485 case Decl::ClassTemplatePartialSpecialization:
5486 case Decl::ClassTemplateSpecialization:
5487 case Decl::Friend:
5488 case Decl::FriendTemplate:
5489 case Decl::FunctionTemplate:
5490 case Decl::LinkageSpec:
5491 case Decl::Namespace:
5492 case Decl::NamespaceAlias:
5493 case Decl::NonTypeTemplateParm:
5494 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005495 case Decl::TemplateTemplateParm:
5496 case Decl::TemplateTypeParm:
5497 case Decl::UnresolvedUsingTypename:
5498 case Decl::UnresolvedUsingValue:
5499 case Decl::Using:
5500 case Decl::UsingDirective:
5501 case Decl::UsingShadow:
5502 return CXLanguage_CPlusPlus;
5503 }
5504
5505 return CXLanguage_C;
5506}
5507
5508extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00005509
5510enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
5511 if (clang_isDeclaration(cursor.kind))
5512 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005513 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Douglas Gregor58ddb602010-08-23 23:00:57 +00005514 return CXAvailability_Available;
5515
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005516 switch (D->getAvailability()) {
5517 case AR_Available:
5518 case AR_NotYetIntroduced:
5519 return CXAvailability_Available;
5520
5521 case AR_Deprecated:
Douglas Gregor58ddb602010-08-23 23:00:57 +00005522 return CXAvailability_Deprecated;
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005523
5524 case AR_Unavailable:
5525 return CXAvailability_NotAvailable;
5526 }
Douglas Gregor58ddb602010-08-23 23:00:57 +00005527 }
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005528
Douglas Gregor58ddb602010-08-23 23:00:57 +00005529 return CXAvailability_Available;
5530}
5531
Douglas Gregorcc889662012-05-08 00:14:45 +00005532static CXVersion convertVersion(VersionTuple In) {
5533 CXVersion Out = { -1, -1, -1 };
5534 if (In.empty())
5535 return Out;
5536
5537 Out.Major = In.getMajor();
5538
5539 if (llvm::Optional<unsigned> Minor = In.getMinor())
5540 Out.Minor = *Minor;
5541 else
5542 return Out;
5543
5544 if (llvm::Optional<unsigned> Subminor = In.getSubminor())
5545 Out.Subminor = *Subminor;
5546
5547 return Out;
5548}
5549
5550int clang_getCursorPlatformAvailability(CXCursor cursor,
5551 int *always_deprecated,
5552 CXString *deprecated_message,
5553 int *always_unavailable,
5554 CXString *unavailable_message,
5555 CXPlatformAvailability *availability,
5556 int availability_size) {
5557 if (always_deprecated)
5558 *always_deprecated = 0;
5559 if (deprecated_message)
5560 *deprecated_message = cxstring::createCXString("", /*DupString=*/false);
5561 if (always_unavailable)
5562 *always_unavailable = 0;
5563 if (unavailable_message)
5564 *unavailable_message = cxstring::createCXString("", /*DupString=*/false);
5565
5566 if (!clang_isDeclaration(cursor.kind))
5567 return 0;
5568
5569 Decl *D = cxcursor::getCursorDecl(cursor);
5570 if (!D)
5571 return 0;
5572
5573 int N = 0;
5574 for (Decl::attr_iterator A = D->attr_begin(), AEnd = D->attr_end(); A != AEnd;
5575 ++A) {
5576 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(*A)) {
5577 if (always_deprecated)
5578 *always_deprecated = 1;
5579 if (deprecated_message)
5580 *deprecated_message = cxstring::createCXString(Deprecated->getMessage());
5581 continue;
5582 }
5583
5584 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(*A)) {
5585 if (always_unavailable)
5586 *always_unavailable = 1;
5587 if (unavailable_message) {
5588 *unavailable_message
5589 = cxstring::createCXString(Unavailable->getMessage());
5590 }
5591 continue;
5592 }
5593
5594 if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(*A)) {
5595 if (N < availability_size) {
5596 availability[N].Platform
5597 = cxstring::createCXString(Avail->getPlatform()->getName());
5598 availability[N].Introduced = convertVersion(Avail->getIntroduced());
5599 availability[N].Deprecated = convertVersion(Avail->getDeprecated());
5600 availability[N].Obsoleted = convertVersion(Avail->getObsoleted());
5601 availability[N].Unavailable = Avail->getUnavailable();
5602 availability[N].Message = cxstring::createCXString(Avail->getMessage());
5603 }
5604 ++N;
5605 }
5606 }
5607
5608 return N;
5609}
5610
5611void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) {
5612 clang_disposeString(availability->Platform);
5613 clang_disposeString(availability->Message);
5614}
5615
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005616CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
5617 if (clang_isDeclaration(cursor.kind))
5618 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
5619
5620 return CXLanguage_Invalid;
5621}
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005622
5623 /// \brief If the given cursor is the "templated" declaration
5624 /// descibing a class or function template, return the class or
5625 /// function template.
5626static Decl *maybeGetTemplateCursor(Decl *D) {
5627 if (!D)
5628 return 0;
5629
5630 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
5631 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
5632 return FunTmpl;
5633
5634 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
5635 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
5636 return ClassTmpl;
5637
5638 return D;
5639}
5640
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005641CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
5642 if (clang_isDeclaration(cursor.kind)) {
5643 if (Decl *D = getCursorDecl(cursor)) {
5644 DeclContext *DC = D->getDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005645 if (!DC)
5646 return clang_getNullCursor();
5647
5648 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5649 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005650 }
5651 }
5652
5653 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
5654 if (Decl *D = getCursorDecl(cursor))
Ted Kremeneka60ed472010-11-16 08:15:36 +00005655 return MakeCXCursor(D, getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005656 }
5657
5658 return clang_getNullCursor();
5659}
5660
5661CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
5662 if (clang_isDeclaration(cursor.kind)) {
5663 if (Decl *D = getCursorDecl(cursor)) {
5664 DeclContext *DC = D->getLexicalDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005665 if (!DC)
5666 return clang_getNullCursor();
5667
5668 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5669 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005670 }
5671 }
5672
5673 // FIXME: Note that we can't easily compute the lexical context of a
5674 // statement or expression, so we return nothing.
5675 return clang_getNullCursor();
5676}
5677
Douglas Gregorecdcb882010-10-20 22:00:55 +00005678CXFile clang_getIncludedFile(CXCursor cursor) {
5679 if (cursor.kind != CXCursor_InclusionDirective)
5680 return 0;
5681
5682 InclusionDirective *ID = getCursorInclusionDirective(cursor);
5683 return (void *)ID->getFile();
5684}
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +00005685
5686CXSourceRange clang_Cursor_getCommentRange(CXCursor C) {
5687 if (!clang_isDeclaration(C.kind))
5688 return clang_getNullRange();
5689
5690 const Decl *D = getCursorDecl(C);
5691 ASTContext &Context = getCursorContext(C);
5692 const RawComment *RC = Context.getRawCommentForDecl(D);
5693 if (!RC)
5694 return clang_getNullRange();
5695
5696 return cxloc::translateSourceRange(Context, RC->getSourceRange());
5697}
5698
5699CXString clang_Cursor_getRawCommentText(CXCursor C) {
5700 if (!clang_isDeclaration(C.kind))
5701 return createCXString((const char *) NULL);
5702
5703 const Decl *D = getCursorDecl(C);
5704 ASTContext &Context = getCursorContext(C);
5705 const RawComment *RC = Context.getRawCommentForDecl(D);
5706 StringRef RawText = RC ? RC->getRawText(Context.getSourceManager()) :
5707 StringRef();
5708
5709 // Don't duplicate the string because RawText points directly into source
5710 // code.
5711 return createCXString(RawText, false);
5712}
5713
Dmitri Gribenko2d44d772012-06-26 20:39:18 +00005714CXString clang_Cursor_getBriefCommentText(CXCursor C) {
5715 if (!clang_isDeclaration(C.kind))
5716 return createCXString((const char *) NULL);
5717
5718 const Decl *D = getCursorDecl(C);
5719 const ASTContext &Context = getCursorContext(C);
5720 const RawComment *RC = Context.getRawCommentForDecl(D);
5721
Dmitri Gribenko8376f592012-06-28 16:25:36 +00005722 if (RC) {
Dmitri Gribenko2d44d772012-06-26 20:39:18 +00005723 StringRef BriefText = RC->getBriefText(Context);
5724
5725 // Don't duplicate the string because RawComment ensures that this memory
5726 // will not go away.
5727 return createCXString(BriefText, false);
5728 }
5729
5730 return createCXString((const char *) NULL);
5731}
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005732
Dmitri Gribenkoae99b752012-07-20 21:34:34 +00005733CXComment clang_Cursor_getParsedComment(CXCursor C) {
5734 if (!clang_isDeclaration(C.kind))
5735 return cxcomment::createCXComment(NULL);
5736
5737 const Decl *D = getCursorDecl(C);
5738 const ASTContext &Context = getCursorContext(C);
5739 const comments::FullComment *FC = Context.getCommentForDecl(D);
5740
5741 return cxcomment::createCXComment(FC);
5742}
5743
Dmitri Gribenkob619e782012-07-17 00:17:45 +00005744} // end: extern "C"
5745
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005746//===----------------------------------------------------------------------===//
5747// C++ AST instrospection.
5748//===----------------------------------------------------------------------===//
5749
5750extern "C" {
5751unsigned clang_CXXMethod_isStatic(CXCursor C) {
5752 if (!clang_isDeclaration(C.kind))
5753 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00005754
5755 CXXMethodDecl *Method = 0;
5756 Decl *D = cxcursor::getCursorDecl(C);
5757 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5758 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5759 else
5760 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5761 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00005762}
Ted Kremenekb12903e2010-05-18 22:32:15 +00005763
Douglas Gregor211924b2011-05-12 15:17:24 +00005764unsigned clang_CXXMethod_isVirtual(CXCursor C) {
5765 if (!clang_isDeclaration(C.kind))
5766 return 0;
5767
5768 CXXMethodDecl *Method = 0;
5769 Decl *D = cxcursor::getCursorDecl(C);
5770 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5771 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5772 else
5773 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5774 return (Method && Method->isVirtual()) ? 1 : 0;
5775}
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005776} // end: extern "C"
5777
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005778//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00005779// Attribute introspection.
5780//===----------------------------------------------------------------------===//
5781
5782extern "C" {
5783CXType clang_getIBOutletCollectionType(CXCursor C) {
5784 if (C.kind != CXCursor_IBOutletCollectionAttr)
Ted Kremeneka60ed472010-11-16 08:15:36 +00005785 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005786
5787 IBOutletCollectionAttr *A =
5788 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
5789
Argyrios Kyrtzidis18aa2ff2011-09-13 18:49:52 +00005790 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005791}
5792} // end: extern "C"
5793
5794//===----------------------------------------------------------------------===//
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005795// Inspecting memory usage.
5796//===----------------------------------------------------------------------===//
5797
Ted Kremenekf7870022011-04-20 16:41:07 +00005798typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005799
Ted Kremenekf7870022011-04-20 16:41:07 +00005800static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
5801 enum CXTUResourceUsageKind k,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005802 unsigned long amount) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005803 CXTUResourceUsageEntry entry = { k, amount };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005804 entries.push_back(entry);
5805}
5806
5807extern "C" {
5808
Ted Kremenekf7870022011-04-20 16:41:07 +00005809const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005810 const char *str = "";
5811 switch (kind) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005812 case CXTUResourceUsage_AST:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005813 str = "ASTContext: expressions, declarations, and types";
5814 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005815 case CXTUResourceUsage_Identifiers:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005816 str = "ASTContext: identifiers";
5817 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005818 case CXTUResourceUsage_Selectors:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005819 str = "ASTContext: selectors";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005820 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005821 case CXTUResourceUsage_GlobalCompletionResults:
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005822 str = "Code completion: cached global results";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005823 break;
Ted Kremenek457aaf02011-04-28 04:10:31 +00005824 case CXTUResourceUsage_SourceManagerContentCache:
5825 str = "SourceManager: content cache allocator";
5826 break;
Ted Kremenekba29bd22011-04-28 04:53:38 +00005827 case CXTUResourceUsage_AST_SideTables:
5828 str = "ASTContext: side tables";
5829 break;
Ted Kremenekf61b8312011-04-28 20:36:42 +00005830 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
5831 str = "SourceManager: malloc'ed memory buffers";
5832 break;
5833 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
5834 str = "SourceManager: mmap'ed memory buffers";
5835 break;
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005836 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
5837 str = "ExternalASTSource: malloc'ed memory buffers";
5838 break;
5839 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
5840 str = "ExternalASTSource: mmap'ed memory buffers";
5841 break;
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005842 case CXTUResourceUsage_Preprocessor:
5843 str = "Preprocessor: malloc'ed memory";
5844 break;
5845 case CXTUResourceUsage_PreprocessingRecord:
5846 str = "Preprocessor: PreprocessingRecord";
5847 break;
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005848 case CXTUResourceUsage_SourceManager_DataStructures:
5849 str = "SourceManager: data structures and tables";
5850 break;
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005851 case CXTUResourceUsage_Preprocessor_HeaderSearch:
5852 str = "Preprocessor: header search tables";
5853 break;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005854 }
5855 return str;
5856}
5857
Ted Kremenekf7870022011-04-20 16:41:07 +00005858CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005859 if (!TU) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005860 CXTUResourceUsage usage = { (void*) 0, 0, 0 };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005861 return usage;
5862 }
5863
5864 ASTUnit *astUnit = static_cast<ASTUnit*>(TU->TUData);
Dylan Noblesmith1e4c01b2012-02-13 12:32:21 +00005865 OwningPtr<MemUsageEntries> entries(new MemUsageEntries());
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005866 ASTContext &astContext = astUnit->getASTContext();
5867
5868 // How much memory is used by AST nodes and types?
Ted Kremenekf7870022011-04-20 16:41:07 +00005869 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005870 (unsigned long) astContext.getASTAllocatedMemory());
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005871
5872 // How much memory is used by identifiers?
Ted Kremenekf7870022011-04-20 16:41:07 +00005873 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005874 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
5875
5876 // How much memory is used for selectors?
Ted Kremenekf7870022011-04-20 16:41:07 +00005877 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005878 (unsigned long) astContext.Selectors.getTotalMemory());
5879
Ted Kremenekba29bd22011-04-28 04:53:38 +00005880 // How much memory is used by ASTContext's side tables?
5881 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
5882 (unsigned long) astContext.getSideTableAllocatedMemory());
5883
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005884 // How much memory is used for caching global code completion results?
5885 unsigned long completionBytes = 0;
5886 if (GlobalCodeCompletionAllocator *completionAllocator =
5887 astUnit->getCachedCompletionAllocator().getPtr()) {
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005888 completionBytes = completionAllocator->getTotalMemory();
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005889 }
Ted Kremenek457aaf02011-04-28 04:10:31 +00005890 createCXTUResourceUsageEntry(*entries,
5891 CXTUResourceUsage_GlobalCompletionResults,
5892 completionBytes);
5893
5894 // How much memory is being used by SourceManager's content cache?
5895 createCXTUResourceUsageEntry(*entries,
5896 CXTUResourceUsage_SourceManagerContentCache,
5897 (unsigned long) astContext.getSourceManager().getContentCacheSize());
Ted Kremenekf61b8312011-04-28 20:36:42 +00005898
5899 // How much memory is being used by the MemoryBuffer's in SourceManager?
5900 const SourceManager::MemoryBufferSizes &srcBufs =
5901 astUnit->getSourceManager().getMemoryBufferSizes();
5902
5903 createCXTUResourceUsageEntry(*entries,
5904 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
5905 (unsigned long) srcBufs.malloc_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005906 createCXTUResourceUsageEntry(*entries,
Ted Kremenekf61b8312011-04-28 20:36:42 +00005907 CXTUResourceUsage_SourceManager_Membuffer_MMap,
5908 (unsigned long) srcBufs.mmap_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005909 createCXTUResourceUsageEntry(*entries,
5910 CXTUResourceUsage_SourceManager_DataStructures,
5911 (unsigned long) astContext.getSourceManager()
5912 .getDataStructureSizes());
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005913
5914 // How much memory is being used by the ExternalASTSource?
5915 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
5916 const ExternalASTSource::MemoryBufferSizes &sizes =
5917 esrc->getMemoryBufferSizes();
5918
5919 createCXTUResourceUsageEntry(*entries,
5920 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
5921 (unsigned long) sizes.malloc_bytes);
5922 createCXTUResourceUsageEntry(*entries,
5923 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
5924 (unsigned long) sizes.mmap_bytes);
5925 }
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005926
5927 // How much memory is being used by the Preprocessor?
5928 Preprocessor &pp = astUnit->getPreprocessor();
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005929 createCXTUResourceUsageEntry(*entries,
5930 CXTUResourceUsage_Preprocessor,
Argyrios Kyrtzidisc5c5e922011-06-29 22:20:04 +00005931 pp.getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005932
5933 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
5934 createCXTUResourceUsageEntry(*entries,
5935 CXTUResourceUsage_PreprocessingRecord,
5936 pRec->getTotalMemory());
5937 }
5938
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005939 createCXTUResourceUsageEntry(*entries,
5940 CXTUResourceUsage_Preprocessor_HeaderSearch,
5941 pp.getHeaderSearchInfo().getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005942
Ted Kremenekf7870022011-04-20 16:41:07 +00005943 CXTUResourceUsage usage = { (void*) entries.get(),
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005944 (unsigned) entries->size(),
5945 entries->size() ? &(*entries)[0] : 0 };
5946 entries.take();
5947 return usage;
5948}
5949
Ted Kremenekf7870022011-04-20 16:41:07 +00005950void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005951 if (usage.data)
5952 delete (MemUsageEntries*) usage.data;
5953}
5954
5955} // end extern "C"
5956
Douglas Gregor6df78732011-05-05 20:27:22 +00005957void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
5958 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
5959 for (unsigned I = 0; I != Usage.numEntries; ++I)
5960 fprintf(stderr, " %s: %lu\n",
5961 clang_getTUResourceUsageName(Usage.entries[I].kind),
5962 Usage.entries[I].amount);
5963
5964 clang_disposeCXTUResourceUsage(Usage);
5965}
5966
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005967//===----------------------------------------------------------------------===//
Ted Kremenek04bb7162010-01-22 22:44:15 +00005968// Misc. utility functions.
5969//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00005970
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00005971/// Default to using an 8 MB stack size on "safety" threads.
5972static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005973
5974namespace clang {
5975
5976bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005977 void (*Fn)(void*), void *UserData,
5978 unsigned Size) {
5979 if (!Size)
5980 Size = GetSafetyThreadStackSize();
5981 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005982 return CRC.RunSafelyOnThread(Fn, UserData, Size);
5983 return CRC.RunSafely(Fn, UserData);
5984}
5985
5986unsigned GetSafetyThreadStackSize() {
5987 return SafetyStackThreadSize;
5988}
5989
5990void SetSafetyThreadStackSize(unsigned Value) {
5991 SafetyStackThreadSize = Value;
5992}
5993
Argyrios Kyrtzidis8e7c48a2012-03-28 02:49:50 +00005994}
5995
Argyrios Kyrtzidis81b5ac32012-03-28 02:49:54 +00005996void clang::setThreadBackgroundPriority() {
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00005997 // FIXME: Move to llvm/Support and make it cross-platform.
5998#ifdef __APPLE__
5999 setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG);
6000#endif
6001}
6002
Argyrios Kyrtzidis97934282012-04-11 03:52:18 +00006003void cxindex::printDiagsToStderr(ASTUnit *Unit) {
6004 if (!Unit)
6005 return;
6006
6007 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
6008 DEnd = Unit->stored_diag_end();
6009 D != DEnd; ++D) {
6010 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOpts());
6011 CXString Msg = clang_formatDiagnostic(&Diag,
6012 clang_defaultDiagnosticDisplayOptions());
6013 fprintf(stderr, "%s\n", clang_getCString(Msg));
6014 clang_disposeString(Msg);
6015 }
6016#ifdef LLVM_ON_WIN32
6017 // On Windows, force a flush, since there may be multiple copies of
6018 // stderr and stdout in the file system, all with different buffers
6019 // but writing to the same device.
6020 fflush(stderr);
6021#endif
6022}
6023
Ted Kremenek04bb7162010-01-22 22:44:15 +00006024extern "C" {
6025
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00006026CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00006027 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00006028}
6029
6030} // end: extern "C"
Ted Kremenek59fc1e52011-04-18 22:47:10 +00006031