blob: abe3eea4afa618486bf54221812baff2f8e23821 [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///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +0000148/// \param CheckedRegionOfInterest if true, then the caller already checked
149/// that this cursor is within the region of interest.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000150///
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
Argyrios Kyrtzidisd579dd52012-09-01 18:27:30 +0000185 case CXChildVisit_Recurse: {
186 bool ret = VisitChildren(Cursor);
187 if (PostChildrenVisitor)
188 if (PostChildrenVisitor(Cursor, ClientData))
189 return true;
190 return ret;
191 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000192 }
193
David Blaikie7530c032012-01-17 06:56:22 +0000194 llvm_unreachable("Invalid CXChildVisitResult!");
Douglas Gregorb1373d02010-01-20 20:59:29 +0000195}
196
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000197static bool visitPreprocessedEntitiesInRange(SourceRange R,
198 PreprocessingRecord &PPRec,
199 CursorVisitor &Visitor) {
200 SourceManager &SM = Visitor.getASTUnit()->getSourceManager();
201 FileID FID;
202
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +0000203 if (!Visitor.shouldVisitIncludedEntities()) {
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000204 // If the begin/end of the range lie in the same FileID, do the optimization
205 // where we skip preprocessed entities that do not come from the same FileID.
Argyrios Kyrtzidisacca4112011-12-21 16:56:38 +0000206 FID = SM.getFileID(SM.getFileLoc(R.getBegin()));
207 if (FID != SM.getFileID(SM.getFileLoc(R.getEnd())))
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000208 FID = FileID();
209 }
210
211 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
212 Entities = PPRec.getPreprocessedEntitiesInRange(R);
213 return Visitor.visitPreprocessedEntities(Entities.first, Entities.second,
214 PPRec, FID);
215}
216
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000217void CursorVisitor::visitFileRegion() {
218 if (RegionOfInterest.isInvalid())
219 return;
220
221 ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData);
222 SourceManager &SM = Unit->getSourceManager();
223
224 std::pair<FileID, unsigned>
225 Begin = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getBegin())),
226 End = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getEnd()));
227
228 if (End.first != Begin.first) {
229 // If the end does not reside in the same file, try to recover by
230 // picking the end of the file of begin location.
231 End.first = Begin.first;
232 End.second = SM.getFileIDSize(Begin.first);
233 }
234
235 assert(Begin.first == End.first);
236 if (Begin.second > End.second)
237 return;
238
239 FileID File = Begin.first;
240 unsigned Offset = Begin.second;
241 unsigned Length = End.second - Begin.second;
242
Argyrios Kyrtzidisb49e7282011-11-29 03:14:11 +0000243 if (!VisitDeclsOnly && !VisitPreprocessorLast)
244 if (visitPreprocessedEntitiesInRegion())
245 return; // visitation break.
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000246
247 visitDeclsFromFileRegion(File, Offset, Length);
248
Argyrios Kyrtzidisb49e7282011-11-29 03:14:11 +0000249 if (!VisitDeclsOnly && VisitPreprocessorLast)
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000250 visitPreprocessedEntitiesInRegion();
251}
252
Argyrios Kyrtzidise2079cf2011-11-16 08:58:54 +0000253static bool isInLexicalContext(Decl *D, DeclContext *DC) {
254 if (!DC)
255 return false;
256
257 for (DeclContext *DeclDC = D->getLexicalDeclContext();
258 DeclDC; DeclDC = DeclDC->getLexicalParent()) {
259 if (DeclDC == DC)
260 return true;
261 }
262 return false;
263}
264
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000265void CursorVisitor::visitDeclsFromFileRegion(FileID File,
266 unsigned Offset, unsigned Length) {
267 ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData);
268 SourceManager &SM = Unit->getSourceManager();
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000269 SourceRange Range = RegionOfInterest;
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000270
271 SmallVector<Decl *, 16> Decls;
272 Unit->findFileRegionDecls(File, Offset, Length, Decls);
273
274 // If we didn't find any file level decls for the file, try looking at the
275 // file that it was included from.
Argyrios Kyrtzidisc14a03d2011-11-23 20:27:36 +0000276 while (Decls.empty() || Decls.front()->isTopLevelDeclInObjCContainer()) {
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000277 bool Invalid = false;
278 const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid);
279 if (Invalid)
280 return;
281
282 SourceLocation Outer;
283 if (SLEntry.isFile())
284 Outer = SLEntry.getFile().getIncludeLoc();
285 else
286 Outer = SLEntry.getExpansion().getExpansionLocStart();
287 if (Outer.isInvalid())
288 return;
289
290 llvm::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer);
291 Length = 0;
292 Unit->findFileRegionDecls(File, Offset, Length, Decls);
293 }
294
295 assert(!Decls.empty());
296
297 bool VisitedAtLeastOnce = false;
Argyrios Kyrtzidise2079cf2011-11-16 08:58:54 +0000298 DeclContext *CurDC = 0;
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000299 SmallVector<Decl *, 16>::iterator DIt = Decls.begin();
300 for (SmallVector<Decl *, 16>::iterator DE = Decls.end(); DIt != DE; ++DIt) {
301 Decl *D = *DIt;
Argyrios Kyrtzidised8bef42011-11-28 22:38:07 +0000302 if (D->getSourceRange().isInvalid())
303 continue;
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000304
Argyrios Kyrtzidise2079cf2011-11-16 08:58:54 +0000305 if (isInLexicalContext(D, CurDC))
306 continue;
307
308 CurDC = dyn_cast<DeclContext>(D);
309
Argyrios Kyrtzidise2079cf2011-11-16 08:58:54 +0000310 if (TagDecl *TD = dyn_cast<TagDecl>(D))
311 if (!TD->isFreeStanding())
312 continue;
313
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000314 RangeComparisonResult CompRes = RangeCompare(SM, D->getSourceRange(),Range);
315 if (CompRes == RangeBefore)
316 continue;
317 if (CompRes == RangeAfter)
318 break;
319
320 assert(CompRes == RangeOverlap);
321 VisitedAtLeastOnce = true;
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +0000322
323 if (isa<ObjCContainerDecl>(D)) {
324 FileDI_current = &DIt;
325 FileDE_current = DE;
326 } else {
327 FileDI_current = 0;
328 }
329
Argyrios Kyrtzidisba986172011-11-03 19:02:28 +0000330 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000331 break;
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000332 }
333
334 if (VisitedAtLeastOnce)
335 return;
336
337 // No Decls overlapped with the range. Move up the lexical context until there
338 // is a context that contains the range or we reach the translation unit
339 // level.
340 DeclContext *DC = DIt == Decls.begin() ? (*DIt)->getLexicalDeclContext()
341 : (*(DIt-1))->getLexicalDeclContext();
342
343 while (DC && !DC->isTranslationUnit()) {
344 Decl *D = cast<Decl>(DC);
345 SourceRange CurDeclRange = D->getSourceRange();
346 if (CurDeclRange.isInvalid())
347 break;
348
349 if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) {
Argyrios Kyrtzidisba986172011-11-03 19:02:28 +0000350 Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true);
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000351 break;
352 }
353
354 DC = D->getLexicalDeclContext();
355 }
356}
357
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000358bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
Argyrios Kyrtzidisb49e7282011-11-29 03:14:11 +0000359 if (!AU->getPreprocessor().getPreprocessingRecord())
360 return false;
361
Douglas Gregor788f5a12010-03-20 00:41:21 +0000362 PreprocessingRecord &PPRec
Ted Kremeneka60ed472010-11-16 08:15:36 +0000363 = *AU->getPreprocessor().getPreprocessingRecord();
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000364 SourceManager &SM = AU->getSourceManager();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000365
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000366 if (RegionOfInterest.isValid()) {
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +0000367 SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000368 SourceLocation B = MappedRange.getBegin();
369 SourceLocation E = MappedRange.getEnd();
370
371 if (AU->isInPreambleFileID(B)) {
372 if (SM.isLoadedSourceLocation(E))
373 return visitPreprocessedEntitiesInRange(SourceRange(B, E),
374 PPRec, *this);
375
376 // Beginning of range lies in the preamble but it also extends beyond
377 // it into the main file. Split the range into 2 parts, one covering
378 // the preamble and another covering the main file. This allows subsequent
379 // calls to visitPreprocessedEntitiesInRange to accept a source range that
380 // lies in the same FileID, allowing it to skip preprocessed entities that
381 // do not come from the same FileID.
382 bool breaked =
383 visitPreprocessedEntitiesInRange(
384 SourceRange(B, AU->getEndOfPreambleFileID()),
385 PPRec, *this);
386 if (breaked) return true;
387 return visitPreprocessedEntitiesInRange(
388 SourceRange(AU->getStartOfMainFileID(), E),
389 PPRec, *this);
390 }
391
392 return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this);
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000393 }
394
Douglas Gregor788f5a12010-03-20 00:41:21 +0000395 bool OnlyLocalDecls
Douglas Gregor32038bb2010-12-21 19:07:48 +0000396 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
397
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000398 if (OnlyLocalDecls)
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000399 return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(),
400 PPRec);
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000401
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000402 return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec);
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000403}
404
405template<typename InputIterator>
406bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000407 InputIterator Last,
408 PreprocessingRecord &PPRec,
409 FileID FID) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000410 for (; First != Last; ++First) {
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000411 if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID))
412 continue;
413
414 PreprocessedEntity *PPE = *First;
415 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000416 if (Visit(MakeMacroExpansionCursor(ME, TU)))
417 return true;
418
419 continue;
420 }
421
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000422 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(PPE)) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000423 if (Visit(MakeMacroDefinitionCursor(MD, TU)))
424 return true;
425
426 continue;
427 }
428
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000429 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000430 if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
431 return true;
432
433 continue;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000434 }
435 }
436
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000437 return false;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000438}
439
Douglas Gregorb1373d02010-01-20 20:59:29 +0000440/// \brief Visit the children of the given cursor.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000441///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000442/// \returns true if the visitation should be aborted, false if it
443/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000444bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregorc314aa42011-03-02 19:17:03 +0000445 if (clang_isReference(Cursor.kind) &&
446 Cursor.kind != CXCursor_CXXBaseSpecifier) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000447 // By definition, references have no children.
448 return false;
449 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000450
451 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000452 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000453 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000454
Douglas Gregorb1373d02010-01-20 20:59:29 +0000455 if (clang_isDeclaration(Cursor.kind)) {
456 Decl *D = getCursorDecl(Cursor);
Douglas Gregor06d9b1a2011-04-14 21:41:34 +0000457 if (!D)
458 return false;
459
Ted Kremenek539311e2010-02-18 18:47:01 +0000460 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000461 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000462
Douglas Gregor06d9b1a2011-04-14 21:41:34 +0000463 if (clang_isStatement(Cursor.kind)) {
464 if (Stmt *S = getCursorStmt(Cursor))
465 return Visit(S);
466
467 return false;
468 }
469
470 if (clang_isExpression(Cursor.kind)) {
471 if (Expr *E = getCursorExpr(Cursor))
472 return Visit(E);
473
474 return false;
475 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000476
Douglas Gregorb1373d02010-01-20 20:59:29 +0000477 if (clang_isTranslationUnit(Cursor.kind)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000478 CXTranslationUnit tu = getCursorTU(Cursor);
479 ASTUnit *CXXUnit = static_cast<ASTUnit*>(tu->TUData);
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000480
481 int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
482 for (unsigned I = 0; I != 2; ++I) {
483 if (VisitOrder[I]) {
484 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
485 RegionOfInterest.isInvalid()) {
486 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
487 TLEnd = CXXUnit->top_level_end();
488 TL != TLEnd; ++TL) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000489 if (Visit(MakeCXCursor(*TL, tu, RegionOfInterest), true))
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000490 return true;
491 }
492 } else if (VisitDeclContext(
493 CXXUnit->getASTContext().getTranslationUnitDecl()))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000494 return true;
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000495 continue;
Douglas Gregor7b691f332010-01-20 21:13:59 +0000496 }
Bob Wilson3178cb62010-03-19 03:57:57 +0000497
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000498 // Walk the preprocessing record.
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000499 if (CXXUnit->getPreprocessor().getPreprocessingRecord())
500 visitPreprocessedEntitiesInRegion();
Douglas Gregor0396f462010-03-19 05:22:59 +0000501 }
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000502
Douglas Gregor7b691f332010-01-20 21:13:59 +0000503 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000504 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000505
Douglas Gregorc314aa42011-03-02 19:17:03 +0000506 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
507 if (CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
508 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
509 return Visit(BaseTSInfo->getTypeLoc());
510 }
511 }
512 }
Argyrios Kyrtzidis221d5a52011-09-13 18:49:56 +0000513
514 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
515 IBOutletCollectionAttr *A =
516 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
517 if (const ObjCInterfaceType *InterT = A->getInterface()->getAs<ObjCInterfaceType>())
518 return Visit(cxcursor::MakeCursorObjCClassRef(InterT->getInterface(),
519 A->getInterfaceLoc(), TU));
520 }
521
Douglas Gregorb1373d02010-01-20 20:59:29 +0000522 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000523 return false;
524}
525
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000526bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
Douglas Gregor13c8ccb2011-04-22 23:49:24 +0000527 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
528 if (Visit(TSInfo->getTypeLoc()))
529 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000530
Ted Kremenek664cffd2010-07-22 11:30:19 +0000531 if (Stmt *Body = B->getBody())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000532 return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest));
Ted Kremenek664cffd2010-07-22 11:30:19 +0000533
534 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000535}
536
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000537llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
538 if (RegionOfInterest.isValid()) {
Douglas Gregor66537982010-11-17 17:14:07 +0000539 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000540 if (Range.isInvalid())
541 return llvm::Optional<bool>();
Douglas Gregor66537982010-11-17 17:14:07 +0000542
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000543 switch (CompareRegionOfInterest(Range)) {
544 case RangeBefore:
545 // This declaration comes before the region of interest; skip it.
546 return llvm::Optional<bool>();
547
548 case RangeAfter:
549 // This declaration comes after the region of interest; we're done.
550 return false;
551
552 case RangeOverlap:
553 // This declaration overlaps the region of interest; visit it.
554 break;
555 }
556 }
557 return true;
558}
559
560bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
561 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
562
563 // FIXME: Eventually remove. This part of a hack to support proper
564 // iteration over all Decls contained lexically within an ObjC container.
565 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
566 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
567
568 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000569 Decl *D = *I;
570 if (D->getLexicalDeclContext() != DC)
571 continue;
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000572 CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
Argyrios Kyrtzidis1836db02012-02-04 01:04:58 +0000573
Argyrios Kyrtzidisc178d762012-08-28 00:04:23 +0000574 // Ignore synthesized ivars here, otherwise if we have something like:
575 // @synthesize prop = _prop;
576 // and '_prop' is not declared, we will encounter a '_prop' ivar before
577 // encountering the 'prop' synthesize declaration and we will think that
578 // we passed the region-of-interest.
579 if (ObjCIvarDecl *ivarD = dyn_cast<ObjCIvarDecl>(D)) {
580 if (ivarD->getSynthesize())
581 continue;
582 }
583
Argyrios Kyrtzidis1836db02012-02-04 01:04:58 +0000584 // FIXME: ObjCClassRef/ObjCProtocolRef for forward class/protocol
585 // declarations is a mismatch with the compiler semantics.
586 if (Cursor.kind == CXCursor_ObjCInterfaceDecl) {
587 ObjCInterfaceDecl *ID = cast<ObjCInterfaceDecl>(D);
588 if (!ID->isThisDeclarationADefinition())
589 Cursor = MakeCursorObjCClassRef(ID, ID->getLocation(), TU);
590
591 } else if (Cursor.kind == CXCursor_ObjCProtocolDecl) {
592 ObjCProtocolDecl *PD = cast<ObjCProtocolDecl>(D);
593 if (!PD->isThisDeclarationADefinition())
594 Cursor = MakeCursorObjCProtocolRef(PD, PD->getLocation(), TU);
595 }
596
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000597 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
598 if (!V.hasValue())
599 continue;
600 if (!V.getValue())
601 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000602 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000603 return true;
604 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000605 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000606}
607
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000608bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
609 llvm_unreachable("Translation units are visited directly by Visit()");
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000610}
611
Richard Smith162e1c12011-04-15 14:24:37 +0000612bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
613 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
614 return Visit(TSInfo->getTypeLoc());
615
616 return false;
617}
618
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000619bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
620 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
621 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000622
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000623 return false;
624}
625
626bool CursorVisitor::VisitTagDecl(TagDecl *D) {
627 return VisitDeclContext(D);
628}
629
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000630bool CursorVisitor::VisitClassTemplateSpecializationDecl(
631 ClassTemplateSpecializationDecl *D) {
632 bool ShouldVisitBody = false;
633 switch (D->getSpecializationKind()) {
634 case TSK_Undeclared:
635 case TSK_ImplicitInstantiation:
636 // Nothing to visit
637 return false;
638
639 case TSK_ExplicitInstantiationDeclaration:
640 case TSK_ExplicitInstantiationDefinition:
641 break;
642
643 case TSK_ExplicitSpecialization:
644 ShouldVisitBody = true;
645 break;
646 }
647
648 // Visit the template arguments used in the specialization.
649 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
650 TypeLoc TL = SpecType->getTypeLoc();
651 if (TemplateSpecializationTypeLoc *TSTLoc
652 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
653 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
654 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
655 return true;
656 }
657 }
658
659 if (ShouldVisitBody && VisitCXXRecordDecl(D))
660 return true;
661
662 return false;
663}
664
Douglas Gregor74dbe642010-08-31 19:31:58 +0000665bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
666 ClassTemplatePartialSpecializationDecl *D) {
667 // FIXME: Visit the "outer" template parameter lists on the TagDecl
668 // before visiting these template parameters.
669 if (VisitTemplateParameters(D->getTemplateParameters()))
670 return true;
671
672 // Visit the partial specialization arguments.
673 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
674 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
675 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
676 return true;
677
678 return VisitCXXRecordDecl(D);
679}
680
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000681bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000682 // Visit the default argument.
683 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
684 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
685 if (Visit(DefArg->getTypeLoc()))
686 return true;
687
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000688 return false;
689}
690
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000691bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
692 if (Expr *Init = D->getInitExpr())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000693 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000694 return false;
695}
696
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000697bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
698 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
699 if (Visit(TSInfo->getTypeLoc()))
700 return true;
701
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000702 // Visit the nested-name-specifier, if present.
703 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
704 if (VisitNestedNameSpecifierLoc(QualifierLoc))
705 return true;
706
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000707 return false;
708}
709
Douglas Gregora67e03f2010-09-09 21:42:20 +0000710/// \brief Compare two base or member initializers based on their source order.
Sean Huntcbb67482011-01-08 20:30:50 +0000711static int CompareCXXCtorInitializers(const void* Xp, const void *Yp) {
712 CXXCtorInitializer const * const *X
713 = static_cast<CXXCtorInitializer const * const *>(Xp);
714 CXXCtorInitializer const * const *Y
715 = static_cast<CXXCtorInitializer const * const *>(Yp);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000716
717 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
718 return -1;
719 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
720 return 1;
721 else
722 return 0;
723}
724
Douglas Gregorb1373d02010-01-20 20:59:29 +0000725bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000726 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
727 // Visit the function declaration's syntactic components in the order
728 // written. This requires a bit of work.
Abramo Bagnara723df242010-12-14 22:11:44 +0000729 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
Douglas Gregor01829d32010-08-31 14:41:23 +0000730 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
731
732 // If we have a function declared directly (without the use of a typedef),
733 // visit just the return type. Otherwise, just visit the function's type
734 // now.
735 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
736 (!FTL && Visit(TL)))
737 return true;
738
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000739 // Visit the nested-name-specifier, if present.
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000740 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
741 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000742 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000743
744 // Visit the declaration name.
745 if (VisitDeclarationNameInfo(ND->getNameInfo()))
746 return true;
747
748 // FIXME: Visit explicitly-specified template arguments!
749
750 // Visit the function parameters, if we have a function type.
751 if (FTL && VisitFunctionTypeLoc(*FTL, true))
752 return true;
753
754 // FIXME: Attributes?
755 }
756
Sean Hunt10620eb2011-05-06 20:44:56 +0000757 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
Douglas Gregora67e03f2010-09-09 21:42:20 +0000758 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
759 // Find the initializers that were written in the source.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000760 SmallVector<CXXCtorInitializer *, 4> WrittenInits;
Douglas Gregora67e03f2010-09-09 21:42:20 +0000761 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
762 IEnd = Constructor->init_end();
763 I != IEnd; ++I) {
764 if (!(*I)->isWritten())
765 continue;
766
767 WrittenInits.push_back(*I);
768 }
769
770 // Sort the initializers in source order
771 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
Sean Huntcbb67482011-01-08 20:30:50 +0000772 &CompareCXXCtorInitializers);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000773
774 // Visit the initializers in source order
775 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
Sean Huntcbb67482011-01-08 20:30:50 +0000776 CXXCtorInitializer *Init = WrittenInits[I];
Francois Pichet00eb3f92010-12-04 09:14:42 +0000777 if (Init->isAnyMemberInitializer()) {
778 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
Douglas Gregora67e03f2010-09-09 21:42:20 +0000779 Init->getMemberLocation(), TU)))
780 return true;
Douglas Gregor76852c22011-11-01 01:16:03 +0000781 } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) {
782 if (Visit(TInfo->getTypeLoc()))
Douglas Gregora67e03f2010-09-09 21:42:20 +0000783 return true;
784 }
785
786 // Visit the initializer value.
787 if (Expr *Initializer = Init->getInit())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000788 if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
Douglas Gregora67e03f2010-09-09 21:42:20 +0000789 return true;
790 }
791 }
792
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000793 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
Douglas Gregora67e03f2010-09-09 21:42:20 +0000794 return true;
795 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000796
Douglas Gregorb1373d02010-01-20 20:59:29 +0000797 return false;
798}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000799
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000800bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
801 if (VisitDeclaratorDecl(D))
802 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000803
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000804 if (Expr *BitWidth = D->getBitWidth())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000805 return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000806
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000807 return false;
808}
809
810bool CursorVisitor::VisitVarDecl(VarDecl *D) {
811 if (VisitDeclaratorDecl(D))
812 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000813
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000814 if (Expr *Init = D->getInit())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000815 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000816
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000817 return false;
818}
819
Douglas Gregor84b51d72010-09-01 20:16:53 +0000820bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
821 if (VisitDeclaratorDecl(D))
822 return true;
823
824 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
825 if (Expr *DefArg = D->getDefaultArgument())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000826 return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
Douglas Gregor84b51d72010-09-01 20:16:53 +0000827
828 return false;
829}
830
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000831bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
832 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
833 // before visiting these template parameters.
834 if (VisitTemplateParameters(D->getTemplateParameters()))
835 return true;
836
837 return VisitFunctionDecl(D->getTemplatedDecl());
838}
839
Douglas Gregor39d6f072010-08-31 19:02:00 +0000840bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
841 // FIXME: Visit the "outer" template parameter lists on the TagDecl
842 // before visiting these template parameters.
843 if (VisitTemplateParameters(D->getTemplateParameters()))
844 return true;
845
846 return VisitCXXRecordDecl(D->getTemplatedDecl());
847}
848
Douglas Gregor84b51d72010-09-01 20:16:53 +0000849bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
850 if (VisitTemplateParameters(D->getTemplateParameters()))
851 return true;
852
853 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
854 VisitTemplateArgumentLoc(D->getDefaultArgument()))
855 return true;
856
857 return false;
858}
859
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000860bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000861 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
862 if (Visit(TSInfo->getTypeLoc()))
863 return true;
864
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000865 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000866 PEnd = ND->param_end();
867 P != PEnd; ++P) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000868 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000869 return true;
870 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000871
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000872 if (ND->isThisDeclarationADefinition() &&
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000873 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000874 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000875
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000876 return false;
877}
878
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +0000879template <typename DeclIt>
880static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current,
881 SourceManager &SM, SourceLocation EndLoc,
882 SmallVectorImpl<Decl *> &Decls) {
883 DeclIt next = *DI_current;
884 while (++next != DE_current) {
885 Decl *D_next = *next;
886 if (!D_next)
887 break;
888 SourceLocation L = D_next->getLocStart();
889 if (!L.isValid())
890 break;
891 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
892 *DI_current = next;
893 Decls.push_back(D_next);
894 continue;
895 }
896 break;
897 }
898}
899
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000900namespace {
901 struct ContainerDeclsSort {
902 SourceManager &SM;
903 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
904 bool operator()(Decl *A, Decl *B) {
905 SourceLocation L_A = A->getLocStart();
906 SourceLocation L_B = B->getLocStart();
907 assert(L_A.isValid() && L_B.isValid());
908 return SM.isBeforeInTranslationUnit(L_A, L_B);
909 }
910 };
911}
912
Douglas Gregora59e3902010-01-21 23:27:09 +0000913bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000914 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
915 // an @implementation can lexically contain Decls that are not properly
916 // nested in the AST. When we identify such cases, we need to retrofit
917 // this nesting here.
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +0000918 if (!DI_current && !FileDI_current)
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000919 return VisitDeclContext(D);
920
921 // Scan the Decls that immediately come after the container
922 // in the current DeclContext. If any fall within the
923 // container's lexical region, stash them into a vector
924 // for later processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000925 SmallVector<Decl *, 24> DeclsInContainer;
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000926 SourceLocation EndLoc = D->getSourceRange().getEnd();
Ted Kremeneka60ed472010-11-16 08:15:36 +0000927 SourceManager &SM = AU->getSourceManager();
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000928 if (EndLoc.isValid()) {
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +0000929 if (DI_current) {
930 addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc,
931 DeclsInContainer);
932 } else {
933 addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc,
934 DeclsInContainer);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000935 }
936 }
937
938 // The common case.
939 if (DeclsInContainer.empty())
940 return VisitDeclContext(D);
941
942 // Get all the Decls in the DeclContext, and sort them with the
943 // additional ones we've collected. Then visit them.
944 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
945 I!=E; ++I) {
946 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000947 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
948 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000949 continue;
950 DeclsInContainer.push_back(subDecl);
951 }
952
953 // Now sort the Decls so that they appear in lexical order.
954 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
955 ContainerDeclsSort(SM));
956
957 // Now visit the decls.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000958 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000959 E = DeclsInContainer.end(); I != E; ++I) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000960 CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000961 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
962 if (!V.hasValue())
963 continue;
964 if (!V.getValue())
965 return false;
966 if (Visit(Cursor, true))
967 return true;
968 }
969 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000970}
971
Douglas Gregorb1373d02010-01-20 20:59:29 +0000972bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000973 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
974 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000975 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000976
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000977 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
978 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
979 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000980 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000981 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000982
Douglas Gregora59e3902010-01-21 23:27:09 +0000983 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000984}
985
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000986bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000987 if (!PID->isThisDeclarationADefinition())
988 return Visit(MakeCursorObjCProtocolRef(PID, PID->getLocation(), TU));
989
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000990 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
991 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
992 E = PID->protocol_end(); I != E; ++I, ++PL)
993 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
994 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000995
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000996 return VisitObjCContainerDecl(PID);
997}
998
Ted Kremenek23173d72010-05-18 21:09:07 +0000999bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +00001000 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +00001001 return true;
1002
Ted Kremenek23173d72010-05-18 21:09:07 +00001003 // FIXME: This implements a workaround with @property declarations also being
1004 // installed in the DeclContext for the @interface. Eventually this code
1005 // should be removed.
1006 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
1007 if (!CDecl || !CDecl->IsClassExtension())
1008 return false;
1009
1010 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
1011 if (!ID)
1012 return false;
1013
1014 IdentifierInfo *PropertyId = PD->getIdentifier();
1015 ObjCPropertyDecl *prevDecl =
1016 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
1017
1018 if (!prevDecl)
1019 return false;
1020
1021 // Visit synthesized methods since they will be skipped when visiting
1022 // the @interface.
1023 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +00001024 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001025 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
Ted Kremenek23173d72010-05-18 21:09:07 +00001026 return true;
1027
1028 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +00001029 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001030 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
Ted Kremenek23173d72010-05-18 21:09:07 +00001031 return true;
1032
1033 return false;
1034}
1035
Douglas Gregorb1373d02010-01-20 20:59:29 +00001036bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Douglas Gregor375bb142011-12-27 22:43:10 +00001037 if (!D->isThisDeclarationADefinition()) {
1038 // Forward declaration is treated like a reference.
1039 return Visit(MakeCursorObjCClassRef(D, D->getLocation(), TU));
1040 }
1041
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001042 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +00001043 if (D->getSuperClass() &&
1044 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001045 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001046 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001047 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001048
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001049 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1050 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1051 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001052 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001053 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001054
Douglas Gregora59e3902010-01-21 23:27:09 +00001055 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001056}
1057
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001058bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1059 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001060}
1061
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001062bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +00001063 // 'ID' could be null when dealing with invalid code.
1064 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1065 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1066 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001067
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001068 return VisitObjCImplDecl(D);
1069}
1070
1071bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1072#if 0
1073 // Issue callbacks for super class.
1074 // FIXME: No source location information!
1075 if (D->getSuperClass() &&
1076 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001077 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001078 TU)))
1079 return true;
1080#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001081
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001082 return VisitObjCImplDecl(D);
1083}
1084
Douglas Gregora4ffd852010-11-17 01:03:52 +00001085bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1086 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
Argyrios Kyrtzidis135bf8e2012-06-09 03:03:02 +00001087 if (PD->isIvarNameSpecified())
1088 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
Douglas Gregora4ffd852010-11-17 01:03:52 +00001089
1090 return false;
1091}
1092
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001093bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1094 return VisitDeclContext(D);
1095}
1096
Douglas Gregor69319002010-08-31 23:48:11 +00001097bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001098 // Visit nested-name-specifier.
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00001099 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1100 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001101 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001102
1103 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1104 D->getTargetNameLoc(), TU));
1105}
1106
Douglas Gregor7e242562010-09-01 19:52:22 +00001107bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001108 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001109 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1110 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001111 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001112 }
Douglas Gregor7e242562010-09-01 19:52:22 +00001113
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001114 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1115 return true;
1116
Douglas Gregor7e242562010-09-01 19:52:22 +00001117 return VisitDeclarationNameInfo(D->getNameInfo());
1118}
1119
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001120bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001121 // Visit nested-name-specifier.
Douglas Gregordb992412011-02-25 16:33:46 +00001122 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1123 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001124 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001125
1126 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1127 D->getIdentLocation(), TU));
1128}
1129
Douglas Gregor7e242562010-09-01 19:52:22 +00001130bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001131 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001132 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1133 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001134 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001135 }
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001136
Douglas Gregor7e242562010-09-01 19:52:22 +00001137 return VisitDeclarationNameInfo(D->getNameInfo());
1138}
1139
1140bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1141 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001142 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001143 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1144 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001145 return true;
1146
Douglas Gregor7e242562010-09-01 19:52:22 +00001147 return false;
1148}
1149
Douglas Gregor01829d32010-08-31 14:41:23 +00001150bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1151 switch (Name.getName().getNameKind()) {
1152 case clang::DeclarationName::Identifier:
1153 case clang::DeclarationName::CXXLiteralOperatorName:
1154 case clang::DeclarationName::CXXOperatorName:
1155 case clang::DeclarationName::CXXUsingDirective:
1156 return false;
1157
1158 case clang::DeclarationName::CXXConstructorName:
1159 case clang::DeclarationName::CXXDestructorName:
1160 case clang::DeclarationName::CXXConversionFunctionName:
1161 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1162 return Visit(TSInfo->getTypeLoc());
1163 return false;
1164
1165 case clang::DeclarationName::ObjCZeroArgSelector:
1166 case clang::DeclarationName::ObjCOneArgSelector:
1167 case clang::DeclarationName::ObjCMultiArgSelector:
1168 // FIXME: Per-identifier location info?
1169 return false;
1170 }
David Blaikie7530c032012-01-17 06:56:22 +00001171
1172 llvm_unreachable("Invalid DeclarationName::Kind!");
Douglas Gregor01829d32010-08-31 14:41:23 +00001173}
1174
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001175bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1176 SourceRange Range) {
1177 // FIXME: This whole routine is a hack to work around the lack of proper
1178 // source information in nested-name-specifiers (PR5791). Since we do have
1179 // a beginning source location, we can visit the first component of the
1180 // nested-name-specifier, if it's a single-token component.
1181 if (!NNS)
1182 return false;
1183
1184 // Get the first component in the nested-name-specifier.
1185 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1186 NNS = Prefix;
1187
1188 switch (NNS->getKind()) {
1189 case NestedNameSpecifier::Namespace:
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001190 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1191 TU));
1192
Douglas Gregor14aba762011-02-24 02:36:08 +00001193 case NestedNameSpecifier::NamespaceAlias:
1194 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1195 Range.getBegin(), TU));
1196
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001197 case NestedNameSpecifier::TypeSpec: {
1198 // If the type has a form where we know that the beginning of the source
1199 // range matches up with a reference cursor. Visit the appropriate reference
1200 // cursor.
John McCallf4c73712011-01-19 06:33:43 +00001201 const Type *T = NNS->getAsType();
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001202 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1203 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1204 if (const TagType *Tag = dyn_cast<TagType>(T))
1205 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1206 if (const TemplateSpecializationType *TST
1207 = dyn_cast<TemplateSpecializationType>(T))
1208 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1209 break;
1210 }
1211
1212 case NestedNameSpecifier::TypeSpecWithTemplate:
1213 case NestedNameSpecifier::Global:
1214 case NestedNameSpecifier::Identifier:
1215 break;
1216 }
1217
1218 return false;
1219}
1220
Douglas Gregordc355712011-02-25 00:36:19 +00001221bool
1222CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001223 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
Douglas Gregordc355712011-02-25 00:36:19 +00001224 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1225 Qualifiers.push_back(Qualifier);
1226
1227 while (!Qualifiers.empty()) {
1228 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1229 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1230 switch (NNS->getKind()) {
1231 case NestedNameSpecifier::Namespace:
1232 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001233 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001234 TU)))
1235 return true;
1236
1237 break;
1238
1239 case NestedNameSpecifier::NamespaceAlias:
1240 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001241 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001242 TU)))
1243 return true;
1244
1245 break;
1246
1247 case NestedNameSpecifier::TypeSpec:
1248 case NestedNameSpecifier::TypeSpecWithTemplate:
1249 if (Visit(Q.getTypeLoc()))
1250 return true;
1251
1252 break;
1253
1254 case NestedNameSpecifier::Global:
1255 case NestedNameSpecifier::Identifier:
1256 break;
1257 }
1258 }
1259
1260 return false;
1261}
1262
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001263bool CursorVisitor::VisitTemplateParameters(
1264 const TemplateParameterList *Params) {
1265 if (!Params)
1266 return false;
1267
1268 for (TemplateParameterList::const_iterator P = Params->begin(),
1269 PEnd = Params->end();
1270 P != PEnd; ++P) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001271 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001272 return true;
1273 }
1274
1275 return false;
1276}
1277
Douglas Gregor0b36e612010-08-31 20:37:03 +00001278bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1279 switch (Name.getKind()) {
1280 case TemplateName::Template:
1281 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1282
1283 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001284 // Visit the overloaded template set.
1285 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1286 return true;
1287
Douglas Gregor0b36e612010-08-31 20:37:03 +00001288 return false;
1289
1290 case TemplateName::DependentTemplate:
1291 // FIXME: Visit nested-name-specifier.
1292 return false;
1293
1294 case TemplateName::QualifiedTemplate:
1295 // FIXME: Visit nested-name-specifier.
1296 return Visit(MakeCursorTemplateRef(
1297 Name.getAsQualifiedTemplateName()->getDecl(),
1298 Loc, TU));
John McCall14606042011-06-30 08:33:18 +00001299
1300 case TemplateName::SubstTemplateTemplateParm:
1301 return Visit(MakeCursorTemplateRef(
1302 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1303 Loc, TU));
Douglas Gregor1aee05d2011-01-15 06:45:20 +00001304
1305 case TemplateName::SubstTemplateTemplateParmPack:
1306 return Visit(MakeCursorTemplateRef(
1307 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1308 Loc, TU));
Douglas Gregor0b36e612010-08-31 20:37:03 +00001309 }
David Blaikie7530c032012-01-17 06:56:22 +00001310
1311 llvm_unreachable("Invalid TemplateName::Kind!");
Douglas Gregor0b36e612010-08-31 20:37:03 +00001312}
1313
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001314bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1315 switch (TAL.getArgument().getKind()) {
1316 case TemplateArgument::Null:
1317 case TemplateArgument::Integral:
Douglas Gregor87dd6972010-12-20 16:52:59 +00001318 case TemplateArgument::Pack:
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001319 return false;
1320
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001321 case TemplateArgument::Type:
1322 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1323 return Visit(TSInfo->getTypeLoc());
1324 return false;
1325
1326 case TemplateArgument::Declaration:
1327 if (Expr *E = TAL.getSourceDeclExpression())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001328 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001329 return false;
Eli Friedmand7a6b162012-09-26 02:36:12 +00001330
1331 case TemplateArgument::NullPtr:
1332 if (Expr *E = TAL.getSourceNullPtrExpression())
1333 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1334 return false;
1335
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001336 case TemplateArgument::Expression:
1337 if (Expr *E = TAL.getSourceExpression())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001338 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001339 return false;
1340
1341 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001342 case TemplateArgument::TemplateExpansion:
Douglas Gregorb6744ef2011-03-02 17:09:35 +00001343 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1344 return true;
1345
Douglas Gregora7fc9012011-01-05 18:58:31 +00001346 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
Douglas Gregor0b36e612010-08-31 20:37:03 +00001347 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001348 }
David Blaikie7530c032012-01-17 06:56:22 +00001349
1350 llvm_unreachable("Invalid TemplateArgument::Kind!");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001351}
1352
Ted Kremeneka0536d82010-05-07 01:04:29 +00001353bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1354 return VisitDeclContext(D);
1355}
1356
Douglas Gregor01829d32010-08-31 14:41:23 +00001357bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1358 return Visit(TL.getUnqualifiedLoc());
1359}
1360
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001361bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00001362 ASTContext &Context = AU->getASTContext();
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001363
1364 // Some builtin types (such as Objective-C's "id", "sel", and
1365 // "Class") have associated declarations. Create cursors for those.
1366 QualType VisitType;
John McCalle0a22d02011-10-18 21:02:43 +00001367 switch (TL.getTypePtr()->getKind()) {
John McCall2dde35b2011-10-18 22:28:37 +00001368
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001369 case BuiltinType::Void:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001370 case BuiltinType::NullPtr:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001371 case BuiltinType::Dependent:
John McCall2dde35b2011-10-18 22:28:37 +00001372#define BUILTIN_TYPE(Id, SingletonId)
1373#define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1374#define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1375#define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
1376#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
1377#include "clang/AST/BuiltinTypes.def"
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001378 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001379
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001380 case BuiltinType::ObjCId:
1381 VisitType = Context.getObjCIdType();
1382 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001383
1384 case BuiltinType::ObjCClass:
1385 VisitType = Context.getObjCClassType();
1386 break;
1387
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001388 case BuiltinType::ObjCSel:
1389 VisitType = Context.getObjCSelType();
1390 break;
1391 }
1392
1393 if (!VisitType.isNull()) {
1394 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001395 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001396 TU));
1397 }
1398
1399 return false;
1400}
1401
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001402bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
Richard Smith162e1c12011-04-15 14:24:37 +00001403 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001404}
1405
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001406bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1407 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1408}
1409
1410bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
Argyrios Kyrtzidis6f155de2011-08-25 22:24:47 +00001411 if (TL.isDefinition())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001412 return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
Argyrios Kyrtzidis6f155de2011-08-25 22:24:47 +00001413
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001414 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1415}
1416
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001417bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Chandler Carruth960d13d2011-05-01 09:53:37 +00001418 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001419}
1420
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001421bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1422 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1423 return true;
1424
John McCallc12c5bb2010-05-15 11:32:37 +00001425 return false;
1426}
1427
1428bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1429 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1430 return true;
1431
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001432 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1433 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1434 TU)))
1435 return true;
1436 }
1437
1438 return false;
1439}
1440
1441bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001442 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001443}
1444
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001445bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1446 return Visit(TL.getInnerLoc());
1447}
1448
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001449bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1450 return Visit(TL.getPointeeLoc());
1451}
1452
1453bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1454 return Visit(TL.getPointeeLoc());
1455}
1456
1457bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1458 return Visit(TL.getPointeeLoc());
1459}
1460
1461bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001462 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001463}
1464
1465bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001466 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001467}
1468
Argyrios Kyrtzidis3422fbc2011-08-15 18:44:43 +00001469bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1470 return Visit(TL.getModifiedLoc());
1471}
1472
Douglas Gregor01829d32010-08-31 14:41:23 +00001473bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1474 bool SkipResultType) {
1475 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001476 return true;
1477
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001478 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001479 if (Decl *D = TL.getArg(I))
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001480 if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001481 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001482
1483 return false;
1484}
1485
1486bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1487 if (Visit(TL.getElementLoc()))
1488 return true;
1489
1490 if (Expr *Size = TL.getSizeExpr())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001491 return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001492
1493 return false;
1494}
1495
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001496bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1497 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001498 // Visit the template name.
1499 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1500 TL.getTemplateNameLoc()))
1501 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001502
1503 // Visit the template arguments.
1504 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1505 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1506 return true;
1507
1508 return false;
1509}
1510
Douglas Gregor2332c112010-01-21 20:48:56 +00001511bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1512 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1513}
1514
1515bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1516 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1517 return Visit(TSInfo->getTypeLoc());
1518
1519 return false;
1520}
1521
Sean Huntca63c202011-05-24 22:41:36 +00001522bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1523 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1524 return Visit(TSInfo->getTypeLoc());
1525
1526 return false;
1527}
1528
Douglas Gregor2494dd02011-03-01 01:34:45 +00001529bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
1530 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1531 return true;
1532
1533 return false;
1534}
1535
Douglas Gregor94fdffa2011-03-01 20:11:18 +00001536bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1537 DependentTemplateSpecializationTypeLoc TL) {
1538 // Visit the nested-name-specifier, if there is one.
1539 if (TL.getQualifierLoc() &&
1540 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1541 return true;
1542
1543 // Visit the template arguments.
1544 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1545 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1546 return true;
1547
1548 return false;
1549}
1550
Douglas Gregor9e876872011-03-01 18:12:44 +00001551bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1552 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1553 return true;
1554
1555 return Visit(TL.getNamedTypeLoc());
1556}
1557
Douglas Gregor7536dd52010-12-20 02:24:11 +00001558bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1559 return Visit(TL.getPatternLoc());
1560}
1561
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +00001562bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1563 if (Expr *E = TL.getUnderlyingExpr())
1564 return Visit(MakeCXCursor(E, StmtParent, TU));
1565
1566 return false;
1567}
1568
1569bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1570 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1571}
1572
Eli Friedmanb001de72011-10-06 23:00:33 +00001573bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1574 return Visit(TL.getValueLoc());
1575}
1576
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +00001577#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1578bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1579 return Visit##PARENT##Loc(TL); \
1580}
1581
1582DEFAULT_TYPELOC_IMPL(Complex, Type)
1583DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1584DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1585DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1586DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
1587DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1588DEFAULT_TYPELOC_IMPL(Vector, Type)
1589DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1590DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1591DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1592DEFAULT_TYPELOC_IMPL(Record, TagType)
1593DEFAULT_TYPELOC_IMPL(Enum, TagType)
1594DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1595DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1596DEFAULT_TYPELOC_IMPL(Auto, Type)
1597
Ted Kremenek3064ef92010-08-27 21:34:58 +00001598bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001599 // Visit the nested-name-specifier, if present.
1600 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1601 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1602 return true;
1603
John McCall5e1cdac2011-10-07 06:10:15 +00001604 if (D->isCompleteDefinition()) {
Ted Kremenek3064ef92010-08-27 21:34:58 +00001605 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1606 E = D->bases_end(); I != E; ++I) {
1607 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1608 return true;
1609 }
1610 }
1611
1612 return VisitTagDecl(D);
1613}
1614
Ted Kremenek09dfa372010-02-18 05:46:33 +00001615bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001616 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1617 i != e; ++i)
1618 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001619 return true;
1620
1621 return false;
1622}
1623
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001624//===----------------------------------------------------------------------===//
1625// Data-recursive visitor methods.
1626//===----------------------------------------------------------------------===//
1627
Ted Kremenek28a71942010-11-13 00:36:47 +00001628namespace {
Ted Kremenek035dc412010-11-13 00:36:50 +00001629#define DEF_JOB(NAME, DATA, KIND)\
1630class NAME : public VisitorJob {\
1631public:\
1632 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1633 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Ted Kremenekf64d8032010-11-18 00:02:32 +00001634 DATA *get() const { return static_cast<DATA*>(data[0]); }\
Ted Kremenek035dc412010-11-13 00:36:50 +00001635};
1636
1637DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1638DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001639DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001640DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001641DEF_JOB(ExplicitTemplateArgsVisit, ASTTemplateArgumentListInfo,
Ted Kremenek60608ec2010-11-17 00:50:47 +00001642 ExplicitTemplateArgsVisitKind)
Douglas Gregor94d96292011-01-19 20:34:17 +00001643DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
Douglas Gregor011d8b92012-02-15 00:54:55 +00001644DEF_JOB(LambdaExprParts, LambdaExpr, LambdaExprPartsKind)
Argyrios Kyrtzidisd579dd52012-09-01 18:27:30 +00001645DEF_JOB(PostChildrenVisit, void, PostChildrenVisitKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001646#undef DEF_JOB
1647
1648class DeclVisit : public VisitorJob {
1649public:
1650 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1651 VisitorJob(parent, VisitorJob::DeclVisitKind,
1652 d, isFirst ? (void*) 1 : (void*) 0) {}
1653 static bool classof(const VisitorJob *VJ) {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001654 return VJ->getKind() == DeclVisitKind;
Ted Kremenek035dc412010-11-13 00:36:50 +00001655 }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001656 Decl *get() const { return static_cast<Decl*>(data[0]); }
1657 bool isFirst() const { return data[1] ? true : false; }
Ted Kremenek035dc412010-11-13 00:36:50 +00001658};
Ted Kremenek035dc412010-11-13 00:36:50 +00001659class TypeLocVisit : public VisitorJob {
1660public:
1661 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1662 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1663 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1664
1665 static bool classof(const VisitorJob *VJ) {
1666 return VJ->getKind() == TypeLocVisitKind;
1667 }
1668
Ted Kremenek82f3c502010-11-15 22:23:26 +00001669 TypeLoc get() const {
Ted Kremenekf64d8032010-11-18 00:02:32 +00001670 QualType T = QualType::getFromOpaquePtr(data[0]);
1671 return TypeLoc(T, data[1]);
Ted Kremenek035dc412010-11-13 00:36:50 +00001672 }
1673};
1674
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001675class LabelRefVisit : public VisitorJob {
1676public:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001677 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1678 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001679 labelLoc.getPtrEncoding()) {}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001680
1681 static bool classof(const VisitorJob *VJ) {
1682 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1683 }
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001684 LabelDecl *get() const { return static_cast<LabelDecl*>(data[0]); }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001685 SourceLocation getLoc() const {
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001686 return SourceLocation::getFromPtrEncoding(data[1]); }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001687};
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001688
1689class NestedNameSpecifierLocVisit : public VisitorJob {
1690public:
1691 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1692 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1693 Qualifier.getNestedNameSpecifier(),
1694 Qualifier.getOpaqueData()) { }
1695
1696 static bool classof(const VisitorJob *VJ) {
1697 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1698 }
1699
1700 NestedNameSpecifierLoc get() const {
1701 return NestedNameSpecifierLoc(static_cast<NestedNameSpecifier*>(data[0]),
1702 data[1]);
1703 }
1704};
1705
Ted Kremenekf64d8032010-11-18 00:02:32 +00001706class DeclarationNameInfoVisit : public VisitorJob {
1707public:
1708 DeclarationNameInfoVisit(Stmt *S, CXCursor parent)
1709 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
1710 static bool classof(const VisitorJob *VJ) {
1711 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1712 }
1713 DeclarationNameInfo get() const {
1714 Stmt *S = static_cast<Stmt*>(data[0]);
1715 switch (S->getStmtClass()) {
1716 default:
1717 llvm_unreachable("Unhandled Stmt");
Douglas Gregorba0513d2011-10-25 01:33:02 +00001718 case clang::Stmt::MSDependentExistsStmtClass:
1719 return cast<MSDependentExistsStmt>(S)->getNameInfo();
Ted Kremenekf64d8032010-11-18 00:02:32 +00001720 case Stmt::CXXDependentScopeMemberExprClass:
1721 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1722 case Stmt::DependentScopeDeclRefExprClass:
1723 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
1724 }
1725 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001726};
Ted Kremenekcdba6592010-11-18 00:42:18 +00001727class MemberRefVisit : public VisitorJob {
1728public:
1729 MemberRefVisit(FieldDecl *D, SourceLocation L, CXCursor parent)
1730 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001731 L.getPtrEncoding()) {}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001732 static bool classof(const VisitorJob *VJ) {
1733 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1734 }
1735 FieldDecl *get() const {
1736 return static_cast<FieldDecl*>(data[0]);
1737 }
1738 SourceLocation getLoc() const {
1739 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1740 }
1741};
Ted Kremenek28a71942010-11-13 00:36:47 +00001742class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1743 VisitorWorkList &WL;
1744 CXCursor Parent;
1745public:
1746 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1747 : WL(wl), Parent(parent) {}
1748
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001749 void VisitAddrLabelExpr(AddrLabelExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001750 void VisitBlockExpr(BlockExpr *B);
Ted Kremenek28a71942010-11-13 00:36:47 +00001751 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek083c7e22010-11-13 05:38:03 +00001752 void VisitCompoundStmt(CompoundStmt *S);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001753 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
Douglas Gregorba0513d2011-10-25 01:33:02 +00001754 void VisitMSDependentExistsStmt(MSDependentExistsStmt *S);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001755 void VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001756 void VisitCXXNewExpr(CXXNewExpr *E);
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001757 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001758 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001759 void VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001760 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001761 void VisitCXXTypeidExpr(CXXTypeidExpr *E);
Ted Kremenek55b933a2010-11-17 00:50:36 +00001762 void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001763 void VisitCXXUuidofExpr(CXXUuidofExpr *E);
Argyrios Kyrtzidisdcbb2fb2011-12-03 03:49:44 +00001764 void VisitCXXCatchStmt(CXXCatchStmt *S);
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001765 void VisitDeclRefExpr(DeclRefExpr *D);
Ted Kremenek035dc412010-11-13 00:36:50 +00001766 void VisitDeclStmt(DeclStmt *S);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001767 void VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001768 void VisitDesignatedInitExpr(DesignatedInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001769 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1770 void VisitForStmt(ForStmt *FS);
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001771 void VisitGotoStmt(GotoStmt *GS);
Ted Kremenek28a71942010-11-13 00:36:47 +00001772 void VisitIfStmt(IfStmt *If);
1773 void VisitInitListExpr(InitListExpr *IE);
1774 void VisitMemberExpr(MemberExpr *M);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001775 void VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001776 void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001777 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1778 void VisitOverloadExpr(OverloadExpr *E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001779 void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001780 void VisitStmt(Stmt *S);
1781 void VisitSwitchStmt(SwitchStmt *S);
1782 void VisitWhileStmt(WhileStmt *W);
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001783 void VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Francois Pichet6ad6f282010-12-07 00:08:36 +00001784 void VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E);
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00001785 void VisitTypeTraitExpr(TypeTraitExpr *E);
John Wiegley21ff2e52011-04-28 00:16:57 +00001786 void VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E);
John Wiegley55262202011-04-25 06:54:41 +00001787 void VisitExpressionTraitExpr(ExpressionTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001788 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001789 void VisitVAArgExpr(VAArgExpr *E);
Douglas Gregor94d96292011-01-19 20:34:17 +00001790 void VisitSizeOfPackExpr(SizeOfPackExpr *E);
John McCall4b9c2d22011-11-06 09:01:30 +00001791 void VisitPseudoObjectExpr(PseudoObjectExpr *E);
1792 void VisitOpaqueValueExpr(OpaqueValueExpr *E);
Douglas Gregor011d8b92012-02-15 00:54:55 +00001793 void VisitLambdaExpr(LambdaExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00001794
Ted Kremenek28a71942010-11-13 00:36:47 +00001795private:
Ted Kremenekf64d8032010-11-18 00:02:32 +00001796 void AddDeclarationNameInfo(Stmt *S);
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001797 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001798 void AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001799 void AddMemberRef(FieldDecl *D, SourceLocation L);
Ted Kremenek28a71942010-11-13 00:36:47 +00001800 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001801 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001802 void AddTypeLoc(TypeSourceInfo *TI);
1803 void EnqueueChildren(Stmt *S);
1804};
1805} // end anonyous namespace
1806
Ted Kremenekf64d8032010-11-18 00:02:32 +00001807void EnqueueVisitor::AddDeclarationNameInfo(Stmt *S) {
1808 // 'S' should always be non-null, since it comes from the
1809 // statement we are visiting.
1810 WL.push_back(DeclarationNameInfoVisit(S, Parent));
1811}
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001812
1813void
1814EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1815 if (Qualifier)
1816 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
1817}
1818
Ted Kremenek28a71942010-11-13 00:36:47 +00001819void EnqueueVisitor::AddStmt(Stmt *S) {
1820 if (S)
1821 WL.push_back(StmtVisit(S, Parent));
1822}
Ted Kremenek035dc412010-11-13 00:36:50 +00001823void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001824 if (D)
Ted Kremenek035dc412010-11-13 00:36:50 +00001825 WL.push_back(DeclVisit(D, Parent, isFirst));
Ted Kremenek28a71942010-11-13 00:36:47 +00001826}
Ted Kremenek60608ec2010-11-17 00:50:47 +00001827void EnqueueVisitor::
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001828 AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001829 if (A)
1830 WL.push_back(ExplicitTemplateArgsVisit(
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001831 const_cast<ASTTemplateArgumentListInfo*>(A), Parent));
Ted Kremenek60608ec2010-11-17 00:50:47 +00001832}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001833void EnqueueVisitor::AddMemberRef(FieldDecl *D, SourceLocation L) {
1834 if (D)
1835 WL.push_back(MemberRefVisit(D, L, Parent));
1836}
Ted Kremenek28a71942010-11-13 00:36:47 +00001837void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1838 if (TI)
1839 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1840 }
1841void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001842 unsigned size = WL.size();
John McCall7502c1d2011-02-13 04:07:26 +00001843 for (Stmt::child_range Child = S->children(); Child; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001844 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001845 }
1846 if (size == WL.size())
1847 return;
1848 // Now reverse the entries we just added. This will match the DFS
1849 // ordering performed by the worklist.
1850 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1851 std::reverse(I, E);
1852}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001853void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1854 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
1855}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001856void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1857 AddDecl(B->getBlockDecl());
1858}
Ted Kremenek28a71942010-11-13 00:36:47 +00001859void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1860 EnqueueChildren(E);
1861 AddTypeLoc(E->getTypeSourceInfo());
1862}
Ted Kremenek083c7e22010-11-13 05:38:03 +00001863void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1864 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1865 E = S->body_rend(); I != E; ++I) {
1866 AddStmt(*I);
1867 }
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001868}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001869void EnqueueVisitor::
Douglas Gregorba0513d2011-10-25 01:33:02 +00001870VisitMSDependentExistsStmt(MSDependentExistsStmt *S) {
1871 AddStmt(S->getSubStmt());
1872 AddDeclarationNameInfo(S);
1873 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
1874 AddNestedNameSpecifierLoc(QualifierLoc);
1875}
1876
1877void EnqueueVisitor::
Ted Kremenekf64d8032010-11-18 00:02:32 +00001878VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
1879 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1880 AddDeclarationNameInfo(E);
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001881 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1882 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001883 if (!E->isImplicitAccess())
1884 AddStmt(E->getBase());
1885}
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001886void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001887 // Enqueue the initializer , if any.
1888 AddStmt(E->getInitializer());
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001889 // Enqueue the array size, if any.
1890 AddStmt(E->getArraySize());
1891 // Enqueue the allocated type.
1892 AddTypeLoc(E->getAllocatedTypeSourceInfo());
1893 // Enqueue the placement arguments.
1894 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1895 AddStmt(E->getPlacementArg(I-1));
1896}
Ted Kremenek28a71942010-11-13 00:36:47 +00001897void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
Ted Kremenek8b8d8c92010-11-13 05:55:56 +00001898 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1899 AddStmt(CE->getArg(I-1));
Ted Kremenek28a71942010-11-13 00:36:47 +00001900 AddStmt(CE->getCallee());
1901 AddStmt(CE->getArg(0));
1902}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001903void EnqueueVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1904 // Visit the name of the type being destroyed.
1905 AddTypeLoc(E->getDestroyedTypeInfo());
1906 // Visit the scope type that looks disturbingly like the nested-name-specifier
1907 // but isn't.
1908 AddTypeLoc(E->getScopeTypeInfo());
1909 // Visit the nested-name-specifier.
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001910 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1911 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001912 // Visit base expression.
1913 AddStmt(E->getBase());
1914}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001915void EnqueueVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1916 AddTypeLoc(E->getTypeSourceInfo());
1917}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001918void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1919 EnqueueChildren(E);
1920 AddTypeLoc(E->getTypeSourceInfo());
1921}
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001922void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1923 EnqueueChildren(E);
1924 if (E->isTypeOperand())
1925 AddTypeLoc(E->getTypeOperandSourceInfo());
1926}
Ted Kremenek55b933a2010-11-17 00:50:36 +00001927
1928void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
1929 *E) {
1930 EnqueueChildren(E);
1931 AddTypeLoc(E->getTypeSourceInfo());
1932}
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001933void EnqueueVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1934 EnqueueChildren(E);
1935 if (E->isTypeOperand())
1936 AddTypeLoc(E->getTypeOperandSourceInfo());
1937}
Argyrios Kyrtzidisdcbb2fb2011-12-03 03:49:44 +00001938
1939void EnqueueVisitor::VisitCXXCatchStmt(CXXCatchStmt *S) {
1940 EnqueueChildren(S);
1941 AddDecl(S->getExceptionDecl());
1942}
1943
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001944void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001945 if (DR->hasExplicitTemplateArgs()) {
1946 AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
1947 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001948 WL.push_back(DeclRefExprParts(DR, Parent));
1949}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001950void EnqueueVisitor::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
1951 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1952 AddDeclarationNameInfo(E);
Douglas Gregor00cf3cc2011-02-25 20:49:16 +00001953 AddNestedNameSpecifierLoc(E->getQualifierLoc());
Ted Kremenekf64d8032010-11-18 00:02:32 +00001954}
Ted Kremenek035dc412010-11-13 00:36:50 +00001955void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1956 unsigned size = WL.size();
1957 bool isFirst = true;
1958 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1959 D != DEnd; ++D) {
1960 AddDecl(*D, isFirst);
1961 isFirst = false;
1962 }
1963 if (size == WL.size())
1964 return;
1965 // Now reverse the entries we just added. This will match the DFS
1966 // ordering performed by the worklist.
1967 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1968 std::reverse(I, E);
1969}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001970void EnqueueVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1971 AddStmt(E->getInit());
1972 typedef DesignatedInitExpr::Designator Designator;
1973 for (DesignatedInitExpr::reverse_designators_iterator
1974 D = E->designators_rbegin(), DEnd = E->designators_rend();
1975 D != DEnd; ++D) {
1976 if (D->isFieldDesignator()) {
1977 if (FieldDecl *Field = D->getField())
1978 AddMemberRef(Field, D->getFieldLoc());
1979 continue;
1980 }
1981 if (D->isArrayDesignator()) {
1982 AddStmt(E->getArrayIndex(*D));
1983 continue;
1984 }
1985 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1986 AddStmt(E->getArrayRangeEnd(*D));
1987 AddStmt(E->getArrayRangeStart(*D));
1988 }
1989}
Ted Kremenek28a71942010-11-13 00:36:47 +00001990void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1991 EnqueueChildren(E);
1992 AddTypeLoc(E->getTypeInfoAsWritten());
1993}
1994void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1995 AddStmt(FS->getBody());
1996 AddStmt(FS->getInc());
1997 AddStmt(FS->getCond());
1998 AddDecl(FS->getConditionVariable());
1999 AddStmt(FS->getInit());
2000}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002001void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) {
2002 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
2003}
Ted Kremenek28a71942010-11-13 00:36:47 +00002004void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
2005 AddStmt(If->getElse());
2006 AddStmt(If->getThen());
2007 AddStmt(If->getCond());
2008 AddDecl(If->getConditionVariable());
2009}
2010void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
2011 // We care about the syntactic form of the initializer list, only.
2012 if (InitListExpr *Syntactic = IE->getSyntacticForm())
2013 IE = Syntactic;
2014 EnqueueChildren(IE);
2015}
2016void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
Douglas Gregor89629a72010-11-17 17:15:08 +00002017 WL.push_back(MemberExprParts(M, Parent));
2018
2019 // If the base of the member access expression is an implicit 'this', don't
2020 // visit it.
2021 // FIXME: If we ever want to show these implicit accesses, this will be
2022 // unfortunate. However, clang_getCursor() relies on this behavior.
Douglas Gregor75e85042011-03-02 21:06:53 +00002023 if (!M->isImplicitAccess())
2024 AddStmt(M->getBase());
Ted Kremenek28a71942010-11-13 00:36:47 +00002025}
Ted Kremenek73d15c42010-11-13 01:09:29 +00002026void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
2027 AddTypeLoc(E->getEncodedTypeSourceInfo());
2028}
Ted Kremenek28a71942010-11-13 00:36:47 +00002029void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
2030 EnqueueChildren(M);
2031 AddTypeLoc(M->getClassReceiverTypeInfo());
2032}
Ted Kremenekcdba6592010-11-18 00:42:18 +00002033void EnqueueVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
2034 // Visit the components of the offsetof expression.
2035 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
2036 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
2037 const OffsetOfNode &Node = E->getComponent(I-1);
2038 switch (Node.getKind()) {
2039 case OffsetOfNode::Array:
2040 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2041 break;
2042 case OffsetOfNode::Field:
Abramo Bagnara06dec892011-03-12 09:45:03 +00002043 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
Ted Kremenekcdba6592010-11-18 00:42:18 +00002044 break;
2045 case OffsetOfNode::Identifier:
2046 case OffsetOfNode::Base:
2047 continue;
2048 }
2049 }
2050 // Visit the type into which we're computing the offset.
2051 AddTypeLoc(E->getTypeSourceInfo());
2052}
Ted Kremenek28a71942010-11-13 00:36:47 +00002053void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00002054 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
Ted Kremenek60458782010-11-12 21:34:16 +00002055 WL.push_back(OverloadExprParts(E, Parent));
2056}
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002057void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
2058 UnaryExprOrTypeTraitExpr *E) {
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00002059 EnqueueChildren(E);
2060 if (E->isArgumentType())
2061 AddTypeLoc(E->getArgumentTypeInfo());
2062}
Ted Kremenek28a71942010-11-13 00:36:47 +00002063void EnqueueVisitor::VisitStmt(Stmt *S) {
2064 EnqueueChildren(S);
2065}
2066void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
2067 AddStmt(S->getBody());
2068 AddStmt(S->getCond());
2069 AddDecl(S->getConditionVariable());
2070}
Ted Kremenekfafa75a2010-11-17 00:50:39 +00002071
Ted Kremenek28a71942010-11-13 00:36:47 +00002072void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
2073 AddStmt(W->getBody());
2074 AddStmt(W->getCond());
2075 AddDecl(W->getConditionVariable());
2076}
John Wiegley21ff2e52011-04-28 00:16:57 +00002077
Ted Kremenek2939b6f2010-11-17 00:50:50 +00002078void EnqueueVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
2079 AddTypeLoc(E->getQueriedTypeSourceInfo());
2080}
Francois Pichet6ad6f282010-12-07 00:08:36 +00002081
2082void EnqueueVisitor::VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
Francois Pichet6ad6f282010-12-07 00:08:36 +00002083 AddTypeLoc(E->getRhsTypeSourceInfo());
Francois Pichet0a03a3f2010-12-08 09:11:05 +00002084 AddTypeLoc(E->getLhsTypeSourceInfo());
Francois Pichet6ad6f282010-12-07 00:08:36 +00002085}
2086
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00002087void EnqueueVisitor::VisitTypeTraitExpr(TypeTraitExpr *E) {
2088 for (unsigned I = E->getNumArgs(); I > 0; --I)
2089 AddTypeLoc(E->getArg(I-1));
2090}
2091
John Wiegley21ff2e52011-04-28 00:16:57 +00002092void EnqueueVisitor::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
2093 AddTypeLoc(E->getQueriedTypeSourceInfo());
2094}
2095
John Wiegley55262202011-04-25 06:54:41 +00002096void EnqueueVisitor::VisitExpressionTraitExpr(ExpressionTraitExpr *E) {
2097 EnqueueChildren(E);
2098}
2099
Ted Kremenek28a71942010-11-13 00:36:47 +00002100void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
2101 VisitOverloadExpr(U);
2102 if (!U->isImplicitAccess())
2103 AddStmt(U->getBase());
2104}
Ted Kremenek9d3bf792010-11-17 00:50:43 +00002105void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) {
2106 AddStmt(E->getSubExpr());
2107 AddTypeLoc(E->getWrittenTypeInfo());
2108}
Douglas Gregor94d96292011-01-19 20:34:17 +00002109void EnqueueVisitor::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
2110 WL.push_back(SizeOfPackExprParts(E, Parent));
2111}
John McCall4b9c2d22011-11-06 09:01:30 +00002112void EnqueueVisitor::VisitOpaqueValueExpr(OpaqueValueExpr *E) {
2113 // If the opaque value has a source expression, just transparently
2114 // visit that. This is useful for (e.g.) pseudo-object expressions.
2115 if (Expr *SourceExpr = E->getSourceExpr())
2116 return Visit(SourceExpr);
John McCall4b9c2d22011-11-06 09:01:30 +00002117}
Douglas Gregor011d8b92012-02-15 00:54:55 +00002118void EnqueueVisitor::VisitLambdaExpr(LambdaExpr *E) {
2119 AddStmt(E->getBody());
2120 WL.push_back(LambdaExprParts(E, Parent));
2121}
John McCall4b9c2d22011-11-06 09:01:30 +00002122void EnqueueVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *E) {
2123 // Treat the expression like its syntactic form.
2124 Visit(E->getSyntacticForm());
2125}
Ted Kremenek60458782010-11-12 21:34:16 +00002126
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002127void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002128 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002129}
2130
2131bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2132 if (RegionOfInterest.isValid()) {
2133 SourceRange Range = getRawCursorExtent(C);
2134 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2135 return false;
2136 }
2137 return true;
2138}
2139
2140bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2141 while (!WL.empty()) {
2142 // Dequeue the worklist item.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002143 VisitorJob LI = WL.back();
2144 WL.pop_back();
2145
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002146 // Set the Parent field, then back to its old value once we're done.
2147 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2148
2149 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00002150 case VisitorJob::DeclVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002151 Decl *D = cast<DeclVisit>(&LI)->get();
Ted Kremenekf1107452010-11-12 18:26:56 +00002152 if (!D)
2153 continue;
2154
2155 // For now, perform default visitation for Decls.
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002156 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2157 cast<DeclVisit>(&LI)->isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00002158 return true;
2159
2160 continue;
2161 }
Ted Kremenek60608ec2010-11-17 00:50:47 +00002162 case VisitorJob::ExplicitTemplateArgsVisitKind: {
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00002163 const ASTTemplateArgumentListInfo *ArgList =
Ted Kremenek60608ec2010-11-17 00:50:47 +00002164 cast<ExplicitTemplateArgsVisit>(&LI)->get();
2165 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2166 *ArgEnd = Arg + ArgList->NumTemplateArgs;
2167 Arg != ArgEnd; ++Arg) {
2168 if (VisitTemplateArgumentLoc(*Arg))
2169 return true;
2170 }
2171 continue;
2172 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002173 case VisitorJob::TypeLocVisitKind: {
2174 // Perform default visitation for TypeLocs.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002175 if (Visit(cast<TypeLocVisit>(&LI)->get()))
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002176 return true;
2177 continue;
2178 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002179 case VisitorJob::LabelRefVisitKind: {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002180 LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Ted Kremeneke7455012011-02-23 04:54:51 +00002181 if (LabelStmt *stmt = LS->getStmt()) {
2182 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2183 TU))) {
2184 return true;
2185 }
2186 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002187 continue;
2188 }
Ted Kremenek47695c82011-08-18 22:25:21 +00002189
Douglas Gregorf3db29f2011-02-25 18:19:59 +00002190 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2191 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2192 if (VisitNestedNameSpecifierLoc(V->get()))
2193 return true;
2194 continue;
2195 }
2196
Ted Kremenekf64d8032010-11-18 00:02:32 +00002197 case VisitorJob::DeclarationNameInfoVisitKind: {
2198 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2199 ->get()))
2200 return true;
2201 continue;
2202 }
Ted Kremenekcdba6592010-11-18 00:42:18 +00002203 case VisitorJob::MemberRefVisitKind: {
2204 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2205 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2206 return true;
2207 continue;
2208 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002209 case VisitorJob::StmtVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002210 Stmt *S = cast<StmtVisit>(&LI)->get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00002211 if (!S)
2212 continue;
2213
Ted Kremenekf1107452010-11-12 18:26:56 +00002214 // Update the current cursor.
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002215 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
Ted Kremenekcdba6592010-11-18 00:42:18 +00002216 if (!IsInRegionOfInterest(Cursor))
2217 continue;
2218 switch (Visitor(Cursor, Parent, ClientData)) {
2219 case CXChildVisit_Break: return true;
2220 case CXChildVisit_Continue: break;
2221 case CXChildVisit_Recurse:
Argyrios Kyrtzidisd579dd52012-09-01 18:27:30 +00002222 if (PostChildrenVisitor)
2223 WL.push_back(PostChildrenVisit(0, Cursor));
Ted Kremenekcdba6592010-11-18 00:42:18 +00002224 EnqueueWorkList(WL, S);
Ted Kremenek82f3c502010-11-15 22:23:26 +00002225 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002226 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00002227 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002228 }
2229 case VisitorJob::MemberExprPartsKind: {
2230 // Handle the other pieces in the MemberExpr besides the base.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002231 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002232
2233 // Visit the nested-name-specifier
Douglas Gregor40d96a62011-02-28 21:54:11 +00002234 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
2235 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002236 return true;
2237
2238 // Visit the declaration name.
2239 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2240 return true;
2241
2242 // Visit the explicitly-specified template arguments, if any.
2243 if (M->hasExplicitTemplateArgs()) {
2244 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2245 *ArgEnd = Arg + M->getNumTemplateArgs();
2246 Arg != ArgEnd; ++Arg) {
2247 if (VisitTemplateArgumentLoc(*Arg))
2248 return true;
2249 }
2250 }
2251 continue;
2252 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002253 case VisitorJob::DeclRefExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002254 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002255 // Visit nested-name-specifier, if present.
Douglas Gregor40d96a62011-02-28 21:54:11 +00002256 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
2257 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002258 return true;
2259 // Visit declaration name.
2260 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2261 return true;
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002262 continue;
2263 }
Ted Kremenek60458782010-11-12 21:34:16 +00002264 case VisitorJob::OverloadExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002265 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Ted Kremenek60458782010-11-12 21:34:16 +00002266 // Visit the nested-name-specifier.
Douglas Gregor4c9be892011-02-28 20:01:57 +00002267 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
2268 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenek60458782010-11-12 21:34:16 +00002269 return true;
2270 // Visit the declaration name.
2271 if (VisitDeclarationNameInfo(O->getNameInfo()))
2272 return true;
2273 // Visit the overloaded declaration reference.
2274 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2275 return true;
Ted Kremenek60458782010-11-12 21:34:16 +00002276 continue;
2277 }
Douglas Gregor94d96292011-01-19 20:34:17 +00002278 case VisitorJob::SizeOfPackExprPartsKind: {
2279 SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
2280 NamedDecl *Pack = E->getPack();
2281 if (isa<TemplateTypeParmDecl>(Pack)) {
2282 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
2283 E->getPackLoc(), TU)))
2284 return true;
2285
2286 continue;
2287 }
2288
2289 if (isa<TemplateTemplateParmDecl>(Pack)) {
2290 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
2291 E->getPackLoc(), TU)))
2292 return true;
2293
2294 continue;
2295 }
2296
2297 // Non-type template parameter packs and function parameter packs are
2298 // treated like DeclRefExpr cursors.
2299 continue;
2300 }
Douglas Gregor011d8b92012-02-15 00:54:55 +00002301
2302 case VisitorJob::LambdaExprPartsKind: {
2303 // Visit captures.
2304 LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
2305 for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
2306 CEnd = E->explicit_capture_end();
2307 C != CEnd; ++C) {
2308 if (C->capturesThis())
2309 continue;
2310
2311 if (Visit(MakeCursorVariableRef(C->getCapturedVar(),
2312 C->getLocation(),
2313 TU)))
2314 return true;
2315 }
2316
2317 // Visit parameters and return type, if present.
2318 if (E->hasExplicitParameters() || E->hasExplicitResultType()) {
2319 TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
2320 if (E->hasExplicitParameters() && E->hasExplicitResultType()) {
2321 // Visit the whole type.
2322 if (Visit(TL))
2323 return true;
2324 } else if (isa<FunctionProtoTypeLoc>(TL)) {
2325 FunctionProtoTypeLoc Proto = cast<FunctionProtoTypeLoc>(TL);
2326 if (E->hasExplicitParameters()) {
2327 // Visit parameters.
2328 for (unsigned I = 0, N = Proto.getNumArgs(); I != N; ++I)
2329 if (Visit(MakeCXCursor(Proto.getArg(I), TU)))
2330 return true;
2331 } else {
2332 // Visit result type.
2333 if (Visit(Proto.getResultLoc()))
2334 return true;
2335 }
2336 }
2337 }
2338 break;
2339 }
Argyrios Kyrtzidisd579dd52012-09-01 18:27:30 +00002340
2341 case VisitorJob::PostChildrenVisitKind:
2342 if (PostChildrenVisitor(Parent, ClientData))
2343 return true;
2344 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002345 }
2346 }
2347 return false;
2348}
2349
Ted Kremenekcdba6592010-11-18 00:42:18 +00002350bool CursorVisitor::Visit(Stmt *S) {
Ted Kremenekd1ded662010-11-15 23:31:32 +00002351 VisitorWorkList *WL = 0;
2352 if (!WorkListFreeList.empty()) {
2353 WL = WorkListFreeList.back();
2354 WL->clear();
2355 WorkListFreeList.pop_back();
2356 }
2357 else {
2358 WL = new VisitorWorkList();
2359 WorkListCache.push_back(WL);
2360 }
2361 EnqueueWorkList(*WL, S);
2362 bool result = RunVisitorWorkList(*WL);
2363 WorkListFreeList.push_back(WL);
2364 return result;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002365}
2366
Francois Pichet48a8d142011-07-25 22:00:44 +00002367namespace {
2368typedef llvm::SmallVector<SourceRange, 4> RefNamePieces;
2369RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
2370 const DeclarationNameInfo &NI,
2371 const SourceRange &QLoc,
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00002372 const ASTTemplateArgumentListInfo *TemplateArgs = 0){
Francois Pichet48a8d142011-07-25 22:00:44 +00002373 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
2374 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
2375 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
2376
2377 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
2378
2379 RefNamePieces Pieces;
2380
2381 if (WantQualifier && QLoc.isValid())
2382 Pieces.push_back(QLoc);
2383
2384 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
2385 Pieces.push_back(NI.getLoc());
2386
2387 if (WantTemplateArgs && TemplateArgs)
2388 Pieces.push_back(SourceRange(TemplateArgs->LAngleLoc,
2389 TemplateArgs->RAngleLoc));
2390
2391 if (Kind == DeclarationName::CXXOperatorName) {
2392 Pieces.push_back(SourceLocation::getFromRawEncoding(
2393 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
2394 Pieces.push_back(SourceLocation::getFromRawEncoding(
2395 NI.getInfo().CXXOperatorName.EndOpNameLoc));
2396 }
2397
2398 if (WantSinglePiece) {
2399 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
2400 Pieces.clear();
2401 Pieces.push_back(R);
2402 }
2403
2404 return Pieces;
2405}
2406}
2407
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002408//===----------------------------------------------------------------------===//
2409// Misc. API hooks.
2410//===----------------------------------------------------------------------===//
2411
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002412static llvm::sys::Mutex EnableMultithreadingMutex;
2413static bool EnabledMultithreading;
2414
Argyrios Kyrtzidisfa39f5b2011-12-15 04:52:41 +00002415static void fatal_error_handler(void *user_data, const std::string& reason) {
Argyrios Kyrtzidisfa39f5b2011-12-15 04:52:41 +00002416 // Write the result out to stderr avoiding errs() because raw_ostreams can
2417 // call report_fatal_error.
Argyrios Kyrtzidisdb7a8002011-12-15 06:51:30 +00002418 fprintf(stderr, "LIBCLANG FATAL ERROR: %s\n", reason.c_str());
Argyrios Kyrtzidisfa39f5b2011-12-15 04:52:41 +00002419 ::abort();
2420}
2421
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002422extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002423CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2424 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002425 // Disable pretty stack trace functionality, which will otherwise be a very
2426 // poor citizen of the world and set up all sorts of signal handlers.
2427 llvm::DisablePrettyStackTrace = true;
2428
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002429 // We use crash recovery to make some of our APIs more reliable, implicitly
2430 // enable it.
2431 llvm::CrashRecoveryContext::Enable();
2432
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002433 // Enable support for multithreading in LLVM.
2434 {
2435 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2436 if (!EnabledMultithreading) {
Argyrios Kyrtzidisfa39f5b2011-12-15 04:52:41 +00002437 llvm::install_fatal_error_handler(fatal_error_handler, 0);
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002438 llvm::llvm_start_multithreaded();
2439 EnabledMultithreading = true;
2440 }
2441 }
2442
Douglas Gregora030b7c2010-01-22 20:35:53 +00002443 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002444 if (excludeDeclarationsFromPCH)
2445 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002446 if (displayDiagnostics)
2447 CIdxr->setDisplayDiagnostics();
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002448
2449 if (getenv("LIBCLANG_BGPRIO_INDEX"))
2450 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
2451 CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
2452 if (getenv("LIBCLANG_BGPRIO_EDIT"))
2453 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
2454 CXGlobalOpt_ThreadBackgroundPriorityForEditing);
2455
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002456 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002457}
2458
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002459void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002460 if (CIdx)
2461 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002462}
2463
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002464void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
2465 if (CIdx)
2466 static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
2467}
2468
2469unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
2470 if (CIdx)
2471 return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
2472 return 0;
2473}
2474
Ted Kremenekd2427dd2011-03-18 23:05:39 +00002475void clang_toggleCrashRecovery(unsigned isEnabled) {
2476 if (isEnabled)
2477 llvm::CrashRecoveryContext::Enable();
2478 else
2479 llvm::CrashRecoveryContext::Disable();
2480}
2481
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002482CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002483 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002484 if (!CIdx)
2485 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002486
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002487 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002488 FileSystemOptions FileSystemOpts;
2489 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002490
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00002491 IntrusiveRefCntPtr<DiagnosticsEngine> Diags;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002492 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002493 CXXIdx->getOnlyLocalDecls(),
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00002494 0, 0,
2495 /*CaptureDiagnostics=*/true,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00002496 /*AllowPCHWithCompilerErrors=*/true,
2497 /*UserFilesAreVolatile=*/true);
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002498 return MakeCXTranslationUnit(CXXIdx, TU);
Steve Naroff600866c2009-08-27 19:51:58 +00002499}
2500
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002501unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002502 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregorb5af8432011-08-25 22:54:01 +00002503 CXTranslationUnit_CacheCompletionResults;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002504}
2505
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002506CXTranslationUnit
2507clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2508 const char *source_filename,
2509 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002510 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002511 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002512 struct CXUnsavedFile *unsaved_files) {
Argyrios Kyrtzidise1d43302012-02-25 02:41:16 +00002513 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
Douglas Gregor5a430212010-07-21 18:52:53 +00002514 return clang_parseTranslationUnit(CIdx, source_filename,
2515 command_line_args, num_command_line_args,
2516 unsaved_files, num_unsaved_files,
Douglas Gregordca8ee82011-05-06 16:33:08 +00002517 Options);
Douglas Gregor5a430212010-07-21 18:52:53 +00002518}
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00002519
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002520struct ParseTranslationUnitInfo {
2521 CXIndex CIdx;
2522 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002523 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002524 int num_command_line_args;
2525 struct CXUnsavedFile *unsaved_files;
2526 unsigned num_unsaved_files;
2527 unsigned options;
2528 CXTranslationUnit result;
2529};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002530static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002531 ParseTranslationUnitInfo *PTUI =
2532 static_cast<ParseTranslationUnitInfo*>(UserData);
2533 CXIndex CIdx = PTUI->CIdx;
2534 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002535 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002536 int num_command_line_args = PTUI->num_command_line_args;
2537 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2538 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2539 unsigned options = PTUI->options;
2540 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002541
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002542 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002543 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002544
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002545 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2546
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002547 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
Argyrios Kyrtzidis81b5ac32012-03-28 02:49:54 +00002548 setThreadBackgroundPriority();
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002549
Douglas Gregor44c181a2010-07-23 00:33:23 +00002550 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregor467dc882011-08-25 22:30:56 +00002551 // FIXME: Add a flag for modules.
2552 TranslationUnitKind TUKind
2553 = (options & CXTranslationUnit_Incomplete)? TU_Prefix : TU_Complete;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002554 bool CacheCodeCompetionResults
2555 = options & CXTranslationUnit_CacheCompletionResults;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002556 bool IncludeBriefCommentsInCodeCompletion
2557 = options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
Erik Verbruggen6a91d382012-04-12 10:11:59 +00002558 bool SkipFunctionBodies = options & CXTranslationUnit_SkipFunctionBodies;
2559
Douglas Gregor5352ac02010-01-28 00:27:43 +00002560 // Configure the diagnostics.
2561 DiagnosticOptions DiagOpts;
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00002562 IntrusiveRefCntPtr<DiagnosticsEngine>
Ted Kremenek25a11e12011-03-22 01:15:24 +00002563 Diags(CompilerInstance::createDiagnostics(DiagOpts, num_command_line_args,
2564 command_line_args));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002565
Ted Kremenek25a11e12011-03-22 01:15:24 +00002566 // Recover resources if we crash before exiting this function.
David Blaikied6471f72011-09-25 23:23:43 +00002567 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
2568 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00002569 DiagCleanup(Diags.getPtr());
2570
Dylan Noblesmith1e4c01b2012-02-13 12:32:21 +00002571 OwningPtr<std::vector<ASTUnit::RemappedFile> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00002572 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2573
2574 // Recover resources if we crash before exiting this function.
2575 llvm::CrashRecoveryContextCleanupRegistrar<
2576 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2577
Douglas Gregor4db64a42010-01-23 00:14:00 +00002578 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002579 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002580 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002581 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002582 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2583 Buffer));
Douglas Gregor4db64a42010-01-23 00:14:00 +00002584 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002585
Dylan Noblesmith1e4c01b2012-02-13 12:32:21 +00002586 OwningPtr<std::vector<const char *> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00002587 Args(new std::vector<const char*>());
2588
2589 // Recover resources if we crash before exiting this method.
2590 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
2591 ArgsCleanup(Args.get());
2592
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002593 // Since the Clang C library is primarily used by batch tools dealing with
2594 // (often very broken) source code, where spell-checking can have a
2595 // significant negative impact on performance (particularly when
2596 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002597 // Only do this if we haven't found a spell-checking-related argument.
2598 bool FoundSpellCheckingArgument = false;
2599 for (int I = 0; I != num_command_line_args; ++I) {
2600 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2601 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2602 FoundSpellCheckingArgument = true;
2603 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002604 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002605 }
2606 if (!FoundSpellCheckingArgument)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002607 Args->push_back("-fno-spell-checking");
Douglas Gregorb10daed2010-10-11 16:52:23 +00002608
Ted Kremenek25a11e12011-03-22 01:15:24 +00002609 Args->insert(Args->end(), command_line_args,
2610 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002611
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002612 // The 'source_filename' argument is optional. If the caller does not
2613 // specify it then it is assumed that the source file is specified
2614 // in the actual argument list.
2615 // Put the source file after command_line_args otherwise if '-x' flag is
2616 // present it will be unused.
2617 if (source_filename)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002618 Args->push_back(source_filename);
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002619
Douglas Gregor44c181a2010-07-23 00:33:23 +00002620 // Do we need the detailed preprocessing record?
2621 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Ted Kremenek25a11e12011-03-22 01:15:24 +00002622 Args->push_back("-Xclang");
2623 Args->push_back("-detailed-preprocessing-record");
Douglas Gregor44c181a2010-07-23 00:33:23 +00002624 }
2625
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002626 unsigned NumErrors = Diags->getClient()->getNumErrors();
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00002627 OwningPtr<ASTUnit> ErrUnit;
Dylan Noblesmith1e4c01b2012-02-13 12:32:21 +00002628 OwningPtr<ASTUnit> Unit(
Ted Kremenek4ee99262011-03-22 20:16:19 +00002629 ASTUnit::LoadFromCommandLine(Args->size() ? &(*Args)[0] : 0
2630 /* vector::data() not portable */,
2631 Args->size() ? (&(*Args)[0] + Args->size()) :0,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002632 Diags,
2633 CXXIdx->getClangResourcesPath(),
2634 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002635 /*CaptureDiagnostics=*/true,
Ted Kremenek4ee99262011-03-22 20:16:19 +00002636 RemappedFiles->size() ? &(*RemappedFiles)[0]:0,
Ted Kremenek25a11e12011-03-22 01:15:24 +00002637 RemappedFiles->size(),
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00002638 /*RemappedFilesKeepOriginalName=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002639 PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00002640 TUKind,
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00002641 CacheCodeCompetionResults,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002642 IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00002643 /*AllowPCHWithCompilerErrors=*/true,
Erik Verbruggen6a91d382012-04-12 10:11:59 +00002644 SkipFunctionBodies,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00002645 /*UserFilesAreVolatile=*/true,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00002646 &ErrUnit));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002647
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002648 if (NumErrors != Diags->getClient()->getNumErrors()) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002649 // Make sure to check that 'Unit' is non-NULL.
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00002650 if (CXXIdx->getDisplayDiagnostics())
2651 printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
Douglas Gregora88084b2010-02-18 18:08:43 +00002652 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002653
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002654 PTUI->result = MakeCXTranslationUnit(CXXIdx, Unit.take());
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002655}
2656CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2657 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002658 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002659 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002660 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002661 unsigned num_unsaved_files,
2662 unsigned options) {
2663 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002664 num_command_line_args, unsaved_files,
2665 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002666 llvm::CrashRecoveryContext CRC;
2667
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002668 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002669 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2670 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2671 fprintf(stderr, " 'command_line_args' : [");
2672 for (int i = 0; i != num_command_line_args; ++i) {
2673 if (i)
2674 fprintf(stderr, ", ");
2675 fprintf(stderr, "'%s'", command_line_args[i]);
2676 }
2677 fprintf(stderr, "],\n");
2678 fprintf(stderr, " 'unsaved_files' : [");
2679 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2680 if (i)
2681 fprintf(stderr, ", ");
2682 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2683 unsaved_files[i].Length);
2684 }
2685 fprintf(stderr, "],\n");
2686 fprintf(stderr, " 'options' : %d,\n", options);
2687 fprintf(stderr, "}\n");
2688
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002689 return 0;
Douglas Gregor6df78732011-05-05 20:27:22 +00002690 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
2691 PrintLibclangResourceUsage(PTUI.result);
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002692 }
Douglas Gregor6df78732011-05-05 20:27:22 +00002693
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002694 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002695}
2696
Douglas Gregor19998442010-08-13 15:35:05 +00002697unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2698 return CXSaveTranslationUnit_None;
2699}
Argyrios Kyrtzidis142bcb52012-03-28 02:17:59 +00002700
2701namespace {
2702
2703struct SaveTranslationUnitInfo {
2704 CXTranslationUnit TU;
2705 const char *FileName;
2706 unsigned options;
2707 CXSaveError result;
2708};
2709
2710}
2711
2712static void clang_saveTranslationUnit_Impl(void *UserData) {
2713 SaveTranslationUnitInfo *STUI =
2714 static_cast<SaveTranslationUnitInfo*>(UserData);
2715
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002716 CIndexer *CXXIdx = (CIndexer*)STUI->TU->CIdx;
2717 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
Argyrios Kyrtzidis81b5ac32012-03-28 02:49:54 +00002718 setThreadBackgroundPriority();
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002719
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002720 bool hadError = static_cast<ASTUnit *>(STUI->TU->TUData)->Save(STUI->FileName);
2721 STUI->result = hadError ? CXSaveError_Unknown : CXSaveError_None;
Argyrios Kyrtzidis142bcb52012-03-28 02:17:59 +00002722}
2723
Douglas Gregor19998442010-08-13 15:35:05 +00002724int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2725 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002726 if (!TU)
Douglas Gregor39c411f2011-07-06 16:43:36 +00002727 return CXSaveError_InvalidTU;
Argyrios Kyrtzidis142bcb52012-03-28 02:17:59 +00002728
2729 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
2730 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Argyrios Kyrtzidis374a00b2012-06-08 05:48:06 +00002731 if (!CXXUnit->hasSema())
2732 return CXSaveError_InvalidTU;
Argyrios Kyrtzidis142bcb52012-03-28 02:17:59 +00002733
2734 SaveTranslationUnitInfo STUI = { TU, FileName, options, CXSaveError_None };
2735
2736 if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred() ||
2737 getenv("LIBCLANG_NOTHREADS")) {
2738 clang_saveTranslationUnit_Impl(&STUI);
2739
2740 if (getenv("LIBCLANG_RESOURCE_USAGE"))
2741 PrintLibclangResourceUsage(TU);
2742
2743 return STUI.result;
2744 }
2745
2746 // We have an AST that has invalid nodes due to compiler errors.
2747 // Use a crash recovery thread for protection.
2748
2749 llvm::CrashRecoveryContext CRC;
2750
2751 if (!RunSafely(CRC, clang_saveTranslationUnit_Impl, &STUI)) {
2752 fprintf(stderr, "libclang: crash detected during AST saving: {\n");
2753 fprintf(stderr, " 'filename' : '%s'\n", FileName);
2754 fprintf(stderr, " 'options' : %d,\n", options);
2755 fprintf(stderr, "}\n");
2756
2757 return CXSaveError_Unknown;
2758
2759 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
Douglas Gregor6df78732011-05-05 20:27:22 +00002760 PrintLibclangResourceUsage(TU);
Argyrios Kyrtzidis142bcb52012-03-28 02:17:59 +00002761 }
2762
2763 return STUI.result;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002764}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002765
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002766void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002767 if (CTUnit) {
2768 // If the translation unit has been marked as unsafe to free, just discard
2769 // it.
Ted Kremeneka60ed472010-11-16 08:15:36 +00002770 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002771 return;
2772
Ted Kremeneka60ed472010-11-16 08:15:36 +00002773 delete static_cast<ASTUnit *>(CTUnit->TUData);
2774 disposeCXStringPool(CTUnit->StringPool);
Ted Kremenek15322172011-11-10 08:43:12 +00002775 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
Ted Kremenekbbf66ca2012-04-30 19:06:49 +00002776 disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002777 delete CTUnit;
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002778 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002779}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002780
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002781unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2782 return CXReparse_None;
2783}
2784
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002785struct ReparseTranslationUnitInfo {
2786 CXTranslationUnit TU;
2787 unsigned num_unsaved_files;
2788 struct CXUnsavedFile *unsaved_files;
2789 unsigned options;
2790 int result;
2791};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002792
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002793static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002794 ReparseTranslationUnitInfo *RTUI =
2795 static_cast<ReparseTranslationUnitInfo*>(UserData);
2796 CXTranslationUnit TU = RTUI->TU;
Ted Kremenek15322172011-11-10 08:43:12 +00002797
2798 // Reset the associated diagnostics.
2799 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
2800 TU->Diagnostics = 0;
2801
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002802 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2803 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2804 unsigned options = RTUI->options;
2805 (void) options;
2806 RTUI->result = 1;
2807
Douglas Gregorabc563f2010-07-19 21:46:24 +00002808 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002809 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002810
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002811 CIndexer *CXXIdx = (CIndexer*)TU->CIdx;
2812 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
Argyrios Kyrtzidis81b5ac32012-03-28 02:49:54 +00002813 setThreadBackgroundPriority();
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002814
Ted Kremeneka60ed472010-11-16 08:15:36 +00002815 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor593b0c12010-09-23 18:47:53 +00002816 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002817
Dylan Noblesmith1e4c01b2012-02-13 12:32:21 +00002818 OwningPtr<std::vector<ASTUnit::RemappedFile> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00002819 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2820
2821 // Recover resources if we crash before exiting this function.
2822 llvm::CrashRecoveryContextCleanupRegistrar<
2823 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2824
Douglas Gregorabc563f2010-07-19 21:46:24 +00002825 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002826 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002827 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002828 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002829 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2830 Buffer));
Douglas Gregorabc563f2010-07-19 21:46:24 +00002831 }
2832
Ted Kremenek4ee99262011-03-22 20:16:19 +00002833 if (!CXXUnit->Reparse(RemappedFiles->size() ? &(*RemappedFiles)[0] : 0,
2834 RemappedFiles->size()))
Douglas Gregor593b0c12010-09-23 18:47:53 +00002835 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002836}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002837
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002838int clang_reparseTranslationUnit(CXTranslationUnit TU,
2839 unsigned num_unsaved_files,
2840 struct CXUnsavedFile *unsaved_files,
2841 unsigned options) {
2842 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2843 options, 0 };
Argyrios Kyrtzidis8c4b47e2011-10-28 22:54:33 +00002844
Argyrios Kyrtzidise7de9b42011-10-29 19:32:39 +00002845 if (getenv("LIBCLANG_NOTHREADS")) {
Argyrios Kyrtzidis8c4b47e2011-10-28 22:54:33 +00002846 clang_reparseTranslationUnit_Impl(&RTUI);
2847 return RTUI.result;
2848 }
2849
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002850 llvm::CrashRecoveryContext CRC;
2851
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002852 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002853 fprintf(stderr, "libclang: crash detected during reparsing\n");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002854 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002855 return 1;
Douglas Gregor6df78732011-05-05 20:27:22 +00002856 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
2857 PrintLibclangResourceUsage(TU);
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002858
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002859 return RTUI.result;
2860}
2861
Douglas Gregordf95a132010-08-09 20:45:32 +00002862
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002863CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002864 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002865 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002866
Ted Kremeneka60ed472010-11-16 08:15:36 +00002867 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002868 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002869}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002870
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002871CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregor8e5900c2012-04-30 23:41:16 +00002872 ASTUnit *CXXUnit = static_cast<ASTUnit*>(TU->TUData);
2873 return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002874}
2875
Ted Kremenekfb480492010-01-13 21:46:36 +00002876} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002877
Ted Kremenekfb480492010-01-13 21:46:36 +00002878//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002879// CXFile Operations.
2880//===----------------------------------------------------------------------===//
2881
2882extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002883CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002884 if (!SFile)
Ted Kremeneka60ed472010-11-16 08:15:36 +00002885 return createCXString((const char*)NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002886
Steve Naroff88145032009-10-27 14:35:18 +00002887 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002888 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002889}
2890
2891time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002892 if (!SFile)
2893 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002894
Steve Naroff88145032009-10-27 14:35:18 +00002895 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2896 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002897}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002898
Douglas Gregorb9790342010-01-22 21:44:22 +00002899CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2900 if (!tu)
2901 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002902
Ted Kremeneka60ed472010-11-16 08:15:36 +00002903 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002904
Douglas Gregorb9790342010-01-22 21:44:22 +00002905 FileManager &FMgr = CXXUnit->getFileManager();
Chris Lattner39b49bc2010-11-23 08:35:12 +00002906 return const_cast<FileEntry *>(FMgr.getFile(file_name));
Douglas Gregorb9790342010-01-22 21:44:22 +00002907}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002908
Douglas Gregordd3e5542011-05-04 00:14:37 +00002909unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit tu, CXFile file) {
2910 if (!tu || !file)
2911 return 0;
2912
2913 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
2914 FileEntry *FEnt = static_cast<FileEntry *>(file);
2915 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
2916 .isFileMultipleIncludeGuarded(FEnt);
2917}
2918
Ted Kremenekfb480492010-01-13 21:46:36 +00002919} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002920
Ted Kremenekfb480492010-01-13 21:46:36 +00002921//===----------------------------------------------------------------------===//
2922// CXCursor Operations.
2923//===----------------------------------------------------------------------===//
2924
Ted Kremenekfb480492010-01-13 21:46:36 +00002925static Decl *getDeclFromExpr(Stmt *E) {
Argyrios Kyrtzidisc2954612011-09-12 22:17:26 +00002926 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Douglas Gregordb1314e2010-10-01 21:11:22 +00002927 return getDeclFromExpr(CE->getSubExpr());
2928
Ted Kremenekfb480492010-01-13 21:46:36 +00002929 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2930 return RefExpr->getDecl();
2931 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2932 return ME->getMemberDecl();
2933 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2934 return RE->getDecl();
Argyrios Kyrtzidisb085d892012-03-30 00:19:18 +00002935 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
2936 if (PRE->isExplicitProperty())
2937 return PRE->getExplicitProperty();
2938 // It could be messaging both getter and setter as in:
2939 // ++myobj.myprop;
2940 // in which case prefer to associate the setter since it is less obvious
2941 // from inspecting the source that the setter is going to get called.
2942 if (PRE->isMessagingSetter())
2943 return PRE->getImplicitPropertySetter();
2944 return PRE->getImplicitPropertyGetter();
2945 }
John McCall4b9c2d22011-11-06 09:01:30 +00002946 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
2947 return getDeclFromExpr(POE->getSyntacticForm());
2948 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
2949 if (Expr *Src = OVE->getSourceExpr())
2950 return getDeclFromExpr(Src);
Douglas Gregordb1314e2010-10-01 21:11:22 +00002951
Ted Kremenekfb480492010-01-13 21:46:36 +00002952 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2953 return getDeclFromExpr(CE->getCallee());
Chris Lattner5f9e2722011-07-23 10:55:15 +00002954 if (CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Douglas Gregor93798e22010-11-05 21:11:19 +00002955 if (!CE->isElidable())
2956 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002957 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2958 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002959
Douglas Gregordb1314e2010-10-01 21:11:22 +00002960 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2961 return PE->getProtocol();
Douglas Gregorc7793c72011-01-15 01:15:58 +00002962 if (SubstNonTypeTemplateParmPackExpr *NTTP
2963 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
2964 return NTTP->getParameterPack();
Douglas Gregor94d96292011-01-19 20:34:17 +00002965 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2966 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
2967 isa<ParmVarDecl>(SizeOfPack->getPack()))
2968 return SizeOfPack->getPack();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002969
Ted Kremenekfb480492010-01-13 21:46:36 +00002970 return 0;
2971}
2972
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002973static SourceLocation getLocationFromExpr(Expr *E) {
Argyrios Kyrtzidisc2954612011-09-12 22:17:26 +00002974 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
2975 return getLocationFromExpr(CE->getSubExpr());
2976
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002977 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2978 return /*FIXME:*/Msg->getLeftLoc();
2979 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2980 return DRE->getLocation();
2981 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2982 return Member->getMemberLoc();
2983 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2984 return Ivar->getLocation();
Douglas Gregor94d96292011-01-19 20:34:17 +00002985 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2986 return SizeOfPack->getPackLoc();
Argyrios Kyrtzidisd0469522012-03-30 00:19:13 +00002987 if (ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
2988 return PropRef->getLocation();
Douglas Gregor94d96292011-01-19 20:34:17 +00002989
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002990 return E->getLocStart();
2991}
2992
Ted Kremenekfb480492010-01-13 21:46:36 +00002993extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002994
2995unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002996 CXCursorVisitor visitor,
2997 CXClientData client_data) {
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00002998 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
2999 /*VisitPreprocessorLast=*/false);
Douglas Gregorb1373d02010-01-20 20:59:29 +00003000 return CursorVis.VisitChildren(parent);
3001}
3002
David Chisnall3387c652010-11-03 14:12:26 +00003003#ifndef __has_feature
3004#define __has_feature(x) 0
3005#endif
3006#if __has_feature(blocks)
3007typedef enum CXChildVisitResult
3008 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
3009
3010static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
3011 CXClientData client_data) {
3012 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
3013 return block(cursor, parent);
3014}
3015#else
3016// If we are compiled with a compiler that doesn't have native blocks support,
3017// define and call the block manually, so the
3018typedef struct _CXChildVisitResult
3019{
3020 void *isa;
3021 int flags;
3022 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003023 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
3024 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00003025} *CXCursorVisitorBlock;
3026
3027static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
3028 CXClientData client_data) {
3029 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
3030 return block->invoke(block, cursor, parent);
3031}
3032#endif
3033
3034
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003035unsigned clang_visitChildrenWithBlock(CXCursor parent,
3036 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00003037 return clang_visitChildren(parent, visitWithBlock, block);
3038}
3039
Douglas Gregor78205d42010-01-20 21:45:58 +00003040static CXString getDeclSpelling(Decl *D) {
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00003041 if (!D)
3042 return createCXString("");
3043
3044 NamedDecl *ND = dyn_cast<NamedDecl>(D);
Douglas Gregore3c60a72010-11-17 00:13:31 +00003045 if (!ND) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003046 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00003047 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3048 return createCXString(Property->getIdentifier()->getName());
3049
Argyrios Kyrtzidis6a010122012-10-05 00:22:24 +00003050 if (ImportDecl *ImportD = dyn_cast<ImportDecl>(D))
3051 if (Module *Mod = ImportD->getImportedModule())
3052 return createCXString(Mod->getFullModuleName());
3053
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003054 return createCXString("");
Douglas Gregore3c60a72010-11-17 00:13:31 +00003055 }
3056
Douglas Gregor78205d42010-01-20 21:45:58 +00003057 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003058 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003059
Douglas Gregor78205d42010-01-20 21:45:58 +00003060 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
3061 // No, this isn't the same as the code below. getIdentifier() is non-virtual
3062 // and returns different names. NamedDecl returns the class name and
3063 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003064 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003065
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003066 if (isa<UsingDirectiveDecl>(D))
3067 return createCXString("");
3068
Dylan Noblesmith36d59272012-02-13 12:32:26 +00003069 SmallString<1024> S;
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00003070 llvm::raw_svector_ostream os(S);
3071 ND->printName(os);
3072
3073 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00003074}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003075
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003076CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003077 if (clang_isTranslationUnit(C.kind))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003078 return clang_getTranslationUnitSpelling(
3079 static_cast<CXTranslationUnit>(C.data[2]));
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003080
Steve Narofff334b4e2009-09-02 18:26:48 +00003081 if (clang_isReference(C.kind)) {
3082 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00003083 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00003084 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003085 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003086 }
3087 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00003088 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003089 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003090 }
3091 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00003092 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00003093 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003094 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003095 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00003096 case CXCursor_CXXBaseSpecifier: {
3097 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
3098 return createCXString(B->getType().getAsString());
3099 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003100 case CXCursor_TypeRef: {
3101 TypeDecl *Type = getCursorTypeRef(C).first;
3102 assert(Type && "Missing type decl");
3103
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003104 return createCXString(getCursorContext(C).getTypeDeclType(Type).
3105 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003106 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003107 case CXCursor_TemplateRef: {
3108 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00003109 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003110
3111 return createCXString(Template->getNameAsString());
3112 }
Douglas Gregor69319002010-08-31 23:48:11 +00003113
3114 case CXCursor_NamespaceRef: {
3115 NamedDecl *NS = getCursorNamespaceRef(C).first;
3116 assert(NS && "Missing namespace decl");
3117
3118 return createCXString(NS->getNameAsString());
3119 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003120
Douglas Gregora67e03f2010-09-09 21:42:20 +00003121 case CXCursor_MemberRef: {
3122 FieldDecl *Field = getCursorMemberRef(C).first;
3123 assert(Field && "Missing member decl");
3124
3125 return createCXString(Field->getNameAsString());
3126 }
3127
Douglas Gregor36897b02010-09-10 00:22:18 +00003128 case CXCursor_LabelRef: {
3129 LabelStmt *Label = getCursorLabelRef(C).first;
3130 assert(Label && "Missing label");
3131
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003132 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00003133 }
3134
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003135 case CXCursor_OverloadedDeclRef: {
3136 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3137 if (Decl *D = Storage.dyn_cast<Decl *>()) {
3138 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
3139 return createCXString(ND->getNameAsString());
3140 return createCXString("");
3141 }
3142 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3143 return createCXString(E->getName().getAsString());
3144 OverloadedTemplateStorage *Ovl
3145 = Storage.get<OverloadedTemplateStorage*>();
3146 if (Ovl->size() == 0)
3147 return createCXString("");
3148 return createCXString((*Ovl->begin())->getNameAsString());
3149 }
3150
Douglas Gregor011d8b92012-02-15 00:54:55 +00003151 case CXCursor_VariableRef: {
3152 VarDecl *Var = getCursorVariableRef(C).first;
3153 assert(Var && "Missing variable decl");
3154
3155 return createCXString(Var->getNameAsString());
3156 }
3157
Daniel Dunbaracca7252009-11-30 20:42:49 +00003158 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003159 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00003160 }
3161 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003162
3163 if (clang_isExpression(C.kind)) {
3164 Decl *D = getDeclFromExpr(getCursorExpr(C));
3165 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00003166 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003167 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00003168 }
3169
Douglas Gregor36897b02010-09-10 00:22:18 +00003170 if (clang_isStatement(C.kind)) {
3171 Stmt *S = getCursorStmt(C);
3172 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003173 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00003174
3175 return createCXString("");
3176 }
3177
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003178 if (C.kind == CXCursor_MacroExpansion)
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003179 return createCXString(getCursorMacroExpansion(C)->getName()
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003180 ->getNameStart());
3181
Douglas Gregor572feb22010-03-18 18:04:21 +00003182 if (C.kind == CXCursor_MacroDefinition)
3183 return createCXString(getCursorMacroDefinition(C)->getName()
3184 ->getNameStart());
3185
Douglas Gregorecdcb882010-10-20 22:00:55 +00003186 if (C.kind == CXCursor_InclusionDirective)
3187 return createCXString(getCursorInclusionDirective(C)->getFileName());
3188
Douglas Gregor60cbfac2010-01-25 16:56:17 +00003189 if (clang_isDeclaration(C.kind))
3190 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00003191
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00003192 if (C.kind == CXCursor_AnnotateAttr) {
3193 AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
3194 return createCXString(AA->getAnnotation());
3195 }
3196
Argyrios Kyrtzidis84b79642011-12-06 22:05:01 +00003197 if (C.kind == CXCursor_AsmLabelAttr) {
3198 AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
3199 return createCXString(AA->getLabel());
3200 }
3201
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003202 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00003203}
3204
Argyrios Kyrtzidisba1da142012-03-30 20:58:35 +00003205CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C,
3206 unsigned pieceIndex,
3207 unsigned options) {
3208 if (clang_Cursor_isNull(C))
3209 return clang_getNullRange();
3210
3211 ASTContext &Ctx = getCursorContext(C);
3212
3213 if (clang_isStatement(C.kind)) {
3214 Stmt *S = getCursorStmt(C);
3215 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
3216 if (pieceIndex > 0)
3217 return clang_getNullRange();
3218 return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
3219 }
3220
3221 return clang_getNullRange();
3222 }
3223
3224 if (C.kind == CXCursor_ObjCMessageExpr) {
3225 if (ObjCMessageExpr *
3226 ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
3227 if (pieceIndex >= ME->getNumSelectorLocs())
3228 return clang_getNullRange();
3229 return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
3230 }
3231 }
3232
3233 if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
3234 C.kind == CXCursor_ObjCClassMethodDecl) {
3235 if (ObjCMethodDecl *
3236 MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
3237 if (pieceIndex >= MD->getNumSelectorLocs())
3238 return clang_getNullRange();
3239 return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
3240 }
3241 }
3242
Argyrios Kyrtzidis9482a182012-04-16 20:01:28 +00003243 if (C.kind == CXCursor_ObjCCategoryDecl ||
3244 C.kind == CXCursor_ObjCCategoryImplDecl) {
3245 if (pieceIndex > 0)
3246 return clang_getNullRange();
3247 if (ObjCCategoryDecl *
3248 CD = dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
3249 return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
3250 if (ObjCCategoryImplDecl *
3251 CID = dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
3252 return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
3253 }
3254
Argyrios Kyrtzidis6a010122012-10-05 00:22:24 +00003255 if (C.kind == CXCursor_ModuleImportDecl) {
3256 if (pieceIndex > 0)
3257 return clang_getNullRange();
3258 if (ImportDecl *ImportD = dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) {
3259 ArrayRef<SourceLocation> Locs = ImportD->getIdentifierLocs();
3260 if (!Locs.empty())
3261 return cxloc::translateSourceRange(Ctx,
3262 SourceRange(Locs.front(), Locs.back()));
3263 }
3264 return clang_getNullRange();
3265 }
3266
Argyrios Kyrtzidisba1da142012-03-30 20:58:35 +00003267 // FIXME: A CXCursor_InclusionDirective should give the location of the
3268 // filename, but we don't keep track of this.
3269
3270 // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
3271 // but we don't keep track of this.
3272
3273 // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
3274 // but we don't keep track of this.
3275
3276 // Default handling, give the location of the cursor.
3277
3278 if (pieceIndex > 0)
3279 return clang_getNullRange();
3280
3281 CXSourceLocation CXLoc = clang_getCursorLocation(C);
3282 SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
3283 return cxloc::translateSourceRange(Ctx, Loc);
3284}
3285
Douglas Gregor358559d2010-10-02 22:49:11 +00003286CXString clang_getCursorDisplayName(CXCursor C) {
3287 if (!clang_isDeclaration(C.kind))
3288 return clang_getCursorSpelling(C);
3289
3290 Decl *D = getCursorDecl(C);
3291 if (!D)
3292 return createCXString("");
3293
Douglas Gregor30c42402011-09-27 22:38:19 +00003294 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
Douglas Gregor358559d2010-10-02 22:49:11 +00003295 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
3296 D = FunTmpl->getTemplatedDecl();
3297
3298 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Dylan Noblesmith36d59272012-02-13 12:32:26 +00003299 SmallString<64> Str;
Douglas Gregor358559d2010-10-02 22:49:11 +00003300 llvm::raw_svector_ostream OS(Str);
Benjamin Kramera59d20b2012-02-07 11:57:57 +00003301 OS << *Function;
Douglas Gregor358559d2010-10-02 22:49:11 +00003302 if (Function->getPrimaryTemplate())
3303 OS << "<>";
3304 OS << "(";
3305 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
3306 if (I)
3307 OS << ", ";
3308 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
3309 }
3310
3311 if (Function->isVariadic()) {
3312 if (Function->getNumParams())
3313 OS << ", ";
3314 OS << "...";
3315 }
3316 OS << ")";
3317 return createCXString(OS.str());
3318 }
3319
3320 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
Dylan Noblesmith36d59272012-02-13 12:32:26 +00003321 SmallString<64> Str;
Douglas Gregor358559d2010-10-02 22:49:11 +00003322 llvm::raw_svector_ostream OS(Str);
Benjamin Kramera59d20b2012-02-07 11:57:57 +00003323 OS << *ClassTemplate;
Douglas Gregor358559d2010-10-02 22:49:11 +00003324 OS << "<";
3325 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
3326 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3327 if (I)
3328 OS << ", ";
3329
3330 NamedDecl *Param = Params->getParam(I);
3331 if (Param->getIdentifier()) {
3332 OS << Param->getIdentifier()->getName();
3333 continue;
3334 }
3335
3336 // There is no parameter name, which makes this tricky. Try to come up
3337 // with something useful that isn't too long.
3338 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3339 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
3340 else if (NonTypeTemplateParmDecl *NTTP
3341 = dyn_cast<NonTypeTemplateParmDecl>(Param))
3342 OS << NTTP->getType().getAsString(Policy);
3343 else
3344 OS << "template<...> class";
3345 }
3346
3347 OS << ">";
3348 return createCXString(OS.str());
3349 }
3350
3351 if (ClassTemplateSpecializationDecl *ClassSpec
3352 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
3353 // If the type was explicitly written, use that.
3354 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
3355 return createCXString(TSInfo->getType().getAsString(Policy));
3356
Dylan Noblesmith36d59272012-02-13 12:32:26 +00003357 SmallString<64> Str;
Douglas Gregor358559d2010-10-02 22:49:11 +00003358 llvm::raw_svector_ostream OS(Str);
Benjamin Kramera59d20b2012-02-07 11:57:57 +00003359 OS << *ClassSpec;
Douglas Gregor358559d2010-10-02 22:49:11 +00003360 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00003361 ClassSpec->getTemplateArgs().data(),
3362 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00003363 Policy);
3364 return createCXString(OS.str());
3365 }
3366
3367 return clang_getCursorSpelling(C);
3368}
3369
Ted Kremeneke68fff62010-02-17 00:41:32 +00003370CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00003371 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00003372 case CXCursor_FunctionDecl:
3373 return createCXString("FunctionDecl");
3374 case CXCursor_TypedefDecl:
3375 return createCXString("TypedefDecl");
3376 case CXCursor_EnumDecl:
3377 return createCXString("EnumDecl");
3378 case CXCursor_EnumConstantDecl:
3379 return createCXString("EnumConstantDecl");
3380 case CXCursor_StructDecl:
3381 return createCXString("StructDecl");
3382 case CXCursor_UnionDecl:
3383 return createCXString("UnionDecl");
3384 case CXCursor_ClassDecl:
3385 return createCXString("ClassDecl");
3386 case CXCursor_FieldDecl:
3387 return createCXString("FieldDecl");
3388 case CXCursor_VarDecl:
3389 return createCXString("VarDecl");
3390 case CXCursor_ParmDecl:
3391 return createCXString("ParmDecl");
3392 case CXCursor_ObjCInterfaceDecl:
3393 return createCXString("ObjCInterfaceDecl");
3394 case CXCursor_ObjCCategoryDecl:
3395 return createCXString("ObjCCategoryDecl");
3396 case CXCursor_ObjCProtocolDecl:
3397 return createCXString("ObjCProtocolDecl");
3398 case CXCursor_ObjCPropertyDecl:
3399 return createCXString("ObjCPropertyDecl");
3400 case CXCursor_ObjCIvarDecl:
3401 return createCXString("ObjCIvarDecl");
3402 case CXCursor_ObjCInstanceMethodDecl:
3403 return createCXString("ObjCInstanceMethodDecl");
3404 case CXCursor_ObjCClassMethodDecl:
3405 return createCXString("ObjCClassMethodDecl");
3406 case CXCursor_ObjCImplementationDecl:
3407 return createCXString("ObjCImplementationDecl");
3408 case CXCursor_ObjCCategoryImplDecl:
3409 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00003410 case CXCursor_CXXMethod:
3411 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003412 case CXCursor_UnexposedDecl:
3413 return createCXString("UnexposedDecl");
3414 case CXCursor_ObjCSuperClassRef:
3415 return createCXString("ObjCSuperClassRef");
3416 case CXCursor_ObjCProtocolRef:
3417 return createCXString("ObjCProtocolRef");
3418 case CXCursor_ObjCClassRef:
3419 return createCXString("ObjCClassRef");
3420 case CXCursor_TypeRef:
3421 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003422 case CXCursor_TemplateRef:
3423 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00003424 case CXCursor_NamespaceRef:
3425 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00003426 case CXCursor_MemberRef:
3427 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00003428 case CXCursor_LabelRef:
3429 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003430 case CXCursor_OverloadedDeclRef:
3431 return createCXString("OverloadedDeclRef");
Douglas Gregor011d8b92012-02-15 00:54:55 +00003432 case CXCursor_VariableRef:
3433 return createCXString("VariableRef");
Douglas Gregor42b29842011-10-05 19:00:14 +00003434 case CXCursor_IntegerLiteral:
3435 return createCXString("IntegerLiteral");
3436 case CXCursor_FloatingLiteral:
3437 return createCXString("FloatingLiteral");
3438 case CXCursor_ImaginaryLiteral:
3439 return createCXString("ImaginaryLiteral");
3440 case CXCursor_StringLiteral:
3441 return createCXString("StringLiteral");
3442 case CXCursor_CharacterLiteral:
3443 return createCXString("CharacterLiteral");
3444 case CXCursor_ParenExpr:
3445 return createCXString("ParenExpr");
3446 case CXCursor_UnaryOperator:
3447 return createCXString("UnaryOperator");
3448 case CXCursor_ArraySubscriptExpr:
3449 return createCXString("ArraySubscriptExpr");
3450 case CXCursor_BinaryOperator:
3451 return createCXString("BinaryOperator");
3452 case CXCursor_CompoundAssignOperator:
3453 return createCXString("CompoundAssignOperator");
3454 case CXCursor_ConditionalOperator:
3455 return createCXString("ConditionalOperator");
3456 case CXCursor_CStyleCastExpr:
3457 return createCXString("CStyleCastExpr");
3458 case CXCursor_CompoundLiteralExpr:
3459 return createCXString("CompoundLiteralExpr");
3460 case CXCursor_InitListExpr:
3461 return createCXString("InitListExpr");
3462 case CXCursor_AddrLabelExpr:
3463 return createCXString("AddrLabelExpr");
3464 case CXCursor_StmtExpr:
3465 return createCXString("StmtExpr");
3466 case CXCursor_GenericSelectionExpr:
3467 return createCXString("GenericSelectionExpr");
3468 case CXCursor_GNUNullExpr:
3469 return createCXString("GNUNullExpr");
3470 case CXCursor_CXXStaticCastExpr:
3471 return createCXString("CXXStaticCastExpr");
3472 case CXCursor_CXXDynamicCastExpr:
3473 return createCXString("CXXDynamicCastExpr");
3474 case CXCursor_CXXReinterpretCastExpr:
3475 return createCXString("CXXReinterpretCastExpr");
3476 case CXCursor_CXXConstCastExpr:
3477 return createCXString("CXXConstCastExpr");
3478 case CXCursor_CXXFunctionalCastExpr:
3479 return createCXString("CXXFunctionalCastExpr");
3480 case CXCursor_CXXTypeidExpr:
3481 return createCXString("CXXTypeidExpr");
3482 case CXCursor_CXXBoolLiteralExpr:
3483 return createCXString("CXXBoolLiteralExpr");
3484 case CXCursor_CXXNullPtrLiteralExpr:
3485 return createCXString("CXXNullPtrLiteralExpr");
3486 case CXCursor_CXXThisExpr:
3487 return createCXString("CXXThisExpr");
3488 case CXCursor_CXXThrowExpr:
3489 return createCXString("CXXThrowExpr");
3490 case CXCursor_CXXNewExpr:
3491 return createCXString("CXXNewExpr");
3492 case CXCursor_CXXDeleteExpr:
3493 return createCXString("CXXDeleteExpr");
3494 case CXCursor_UnaryExpr:
3495 return createCXString("UnaryExpr");
3496 case CXCursor_ObjCStringLiteral:
3497 return createCXString("ObjCStringLiteral");
Ted Kremenekb3f75422012-03-06 20:06:06 +00003498 case CXCursor_ObjCBoolLiteralExpr:
3499 return createCXString("ObjCBoolLiteralExpr");
Douglas Gregor42b29842011-10-05 19:00:14 +00003500 case CXCursor_ObjCEncodeExpr:
3501 return createCXString("ObjCEncodeExpr");
3502 case CXCursor_ObjCSelectorExpr:
3503 return createCXString("ObjCSelectorExpr");
3504 case CXCursor_ObjCProtocolExpr:
3505 return createCXString("ObjCProtocolExpr");
3506 case CXCursor_ObjCBridgedCastExpr:
3507 return createCXString("ObjCBridgedCastExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00003508 case CXCursor_BlockExpr:
3509 return createCXString("BlockExpr");
Douglas Gregor42b29842011-10-05 19:00:14 +00003510 case CXCursor_PackExpansionExpr:
3511 return createCXString("PackExpansionExpr");
3512 case CXCursor_SizeOfPackExpr:
3513 return createCXString("SizeOfPackExpr");
Douglas Gregor011d8b92012-02-15 00:54:55 +00003514 case CXCursor_LambdaExpr:
3515 return createCXString("LambdaExpr");
Douglas Gregor42b29842011-10-05 19:00:14 +00003516 case CXCursor_UnexposedExpr:
3517 return createCXString("UnexposedExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003518 case CXCursor_DeclRefExpr:
3519 return createCXString("DeclRefExpr");
3520 case CXCursor_MemberRefExpr:
3521 return createCXString("MemberRefExpr");
3522 case CXCursor_CallExpr:
3523 return createCXString("CallExpr");
3524 case CXCursor_ObjCMessageExpr:
3525 return createCXString("ObjCMessageExpr");
3526 case CXCursor_UnexposedStmt:
3527 return createCXString("UnexposedStmt");
Douglas Gregor42b29842011-10-05 19:00:14 +00003528 case CXCursor_DeclStmt:
3529 return createCXString("DeclStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00003530 case CXCursor_LabelStmt:
3531 return createCXString("LabelStmt");
Douglas Gregor42b29842011-10-05 19:00:14 +00003532 case CXCursor_CompoundStmt:
3533 return createCXString("CompoundStmt");
3534 case CXCursor_CaseStmt:
3535 return createCXString("CaseStmt");
3536 case CXCursor_DefaultStmt:
3537 return createCXString("DefaultStmt");
3538 case CXCursor_IfStmt:
3539 return createCXString("IfStmt");
3540 case CXCursor_SwitchStmt:
3541 return createCXString("SwitchStmt");
3542 case CXCursor_WhileStmt:
3543 return createCXString("WhileStmt");
3544 case CXCursor_DoStmt:
3545 return createCXString("DoStmt");
3546 case CXCursor_ForStmt:
3547 return createCXString("ForStmt");
3548 case CXCursor_GotoStmt:
3549 return createCXString("GotoStmt");
3550 case CXCursor_IndirectGotoStmt:
3551 return createCXString("IndirectGotoStmt");
3552 case CXCursor_ContinueStmt:
3553 return createCXString("ContinueStmt");
3554 case CXCursor_BreakStmt:
3555 return createCXString("BreakStmt");
3556 case CXCursor_ReturnStmt:
3557 return createCXString("ReturnStmt");
Chad Rosierdf5faf52012-08-25 00:11:56 +00003558 case CXCursor_GCCAsmStmt:
3559 return createCXString("GCCAsmStmt");
Chad Rosier8cd64b42012-06-11 20:47:18 +00003560 case CXCursor_MSAsmStmt:
3561 return createCXString("MSAsmStmt");
Douglas Gregor42b29842011-10-05 19:00:14 +00003562 case CXCursor_ObjCAtTryStmt:
3563 return createCXString("ObjCAtTryStmt");
3564 case CXCursor_ObjCAtCatchStmt:
3565 return createCXString("ObjCAtCatchStmt");
3566 case CXCursor_ObjCAtFinallyStmt:
3567 return createCXString("ObjCAtFinallyStmt");
3568 case CXCursor_ObjCAtThrowStmt:
3569 return createCXString("ObjCAtThrowStmt");
3570 case CXCursor_ObjCAtSynchronizedStmt:
3571 return createCXString("ObjCAtSynchronizedStmt");
3572 case CXCursor_ObjCAutoreleasePoolStmt:
3573 return createCXString("ObjCAutoreleasePoolStmt");
3574 case CXCursor_ObjCForCollectionStmt:
3575 return createCXString("ObjCForCollectionStmt");
3576 case CXCursor_CXXCatchStmt:
3577 return createCXString("CXXCatchStmt");
3578 case CXCursor_CXXTryStmt:
3579 return createCXString("CXXTryStmt");
3580 case CXCursor_CXXForRangeStmt:
3581 return createCXString("CXXForRangeStmt");
3582 case CXCursor_SEHTryStmt:
3583 return createCXString("SEHTryStmt");
3584 case CXCursor_SEHExceptStmt:
3585 return createCXString("SEHExceptStmt");
3586 case CXCursor_SEHFinallyStmt:
3587 return createCXString("SEHFinallyStmt");
3588 case CXCursor_NullStmt:
3589 return createCXString("NullStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003590 case CXCursor_InvalidFile:
3591 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00003592 case CXCursor_InvalidCode:
3593 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003594 case CXCursor_NoDeclFound:
3595 return createCXString("NoDeclFound");
3596 case CXCursor_NotImplemented:
3597 return createCXString("NotImplemented");
3598 case CXCursor_TranslationUnit:
3599 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00003600 case CXCursor_UnexposedAttr:
3601 return createCXString("UnexposedAttr");
3602 case CXCursor_IBActionAttr:
3603 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003604 case CXCursor_IBOutletAttr:
3605 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003606 case CXCursor_IBOutletCollectionAttr:
3607 return createCXString("attribute(iboutletcollection)");
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00003608 case CXCursor_CXXFinalAttr:
3609 return createCXString("attribute(final)");
3610 case CXCursor_CXXOverrideAttr:
3611 return createCXString("attribute(override)");
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00003612 case CXCursor_AnnotateAttr:
3613 return createCXString("attribute(annotate)");
Argyrios Kyrtzidis84b79642011-12-06 22:05:01 +00003614 case CXCursor_AsmLabelAttr:
3615 return createCXString("asm label");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003616 case CXCursor_PreprocessingDirective:
3617 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003618 case CXCursor_MacroDefinition:
3619 return createCXString("macro definition");
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003620 case CXCursor_MacroExpansion:
3621 return createCXString("macro expansion");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003622 case CXCursor_InclusionDirective:
3623 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003624 case CXCursor_Namespace:
3625 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003626 case CXCursor_LinkageSpec:
3627 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003628 case CXCursor_CXXBaseSpecifier:
3629 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003630 case CXCursor_Constructor:
3631 return createCXString("CXXConstructor");
3632 case CXCursor_Destructor:
3633 return createCXString("CXXDestructor");
3634 case CXCursor_ConversionFunction:
3635 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003636 case CXCursor_TemplateTypeParameter:
3637 return createCXString("TemplateTypeParameter");
3638 case CXCursor_NonTypeTemplateParameter:
3639 return createCXString("NonTypeTemplateParameter");
3640 case CXCursor_TemplateTemplateParameter:
3641 return createCXString("TemplateTemplateParameter");
3642 case CXCursor_FunctionTemplate:
3643 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003644 case CXCursor_ClassTemplate:
3645 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003646 case CXCursor_ClassTemplatePartialSpecialization:
3647 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003648 case CXCursor_NamespaceAlias:
3649 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003650 case CXCursor_UsingDirective:
3651 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003652 case CXCursor_UsingDeclaration:
3653 return createCXString("UsingDeclaration");
Richard Smith162e1c12011-04-15 14:24:37 +00003654 case CXCursor_TypeAliasDecl:
Douglas Gregor352697a2011-06-03 23:08:58 +00003655 return createCXString("TypeAliasDecl");
3656 case CXCursor_ObjCSynthesizeDecl:
3657 return createCXString("ObjCSynthesizeDecl");
3658 case CXCursor_ObjCDynamicDecl:
3659 return createCXString("ObjCDynamicDecl");
Argyrios Kyrtzidis2dfdb942011-09-30 17:58:23 +00003660 case CXCursor_CXXAccessSpecifier:
3661 return createCXString("CXXAccessSpecifier");
Argyrios Kyrtzidis6a010122012-10-05 00:22:24 +00003662 case CXCursor_ModuleImportDecl:
3663 return createCXString("ModuleImport");
Steve Naroff89922f82009-08-31 00:59:03 +00003664 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003665
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003666 llvm_unreachable("Unhandled CXCursorKind");
Steve Naroff600866c2009-08-27 19:51:58 +00003667}
Steve Naroff89922f82009-08-31 00:59:03 +00003668
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003669struct GetCursorData {
3670 SourceLocation TokenBeginLoc;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003671 bool PointsAtMacroArgExpansion;
Argyrios Kyrtzidis135bf8e2012-06-09 03:03:02 +00003672 bool VisitedObjCPropertyImplDecl;
3673 SourceLocation VisitedDeclaratorDeclStartLoc;
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003674 CXCursor &BestCursor;
3675
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003676 GetCursorData(SourceManager &SM,
3677 SourceLocation tokenBegin, CXCursor &outputCursor)
3678 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
3679 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
Argyrios Kyrtzidis135bf8e2012-06-09 03:03:02 +00003680 VisitedObjCPropertyImplDecl = false;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003681 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003682};
3683
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003684static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3685 CXCursor parent,
3686 CXClientData client_data) {
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003687 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
3688 CXCursor *BestCursor = &Data->BestCursor;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003689
3690 // If we point inside a macro argument we should provide info of what the
3691 // token is so use the actual cursor, don't replace it with a macro expansion
3692 // cursor.
3693 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
3694 return CXChildVisit_Recurse;
Argyrios Kyrtzidis65ab9072011-09-26 19:05:37 +00003695
3696 if (clang_isDeclaration(cursor.kind)) {
3697 // Avoid having the implicit methods override the property decls.
Argyrios Kyrtzidisa9d45a32012-04-16 22:42:01 +00003698 if (ObjCMethodDecl *MD
3699 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
Argyrios Kyrtzidis65ab9072011-09-26 19:05:37 +00003700 if (MD->isImplicit())
3701 return CXChildVisit_Break;
Argyrios Kyrtzidisa9d45a32012-04-16 22:42:01 +00003702
3703 } else if (ObjCInterfaceDecl *ID
3704 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) {
3705 // Check that when we have multiple @class references in the same line,
3706 // that later ones do not override the previous ones.
3707 // If we have:
3708 // @class Foo, Bar;
3709 // source ranges for both start at '@', so 'Bar' will end up overriding
3710 // 'Foo' even though the cursor location was at 'Foo'.
3711 if (BestCursor->kind == CXCursor_ObjCInterfaceDecl ||
3712 BestCursor->kind == CXCursor_ObjCClassRef)
3713 if (ObjCInterfaceDecl *PrevID
3714 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(*BestCursor))){
3715 if (PrevID != ID &&
3716 !PrevID->isThisDeclarationADefinition() &&
3717 !ID->isThisDeclarationADefinition())
3718 return CXChildVisit_Break;
3719 }
Argyrios Kyrtzidis135bf8e2012-06-09 03:03:02 +00003720
3721 } else if (DeclaratorDecl *DD
3722 = dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) {
3723 SourceLocation StartLoc = DD->getSourceRange().getBegin();
3724 // Check that when we have multiple declarators in the same line,
3725 // that later ones do not override the previous ones.
3726 // If we have:
3727 // int Foo, Bar;
3728 // source ranges for both start at 'int', so 'Bar' will end up overriding
3729 // 'Foo' even though the cursor location was at 'Foo'.
3730 if (Data->VisitedDeclaratorDeclStartLoc == StartLoc)
3731 return CXChildVisit_Break;
3732 Data->VisitedDeclaratorDeclStartLoc = StartLoc;
3733
3734 } else if (ObjCPropertyImplDecl *PropImp
3735 = dyn_cast_or_null<ObjCPropertyImplDecl>(getCursorDecl(cursor))) {
3736 (void)PropImp;
3737 // Check that when we have multiple @synthesize in the same line,
3738 // that later ones do not override the previous ones.
3739 // If we have:
3740 // @synthesize Foo, Bar;
3741 // source ranges for both start at '@', so 'Bar' will end up overriding
3742 // 'Foo' even though the cursor location was at 'Foo'.
3743 if (Data->VisitedObjCPropertyImplDecl)
3744 return CXChildVisit_Break;
3745 Data->VisitedObjCPropertyImplDecl = true;
Argyrios Kyrtzidisa9d45a32012-04-16 22:42:01 +00003746 }
Argyrios Kyrtzidis65ab9072011-09-26 19:05:37 +00003747 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003748
3749 if (clang_isExpression(cursor.kind) &&
3750 clang_isDeclaration(BestCursor->kind)) {
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00003751 if (Decl *D = getCursorDecl(*BestCursor)) {
3752 // Avoid having the cursor of an expression replace the declaration cursor
3753 // when the expression source range overlaps the declaration range.
3754 // This can happen for C++ constructor expressions whose range generally
3755 // include the variable declaration, e.g.:
3756 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
3757 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
3758 D->getLocation() == Data->TokenBeginLoc)
3759 return CXChildVisit_Break;
3760 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003761 }
3762
Douglas Gregor93798e22010-11-05 21:11:19 +00003763 // If our current best cursor is the construction of a temporary object,
3764 // don't replace that cursor with a type reference, because we want
3765 // clang_getCursor() to point at the constructor.
3766 if (clang_isExpression(BestCursor->kind) &&
3767 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003768 cursor.kind == CXCursor_TypeRef) {
3769 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
3770 // as having the actual point on the type reference.
3771 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
Douglas Gregor93798e22010-11-05 21:11:19 +00003772 return CXChildVisit_Recurse;
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003773 }
Douglas Gregor93798e22010-11-05 21:11:19 +00003774
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003775 *BestCursor = cursor;
3776 return CXChildVisit_Recurse;
3777}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003778
Douglas Gregorb9790342010-01-22 21:44:22 +00003779CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3780 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003781 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003782
Ted Kremeneka60ed472010-11-16 08:15:36 +00003783 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003784 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3785
Ted Kremeneka297de22010-01-25 22:34:44 +00003786 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003787 CXCursor Result = cxcursor::getCursor(TU, SLoc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003788
Douglas Gregor40749ee2010-11-03 00:35:38 +00003789 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregor40749ee2010-11-03 00:35:38 +00003790 if (Logging) {
3791 CXFile SearchFile;
3792 unsigned SearchLine, SearchColumn;
3793 CXFile ResultFile;
3794 unsigned ResultLine, ResultColumn;
Douglas Gregor66537982010-11-17 17:14:07 +00003795 CXString SearchFileName, ResultFileName, KindSpelling, USR;
3796 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
Douglas Gregor40749ee2010-11-03 00:35:38 +00003797 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3798
Chandler Carruth20174222011-08-31 16:53:37 +00003799 clang_getExpansionLocation(Loc, &SearchFile, &SearchLine, &SearchColumn, 0);
3800 clang_getExpansionLocation(ResultLoc, &ResultFile, &ResultLine,
3801 &ResultColumn, 0);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003802 SearchFileName = clang_getFileName(SearchFile);
3803 ResultFileName = clang_getFileName(ResultFile);
3804 KindSpelling = clang_getCursorKindSpelling(Result.kind);
Douglas Gregor66537982010-11-17 17:14:07 +00003805 USR = clang_getCursorUSR(Result);
3806 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n",
Douglas Gregor40749ee2010-11-03 00:35:38 +00003807 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3808 clang_getCString(KindSpelling),
Douglas Gregor66537982010-11-17 17:14:07 +00003809 clang_getCString(ResultFileName), ResultLine, ResultColumn,
3810 clang_getCString(USR), IsDef);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003811 clang_disposeString(SearchFileName);
3812 clang_disposeString(ResultFileName);
3813 clang_disposeString(KindSpelling);
Douglas Gregor66537982010-11-17 17:14:07 +00003814 clang_disposeString(USR);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003815
3816 CXCursor Definition = clang_getCursorDefinition(Result);
3817 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
3818 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
3819 CXString DefinitionKindSpelling
3820 = clang_getCursorKindSpelling(Definition.kind);
3821 CXFile DefinitionFile;
3822 unsigned DefinitionLine, DefinitionColumn;
Chandler Carruth20174222011-08-31 16:53:37 +00003823 clang_getExpansionLocation(DefinitionLoc, &DefinitionFile,
3824 &DefinitionLine, &DefinitionColumn, 0);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003825 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
3826 fprintf(stderr, " -> %s(%s:%d:%d)\n",
3827 clang_getCString(DefinitionKindSpelling),
3828 clang_getCString(DefinitionFileName),
3829 DefinitionLine, DefinitionColumn);
3830 clang_disposeString(DefinitionFileName);
3831 clang_disposeString(DefinitionKindSpelling);
3832 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003833 }
3834
Ted Kremeneke68fff62010-02-17 00:41:32 +00003835 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003836}
3837
Ted Kremenek73885552009-11-17 19:28:59 +00003838CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003839 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003840}
3841
3842unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003843 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003844}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003845
Douglas Gregor9ce55842010-11-20 00:09:34 +00003846unsigned clang_hashCursor(CXCursor C) {
3847 unsigned Index = 0;
3848 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
3849 Index = 1;
3850
3851 return llvm::DenseMapInfo<std::pair<unsigned, void*> >::getHashValue(
3852 std::make_pair(C.kind, C.data[Index]));
3853}
3854
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003855unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003856 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3857}
3858
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003859unsigned clang_isDeclaration(enum CXCursorKind K) {
Argyrios Kyrtzidis6a010122012-10-05 00:22:24 +00003860 return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) ||
3861 (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl);
Steve Naroff89922f82009-08-31 00:59:03 +00003862}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003863
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003864unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003865 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3866}
3867
Douglas Gregor97b98722010-01-19 23:20:36 +00003868unsigned clang_isExpression(enum CXCursorKind K) {
3869 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3870}
3871
3872unsigned clang_isStatement(enum CXCursorKind K) {
3873 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3874}
3875
Douglas Gregor8be80e12011-07-06 03:00:34 +00003876unsigned clang_isAttribute(enum CXCursorKind K) {
3877 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
3878}
3879
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003880unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3881 return K == CXCursor_TranslationUnit;
3882}
3883
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003884unsigned clang_isPreprocessing(enum CXCursorKind K) {
3885 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3886}
3887
Ted Kremenekad6eff62010-03-08 21:17:29 +00003888unsigned clang_isUnexposed(enum CXCursorKind K) {
3889 switch (K) {
3890 case CXCursor_UnexposedDecl:
3891 case CXCursor_UnexposedExpr:
3892 case CXCursor_UnexposedStmt:
3893 case CXCursor_UnexposedAttr:
3894 return true;
3895 default:
3896 return false;
3897 }
3898}
3899
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003900CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003901 return C.kind;
3902}
3903
Douglas Gregor98258af2010-01-18 22:46:11 +00003904CXSourceLocation clang_getCursorLocation(CXCursor C) {
3905 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003906 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003907 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003908 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3909 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003910 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003911 }
3912
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003913 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003914 std::pair<ObjCProtocolDecl *, SourceLocation> P
3915 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003916 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003917 }
3918
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003919 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003920 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3921 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003922 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003923 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003924
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003925 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003926 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003927 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003928 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003929
3930 case CXCursor_TemplateRef: {
3931 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3932 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3933 }
3934
Douglas Gregor69319002010-08-31 23:48:11 +00003935 case CXCursor_NamespaceRef: {
3936 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3937 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3938 }
3939
Douglas Gregora67e03f2010-09-09 21:42:20 +00003940 case CXCursor_MemberRef: {
3941 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3942 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3943 }
3944
Douglas Gregor011d8b92012-02-15 00:54:55 +00003945 case CXCursor_VariableRef: {
3946 std::pair<VarDecl *, SourceLocation> P = getCursorVariableRef(C);
3947 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3948 }
3949
Ted Kremenek3064ef92010-08-27 21:34:58 +00003950 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003951 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3952 if (!BaseSpec)
3953 return clang_getNullLocation();
3954
3955 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3956 return cxloc::translateSourceLocation(getCursorContext(C),
3957 TSInfo->getTypeLoc().getBeginLoc());
3958
3959 return cxloc::translateSourceLocation(getCursorContext(C),
Daniel Dunbar96a00142012-03-09 18:35:03 +00003960 BaseSpec->getLocStart());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003961 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003962
Douglas Gregor36897b02010-09-10 00:22:18 +00003963 case CXCursor_LabelRef: {
3964 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3965 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3966 }
3967
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003968 case CXCursor_OverloadedDeclRef:
3969 return cxloc::translateSourceLocation(getCursorContext(C),
3970 getCursorOverloadedDeclRef(C).second);
3971
Douglas Gregorf46034a2010-01-18 23:41:10 +00003972 default:
3973 // FIXME: Need a way to enumerate all non-reference cases.
3974 llvm_unreachable("Missed a reference kind");
3975 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003976 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003977
3978 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003979 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003980 getLocationFromExpr(getCursorExpr(C)));
3981
Douglas Gregor36897b02010-09-10 00:22:18 +00003982 if (clang_isStatement(C.kind))
3983 return cxloc::translateSourceLocation(getCursorContext(C),
3984 getCursorStmt(C)->getLocStart());
3985
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003986 if (C.kind == CXCursor_PreprocessingDirective) {
3987 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3988 return cxloc::translateSourceLocation(getCursorContext(C), L);
3989 }
Douglas Gregor48072312010-03-18 15:23:44 +00003990
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003991 if (C.kind == CXCursor_MacroExpansion) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003992 SourceLocation L
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003993 = cxcursor::getCursorMacroExpansion(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003994 return cxloc::translateSourceLocation(getCursorContext(C), L);
3995 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003996
3997 if (C.kind == CXCursor_MacroDefinition) {
3998 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3999 return cxloc::translateSourceLocation(getCursorContext(C), L);
4000 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00004001
4002 if (C.kind == CXCursor_InclusionDirective) {
4003 SourceLocation L
4004 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
4005 return cxloc::translateSourceLocation(getCursorContext(C), L);
4006 }
4007
Argyrios Kyrtzidis6a010122012-10-05 00:22:24 +00004008 if (!clang_isDeclaration(C.kind))
Douglas Gregor5352ac02010-01-28 00:27:43 +00004009 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00004010
Douglas Gregorf46034a2010-01-18 23:41:10 +00004011 Decl *D = getCursorDecl(C);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00004012 if (!D)
4013 return clang_getNullLocation();
4014
Douglas Gregorf46034a2010-01-18 23:41:10 +00004015 SourceLocation Loc = D->getLocation();
Ted Kremenek007a7c92010-11-01 23:26:51 +00004016 // FIXME: Multiple variables declared in a single declaration
4017 // currently lack the information needed to correctly determine their
4018 // ranges when accounting for the type-specifier. We use context
4019 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
4020 // and if so, whether it is the first decl.
4021 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4022 if (!cxcursor::isFirstInDeclGroup(C))
4023 Loc = VD->getLocation();
4024 }
4025
Argyrios Kyrtzidisccc6f362012-03-23 03:33:19 +00004026 // For ObjC methods, give the start location of the method name.
4027 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
4028 Loc = MD->getSelectorStartLoc();
4029
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00004030 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00004031}
Douglas Gregora7bde202010-01-19 00:34:46 +00004032
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004033} // end extern "C"
4034
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00004035CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
4036 assert(TU);
4037
4038 // Guard against an invalid SourceLocation, or we may assert in one
4039 // of the following calls.
4040 if (SLoc.isInvalid())
4041 return clang_getNullCursor();
4042
4043 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4044
4045 // Translate the given source location to make it point at the beginning of
4046 // the token under the cursor.
4047 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +00004048 CXXUnit->getASTContext().getLangOpts());
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00004049
4050 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
4051 if (SLoc.isValid()) {
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00004052 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00004053 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
4054 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00004055 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00004056 SourceLocation(SLoc));
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00004057 CursorVis.visitFileRegion();
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00004058 }
4059
4060 return Result;
4061}
4062
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004063static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00004064 if (clang_isReference(C.kind)) {
4065 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004066 case CXCursor_ObjCSuperClassRef:
4067 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004068
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004069 case CXCursor_ObjCProtocolRef:
4070 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004071
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004072 case CXCursor_ObjCClassRef:
4073 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004074
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004075 case CXCursor_TypeRef:
4076 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00004077
4078 case CXCursor_TemplateRef:
4079 return getCursorTemplateRef(C).second;
4080
Douglas Gregor69319002010-08-31 23:48:11 +00004081 case CXCursor_NamespaceRef:
4082 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00004083
4084 case CXCursor_MemberRef:
4085 return getCursorMemberRef(C).second;
4086
Ted Kremenek3064ef92010-08-27 21:34:58 +00004087 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00004088 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00004089
Douglas Gregor36897b02010-09-10 00:22:18 +00004090 case CXCursor_LabelRef:
4091 return getCursorLabelRef(C).second;
4092
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004093 case CXCursor_OverloadedDeclRef:
4094 return getCursorOverloadedDeclRef(C).second;
4095
Douglas Gregor011d8b92012-02-15 00:54:55 +00004096 case CXCursor_VariableRef:
4097 return getCursorVariableRef(C).second;
4098
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004099 default:
4100 // FIXME: Need a way to enumerate all non-reference cases.
4101 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00004102 }
4103 }
Douglas Gregor97b98722010-01-19 23:20:36 +00004104
4105 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004106 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00004107
4108 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004109 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004110
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00004111 if (clang_isAttribute(C.kind))
4112 return getCursorAttr(C)->getRange();
4113
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004114 if (C.kind == CXCursor_PreprocessingDirective)
4115 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00004116
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004117 if (C.kind == CXCursor_MacroExpansion) {
4118 ASTUnit *TU = getCursorASTUnit(C);
4119 SourceRange Range = cxcursor::getCursorMacroExpansion(C)->getSourceRange();
4120 return TU->mapRangeFromPreamble(Range);
4121 }
Douglas Gregor572feb22010-03-18 18:04:21 +00004122
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004123 if (C.kind == CXCursor_MacroDefinition) {
4124 ASTUnit *TU = getCursorASTUnit(C);
4125 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
4126 return TU->mapRangeFromPreamble(Range);
4127 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00004128
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004129 if (C.kind == CXCursor_InclusionDirective) {
4130 ASTUnit *TU = getCursorASTUnit(C);
4131 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
4132 return TU->mapRangeFromPreamble(Range);
4133 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00004134
Argyrios Kyrtzidis0822c5f2012-03-19 23:17:58 +00004135 if (C.kind == CXCursor_TranslationUnit) {
4136 ASTUnit *TU = getCursorASTUnit(C);
4137 FileID MainID = TU->getSourceManager().getMainFileID();
4138 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
4139 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
4140 return SourceRange(Start, End);
4141 }
4142
Argyrios Kyrtzidis6a010122012-10-05 00:22:24 +00004143 if (clang_isDeclaration(C.kind)) {
Ted Kremenek007a7c92010-11-01 23:26:51 +00004144 Decl *D = cxcursor::getCursorDecl(C);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00004145 if (!D)
4146 return SourceRange();
4147
Ted Kremenek007a7c92010-11-01 23:26:51 +00004148 SourceRange R = D->getSourceRange();
4149 // FIXME: Multiple variables declared in a single declaration
4150 // currently lack the information needed to correctly determine their
4151 // ranges when accounting for the type-specifier. We use context
4152 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
4153 // and if so, whether it is the first decl.
4154 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4155 if (!cxcursor::isFirstInDeclGroup(C))
4156 R.setBegin(VD->getLocation());
4157 }
4158 return R;
4159 }
Douglas Gregor66537982010-11-17 17:14:07 +00004160 return SourceRange();
4161}
4162
4163/// \brief Retrieves the "raw" cursor extent, which is then extended to include
4164/// the decl-specifier-seq for declarations.
4165static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
Argyrios Kyrtzidis6a010122012-10-05 00:22:24 +00004166 if (clang_isDeclaration(C.kind)) {
Douglas Gregor66537982010-11-17 17:14:07 +00004167 Decl *D = cxcursor::getCursorDecl(C);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00004168 if (!D)
4169 return SourceRange();
4170
Douglas Gregor66537982010-11-17 17:14:07 +00004171 SourceRange R = D->getSourceRange();
Douglas Gregor66537982010-11-17 17:14:07 +00004172
Douglas Gregor2494dd02011-03-01 01:34:45 +00004173 // Adjust the start of the location for declarations preceded by
4174 // declaration specifiers.
4175 SourceLocation StartLoc;
4176 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
4177 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
Daniel Dunbar96a00142012-03-09 18:35:03 +00004178 StartLoc = TI->getTypeLoc().getLocStart();
Douglas Gregor2494dd02011-03-01 01:34:45 +00004179 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
4180 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
Daniel Dunbar96a00142012-03-09 18:35:03 +00004181 StartLoc = TI->getTypeLoc().getLocStart();
Douglas Gregor2494dd02011-03-01 01:34:45 +00004182 }
4183
4184 if (StartLoc.isValid() && R.getBegin().isValid() &&
4185 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
4186 R.setBegin(StartLoc);
4187
4188 // FIXME: Multiple variables declared in a single declaration
4189 // currently lack the information needed to correctly determine their
4190 // ranges when accounting for the type-specifier. We use context
4191 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
4192 // and if so, whether it is the first decl.
4193 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4194 if (!cxcursor::isFirstInDeclGroup(C))
4195 R.setBegin(VD->getLocation());
Douglas Gregor66537982010-11-17 17:14:07 +00004196 }
4197
4198 return R;
4199 }
4200
4201 return getRawCursorExtent(C);
4202}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004203
4204extern "C" {
4205
4206CXSourceRange clang_getCursorExtent(CXCursor C) {
4207 SourceRange R = getRawCursorExtent(C);
4208 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00004209 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004210
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004211 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00004212}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004213
4214CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00004215 if (clang_isInvalid(C.kind))
4216 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004217
Ted Kremeneka60ed472010-11-16 08:15:36 +00004218 CXTranslationUnit tu = getCursorTU(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004219 if (clang_isDeclaration(C.kind)) {
4220 Decl *D = getCursorDecl(C);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00004221 if (!D)
4222 return clang_getNullCursor();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004223 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004224 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Chris Lattner5f9e2722011-07-23 10:55:15 +00004225 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00004226 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
4227 return MakeCXCursor(Property, tu);
4228
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004229 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004230 }
4231
Douglas Gregor97b98722010-01-19 23:20:36 +00004232 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004233 Expr *E = getCursorExpr(C);
4234 Decl *D = getDeclFromExpr(E);
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00004235 if (D) {
4236 CXCursor declCursor = MakeCXCursor(D, tu);
4237 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
4238 declCursor);
4239 return declCursor;
4240 }
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004241
4242 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004243 return MakeCursorOverloadedDeclRef(Ovl, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004244
Douglas Gregor97b98722010-01-19 23:20:36 +00004245 return clang_getNullCursor();
4246 }
4247
Douglas Gregor36897b02010-09-10 00:22:18 +00004248 if (clang_isStatement(C.kind)) {
4249 Stmt *S = getCursorStmt(C);
4250 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Ted Kremenek37c2e962011-03-15 23:47:49 +00004251 if (LabelDecl *label = Goto->getLabel())
4252 if (LabelStmt *labelS = label->getStmt())
4253 return MakeCXCursor(labelS, getCursorDecl(C), tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00004254
4255 return clang_getNullCursor();
4256 }
4257
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004258 if (C.kind == CXCursor_MacroExpansion) {
Chandler Carruth9e5bb852011-07-14 08:20:46 +00004259 if (MacroDefinition *Def = getCursorMacroExpansion(C)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004260 return MakeMacroDefinitionCursor(Def, tu);
Douglas Gregorbf7efa22010-03-18 18:23:03 +00004261 }
4262
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004263 if (!clang_isReference(C.kind))
4264 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004265
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004266 switch (C.kind) {
4267 case CXCursor_ObjCSuperClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004268 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004269
4270 case CXCursor_ObjCProtocolRef: {
Argyrios Kyrtzidis98c16b82012-01-24 19:40:15 +00004271 ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
4272 if (ObjCProtocolDecl *Def = Prot->getDefinition())
4273 return MakeCXCursor(Def, tu);
4274
Argyrios Kyrtzidisc15707d2012-01-24 21:39:26 +00004275 return MakeCXCursor(Prot, tu);
Argyrios Kyrtzidis98c16b82012-01-24 19:40:15 +00004276 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004277
Douglas Gregor7723fec2011-12-15 20:29:51 +00004278 case CXCursor_ObjCClassRef: {
4279 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
4280 if (ObjCInterfaceDecl *Def = Class->getDefinition())
4281 return MakeCXCursor(Def, tu);
4282
Argyrios Kyrtzidisc15707d2012-01-24 21:39:26 +00004283 return MakeCXCursor(Class, tu);
Douglas Gregor7723fec2011-12-15 20:29:51 +00004284 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00004285
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004286 case CXCursor_TypeRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004287 return MakeCXCursor(getCursorTypeRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00004288
4289 case CXCursor_TemplateRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004290 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00004291
Douglas Gregor69319002010-08-31 23:48:11 +00004292 case CXCursor_NamespaceRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004293 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
Douglas Gregor69319002010-08-31 23:48:11 +00004294
Douglas Gregora67e03f2010-09-09 21:42:20 +00004295 case CXCursor_MemberRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004296 return MakeCXCursor(getCursorMemberRef(C).first, tu );
Douglas Gregora67e03f2010-09-09 21:42:20 +00004297
Ted Kremenek3064ef92010-08-27 21:34:58 +00004298 case CXCursor_CXXBaseSpecifier: {
4299 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
4300 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004301 tu ));
Ted Kremenek3064ef92010-08-27 21:34:58 +00004302 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004303
Douglas Gregor36897b02010-09-10 00:22:18 +00004304 case CXCursor_LabelRef:
4305 // FIXME: We end up faking the "parent" declaration here because we
4306 // don't want to make CXCursor larger.
4307 return MakeCXCursor(getCursorLabelRef(C).first,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004308 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
4309 .getTranslationUnitDecl(),
4310 tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00004311
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004312 case CXCursor_OverloadedDeclRef:
4313 return C;
Douglas Gregor011d8b92012-02-15 00:54:55 +00004314
4315 case CXCursor_VariableRef:
4316 return MakeCXCursor(getCursorVariableRef(C).first, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004317
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004318 default:
4319 // We would prefer to enumerate all non-reference cursor kinds here.
4320 llvm_unreachable("Unhandled reference cursor kind");
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004321 }
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004322}
4323
Douglas Gregorb6998662010-01-19 19:34:47 +00004324CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00004325 if (clang_isInvalid(C.kind))
4326 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004327
Ted Kremeneka60ed472010-11-16 08:15:36 +00004328 CXTranslationUnit TU = getCursorTU(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004329
Douglas Gregorb6998662010-01-19 19:34:47 +00004330 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00004331 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00004332 C = clang_getCursorReferenced(C);
4333 WasReference = true;
4334 }
4335
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004336 if (C.kind == CXCursor_MacroExpansion)
Douglas Gregorbf7efa22010-03-18 18:23:03 +00004337 return clang_getCursorReferenced(C);
4338
Douglas Gregorb6998662010-01-19 19:34:47 +00004339 if (!clang_isDeclaration(C.kind))
4340 return clang_getNullCursor();
4341
4342 Decl *D = getCursorDecl(C);
4343 if (!D)
4344 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004345
Douglas Gregorb6998662010-01-19 19:34:47 +00004346 switch (D->getKind()) {
4347 // Declaration kinds that don't really separate the notions of
4348 // declaration and definition.
4349 case Decl::Namespace:
4350 case Decl::Typedef:
Richard Smith162e1c12011-04-15 14:24:37 +00004351 case Decl::TypeAlias:
Richard Smith3e4c6c42011-05-05 21:57:07 +00004352 case Decl::TypeAliasTemplate:
Douglas Gregorb6998662010-01-19 19:34:47 +00004353 case Decl::TemplateTypeParm:
4354 case Decl::EnumConstant:
4355 case Decl::Field:
Benjamin Kramerd9811462010-11-21 14:11:41 +00004356 case Decl::IndirectField:
Douglas Gregorb6998662010-01-19 19:34:47 +00004357 case Decl::ObjCIvar:
4358 case Decl::ObjCAtDefsField:
4359 case Decl::ImplicitParam:
4360 case Decl::ParmVar:
4361 case Decl::NonTypeTemplateParm:
4362 case Decl::TemplateTemplateParm:
4363 case Decl::ObjCCategoryImpl:
4364 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00004365 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00004366 case Decl::LinkageSpec:
4367 case Decl::ObjCPropertyImpl:
4368 case Decl::FileScopeAsm:
4369 case Decl::StaticAssert:
4370 case Decl::Block:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00004371 case Decl::Label: // FIXME: Is this right??
Francois Pichetaf0f4d02011-08-14 03:52:19 +00004372 case Decl::ClassScopeFunctionSpecialization:
Douglas Gregor15de72c2011-12-02 23:23:56 +00004373 case Decl::Import:
Douglas Gregorb6998662010-01-19 19:34:47 +00004374 return C;
4375
4376 // Declaration kinds that don't make any sense here, but are
4377 // nonetheless harmless.
4378 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00004379 break;
4380
4381 // Declaration kinds for which the definition is not resolvable.
4382 case Decl::UnresolvedUsingTypename:
4383 case Decl::UnresolvedUsingValue:
4384 break;
4385
4386 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00004387 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004388 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004389
4390 case Decl::NamespaceAlias:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004391 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004392
4393 case Decl::Enum:
4394 case Decl::Record:
4395 case Decl::CXXRecord:
4396 case Decl::ClassTemplateSpecialization:
4397 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00004398 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004399 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004400 return clang_getNullCursor();
4401
4402 case Decl::Function:
4403 case Decl::CXXMethod:
4404 case Decl::CXXConstructor:
4405 case Decl::CXXDestructor:
4406 case Decl::CXXConversion: {
4407 const FunctionDecl *Def = 0;
4408 if (cast<FunctionDecl>(D)->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004409 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004410 return clang_getNullCursor();
4411 }
4412
4413 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00004414 // Ask the variable if it has a definition.
4415 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004416 return MakeCXCursor(Def, TU);
Sebastian Redl31310a22010-02-01 20:16:42 +00004417 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00004418 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004419
Douglas Gregorb6998662010-01-19 19:34:47 +00004420 case Decl::FunctionTemplate: {
4421 const FunctionDecl *Def = 0;
4422 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004423 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004424 return clang_getNullCursor();
4425 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004426
Douglas Gregorb6998662010-01-19 19:34:47 +00004427 case Decl::ClassTemplate: {
4428 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00004429 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00004430 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004431 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004432 return clang_getNullCursor();
4433 }
4434
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004435 case Decl::Using:
4436 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004437 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004438
4439 case Decl::UsingShadow:
4440 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004441 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004442 TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004443
4444 case Decl::ObjCMethod: {
4445 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
4446 if (Method->isThisDeclarationADefinition())
4447 return C;
4448
4449 // Dig out the method definition in the associated
4450 // @implementation, if we have it.
4451 // FIXME: The ASTs should make finding the definition easier.
4452 if (ObjCInterfaceDecl *Class
4453 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
4454 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
4455 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
4456 Method->isInstanceMethod()))
4457 if (Def->isThisDeclarationADefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004458 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004459
4460 return clang_getNullCursor();
4461 }
4462
4463 case Decl::ObjCCategory:
4464 if (ObjCCategoryImplDecl *Impl
4465 = cast<ObjCCategoryDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004466 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004467 return clang_getNullCursor();
4468
4469 case Decl::ObjCProtocol:
Douglas Gregor5e2a1ff2012-01-01 19:29:29 +00004470 if (ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
4471 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004472 return clang_getNullCursor();
4473
Douglas Gregor375bb142011-12-27 22:43:10 +00004474 case Decl::ObjCInterface: {
Douglas Gregorb6998662010-01-19 19:34:47 +00004475 // There are two notions of a "definition" for an Objective-C
4476 // class: the interface and its implementation. When we resolved a
4477 // reference to an Objective-C class, produce the @interface as
4478 // the definition; when we were provided with the interface,
4479 // produce the @implementation as the definition.
Douglas Gregor375bb142011-12-27 22:43:10 +00004480 ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
Douglas Gregorb6998662010-01-19 19:34:47 +00004481 if (WasReference) {
Douglas Gregor375bb142011-12-27 22:43:10 +00004482 if (ObjCInterfaceDecl *Def = IFace->getDefinition())
Douglas Gregor7723fec2011-12-15 20:29:51 +00004483 return MakeCXCursor(Def, TU);
Douglas Gregor375bb142011-12-27 22:43:10 +00004484 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004485 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004486 return clang_getNullCursor();
Douglas Gregor375bb142011-12-27 22:43:10 +00004487 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004488
Douglas Gregorb6998662010-01-19 19:34:47 +00004489 case Decl::ObjCProperty:
4490 // FIXME: We don't really know where to find the
4491 // ObjCPropertyImplDecls that implement this property.
4492 return clang_getNullCursor();
4493
4494 case Decl::ObjCCompatibleAlias:
4495 if (ObjCInterfaceDecl *Class
4496 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
Douglas Gregor7723fec2011-12-15 20:29:51 +00004497 if (ObjCInterfaceDecl *Def = Class->getDefinition())
4498 return MakeCXCursor(Def, TU);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004499
Douglas Gregorb6998662010-01-19 19:34:47 +00004500 return clang_getNullCursor();
4501
Douglas Gregorb6998662010-01-19 19:34:47 +00004502 case Decl::Friend:
4503 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004504 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004505 return clang_getNullCursor();
4506
4507 case Decl::FriendTemplate:
4508 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004509 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004510 return clang_getNullCursor();
4511 }
4512
4513 return clang_getNullCursor();
4514}
4515
4516unsigned clang_isCursorDefinition(CXCursor C) {
4517 if (!clang_isDeclaration(C.kind))
4518 return 0;
4519
4520 return clang_getCursorDefinition(C) == C;
4521}
4522
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004523CXCursor clang_getCanonicalCursor(CXCursor C) {
4524 if (!clang_isDeclaration(C.kind))
4525 return C;
4526
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004527 if (Decl *D = getCursorDecl(C)) {
Argyrios Kyrtzidisdebb00f2011-07-15 22:37:58 +00004528 if (ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
4529 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
4530 return MakeCXCursor(CatD, getCursorTU(C));
4531
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004532 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
4533 if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
4534 return MakeCXCursor(IFD, getCursorTU(C));
4535
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004536 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004537 }
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004538
4539 return C;
4540}
Argyrios Kyrtzidis34ebe1e2012-03-30 22:15:48 +00004541
4542int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) {
4543 return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first;
4544}
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004545
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004546unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004547 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004548 return 0;
4549
4550 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
4551 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
4552 return E->getNumDecls();
4553
4554 if (OverloadedTemplateStorage *S
4555 = Storage.dyn_cast<OverloadedTemplateStorage*>())
4556 return S->size();
4557
4558 Decl *D = Storage.get<Decl*>();
4559 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00004560 return Using->shadow_size();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004561
4562 return 0;
4563}
4564
4565CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004566 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004567 return clang_getNullCursor();
4568
4569 if (index >= clang_getNumOverloadedDecls(cursor))
4570 return clang_getNullCursor();
4571
Ted Kremeneka60ed472010-11-16 08:15:36 +00004572 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004573 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
4574 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004575 return MakeCXCursor(E->decls_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004576
4577 if (OverloadedTemplateStorage *S
4578 = Storage.dyn_cast<OverloadedTemplateStorage*>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004579 return MakeCXCursor(S->begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004580
4581 Decl *D = Storage.get<Decl*>();
4582 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
4583 // FIXME: This is, unfortunately, linear time.
4584 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
4585 std::advance(Pos, index);
Ted Kremeneka60ed472010-11-16 08:15:36 +00004586 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004587 }
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004588
4589 return clang_getNullCursor();
4590}
4591
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00004592void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00004593 const char **startBuf,
4594 const char **endBuf,
4595 unsigned *startLine,
4596 unsigned *startColumn,
4597 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00004598 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00004599 assert(getCursorDecl(C) && "CXCursor has null decl");
4600 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00004601 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
4602 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004603
Steve Naroff4ade6d62009-09-23 17:52:52 +00004604 SourceManager &SM = FD->getASTContext().getSourceManager();
4605 *startBuf = SM.getCharacterData(Body->getLBracLoc());
4606 *endBuf = SM.getCharacterData(Body->getRBracLoc());
4607 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
4608 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
4609 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
4610 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
4611}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004612
Douglas Gregor430d7a12011-07-25 17:48:11 +00004613
4614CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
4615 unsigned PieceIndex) {
4616 RefNamePieces Pieces;
4617
4618 switch (C.kind) {
4619 case CXCursor_MemberRefExpr:
4620 if (MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
4621 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
4622 E->getQualifierLoc().getSourceRange());
4623 break;
4624
4625 case CXCursor_DeclRefExpr:
4626 if (DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C)))
4627 Pieces = buildPieces(NameFlags, false, E->getNameInfo(),
4628 E->getQualifierLoc().getSourceRange(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00004629 E->getOptionalExplicitTemplateArgs());
Douglas Gregor430d7a12011-07-25 17:48:11 +00004630 break;
4631
4632 case CXCursor_CallExpr:
4633 if (CXXOperatorCallExpr *OCE =
4634 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
4635 Expr *Callee = OCE->getCallee();
4636 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
4637 Callee = ICE->getSubExpr();
4638
4639 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
4640 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
4641 DRE->getQualifierLoc().getSourceRange());
4642 }
4643 break;
4644
4645 default:
4646 break;
4647 }
4648
4649 if (Pieces.empty()) {
4650 if (PieceIndex == 0)
4651 return clang_getCursorExtent(C);
4652 } else if (PieceIndex < Pieces.size()) {
4653 SourceRange R = Pieces[PieceIndex];
4654 if (R.isValid())
4655 return cxloc::translateSourceRange(getCursorContext(C), R);
4656 }
4657
4658 return clang_getNullRange();
4659}
4660
Douglas Gregor0a812cf2010-02-18 23:07:20 +00004661void clang_enableStackTraces(void) {
4662 llvm::sys::PrintStackTraceOnErrorSignal();
4663}
4664
Daniel Dunbar995aaf92010-11-04 01:26:29 +00004665void clang_executeOnThread(void (*fn)(void*), void *user_data,
4666 unsigned stack_size) {
4667 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
4668}
4669
Ted Kremenekfb480492010-01-13 21:46:36 +00004670} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00004671
Ted Kremenekfb480492010-01-13 21:46:36 +00004672//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004673// Token-based Operations.
4674//===----------------------------------------------------------------------===//
4675
4676/* CXToken layout:
4677 * int_data[0]: a CXTokenKind
4678 * int_data[1]: starting token location
4679 * int_data[2]: token length
4680 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004681 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004682 * otherwise unused.
4683 */
4684extern "C" {
4685
4686CXTokenKind clang_getTokenKind(CXToken CXTok) {
4687 return static_cast<CXTokenKind>(CXTok.int_data[0]);
4688}
4689
4690CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
4691 switch (clang_getTokenKind(CXTok)) {
4692 case CXToken_Identifier:
4693 case CXToken_Keyword:
4694 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004695 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
4696 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004697
4698 case CXToken_Literal: {
4699 // We have stashed the starting pointer in the ptr_data field. Use it.
4700 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Chris Lattner5f9e2722011-07-23 10:55:15 +00004701 return createCXString(StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004702 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004703
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004704 case CXToken_Punctuation:
4705 case CXToken_Comment:
4706 break;
4707 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004708
4709 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004710 // deconstructing the source location.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004711 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004712 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004713 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004714
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004715 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
4716 std::pair<FileID, unsigned> LocInfo
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004717 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00004718 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004719 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004720 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
4721 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00004722 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004723
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004724 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004725}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004726
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004727CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004728 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004729 if (!CXXUnit)
4730 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004731
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004732 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
4733 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4734}
4735
4736CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004737 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor5352ac02010-01-28 00:27:43 +00004738 if (!CXXUnit)
4739 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004740
4741 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004742 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4743}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004744
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004745static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
4746 SmallVectorImpl<CXToken> &CXTokens) {
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004747 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4748 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004749 = SourceMgr.getDecomposedLoc(Range.getBegin());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004750 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004751 = SourceMgr.getDecomposedLoc(Range.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004752
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004753 // Cannot tokenize across files.
4754 if (BeginLocInfo.first != EndLocInfo.first)
4755 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004756
4757 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004758 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004759 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004760 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00004761 if (Invalid)
4762 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00004763
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004764 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
David Blaikie4e4d0842012-03-11 07:00:24 +00004765 CXXUnit->getASTContext().getLangOpts(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004766 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004767 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004768
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004769 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004770 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004771 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00004772 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004773 do {
4774 // Lex the next token
4775 Lex.LexFromRawLexer(Tok);
4776 if (Tok.is(tok::eof))
4777 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004778
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004779 // Initialize the CXToken.
4780 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004781
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004782 // - Common fields
4783 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
4784 CXTok.int_data[2] = Tok.getLength();
4785 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004786
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004787 // - Kind-specific fields
4788 if (Tok.isLiteral()) {
4789 CXTok.int_data[0] = CXToken_Literal;
4790 CXTok.ptr_data = (void *)Tok.getLiteralData();
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004791 } else if (Tok.is(tok::raw_identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00004792 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004793 IdentifierInfo *II
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004794 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004795
David Chisnall096428b2010-10-13 21:44:48 +00004796 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004797 CXTok.int_data[0] = CXToken_Keyword;
4798 }
4799 else {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004800 CXTok.int_data[0] = Tok.is(tok::identifier)
4801 ? CXToken_Identifier
4802 : CXToken_Keyword;
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004803 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004804 CXTok.ptr_data = II;
4805 } else if (Tok.is(tok::comment)) {
4806 CXTok.int_data[0] = CXToken_Comment;
4807 CXTok.ptr_data = 0;
4808 } else {
4809 CXTok.int_data[0] = CXToken_Punctuation;
4810 CXTok.ptr_data = 0;
4811 }
4812 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00004813 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004814 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004815}
4816
4817void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
4818 CXToken **Tokens, unsigned *NumTokens) {
4819 if (Tokens)
4820 *Tokens = 0;
4821 if (NumTokens)
4822 *NumTokens = 0;
4823
4824 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4825 if (!CXXUnit || !Tokens || !NumTokens)
4826 return;
4827
4828 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4829
4830 SourceRange R = cxloc::translateCXSourceRange(Range);
4831 if (R.isInvalid())
4832 return;
4833
4834 SmallVector<CXToken, 32> CXTokens;
4835 getTokens(CXXUnit, R, CXTokens);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004836
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004837 if (CXTokens.empty())
4838 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004839
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004840 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
4841 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
4842 *NumTokens = CXTokens.size();
4843}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004844
Ted Kremenek6db61092010-05-05 00:55:15 +00004845void clang_disposeTokens(CXTranslationUnit TU,
4846 CXToken *Tokens, unsigned NumTokens) {
4847 free(Tokens);
4848}
4849
4850} // end: extern "C"
4851
4852//===----------------------------------------------------------------------===//
4853// Token annotation APIs.
4854//===----------------------------------------------------------------------===//
4855
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004856typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004857static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4858 CXCursor parent,
4859 CXClientData client_data);
Argyrios Kyrtzidisd579dd52012-09-01 18:27:30 +00004860static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
4861 CXClientData client_data);
4862
Ted Kremenek6db61092010-05-05 00:55:15 +00004863namespace {
4864class AnnotateTokensWorker {
4865 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004866 CXToken *Tokens;
4867 CXCursor *Cursors;
4868 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004869 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00004870 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004871 CursorVisitor AnnotateVis;
4872 SourceManager &SrcMgr;
Douglas Gregorf5251602011-03-08 17:10:18 +00004873 bool HasContextSensitiveKeywords;
Argyrios Kyrtzidisd579dd52012-09-01 18:27:30 +00004874
4875 struct PostChildrenInfo {
4876 CXCursor Cursor;
4877 SourceRange CursorRange;
4878 unsigned BeforeChildrenTokenIdx;
4879 };
4880 llvm::SmallVector<PostChildrenInfo, 8> PostChildrenInfos;
Douglas Gregorf5251602011-03-08 17:10:18 +00004881
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004882 bool MoreTokens() const { return TokIdx < NumTokens; }
4883 unsigned NextToken() const { return TokIdx; }
4884 void AdvanceToken() { ++TokIdx; }
4885 SourceLocation GetTokenLoc(unsigned tokI) {
4886 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4887 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004888 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004889 return Tokens[tokI].int_data[3] != 0;
4890 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004891 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004892 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[3]);
4893 }
4894
4895 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004896 void annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
4897 SourceRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004898
Ted Kremenek6db61092010-05-05 00:55:15 +00004899public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00004900 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004901 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004902 CXTranslationUnit tu, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00004903 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00004904 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004905 AnnotateVis(tu,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00004906 AnnotateTokensVisitor, this,
4907 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00004908 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidisd579dd52012-09-01 18:27:30 +00004909 RegionOfInterest,
4910 /*VisitDeclsOnly=*/false,
4911 AnnotateTokensPostChildrenVisitor),
Douglas Gregorf5251602011-03-08 17:10:18 +00004912 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()),
4913 HasContextSensitiveKeywords(false) { }
Ted Kremenek11949cb2010-05-05 00:55:17 +00004914
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004915 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00004916 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Argyrios Kyrtzidisd579dd52012-09-01 18:27:30 +00004917 bool postVisitChildren(CXCursor cursor);
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004918 void AnnotateTokens();
Douglas Gregorf5251602011-03-08 17:10:18 +00004919
4920 /// \brief Determine whether the annotator saw any cursors that have
4921 /// context-sensitive keywords.
4922 bool hasContextSensitiveKeywords() const {
4923 return HasContextSensitiveKeywords;
4924 }
Argyrios Kyrtzidisd579dd52012-09-01 18:27:30 +00004925
4926 ~AnnotateTokensWorker() {
4927 assert(PostChildrenInfos.empty());
4928 }
Ted Kremenek6db61092010-05-05 00:55:15 +00004929};
4930}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004931
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004932void AnnotateTokensWorker::AnnotateTokens() {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004933 // Walk the AST within the region of interest, annotating tokens
4934 // along the way.
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004935 AnnotateVis.visitFileRegion();
Ted Kremenek11949cb2010-05-05 00:55:17 +00004936
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004937 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4938 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004939 if (Pos != Annotated.end() &&
4940 (clang_isInvalid(Cursors[I].kind) ||
4941 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004942 Cursors[I] = Pos->second;
4943 }
4944
4945 // Finish up annotating any tokens left.
4946 if (!MoreTokens())
4947 return;
4948
4949 const CXCursor &C = clang_getNullCursor();
4950 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004951 if (I < PreprocessingTokIdx && clang_isPreprocessing(Cursors[I].kind))
4952 continue;
4953
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004954 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4955 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004956 }
4957}
4958
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004959/// \brief It annotates and advances tokens with a cursor until the comparison
4960//// between the cursor location and the source range is the same as
4961/// \arg compResult.
4962///
4963/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
4964/// Pass RangeOverlap to annotate tokens inside a range.
4965void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
4966 RangeComparisonResult compResult,
4967 SourceRange range) {
4968 while (MoreTokens()) {
4969 const unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004970 if (isFunctionMacroToken(I))
4971 return annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004972
4973 SourceLocation TokLoc = GetTokenLoc(I);
4974 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4975 Cursors[I] = updateC;
4976 AdvanceToken();
4977 continue;
4978 }
4979 break;
4980 }
4981}
4982
4983/// \brief Special annotation handling for macro argument tokens.
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004984void AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
4985 CXCursor updateC,
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004986 RangeComparisonResult compResult,
4987 SourceRange range) {
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004988 assert(MoreTokens());
4989 assert(isFunctionMacroToken(NextToken()) &&
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004990 "Should be called only for macro arg tokens");
4991
4992 // This works differently than annotateAndAdvanceTokens; because expanded
4993 // macro arguments can have arbitrary translation-unit source order, we do not
4994 // advance the token index one by one until a token fails the range test.
4995 // We only advance once past all of the macro arg tokens if all of them
4996 // pass the range test. If one of them fails we keep the token index pointing
4997 // at the start of the macro arg tokens so that the failing token will be
4998 // annotated by a subsequent annotation try.
4999
5000 bool atLeastOneCompFail = false;
5001
5002 unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00005003 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
5004 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005005 if (TokLoc.isFileID())
5006 continue; // not macro arg token, it's parens or comma.
5007 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
5008 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
5009 Cursors[I] = updateC;
5010 } else
5011 atLeastOneCompFail = true;
5012 }
5013
5014 if (!atLeastOneCompFail)
5015 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
5016}
5017
Ted Kremenek6db61092010-05-05 00:55:15 +00005018enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00005019AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005020 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00005021 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00005022 if (cursorRange.isInvalid())
5023 return CXChildVisit_Recurse;
Douglas Gregorf5251602011-03-08 17:10:18 +00005024
5025 if (!HasContextSensitiveKeywords) {
5026 // Objective-C properties can have context-sensitive keywords.
5027 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
5028 if (ObjCPropertyDecl *Property
5029 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
5030 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
5031 }
5032 // Objective-C methods can have context-sensitive keywords.
5033 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
5034 cursor.kind == CXCursor_ObjCClassMethodDecl) {
5035 if (ObjCMethodDecl *Method
5036 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
5037 if (Method->getObjCDeclQualifier())
5038 HasContextSensitiveKeywords = true;
5039 else {
5040 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
5041 PEnd = Method->param_end();
5042 P != PEnd; ++P) {
5043 if ((*P)->getObjCDeclQualifier()) {
5044 HasContextSensitiveKeywords = true;
5045 break;
5046 }
5047 }
5048 }
5049 }
5050 }
5051 // C++ methods can have context-sensitive keywords.
5052 else if (cursor.kind == CXCursor_CXXMethod) {
5053 if (CXXMethodDecl *Method
5054 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
5055 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
5056 HasContextSensitiveKeywords = true;
5057 }
5058 }
5059 // C++ classes can have context-sensitive keywords.
5060 else if (cursor.kind == CXCursor_StructDecl ||
5061 cursor.kind == CXCursor_ClassDecl ||
5062 cursor.kind == CXCursor_ClassTemplate ||
5063 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
5064 if (Decl *D = getCursorDecl(cursor))
5065 if (D->hasAttr<FinalAttr>())
5066 HasContextSensitiveKeywords = true;
5067 }
5068 }
5069
Douglas Gregor4419b672010-10-21 06:10:04 +00005070 if (clang_isPreprocessing(cursor.kind)) {
Chandler Carruthcea731a2011-07-14 16:07:57 +00005071 // For macro expansions, just note where the beginning of the macro
5072 // expansion occurs.
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00005073 if (cursor.kind == CXCursor_MacroExpansion) {
Douglas Gregor4419b672010-10-21 06:10:04 +00005074 Annotated[Loc.int_data] = cursor;
5075 return CXChildVisit_Recurse;
5076 }
5077
Douglas Gregor4419b672010-10-21 06:10:04 +00005078 // Items in the preprocessing record are kept separate from items in
5079 // declarations, so we keep a separate token index.
5080 unsigned SavedTokIdx = TokIdx;
5081 TokIdx = PreprocessingTokIdx;
5082
5083 // Skip tokens up until we catch up to the beginning of the preprocessing
5084 // entry.
5085 while (MoreTokens()) {
5086 const unsigned I = NextToken();
5087 SourceLocation TokLoc = GetTokenLoc(I);
5088 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
5089 case RangeBefore:
5090 AdvanceToken();
5091 continue;
5092 case RangeAfter:
5093 case RangeOverlap:
5094 break;
5095 }
5096 break;
5097 }
5098
5099 // Look at all of the tokens within this range.
5100 while (MoreTokens()) {
5101 const unsigned I = NextToken();
5102 SourceLocation TokLoc = GetTokenLoc(I);
5103 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
5104 case RangeBefore:
David Blaikieb219cfc2011-09-23 05:06:16 +00005105 llvm_unreachable("Infeasible");
Douglas Gregor4419b672010-10-21 06:10:04 +00005106 case RangeAfter:
5107 break;
5108 case RangeOverlap:
5109 Cursors[I] = cursor;
5110 AdvanceToken();
5111 continue;
5112 }
5113 break;
5114 }
5115
5116 // Save the preprocessing token index; restore the non-preprocessing
5117 // token index.
5118 PreprocessingTokIdx = TokIdx;
5119 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005120 return CXChildVisit_Recurse;
5121 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005122
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005123 if (cursorRange.isInvalid())
5124 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00005125
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005126 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
5127
Ted Kremeneka333c662010-05-12 05:29:33 +00005128 // Adjust the annotated range based specific declarations.
5129 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
Argyrios Kyrtzidis6a010122012-10-05 00:22:24 +00005130 if (clang_isDeclaration(cursorK)) {
Ted Kremenek23173d72010-05-18 21:09:07 +00005131 Decl *D = cxcursor::getCursorDecl(cursor);
Douglas Gregor2494dd02011-03-01 01:34:45 +00005132
5133 SourceLocation StartLoc;
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00005134 if (const DeclaratorDecl *DD = dyn_cast_or_null<DeclaratorDecl>(D)) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00005135 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
Daniel Dunbar96a00142012-03-09 18:35:03 +00005136 StartLoc = TI->getTypeLoc().getLocStart();
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00005137 } else if (TypedefDecl *Typedef = dyn_cast_or_null<TypedefDecl>(D)) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00005138 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
Daniel Dunbar96a00142012-03-09 18:35:03 +00005139 StartLoc = TI->getTypeLoc().getLocStart();
Ted Kremeneka333c662010-05-12 05:29:33 +00005140 }
Douglas Gregor2494dd02011-03-01 01:34:45 +00005141
5142 if (StartLoc.isValid() && L.isValid() &&
5143 SrcMgr.isBeforeInTranslationUnit(StartLoc, L))
5144 cursorRange.setBegin(StartLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00005145 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00005146
Ted Kremenek3f404602010-08-14 01:14:06 +00005147 // If the location of the cursor occurs within a macro instantiation, record
5148 // the spelling location of the cursor in our annotation map. We can then
5149 // paper over the token labelings during a post-processing step to try and
5150 // get cursor mappings for tokens that are the *arguments* of a macro
5151 // instantiation.
5152 if (L.isMacroID()) {
5153 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
5154 // Only invalidate the old annotation if it isn't part of a preprocessing
5155 // directive. Here we assume that the default construction of CXCursor
5156 // results in CXCursor.kind being an initialized value (i.e., 0). If
5157 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00005158
Ted Kremenek3f404602010-08-14 01:14:06 +00005159 CXCursor &oldC = Annotated[rawEncoding];
5160 if (!clang_isPreprocessing(oldC.kind))
5161 oldC = cursor;
5162 }
5163
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005164 const enum CXCursorKind K = clang_getCursorKind(parent);
5165 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00005166 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
5167 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005168
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005169 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005170
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00005171 // Avoid having the cursor of an expression "overwrite" the annotation of the
5172 // variable declaration that it belongs to.
5173 // This can happen for C++ constructor expressions whose range generally
5174 // include the variable declaration, e.g.:
5175 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
5176 if (clang_isExpression(cursorK)) {
5177 Expr *E = getCursorExpr(cursor);
Argyrios Kyrtzidis8ccac3d2011-06-29 22:20:07 +00005178 if (Decl *D = getCursorParentDecl(cursor)) {
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00005179 const unsigned I = NextToken();
5180 if (E->getLocStart().isValid() && D->getLocation().isValid() &&
5181 E->getLocStart() == D->getLocation() &&
5182 E->getLocStart() == GetTokenLoc(I)) {
5183 Cursors[I] = updateC;
5184 AdvanceToken();
5185 }
5186 }
5187 }
5188
Argyrios Kyrtzidisd579dd52012-09-01 18:27:30 +00005189 // Before recursing into the children keep some state that we are going
5190 // to use in the AnnotateTokensWorker::postVisitChildren callback to do some
5191 // extra work after the child nodes are visited.
5192 // Note that we don't call VisitChildren here to avoid traversing statements
5193 // code-recursively which can blow the stack.
5194
5195 PostChildrenInfo Info;
5196 Info.Cursor = cursor;
5197 Info.CursorRange = cursorRange;
5198 Info.BeforeChildrenTokenIdx = NextToken();
5199 PostChildrenInfos.push_back(Info);
5200
5201 return CXChildVisit_Recurse;
5202}
5203
5204bool AnnotateTokensWorker::postVisitChildren(CXCursor cursor) {
5205 if (PostChildrenInfos.empty())
5206 return false;
5207 const PostChildrenInfo &Info = PostChildrenInfos.back();
5208 if (!clang_equalCursors(Info.Cursor, cursor))
5209 return false;
5210
5211 const unsigned BeforeChildren = Info.BeforeChildrenTokenIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005212 const unsigned AfterChildren = NextToken();
Argyrios Kyrtzidisd579dd52012-09-01 18:27:30 +00005213 SourceRange cursorRange = Info.CursorRange;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005214
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005215 // Scan the tokens that are at the end of the cursor, but are not captured
5216 // but the child cursors.
5217 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
Argyrios Kyrtzidisd579dd52012-09-01 18:27:30 +00005218
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005219 // Scan the tokens that are at the beginning of the cursor, but are not
5220 // capture by the child cursors.
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005221 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
5222 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
5223 break;
Argyrios Kyrtzidisd579dd52012-09-01 18:27:30 +00005224
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005225 Cursors[I] = cursor;
5226 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005227
Argyrios Kyrtzidisd579dd52012-09-01 18:27:30 +00005228 PostChildrenInfos.pop_back();
5229 return false;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005230}
5231
Ted Kremenek6db61092010-05-05 00:55:15 +00005232static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
5233 CXCursor parent,
5234 CXClientData client_data) {
5235 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
5236}
5237
Argyrios Kyrtzidisd579dd52012-09-01 18:27:30 +00005238static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
5239 CXClientData client_data) {
5240 return static_cast<AnnotateTokensWorker*>(client_data)->
5241 postVisitChildren(cursor);
5242}
5243
Ted Kremenek6628a612011-03-18 22:51:30 +00005244namespace {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005245
5246/// \brief Uses the macro expansions in the preprocessing record to find
5247/// and mark tokens that are macro arguments. This info is used by the
5248/// AnnotateTokensWorker.
5249class MarkMacroArgTokensVisitor {
5250 SourceManager &SM;
5251 CXToken *Tokens;
5252 unsigned NumTokens;
5253 unsigned CurIdx;
5254
5255public:
5256 MarkMacroArgTokensVisitor(SourceManager &SM,
5257 CXToken *tokens, unsigned numTokens)
5258 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
5259
5260 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
5261 if (cursor.kind != CXCursor_MacroExpansion)
5262 return CXChildVisit_Continue;
5263
5264 SourceRange macroRange = getCursorMacroExpansion(cursor)->getSourceRange();
5265 if (macroRange.getBegin() == macroRange.getEnd())
5266 return CXChildVisit_Continue; // it's not a function macro.
5267
5268 for (; CurIdx < NumTokens; ++CurIdx) {
5269 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
5270 macroRange.getBegin()))
5271 break;
5272 }
5273
5274 if (CurIdx == NumTokens)
5275 return CXChildVisit_Break;
5276
5277 for (; CurIdx < NumTokens; ++CurIdx) {
5278 SourceLocation tokLoc = getTokenLoc(CurIdx);
5279 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
5280 break;
5281
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00005282 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005283 }
5284
5285 if (CurIdx == NumTokens)
5286 return CXChildVisit_Break;
5287
5288 return CXChildVisit_Continue;
5289 }
5290
5291private:
5292 SourceLocation getTokenLoc(unsigned tokI) {
5293 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
5294 }
5295
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00005296 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005297 // The third field is reserved and currently not used. Use it here
5298 // to mark macro arg expanded tokens with their expanded locations.
5299 Tokens[tokI].int_data[3] = loc.getRawEncoding();
5300 }
5301};
5302
5303} // end anonymous namespace
5304
5305static CXChildVisitResult
5306MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
5307 CXClientData client_data) {
5308 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
5309 parent);
5310}
5311
5312namespace {
Ted Kremenek6628a612011-03-18 22:51:30 +00005313 struct clang_annotateTokens_Data {
5314 CXTranslationUnit TU;
5315 ASTUnit *CXXUnit;
5316 CXToken *Tokens;
5317 unsigned NumTokens;
5318 CXCursor *Cursors;
5319 };
5320}
5321
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005322static void annotatePreprocessorTokens(CXTranslationUnit TU,
5323 SourceRange RegionOfInterest,
5324 AnnotateTokensData &Annotated) {
5325 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
5326
5327 SourceManager &SourceMgr = CXXUnit->getSourceManager();
5328 std::pair<FileID, unsigned> BeginLocInfo
5329 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
5330 std::pair<FileID, unsigned> EndLocInfo
5331 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
5332
5333 if (BeginLocInfo.first != EndLocInfo.first)
5334 return;
5335
5336 StringRef Buffer;
5337 bool Invalid = false;
5338 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
5339 if (Buffer.empty() || Invalid)
5340 return;
5341
5342 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
David Blaikie4e4d0842012-03-11 07:00:24 +00005343 CXXUnit->getASTContext().getLangOpts(),
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005344 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
5345 Buffer.end());
5346 Lex.SetCommentRetentionState(true);
5347
5348 // Lex tokens in raw mode until we hit the end of the range, to avoid
5349 // entering #includes or expanding macros.
5350 while (true) {
5351 Token Tok;
5352 Lex.LexFromRawLexer(Tok);
5353
5354 reprocess:
5355 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
5356 // We have found a preprocessing directive. Gobble it up so that we
5357 // don't see it while preprocessing these tokens later, but keep track
5358 // of all of the token locations inside this preprocessing directive so
5359 // that we can annotate them appropriately.
5360 //
5361 // FIXME: Some simple tests here could identify macro definitions and
5362 // #undefs, to provide specific cursor kinds for those.
5363 SmallVector<SourceLocation, 32> Locations;
5364 do {
5365 Locations.push_back(Tok.getLocation());
5366 Lex.LexFromRawLexer(Tok);
5367 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
5368
5369 using namespace cxcursor;
5370 CXCursor Cursor
5371 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
5372 Locations.back()),
5373 TU);
5374 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
5375 Annotated[Locations[I].getRawEncoding()] = Cursor;
5376 }
5377
5378 if (Tok.isAtStartOfLine())
5379 goto reprocess;
5380
5381 continue;
5382 }
5383
5384 if (Tok.is(tok::eof))
5385 break;
5386 }
5387}
5388
Ted Kremenekab979612010-11-11 08:05:23 +00005389// This gets run a separate thread to avoid stack blowout.
Ted Kremenek6628a612011-03-18 22:51:30 +00005390static void clang_annotateTokensImpl(void *UserData) {
5391 CXTranslationUnit TU = ((clang_annotateTokens_Data*)UserData)->TU;
5392 ASTUnit *CXXUnit = ((clang_annotateTokens_Data*)UserData)->CXXUnit;
5393 CXToken *Tokens = ((clang_annotateTokens_Data*)UserData)->Tokens;
5394 const unsigned NumTokens = ((clang_annotateTokens_Data*)UserData)->NumTokens;
5395 CXCursor *Cursors = ((clang_annotateTokens_Data*)UserData)->Cursors;
5396
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00005397 CIndexer *CXXIdx = (CIndexer*)TU->CIdx;
5398 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
Argyrios Kyrtzidis81b5ac32012-03-28 02:49:54 +00005399 setThreadBackgroundPriority();
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00005400
Ted Kremenek6628a612011-03-18 22:51:30 +00005401 // Determine the region of interest, which contains all of the tokens.
5402 SourceRange RegionOfInterest;
5403 RegionOfInterest.setBegin(
5404 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
5405 RegionOfInterest.setEnd(
5406 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
5407 Tokens[NumTokens-1])));
5408
5409 // A mapping from the source locations found when re-lexing or traversing the
5410 // region of interest to the corresponding cursors.
5411 AnnotateTokensData Annotated;
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005412
Ted Kremenek6628a612011-03-18 22:51:30 +00005413 // Relex the tokens within the source range to look for preprocessing
5414 // directives.
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005415 annotatePreprocessorTokens(TU, RegionOfInterest, Annotated);
Ted Kremenek6628a612011-03-18 22:51:30 +00005416
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005417 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
5418 // Search and mark tokens that are macro argument expansions.
5419 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
5420 Tokens, NumTokens);
5421 CursorVisitor MacroArgMarker(TU,
5422 MarkMacroArgTokensVisitorDelegate, &Visitor,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00005423 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00005424 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00005425 RegionOfInterest);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005426 MacroArgMarker.visitPreprocessedEntitiesInRegion();
5427 }
5428
Ted Kremenek6628a612011-03-18 22:51:30 +00005429 // Annotate all of the source locations in the region of interest that map to
5430 // a specific cursor.
5431 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
5432 TU, RegionOfInterest);
5433
5434 // FIXME: We use a ridiculous stack size here because the data-recursion
5435 // algorithm uses a large stack frame than the non-data recursive version,
5436 // and AnnotationTokensWorker currently transforms the data-recursion
5437 // algorithm back into a traditional recursion by explicitly calling
5438 // VisitChildren(). We will need to remove this explicit recursive call.
5439 W.AnnotateTokens();
5440
5441 // If we ran into any entities that involve context-sensitive keywords,
5442 // take another pass through the tokens to mark them as such.
5443 if (W.hasContextSensitiveKeywords()) {
5444 for (unsigned I = 0; I != NumTokens; ++I) {
5445 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
5446 continue;
5447
5448 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
5449 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5450 if (ObjCPropertyDecl *Property
5451 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
5452 if (Property->getPropertyAttributesAsWritten() != 0 &&
5453 llvm::StringSwitch<bool>(II->getName())
5454 .Case("readonly", true)
5455 .Case("assign", true)
John McCallf85e1932011-06-15 23:02:42 +00005456 .Case("unsafe_unretained", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00005457 .Case("readwrite", true)
5458 .Case("retain", true)
5459 .Case("copy", true)
5460 .Case("nonatomic", true)
5461 .Case("atomic", true)
5462 .Case("getter", true)
5463 .Case("setter", true)
John McCallf85e1932011-06-15 23:02:42 +00005464 .Case("strong", true)
5465 .Case("weak", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00005466 .Default(false))
5467 Tokens[I].int_data[0] = CXToken_Keyword;
5468 }
5469 continue;
5470 }
5471
5472 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
5473 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
5474 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5475 if (llvm::StringSwitch<bool>(II->getName())
5476 .Case("in", true)
5477 .Case("out", true)
5478 .Case("inout", true)
5479 .Case("oneway", true)
5480 .Case("bycopy", true)
5481 .Case("byref", true)
5482 .Default(false))
5483 Tokens[I].int_data[0] = CXToken_Keyword;
5484 continue;
5485 }
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00005486
5487 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
5488 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
5489 Tokens[I].int_data[0] = CXToken_Keyword;
Ted Kremenek6628a612011-03-18 22:51:30 +00005490 continue;
5491 }
5492 }
5493 }
Ted Kremenekab979612010-11-11 08:05:23 +00005494}
5495
Ted Kremenek6db61092010-05-05 00:55:15 +00005496extern "C" {
5497
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005498void clang_annotateTokens(CXTranslationUnit TU,
5499 CXToken *Tokens, unsigned NumTokens,
5500 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005501
5502 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005503 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005504
Douglas Gregor4419b672010-10-21 06:10:04 +00005505 // Any token we don't specifically annotate will have a NULL cursor.
5506 CXCursor C = clang_getNullCursor();
5507 for (unsigned I = 0; I != NumTokens; ++I)
5508 Cursors[I] = C;
5509
Ted Kremeneka60ed472010-11-16 08:15:36 +00005510 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor4419b672010-10-21 06:10:04 +00005511 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005512 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005513
Douglas Gregorbdf60622010-03-05 21:16:25 +00005514 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenek6628a612011-03-18 22:51:30 +00005515
5516 clang_annotateTokens_Data data = { TU, CXXUnit, Tokens, NumTokens, Cursors };
Ted Kremenekab979612010-11-11 08:05:23 +00005517 llvm::CrashRecoveryContext CRC;
Ted Kremenek6628a612011-03-18 22:51:30 +00005518 if (!RunSafely(CRC, clang_annotateTokensImpl, &data,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005519 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00005520 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
5521 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005522}
Ted Kremenek6628a612011-03-18 22:51:30 +00005523
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005524} // end: extern "C"
5525
5526//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00005527// Operations for querying linkage of a cursor.
5528//===----------------------------------------------------------------------===//
5529
5530extern "C" {
5531CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00005532 if (!clang_isDeclaration(cursor.kind))
5533 return CXLinkage_Invalid;
5534
Ted Kremenek16b42592010-03-03 06:36:57 +00005535 Decl *D = cxcursor::getCursorDecl(cursor);
5536 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
5537 switch (ND->getLinkage()) {
5538 case NoLinkage: return CXLinkage_NoLinkage;
5539 case InternalLinkage: return CXLinkage_Internal;
5540 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
5541 case ExternalLinkage: return CXLinkage_External;
5542 };
5543
5544 return CXLinkage_Invalid;
5545}
5546} // end: extern "C"
5547
5548//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005549// Operations for querying language of a cursor.
5550//===----------------------------------------------------------------------===//
5551
5552static CXLanguageKind getDeclLanguage(const Decl *D) {
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00005553 if (!D)
5554 return CXLanguage_C;
5555
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005556 switch (D->getKind()) {
5557 default:
5558 break;
5559 case Decl::ImplicitParam:
5560 case Decl::ObjCAtDefsField:
5561 case Decl::ObjCCategory:
5562 case Decl::ObjCCategoryImpl:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005563 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005564 case Decl::ObjCImplementation:
5565 case Decl::ObjCInterface:
5566 case Decl::ObjCIvar:
5567 case Decl::ObjCMethod:
5568 case Decl::ObjCProperty:
5569 case Decl::ObjCPropertyImpl:
5570 case Decl::ObjCProtocol:
5571 return CXLanguage_ObjC;
5572 case Decl::CXXConstructor:
5573 case Decl::CXXConversion:
5574 case Decl::CXXDestructor:
5575 case Decl::CXXMethod:
5576 case Decl::CXXRecord:
5577 case Decl::ClassTemplate:
5578 case Decl::ClassTemplatePartialSpecialization:
5579 case Decl::ClassTemplateSpecialization:
5580 case Decl::Friend:
5581 case Decl::FriendTemplate:
5582 case Decl::FunctionTemplate:
5583 case Decl::LinkageSpec:
5584 case Decl::Namespace:
5585 case Decl::NamespaceAlias:
5586 case Decl::NonTypeTemplateParm:
5587 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005588 case Decl::TemplateTemplateParm:
5589 case Decl::TemplateTypeParm:
5590 case Decl::UnresolvedUsingTypename:
5591 case Decl::UnresolvedUsingValue:
5592 case Decl::Using:
5593 case Decl::UsingDirective:
5594 case Decl::UsingShadow:
5595 return CXLanguage_CPlusPlus;
5596 }
5597
5598 return CXLanguage_C;
5599}
5600
5601extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00005602
5603enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
5604 if (clang_isDeclaration(cursor.kind))
5605 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005606 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Douglas Gregor58ddb602010-08-23 23:00:57 +00005607 return CXAvailability_Available;
5608
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005609 switch (D->getAvailability()) {
5610 case AR_Available:
5611 case AR_NotYetIntroduced:
5612 return CXAvailability_Available;
5613
5614 case AR_Deprecated:
Douglas Gregor58ddb602010-08-23 23:00:57 +00005615 return CXAvailability_Deprecated;
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005616
5617 case AR_Unavailable:
5618 return CXAvailability_NotAvailable;
5619 }
Douglas Gregor58ddb602010-08-23 23:00:57 +00005620 }
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005621
Douglas Gregor58ddb602010-08-23 23:00:57 +00005622 return CXAvailability_Available;
5623}
5624
Douglas Gregorcc889662012-05-08 00:14:45 +00005625static CXVersion convertVersion(VersionTuple In) {
5626 CXVersion Out = { -1, -1, -1 };
5627 if (In.empty())
5628 return Out;
5629
5630 Out.Major = In.getMajor();
5631
5632 if (llvm::Optional<unsigned> Minor = In.getMinor())
5633 Out.Minor = *Minor;
5634 else
5635 return Out;
5636
5637 if (llvm::Optional<unsigned> Subminor = In.getSubminor())
5638 Out.Subminor = *Subminor;
5639
5640 return Out;
5641}
5642
5643int clang_getCursorPlatformAvailability(CXCursor cursor,
5644 int *always_deprecated,
5645 CXString *deprecated_message,
5646 int *always_unavailable,
5647 CXString *unavailable_message,
5648 CXPlatformAvailability *availability,
5649 int availability_size) {
5650 if (always_deprecated)
5651 *always_deprecated = 0;
5652 if (deprecated_message)
5653 *deprecated_message = cxstring::createCXString("", /*DupString=*/false);
5654 if (always_unavailable)
5655 *always_unavailable = 0;
5656 if (unavailable_message)
5657 *unavailable_message = cxstring::createCXString("", /*DupString=*/false);
5658
5659 if (!clang_isDeclaration(cursor.kind))
5660 return 0;
5661
5662 Decl *D = cxcursor::getCursorDecl(cursor);
5663 if (!D)
5664 return 0;
5665
5666 int N = 0;
5667 for (Decl::attr_iterator A = D->attr_begin(), AEnd = D->attr_end(); A != AEnd;
5668 ++A) {
5669 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(*A)) {
5670 if (always_deprecated)
5671 *always_deprecated = 1;
5672 if (deprecated_message)
5673 *deprecated_message = cxstring::createCXString(Deprecated->getMessage());
5674 continue;
5675 }
5676
5677 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(*A)) {
5678 if (always_unavailable)
5679 *always_unavailable = 1;
5680 if (unavailable_message) {
5681 *unavailable_message
5682 = cxstring::createCXString(Unavailable->getMessage());
5683 }
5684 continue;
5685 }
5686
5687 if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(*A)) {
5688 if (N < availability_size) {
5689 availability[N].Platform
5690 = cxstring::createCXString(Avail->getPlatform()->getName());
5691 availability[N].Introduced = convertVersion(Avail->getIntroduced());
5692 availability[N].Deprecated = convertVersion(Avail->getDeprecated());
5693 availability[N].Obsoleted = convertVersion(Avail->getObsoleted());
5694 availability[N].Unavailable = Avail->getUnavailable();
5695 availability[N].Message = cxstring::createCXString(Avail->getMessage());
5696 }
5697 ++N;
5698 }
5699 }
5700
5701 return N;
5702}
5703
5704void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) {
5705 clang_disposeString(availability->Platform);
5706 clang_disposeString(availability->Message);
5707}
5708
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005709CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
5710 if (clang_isDeclaration(cursor.kind))
5711 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
5712
5713 return CXLanguage_Invalid;
5714}
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005715
5716 /// \brief If the given cursor is the "templated" declaration
5717 /// descibing a class or function template, return the class or
5718 /// function template.
5719static Decl *maybeGetTemplateCursor(Decl *D) {
5720 if (!D)
5721 return 0;
5722
5723 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
5724 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
5725 return FunTmpl;
5726
5727 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
5728 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
5729 return ClassTmpl;
5730
5731 return D;
5732}
5733
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005734CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
5735 if (clang_isDeclaration(cursor.kind)) {
5736 if (Decl *D = getCursorDecl(cursor)) {
5737 DeclContext *DC = D->getDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005738 if (!DC)
5739 return clang_getNullCursor();
5740
5741 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5742 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005743 }
5744 }
5745
5746 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
5747 if (Decl *D = getCursorDecl(cursor))
Ted Kremeneka60ed472010-11-16 08:15:36 +00005748 return MakeCXCursor(D, getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005749 }
5750
5751 return clang_getNullCursor();
5752}
5753
5754CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
5755 if (clang_isDeclaration(cursor.kind)) {
5756 if (Decl *D = getCursorDecl(cursor)) {
5757 DeclContext *DC = D->getLexicalDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005758 if (!DC)
5759 return clang_getNullCursor();
5760
5761 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5762 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005763 }
5764 }
5765
5766 // FIXME: Note that we can't easily compute the lexical context of a
5767 // statement or expression, so we return nothing.
5768 return clang_getNullCursor();
5769}
5770
Douglas Gregorecdcb882010-10-20 22:00:55 +00005771CXFile clang_getIncludedFile(CXCursor cursor) {
5772 if (cursor.kind != CXCursor_InclusionDirective)
5773 return 0;
5774
5775 InclusionDirective *ID = getCursorInclusionDirective(cursor);
5776 return (void *)ID->getFile();
5777}
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +00005778
5779CXSourceRange clang_Cursor_getCommentRange(CXCursor C) {
5780 if (!clang_isDeclaration(C.kind))
5781 return clang_getNullRange();
5782
5783 const Decl *D = getCursorDecl(C);
5784 ASTContext &Context = getCursorContext(C);
Dmitri Gribenkof50555e2012-08-11 00:51:43 +00005785 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +00005786 if (!RC)
5787 return clang_getNullRange();
5788
5789 return cxloc::translateSourceRange(Context, RC->getSourceRange());
5790}
5791
5792CXString clang_Cursor_getRawCommentText(CXCursor C) {
5793 if (!clang_isDeclaration(C.kind))
5794 return createCXString((const char *) NULL);
5795
5796 const Decl *D = getCursorDecl(C);
5797 ASTContext &Context = getCursorContext(C);
Dmitri Gribenkof50555e2012-08-11 00:51:43 +00005798 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +00005799 StringRef RawText = RC ? RC->getRawText(Context.getSourceManager()) :
5800 StringRef();
5801
5802 // Don't duplicate the string because RawText points directly into source
5803 // code.
5804 return createCXString(RawText, false);
5805}
5806
Dmitri Gribenko2d44d772012-06-26 20:39:18 +00005807CXString clang_Cursor_getBriefCommentText(CXCursor C) {
5808 if (!clang_isDeclaration(C.kind))
5809 return createCXString((const char *) NULL);
5810
5811 const Decl *D = getCursorDecl(C);
5812 const ASTContext &Context = getCursorContext(C);
Dmitri Gribenkof50555e2012-08-11 00:51:43 +00005813 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
Dmitri Gribenko2d44d772012-06-26 20:39:18 +00005814
Dmitri Gribenko8376f592012-06-28 16:25:36 +00005815 if (RC) {
Dmitri Gribenko2d44d772012-06-26 20:39:18 +00005816 StringRef BriefText = RC->getBriefText(Context);
5817
5818 // Don't duplicate the string because RawComment ensures that this memory
5819 // will not go away.
5820 return createCXString(BriefText, false);
5821 }
5822
5823 return createCXString((const char *) NULL);
5824}
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005825
Dmitri Gribenkoae99b752012-07-20 21:34:34 +00005826CXComment clang_Cursor_getParsedComment(CXCursor C) {
5827 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkoe4330a32012-09-10 20:32:42 +00005828 return cxcomment::createCXComment(NULL, NULL);
Dmitri Gribenkoae99b752012-07-20 21:34:34 +00005829
5830 const Decl *D = getCursorDecl(C);
5831 const ASTContext &Context = getCursorContext(C);
Dmitri Gribenko19523542012-09-29 11:40:46 +00005832 const comments::FullComment *FC = Context.getCommentForDecl(D, /*PP=*/ NULL);
Dmitri Gribenkoae99b752012-07-20 21:34:34 +00005833
Dmitri Gribenkoe4330a32012-09-10 20:32:42 +00005834 return cxcomment::createCXComment(FC, getCursorTU(C));
Dmitri Gribenkoae99b752012-07-20 21:34:34 +00005835}
5836
Dmitri Gribenkob619e782012-07-17 00:17:45 +00005837} // end: extern "C"
5838
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005839//===----------------------------------------------------------------------===//
5840// C++ AST instrospection.
5841//===----------------------------------------------------------------------===//
5842
5843extern "C" {
5844unsigned clang_CXXMethod_isStatic(CXCursor C) {
5845 if (!clang_isDeclaration(C.kind))
5846 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00005847
5848 CXXMethodDecl *Method = 0;
5849 Decl *D = cxcursor::getCursorDecl(C);
5850 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5851 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5852 else
5853 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5854 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00005855}
Ted Kremenekb12903e2010-05-18 22:32:15 +00005856
Douglas Gregor211924b2011-05-12 15:17:24 +00005857unsigned clang_CXXMethod_isVirtual(CXCursor C) {
5858 if (!clang_isDeclaration(C.kind))
5859 return 0;
5860
5861 CXXMethodDecl *Method = 0;
5862 Decl *D = cxcursor::getCursorDecl(C);
5863 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5864 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5865 else
5866 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5867 return (Method && Method->isVirtual()) ? 1 : 0;
5868}
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005869} // end: extern "C"
5870
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005871//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00005872// Attribute introspection.
5873//===----------------------------------------------------------------------===//
5874
5875extern "C" {
5876CXType clang_getIBOutletCollectionType(CXCursor C) {
5877 if (C.kind != CXCursor_IBOutletCollectionAttr)
Ted Kremeneka60ed472010-11-16 08:15:36 +00005878 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005879
5880 IBOutletCollectionAttr *A =
5881 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
5882
Argyrios Kyrtzidis18aa2ff2011-09-13 18:49:52 +00005883 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005884}
5885} // end: extern "C"
5886
5887//===----------------------------------------------------------------------===//
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005888// Inspecting memory usage.
5889//===----------------------------------------------------------------------===//
5890
Ted Kremenekf7870022011-04-20 16:41:07 +00005891typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005892
Ted Kremenekf7870022011-04-20 16:41:07 +00005893static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
5894 enum CXTUResourceUsageKind k,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005895 unsigned long amount) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005896 CXTUResourceUsageEntry entry = { k, amount };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005897 entries.push_back(entry);
5898}
5899
5900extern "C" {
5901
Ted Kremenekf7870022011-04-20 16:41:07 +00005902const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005903 const char *str = "";
5904 switch (kind) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005905 case CXTUResourceUsage_AST:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005906 str = "ASTContext: expressions, declarations, and types";
5907 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005908 case CXTUResourceUsage_Identifiers:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005909 str = "ASTContext: identifiers";
5910 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005911 case CXTUResourceUsage_Selectors:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005912 str = "ASTContext: selectors";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005913 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005914 case CXTUResourceUsage_GlobalCompletionResults:
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005915 str = "Code completion: cached global results";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005916 break;
Ted Kremenek457aaf02011-04-28 04:10:31 +00005917 case CXTUResourceUsage_SourceManagerContentCache:
5918 str = "SourceManager: content cache allocator";
5919 break;
Ted Kremenekba29bd22011-04-28 04:53:38 +00005920 case CXTUResourceUsage_AST_SideTables:
5921 str = "ASTContext: side tables";
5922 break;
Ted Kremenekf61b8312011-04-28 20:36:42 +00005923 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
5924 str = "SourceManager: malloc'ed memory buffers";
5925 break;
5926 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
5927 str = "SourceManager: mmap'ed memory buffers";
5928 break;
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005929 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
5930 str = "ExternalASTSource: malloc'ed memory buffers";
5931 break;
5932 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
5933 str = "ExternalASTSource: mmap'ed memory buffers";
5934 break;
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005935 case CXTUResourceUsage_Preprocessor:
5936 str = "Preprocessor: malloc'ed memory";
5937 break;
5938 case CXTUResourceUsage_PreprocessingRecord:
5939 str = "Preprocessor: PreprocessingRecord";
5940 break;
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005941 case CXTUResourceUsage_SourceManager_DataStructures:
5942 str = "SourceManager: data structures and tables";
5943 break;
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005944 case CXTUResourceUsage_Preprocessor_HeaderSearch:
5945 str = "Preprocessor: header search tables";
5946 break;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005947 }
5948 return str;
5949}
5950
Ted Kremenekf7870022011-04-20 16:41:07 +00005951CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005952 if (!TU) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005953 CXTUResourceUsage usage = { (void*) 0, 0, 0 };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005954 return usage;
5955 }
5956
5957 ASTUnit *astUnit = static_cast<ASTUnit*>(TU->TUData);
Dylan Noblesmith1e4c01b2012-02-13 12:32:21 +00005958 OwningPtr<MemUsageEntries> entries(new MemUsageEntries());
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005959 ASTContext &astContext = astUnit->getASTContext();
5960
5961 // How much memory is used by AST nodes and types?
Ted Kremenekf7870022011-04-20 16:41:07 +00005962 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005963 (unsigned long) astContext.getASTAllocatedMemory());
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005964
5965 // How much memory is used by identifiers?
Ted Kremenekf7870022011-04-20 16:41:07 +00005966 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005967 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
5968
5969 // How much memory is used for selectors?
Ted Kremenekf7870022011-04-20 16:41:07 +00005970 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005971 (unsigned long) astContext.Selectors.getTotalMemory());
5972
Ted Kremenekba29bd22011-04-28 04:53:38 +00005973 // How much memory is used by ASTContext's side tables?
5974 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
5975 (unsigned long) astContext.getSideTableAllocatedMemory());
5976
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005977 // How much memory is used for caching global code completion results?
5978 unsigned long completionBytes = 0;
5979 if (GlobalCodeCompletionAllocator *completionAllocator =
5980 astUnit->getCachedCompletionAllocator().getPtr()) {
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005981 completionBytes = completionAllocator->getTotalMemory();
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005982 }
Ted Kremenek457aaf02011-04-28 04:10:31 +00005983 createCXTUResourceUsageEntry(*entries,
5984 CXTUResourceUsage_GlobalCompletionResults,
5985 completionBytes);
5986
5987 // How much memory is being used by SourceManager's content cache?
5988 createCXTUResourceUsageEntry(*entries,
5989 CXTUResourceUsage_SourceManagerContentCache,
5990 (unsigned long) astContext.getSourceManager().getContentCacheSize());
Ted Kremenekf61b8312011-04-28 20:36:42 +00005991
5992 // How much memory is being used by the MemoryBuffer's in SourceManager?
5993 const SourceManager::MemoryBufferSizes &srcBufs =
5994 astUnit->getSourceManager().getMemoryBufferSizes();
5995
5996 createCXTUResourceUsageEntry(*entries,
5997 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
5998 (unsigned long) srcBufs.malloc_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005999 createCXTUResourceUsageEntry(*entries,
Ted Kremenekf61b8312011-04-28 20:36:42 +00006000 CXTUResourceUsage_SourceManager_Membuffer_MMap,
6001 (unsigned long) srcBufs.mmap_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00006002 createCXTUResourceUsageEntry(*entries,
6003 CXTUResourceUsage_SourceManager_DataStructures,
6004 (unsigned long) astContext.getSourceManager()
6005 .getDataStructureSizes());
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00006006
6007 // How much memory is being used by the ExternalASTSource?
6008 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
6009 const ExternalASTSource::MemoryBufferSizes &sizes =
6010 esrc->getMemoryBufferSizes();
6011
6012 createCXTUResourceUsageEntry(*entries,
6013 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
6014 (unsigned long) sizes.malloc_bytes);
6015 createCXTUResourceUsageEntry(*entries,
6016 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
6017 (unsigned long) sizes.mmap_bytes);
6018 }
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00006019
6020 // How much memory is being used by the Preprocessor?
6021 Preprocessor &pp = astUnit->getPreprocessor();
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00006022 createCXTUResourceUsageEntry(*entries,
6023 CXTUResourceUsage_Preprocessor,
Argyrios Kyrtzidisc5c5e922011-06-29 22:20:04 +00006024 pp.getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00006025
6026 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
6027 createCXTUResourceUsageEntry(*entries,
6028 CXTUResourceUsage_PreprocessingRecord,
6029 pRec->getTotalMemory());
6030 }
6031
Ted Kremenekd1194fb2011-07-26 23:46:11 +00006032 createCXTUResourceUsageEntry(*entries,
6033 CXTUResourceUsage_Preprocessor_HeaderSearch,
6034 pp.getHeaderSearchInfo().getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00006035
Ted Kremenekf7870022011-04-20 16:41:07 +00006036 CXTUResourceUsage usage = { (void*) entries.get(),
Ted Kremenek59fc1e52011-04-18 22:47:10 +00006037 (unsigned) entries->size(),
6038 entries->size() ? &(*entries)[0] : 0 };
6039 entries.take();
6040 return usage;
6041}
6042
Ted Kremenekf7870022011-04-20 16:41:07 +00006043void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00006044 if (usage.data)
6045 delete (MemUsageEntries*) usage.data;
6046}
6047
6048} // end extern "C"
6049
Douglas Gregor6df78732011-05-05 20:27:22 +00006050void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
6051 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
6052 for (unsigned I = 0; I != Usage.numEntries; ++I)
6053 fprintf(stderr, " %s: %lu\n",
6054 clang_getTUResourceUsageName(Usage.entries[I].kind),
6055 Usage.entries[I].amount);
6056
6057 clang_disposeCXTUResourceUsage(Usage);
6058}
6059
Ted Kremenek59fc1e52011-04-18 22:47:10 +00006060//===----------------------------------------------------------------------===//
Ted Kremenek04bb7162010-01-22 22:44:15 +00006061// Misc. utility functions.
6062//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00006063
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00006064/// Default to using an 8 MB stack size on "safety" threads.
6065static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00006066
6067namespace clang {
6068
6069bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00006070 void (*Fn)(void*), void *UserData,
6071 unsigned Size) {
6072 if (!Size)
6073 Size = GetSafetyThreadStackSize();
6074 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00006075 return CRC.RunSafelyOnThread(Fn, UserData, Size);
6076 return CRC.RunSafely(Fn, UserData);
6077}
6078
6079unsigned GetSafetyThreadStackSize() {
6080 return SafetyStackThreadSize;
6081}
6082
6083void SetSafetyThreadStackSize(unsigned Value) {
6084 SafetyStackThreadSize = Value;
6085}
6086
Argyrios Kyrtzidis8e7c48a2012-03-28 02:49:50 +00006087}
6088
Argyrios Kyrtzidis81b5ac32012-03-28 02:49:54 +00006089void clang::setThreadBackgroundPriority() {
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00006090 // FIXME: Move to llvm/Support and make it cross-platform.
6091#ifdef __APPLE__
6092 setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG);
6093#endif
6094}
6095
Argyrios Kyrtzidis97934282012-04-11 03:52:18 +00006096void cxindex::printDiagsToStderr(ASTUnit *Unit) {
6097 if (!Unit)
6098 return;
6099
6100 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
6101 DEnd = Unit->stored_diag_end();
6102 D != DEnd; ++D) {
6103 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOpts());
6104 CXString Msg = clang_formatDiagnostic(&Diag,
6105 clang_defaultDiagnosticDisplayOptions());
6106 fprintf(stderr, "%s\n", clang_getCString(Msg));
6107 clang_disposeString(Msg);
6108 }
6109#ifdef LLVM_ON_WIN32
6110 // On Windows, force a flush, since there may be multiple copies of
6111 // stderr and stdout in the file system, all with different buffers
6112 // but writing to the same device.
6113 fflush(stderr);
6114#endif
6115}
6116
Ted Kremenek04bb7162010-01-22 22:44:15 +00006117extern "C" {
6118
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00006119CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00006120 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00006121}
6122
6123} // end: extern "C"
Ted Kremenek59fc1e52011-04-18 22:47:10 +00006124