blob: f1080f68e800d01de9db4e489e8005f2543bdcf9 [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
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003050 return createCXString("");
Douglas Gregore3c60a72010-11-17 00:13:31 +00003051 }
3052
Douglas Gregor78205d42010-01-20 21:45:58 +00003053 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003054 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003055
Douglas Gregor78205d42010-01-20 21:45:58 +00003056 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
3057 // No, this isn't the same as the code below. getIdentifier() is non-virtual
3058 // and returns different names. NamedDecl returns the class name and
3059 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003060 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003061
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003062 if (isa<UsingDirectiveDecl>(D))
3063 return createCXString("");
3064
Dylan Noblesmith36d59272012-02-13 12:32:26 +00003065 SmallString<1024> S;
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00003066 llvm::raw_svector_ostream os(S);
3067 ND->printName(os);
3068
3069 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00003070}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003071
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003072CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003073 if (clang_isTranslationUnit(C.kind))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003074 return clang_getTranslationUnitSpelling(
3075 static_cast<CXTranslationUnit>(C.data[2]));
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003076
Steve Narofff334b4e2009-09-02 18:26:48 +00003077 if (clang_isReference(C.kind)) {
3078 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00003079 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00003080 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003081 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003082 }
3083 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00003084 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003085 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003086 }
3087 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00003088 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00003089 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003090 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003091 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00003092 case CXCursor_CXXBaseSpecifier: {
3093 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
3094 return createCXString(B->getType().getAsString());
3095 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003096 case CXCursor_TypeRef: {
3097 TypeDecl *Type = getCursorTypeRef(C).first;
3098 assert(Type && "Missing type decl");
3099
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003100 return createCXString(getCursorContext(C).getTypeDeclType(Type).
3101 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003102 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003103 case CXCursor_TemplateRef: {
3104 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00003105 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003106
3107 return createCXString(Template->getNameAsString());
3108 }
Douglas Gregor69319002010-08-31 23:48:11 +00003109
3110 case CXCursor_NamespaceRef: {
3111 NamedDecl *NS = getCursorNamespaceRef(C).first;
3112 assert(NS && "Missing namespace decl");
3113
3114 return createCXString(NS->getNameAsString());
3115 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003116
Douglas Gregora67e03f2010-09-09 21:42:20 +00003117 case CXCursor_MemberRef: {
3118 FieldDecl *Field = getCursorMemberRef(C).first;
3119 assert(Field && "Missing member decl");
3120
3121 return createCXString(Field->getNameAsString());
3122 }
3123
Douglas Gregor36897b02010-09-10 00:22:18 +00003124 case CXCursor_LabelRef: {
3125 LabelStmt *Label = getCursorLabelRef(C).first;
3126 assert(Label && "Missing label");
3127
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003128 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00003129 }
3130
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003131 case CXCursor_OverloadedDeclRef: {
3132 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3133 if (Decl *D = Storage.dyn_cast<Decl *>()) {
3134 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
3135 return createCXString(ND->getNameAsString());
3136 return createCXString("");
3137 }
3138 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3139 return createCXString(E->getName().getAsString());
3140 OverloadedTemplateStorage *Ovl
3141 = Storage.get<OverloadedTemplateStorage*>();
3142 if (Ovl->size() == 0)
3143 return createCXString("");
3144 return createCXString((*Ovl->begin())->getNameAsString());
3145 }
3146
Douglas Gregor011d8b92012-02-15 00:54:55 +00003147 case CXCursor_VariableRef: {
3148 VarDecl *Var = getCursorVariableRef(C).first;
3149 assert(Var && "Missing variable decl");
3150
3151 return createCXString(Var->getNameAsString());
3152 }
3153
Daniel Dunbaracca7252009-11-30 20:42:49 +00003154 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003155 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00003156 }
3157 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003158
3159 if (clang_isExpression(C.kind)) {
3160 Decl *D = getDeclFromExpr(getCursorExpr(C));
3161 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00003162 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003163 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00003164 }
3165
Douglas Gregor36897b02010-09-10 00:22:18 +00003166 if (clang_isStatement(C.kind)) {
3167 Stmt *S = getCursorStmt(C);
3168 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003169 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00003170
3171 return createCXString("");
3172 }
3173
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003174 if (C.kind == CXCursor_MacroExpansion)
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003175 return createCXString(getCursorMacroExpansion(C)->getName()
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003176 ->getNameStart());
3177
Douglas Gregor572feb22010-03-18 18:04:21 +00003178 if (C.kind == CXCursor_MacroDefinition)
3179 return createCXString(getCursorMacroDefinition(C)->getName()
3180 ->getNameStart());
3181
Douglas Gregorecdcb882010-10-20 22:00:55 +00003182 if (C.kind == CXCursor_InclusionDirective)
3183 return createCXString(getCursorInclusionDirective(C)->getFileName());
3184
Douglas Gregor60cbfac2010-01-25 16:56:17 +00003185 if (clang_isDeclaration(C.kind))
3186 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00003187
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00003188 if (C.kind == CXCursor_AnnotateAttr) {
3189 AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
3190 return createCXString(AA->getAnnotation());
3191 }
3192
Argyrios Kyrtzidis84b79642011-12-06 22:05:01 +00003193 if (C.kind == CXCursor_AsmLabelAttr) {
3194 AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
3195 return createCXString(AA->getLabel());
3196 }
3197
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003198 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00003199}
3200
Argyrios Kyrtzidisba1da142012-03-30 20:58:35 +00003201CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C,
3202 unsigned pieceIndex,
3203 unsigned options) {
3204 if (clang_Cursor_isNull(C))
3205 return clang_getNullRange();
3206
3207 ASTContext &Ctx = getCursorContext(C);
3208
3209 if (clang_isStatement(C.kind)) {
3210 Stmt *S = getCursorStmt(C);
3211 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
3212 if (pieceIndex > 0)
3213 return clang_getNullRange();
3214 return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
3215 }
3216
3217 return clang_getNullRange();
3218 }
3219
3220 if (C.kind == CXCursor_ObjCMessageExpr) {
3221 if (ObjCMessageExpr *
3222 ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
3223 if (pieceIndex >= ME->getNumSelectorLocs())
3224 return clang_getNullRange();
3225 return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
3226 }
3227 }
3228
3229 if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
3230 C.kind == CXCursor_ObjCClassMethodDecl) {
3231 if (ObjCMethodDecl *
3232 MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
3233 if (pieceIndex >= MD->getNumSelectorLocs())
3234 return clang_getNullRange();
3235 return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
3236 }
3237 }
3238
Argyrios Kyrtzidis9482a182012-04-16 20:01:28 +00003239 if (C.kind == CXCursor_ObjCCategoryDecl ||
3240 C.kind == CXCursor_ObjCCategoryImplDecl) {
3241 if (pieceIndex > 0)
3242 return clang_getNullRange();
3243 if (ObjCCategoryDecl *
3244 CD = dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
3245 return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
3246 if (ObjCCategoryImplDecl *
3247 CID = dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
3248 return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
3249 }
3250
Argyrios Kyrtzidisba1da142012-03-30 20:58:35 +00003251 // FIXME: A CXCursor_InclusionDirective should give the location of the
3252 // filename, but we don't keep track of this.
3253
3254 // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
3255 // but we don't keep track of this.
3256
3257 // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
3258 // but we don't keep track of this.
3259
3260 // Default handling, give the location of the cursor.
3261
3262 if (pieceIndex > 0)
3263 return clang_getNullRange();
3264
3265 CXSourceLocation CXLoc = clang_getCursorLocation(C);
3266 SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
3267 return cxloc::translateSourceRange(Ctx, Loc);
3268}
3269
Douglas Gregor358559d2010-10-02 22:49:11 +00003270CXString clang_getCursorDisplayName(CXCursor C) {
3271 if (!clang_isDeclaration(C.kind))
3272 return clang_getCursorSpelling(C);
3273
3274 Decl *D = getCursorDecl(C);
3275 if (!D)
3276 return createCXString("");
3277
Douglas Gregor30c42402011-09-27 22:38:19 +00003278 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
Douglas Gregor358559d2010-10-02 22:49:11 +00003279 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
3280 D = FunTmpl->getTemplatedDecl();
3281
3282 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Dylan Noblesmith36d59272012-02-13 12:32:26 +00003283 SmallString<64> Str;
Douglas Gregor358559d2010-10-02 22:49:11 +00003284 llvm::raw_svector_ostream OS(Str);
Benjamin Kramera59d20b2012-02-07 11:57:57 +00003285 OS << *Function;
Douglas Gregor358559d2010-10-02 22:49:11 +00003286 if (Function->getPrimaryTemplate())
3287 OS << "<>";
3288 OS << "(";
3289 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
3290 if (I)
3291 OS << ", ";
3292 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
3293 }
3294
3295 if (Function->isVariadic()) {
3296 if (Function->getNumParams())
3297 OS << ", ";
3298 OS << "...";
3299 }
3300 OS << ")";
3301 return createCXString(OS.str());
3302 }
3303
3304 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
Dylan Noblesmith36d59272012-02-13 12:32:26 +00003305 SmallString<64> Str;
Douglas Gregor358559d2010-10-02 22:49:11 +00003306 llvm::raw_svector_ostream OS(Str);
Benjamin Kramera59d20b2012-02-07 11:57:57 +00003307 OS << *ClassTemplate;
Douglas Gregor358559d2010-10-02 22:49:11 +00003308 OS << "<";
3309 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
3310 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3311 if (I)
3312 OS << ", ";
3313
3314 NamedDecl *Param = Params->getParam(I);
3315 if (Param->getIdentifier()) {
3316 OS << Param->getIdentifier()->getName();
3317 continue;
3318 }
3319
3320 // There is no parameter name, which makes this tricky. Try to come up
3321 // with something useful that isn't too long.
3322 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3323 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
3324 else if (NonTypeTemplateParmDecl *NTTP
3325 = dyn_cast<NonTypeTemplateParmDecl>(Param))
3326 OS << NTTP->getType().getAsString(Policy);
3327 else
3328 OS << "template<...> class";
3329 }
3330
3331 OS << ">";
3332 return createCXString(OS.str());
3333 }
3334
3335 if (ClassTemplateSpecializationDecl *ClassSpec
3336 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
3337 // If the type was explicitly written, use that.
3338 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
3339 return createCXString(TSInfo->getType().getAsString(Policy));
3340
Dylan Noblesmith36d59272012-02-13 12:32:26 +00003341 SmallString<64> Str;
Douglas Gregor358559d2010-10-02 22:49:11 +00003342 llvm::raw_svector_ostream OS(Str);
Benjamin Kramera59d20b2012-02-07 11:57:57 +00003343 OS << *ClassSpec;
Douglas Gregor358559d2010-10-02 22:49:11 +00003344 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00003345 ClassSpec->getTemplateArgs().data(),
3346 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00003347 Policy);
3348 return createCXString(OS.str());
3349 }
3350
3351 return clang_getCursorSpelling(C);
3352}
3353
Ted Kremeneke68fff62010-02-17 00:41:32 +00003354CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00003355 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00003356 case CXCursor_FunctionDecl:
3357 return createCXString("FunctionDecl");
3358 case CXCursor_TypedefDecl:
3359 return createCXString("TypedefDecl");
3360 case CXCursor_EnumDecl:
3361 return createCXString("EnumDecl");
3362 case CXCursor_EnumConstantDecl:
3363 return createCXString("EnumConstantDecl");
3364 case CXCursor_StructDecl:
3365 return createCXString("StructDecl");
3366 case CXCursor_UnionDecl:
3367 return createCXString("UnionDecl");
3368 case CXCursor_ClassDecl:
3369 return createCXString("ClassDecl");
3370 case CXCursor_FieldDecl:
3371 return createCXString("FieldDecl");
3372 case CXCursor_VarDecl:
3373 return createCXString("VarDecl");
3374 case CXCursor_ParmDecl:
3375 return createCXString("ParmDecl");
3376 case CXCursor_ObjCInterfaceDecl:
3377 return createCXString("ObjCInterfaceDecl");
3378 case CXCursor_ObjCCategoryDecl:
3379 return createCXString("ObjCCategoryDecl");
3380 case CXCursor_ObjCProtocolDecl:
3381 return createCXString("ObjCProtocolDecl");
3382 case CXCursor_ObjCPropertyDecl:
3383 return createCXString("ObjCPropertyDecl");
3384 case CXCursor_ObjCIvarDecl:
3385 return createCXString("ObjCIvarDecl");
3386 case CXCursor_ObjCInstanceMethodDecl:
3387 return createCXString("ObjCInstanceMethodDecl");
3388 case CXCursor_ObjCClassMethodDecl:
3389 return createCXString("ObjCClassMethodDecl");
3390 case CXCursor_ObjCImplementationDecl:
3391 return createCXString("ObjCImplementationDecl");
3392 case CXCursor_ObjCCategoryImplDecl:
3393 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00003394 case CXCursor_CXXMethod:
3395 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003396 case CXCursor_UnexposedDecl:
3397 return createCXString("UnexposedDecl");
3398 case CXCursor_ObjCSuperClassRef:
3399 return createCXString("ObjCSuperClassRef");
3400 case CXCursor_ObjCProtocolRef:
3401 return createCXString("ObjCProtocolRef");
3402 case CXCursor_ObjCClassRef:
3403 return createCXString("ObjCClassRef");
3404 case CXCursor_TypeRef:
3405 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003406 case CXCursor_TemplateRef:
3407 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00003408 case CXCursor_NamespaceRef:
3409 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00003410 case CXCursor_MemberRef:
3411 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00003412 case CXCursor_LabelRef:
3413 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003414 case CXCursor_OverloadedDeclRef:
3415 return createCXString("OverloadedDeclRef");
Douglas Gregor011d8b92012-02-15 00:54:55 +00003416 case CXCursor_VariableRef:
3417 return createCXString("VariableRef");
Douglas Gregor42b29842011-10-05 19:00:14 +00003418 case CXCursor_IntegerLiteral:
3419 return createCXString("IntegerLiteral");
3420 case CXCursor_FloatingLiteral:
3421 return createCXString("FloatingLiteral");
3422 case CXCursor_ImaginaryLiteral:
3423 return createCXString("ImaginaryLiteral");
3424 case CXCursor_StringLiteral:
3425 return createCXString("StringLiteral");
3426 case CXCursor_CharacterLiteral:
3427 return createCXString("CharacterLiteral");
3428 case CXCursor_ParenExpr:
3429 return createCXString("ParenExpr");
3430 case CXCursor_UnaryOperator:
3431 return createCXString("UnaryOperator");
3432 case CXCursor_ArraySubscriptExpr:
3433 return createCXString("ArraySubscriptExpr");
3434 case CXCursor_BinaryOperator:
3435 return createCXString("BinaryOperator");
3436 case CXCursor_CompoundAssignOperator:
3437 return createCXString("CompoundAssignOperator");
3438 case CXCursor_ConditionalOperator:
3439 return createCXString("ConditionalOperator");
3440 case CXCursor_CStyleCastExpr:
3441 return createCXString("CStyleCastExpr");
3442 case CXCursor_CompoundLiteralExpr:
3443 return createCXString("CompoundLiteralExpr");
3444 case CXCursor_InitListExpr:
3445 return createCXString("InitListExpr");
3446 case CXCursor_AddrLabelExpr:
3447 return createCXString("AddrLabelExpr");
3448 case CXCursor_StmtExpr:
3449 return createCXString("StmtExpr");
3450 case CXCursor_GenericSelectionExpr:
3451 return createCXString("GenericSelectionExpr");
3452 case CXCursor_GNUNullExpr:
3453 return createCXString("GNUNullExpr");
3454 case CXCursor_CXXStaticCastExpr:
3455 return createCXString("CXXStaticCastExpr");
3456 case CXCursor_CXXDynamicCastExpr:
3457 return createCXString("CXXDynamicCastExpr");
3458 case CXCursor_CXXReinterpretCastExpr:
3459 return createCXString("CXXReinterpretCastExpr");
3460 case CXCursor_CXXConstCastExpr:
3461 return createCXString("CXXConstCastExpr");
3462 case CXCursor_CXXFunctionalCastExpr:
3463 return createCXString("CXXFunctionalCastExpr");
3464 case CXCursor_CXXTypeidExpr:
3465 return createCXString("CXXTypeidExpr");
3466 case CXCursor_CXXBoolLiteralExpr:
3467 return createCXString("CXXBoolLiteralExpr");
3468 case CXCursor_CXXNullPtrLiteralExpr:
3469 return createCXString("CXXNullPtrLiteralExpr");
3470 case CXCursor_CXXThisExpr:
3471 return createCXString("CXXThisExpr");
3472 case CXCursor_CXXThrowExpr:
3473 return createCXString("CXXThrowExpr");
3474 case CXCursor_CXXNewExpr:
3475 return createCXString("CXXNewExpr");
3476 case CXCursor_CXXDeleteExpr:
3477 return createCXString("CXXDeleteExpr");
3478 case CXCursor_UnaryExpr:
3479 return createCXString("UnaryExpr");
3480 case CXCursor_ObjCStringLiteral:
3481 return createCXString("ObjCStringLiteral");
Ted Kremenekb3f75422012-03-06 20:06:06 +00003482 case CXCursor_ObjCBoolLiteralExpr:
3483 return createCXString("ObjCBoolLiteralExpr");
Douglas Gregor42b29842011-10-05 19:00:14 +00003484 case CXCursor_ObjCEncodeExpr:
3485 return createCXString("ObjCEncodeExpr");
3486 case CXCursor_ObjCSelectorExpr:
3487 return createCXString("ObjCSelectorExpr");
3488 case CXCursor_ObjCProtocolExpr:
3489 return createCXString("ObjCProtocolExpr");
3490 case CXCursor_ObjCBridgedCastExpr:
3491 return createCXString("ObjCBridgedCastExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00003492 case CXCursor_BlockExpr:
3493 return createCXString("BlockExpr");
Douglas Gregor42b29842011-10-05 19:00:14 +00003494 case CXCursor_PackExpansionExpr:
3495 return createCXString("PackExpansionExpr");
3496 case CXCursor_SizeOfPackExpr:
3497 return createCXString("SizeOfPackExpr");
Douglas Gregor011d8b92012-02-15 00:54:55 +00003498 case CXCursor_LambdaExpr:
3499 return createCXString("LambdaExpr");
Douglas Gregor42b29842011-10-05 19:00:14 +00003500 case CXCursor_UnexposedExpr:
3501 return createCXString("UnexposedExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003502 case CXCursor_DeclRefExpr:
3503 return createCXString("DeclRefExpr");
3504 case CXCursor_MemberRefExpr:
3505 return createCXString("MemberRefExpr");
3506 case CXCursor_CallExpr:
3507 return createCXString("CallExpr");
3508 case CXCursor_ObjCMessageExpr:
3509 return createCXString("ObjCMessageExpr");
3510 case CXCursor_UnexposedStmt:
3511 return createCXString("UnexposedStmt");
Douglas Gregor42b29842011-10-05 19:00:14 +00003512 case CXCursor_DeclStmt:
3513 return createCXString("DeclStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00003514 case CXCursor_LabelStmt:
3515 return createCXString("LabelStmt");
Douglas Gregor42b29842011-10-05 19:00:14 +00003516 case CXCursor_CompoundStmt:
3517 return createCXString("CompoundStmt");
3518 case CXCursor_CaseStmt:
3519 return createCXString("CaseStmt");
3520 case CXCursor_DefaultStmt:
3521 return createCXString("DefaultStmt");
3522 case CXCursor_IfStmt:
3523 return createCXString("IfStmt");
3524 case CXCursor_SwitchStmt:
3525 return createCXString("SwitchStmt");
3526 case CXCursor_WhileStmt:
3527 return createCXString("WhileStmt");
3528 case CXCursor_DoStmt:
3529 return createCXString("DoStmt");
3530 case CXCursor_ForStmt:
3531 return createCXString("ForStmt");
3532 case CXCursor_GotoStmt:
3533 return createCXString("GotoStmt");
3534 case CXCursor_IndirectGotoStmt:
3535 return createCXString("IndirectGotoStmt");
3536 case CXCursor_ContinueStmt:
3537 return createCXString("ContinueStmt");
3538 case CXCursor_BreakStmt:
3539 return createCXString("BreakStmt");
3540 case CXCursor_ReturnStmt:
3541 return createCXString("ReturnStmt");
Chad Rosierdf5faf52012-08-25 00:11:56 +00003542 case CXCursor_GCCAsmStmt:
3543 return createCXString("GCCAsmStmt");
Chad Rosier8cd64b42012-06-11 20:47:18 +00003544 case CXCursor_MSAsmStmt:
3545 return createCXString("MSAsmStmt");
Douglas Gregor42b29842011-10-05 19:00:14 +00003546 case CXCursor_ObjCAtTryStmt:
3547 return createCXString("ObjCAtTryStmt");
3548 case CXCursor_ObjCAtCatchStmt:
3549 return createCXString("ObjCAtCatchStmt");
3550 case CXCursor_ObjCAtFinallyStmt:
3551 return createCXString("ObjCAtFinallyStmt");
3552 case CXCursor_ObjCAtThrowStmt:
3553 return createCXString("ObjCAtThrowStmt");
3554 case CXCursor_ObjCAtSynchronizedStmt:
3555 return createCXString("ObjCAtSynchronizedStmt");
3556 case CXCursor_ObjCAutoreleasePoolStmt:
3557 return createCXString("ObjCAutoreleasePoolStmt");
3558 case CXCursor_ObjCForCollectionStmt:
3559 return createCXString("ObjCForCollectionStmt");
3560 case CXCursor_CXXCatchStmt:
3561 return createCXString("CXXCatchStmt");
3562 case CXCursor_CXXTryStmt:
3563 return createCXString("CXXTryStmt");
3564 case CXCursor_CXXForRangeStmt:
3565 return createCXString("CXXForRangeStmt");
3566 case CXCursor_SEHTryStmt:
3567 return createCXString("SEHTryStmt");
3568 case CXCursor_SEHExceptStmt:
3569 return createCXString("SEHExceptStmt");
3570 case CXCursor_SEHFinallyStmt:
3571 return createCXString("SEHFinallyStmt");
3572 case CXCursor_NullStmt:
3573 return createCXString("NullStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003574 case CXCursor_InvalidFile:
3575 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00003576 case CXCursor_InvalidCode:
3577 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003578 case CXCursor_NoDeclFound:
3579 return createCXString("NoDeclFound");
3580 case CXCursor_NotImplemented:
3581 return createCXString("NotImplemented");
3582 case CXCursor_TranslationUnit:
3583 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00003584 case CXCursor_UnexposedAttr:
3585 return createCXString("UnexposedAttr");
3586 case CXCursor_IBActionAttr:
3587 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003588 case CXCursor_IBOutletAttr:
3589 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003590 case CXCursor_IBOutletCollectionAttr:
3591 return createCXString("attribute(iboutletcollection)");
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00003592 case CXCursor_CXXFinalAttr:
3593 return createCXString("attribute(final)");
3594 case CXCursor_CXXOverrideAttr:
3595 return createCXString("attribute(override)");
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00003596 case CXCursor_AnnotateAttr:
3597 return createCXString("attribute(annotate)");
Argyrios Kyrtzidis84b79642011-12-06 22:05:01 +00003598 case CXCursor_AsmLabelAttr:
3599 return createCXString("asm label");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003600 case CXCursor_PreprocessingDirective:
3601 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003602 case CXCursor_MacroDefinition:
3603 return createCXString("macro definition");
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003604 case CXCursor_MacroExpansion:
3605 return createCXString("macro expansion");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003606 case CXCursor_InclusionDirective:
3607 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003608 case CXCursor_Namespace:
3609 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003610 case CXCursor_LinkageSpec:
3611 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003612 case CXCursor_CXXBaseSpecifier:
3613 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003614 case CXCursor_Constructor:
3615 return createCXString("CXXConstructor");
3616 case CXCursor_Destructor:
3617 return createCXString("CXXDestructor");
3618 case CXCursor_ConversionFunction:
3619 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003620 case CXCursor_TemplateTypeParameter:
3621 return createCXString("TemplateTypeParameter");
3622 case CXCursor_NonTypeTemplateParameter:
3623 return createCXString("NonTypeTemplateParameter");
3624 case CXCursor_TemplateTemplateParameter:
3625 return createCXString("TemplateTemplateParameter");
3626 case CXCursor_FunctionTemplate:
3627 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003628 case CXCursor_ClassTemplate:
3629 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003630 case CXCursor_ClassTemplatePartialSpecialization:
3631 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003632 case CXCursor_NamespaceAlias:
3633 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003634 case CXCursor_UsingDirective:
3635 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003636 case CXCursor_UsingDeclaration:
3637 return createCXString("UsingDeclaration");
Richard Smith162e1c12011-04-15 14:24:37 +00003638 case CXCursor_TypeAliasDecl:
Douglas Gregor352697a2011-06-03 23:08:58 +00003639 return createCXString("TypeAliasDecl");
3640 case CXCursor_ObjCSynthesizeDecl:
3641 return createCXString("ObjCSynthesizeDecl");
3642 case CXCursor_ObjCDynamicDecl:
3643 return createCXString("ObjCDynamicDecl");
Argyrios Kyrtzidis2dfdb942011-09-30 17:58:23 +00003644 case CXCursor_CXXAccessSpecifier:
3645 return createCXString("CXXAccessSpecifier");
Steve Naroff89922f82009-08-31 00:59:03 +00003646 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003647
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003648 llvm_unreachable("Unhandled CXCursorKind");
Steve Naroff600866c2009-08-27 19:51:58 +00003649}
Steve Naroff89922f82009-08-31 00:59:03 +00003650
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003651struct GetCursorData {
3652 SourceLocation TokenBeginLoc;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003653 bool PointsAtMacroArgExpansion;
Argyrios Kyrtzidis135bf8e2012-06-09 03:03:02 +00003654 bool VisitedObjCPropertyImplDecl;
3655 SourceLocation VisitedDeclaratorDeclStartLoc;
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003656 CXCursor &BestCursor;
3657
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003658 GetCursorData(SourceManager &SM,
3659 SourceLocation tokenBegin, CXCursor &outputCursor)
3660 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
3661 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
Argyrios Kyrtzidis135bf8e2012-06-09 03:03:02 +00003662 VisitedObjCPropertyImplDecl = false;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003663 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003664};
3665
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003666static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3667 CXCursor parent,
3668 CXClientData client_data) {
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003669 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
3670 CXCursor *BestCursor = &Data->BestCursor;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003671
3672 // If we point inside a macro argument we should provide info of what the
3673 // token is so use the actual cursor, don't replace it with a macro expansion
3674 // cursor.
3675 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
3676 return CXChildVisit_Recurse;
Argyrios Kyrtzidis65ab9072011-09-26 19:05:37 +00003677
3678 if (clang_isDeclaration(cursor.kind)) {
3679 // Avoid having the implicit methods override the property decls.
Argyrios Kyrtzidisa9d45a32012-04-16 22:42:01 +00003680 if (ObjCMethodDecl *MD
3681 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
Argyrios Kyrtzidis65ab9072011-09-26 19:05:37 +00003682 if (MD->isImplicit())
3683 return CXChildVisit_Break;
Argyrios Kyrtzidisa9d45a32012-04-16 22:42:01 +00003684
3685 } else if (ObjCInterfaceDecl *ID
3686 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) {
3687 // Check that when we have multiple @class references in the same line,
3688 // that later ones do not override the previous ones.
3689 // If we have:
3690 // @class Foo, Bar;
3691 // source ranges for both start at '@', so 'Bar' will end up overriding
3692 // 'Foo' even though the cursor location was at 'Foo'.
3693 if (BestCursor->kind == CXCursor_ObjCInterfaceDecl ||
3694 BestCursor->kind == CXCursor_ObjCClassRef)
3695 if (ObjCInterfaceDecl *PrevID
3696 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(*BestCursor))){
3697 if (PrevID != ID &&
3698 !PrevID->isThisDeclarationADefinition() &&
3699 !ID->isThisDeclarationADefinition())
3700 return CXChildVisit_Break;
3701 }
Argyrios Kyrtzidis135bf8e2012-06-09 03:03:02 +00003702
3703 } else if (DeclaratorDecl *DD
3704 = dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) {
3705 SourceLocation StartLoc = DD->getSourceRange().getBegin();
3706 // Check that when we have multiple declarators in the same line,
3707 // that later ones do not override the previous ones.
3708 // If we have:
3709 // int Foo, Bar;
3710 // source ranges for both start at 'int', so 'Bar' will end up overriding
3711 // 'Foo' even though the cursor location was at 'Foo'.
3712 if (Data->VisitedDeclaratorDeclStartLoc == StartLoc)
3713 return CXChildVisit_Break;
3714 Data->VisitedDeclaratorDeclStartLoc = StartLoc;
3715
3716 } else if (ObjCPropertyImplDecl *PropImp
3717 = dyn_cast_or_null<ObjCPropertyImplDecl>(getCursorDecl(cursor))) {
3718 (void)PropImp;
3719 // Check that when we have multiple @synthesize in the same line,
3720 // that later ones do not override the previous ones.
3721 // If we have:
3722 // @synthesize Foo, Bar;
3723 // source ranges for both start at '@', so 'Bar' will end up overriding
3724 // 'Foo' even though the cursor location was at 'Foo'.
3725 if (Data->VisitedObjCPropertyImplDecl)
3726 return CXChildVisit_Break;
3727 Data->VisitedObjCPropertyImplDecl = true;
Argyrios Kyrtzidisa9d45a32012-04-16 22:42:01 +00003728 }
Argyrios Kyrtzidis65ab9072011-09-26 19:05:37 +00003729 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003730
3731 if (clang_isExpression(cursor.kind) &&
3732 clang_isDeclaration(BestCursor->kind)) {
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00003733 if (Decl *D = getCursorDecl(*BestCursor)) {
3734 // Avoid having the cursor of an expression replace the declaration cursor
3735 // when the expression source range overlaps the declaration range.
3736 // This can happen for C++ constructor expressions whose range generally
3737 // include the variable declaration, e.g.:
3738 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
3739 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
3740 D->getLocation() == Data->TokenBeginLoc)
3741 return CXChildVisit_Break;
3742 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003743 }
3744
Douglas Gregor93798e22010-11-05 21:11:19 +00003745 // If our current best cursor is the construction of a temporary object,
3746 // don't replace that cursor with a type reference, because we want
3747 // clang_getCursor() to point at the constructor.
3748 if (clang_isExpression(BestCursor->kind) &&
3749 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003750 cursor.kind == CXCursor_TypeRef) {
3751 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
3752 // as having the actual point on the type reference.
3753 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
Douglas Gregor93798e22010-11-05 21:11:19 +00003754 return CXChildVisit_Recurse;
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003755 }
Douglas Gregor93798e22010-11-05 21:11:19 +00003756
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003757 *BestCursor = cursor;
3758 return CXChildVisit_Recurse;
3759}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003760
Douglas Gregorb9790342010-01-22 21:44:22 +00003761CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3762 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003763 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003764
Ted Kremeneka60ed472010-11-16 08:15:36 +00003765 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003766 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3767
Ted Kremeneka297de22010-01-25 22:34:44 +00003768 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003769 CXCursor Result = cxcursor::getCursor(TU, SLoc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003770
Douglas Gregor40749ee2010-11-03 00:35:38 +00003771 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregor40749ee2010-11-03 00:35:38 +00003772 if (Logging) {
3773 CXFile SearchFile;
3774 unsigned SearchLine, SearchColumn;
3775 CXFile ResultFile;
3776 unsigned ResultLine, ResultColumn;
Douglas Gregor66537982010-11-17 17:14:07 +00003777 CXString SearchFileName, ResultFileName, KindSpelling, USR;
3778 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
Douglas Gregor40749ee2010-11-03 00:35:38 +00003779 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3780
Chandler Carruth20174222011-08-31 16:53:37 +00003781 clang_getExpansionLocation(Loc, &SearchFile, &SearchLine, &SearchColumn, 0);
3782 clang_getExpansionLocation(ResultLoc, &ResultFile, &ResultLine,
3783 &ResultColumn, 0);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003784 SearchFileName = clang_getFileName(SearchFile);
3785 ResultFileName = clang_getFileName(ResultFile);
3786 KindSpelling = clang_getCursorKindSpelling(Result.kind);
Douglas Gregor66537982010-11-17 17:14:07 +00003787 USR = clang_getCursorUSR(Result);
3788 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n",
Douglas Gregor40749ee2010-11-03 00:35:38 +00003789 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3790 clang_getCString(KindSpelling),
Douglas Gregor66537982010-11-17 17:14:07 +00003791 clang_getCString(ResultFileName), ResultLine, ResultColumn,
3792 clang_getCString(USR), IsDef);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003793 clang_disposeString(SearchFileName);
3794 clang_disposeString(ResultFileName);
3795 clang_disposeString(KindSpelling);
Douglas Gregor66537982010-11-17 17:14:07 +00003796 clang_disposeString(USR);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003797
3798 CXCursor Definition = clang_getCursorDefinition(Result);
3799 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
3800 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
3801 CXString DefinitionKindSpelling
3802 = clang_getCursorKindSpelling(Definition.kind);
3803 CXFile DefinitionFile;
3804 unsigned DefinitionLine, DefinitionColumn;
Chandler Carruth20174222011-08-31 16:53:37 +00003805 clang_getExpansionLocation(DefinitionLoc, &DefinitionFile,
3806 &DefinitionLine, &DefinitionColumn, 0);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003807 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
3808 fprintf(stderr, " -> %s(%s:%d:%d)\n",
3809 clang_getCString(DefinitionKindSpelling),
3810 clang_getCString(DefinitionFileName),
3811 DefinitionLine, DefinitionColumn);
3812 clang_disposeString(DefinitionFileName);
3813 clang_disposeString(DefinitionKindSpelling);
3814 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003815 }
3816
Ted Kremeneke68fff62010-02-17 00:41:32 +00003817 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003818}
3819
Ted Kremenek73885552009-11-17 19:28:59 +00003820CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003821 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003822}
3823
3824unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003825 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003826}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003827
Douglas Gregor9ce55842010-11-20 00:09:34 +00003828unsigned clang_hashCursor(CXCursor C) {
3829 unsigned Index = 0;
3830 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
3831 Index = 1;
3832
3833 return llvm::DenseMapInfo<std::pair<unsigned, void*> >::getHashValue(
3834 std::make_pair(C.kind, C.data[Index]));
3835}
3836
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003837unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003838 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3839}
3840
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003841unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003842 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3843}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003844
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003845unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003846 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3847}
3848
Douglas Gregor97b98722010-01-19 23:20:36 +00003849unsigned clang_isExpression(enum CXCursorKind K) {
3850 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3851}
3852
3853unsigned clang_isStatement(enum CXCursorKind K) {
3854 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3855}
3856
Douglas Gregor8be80e12011-07-06 03:00:34 +00003857unsigned clang_isAttribute(enum CXCursorKind K) {
3858 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
3859}
3860
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003861unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3862 return K == CXCursor_TranslationUnit;
3863}
3864
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003865unsigned clang_isPreprocessing(enum CXCursorKind K) {
3866 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3867}
3868
Ted Kremenekad6eff62010-03-08 21:17:29 +00003869unsigned clang_isUnexposed(enum CXCursorKind K) {
3870 switch (K) {
3871 case CXCursor_UnexposedDecl:
3872 case CXCursor_UnexposedExpr:
3873 case CXCursor_UnexposedStmt:
3874 case CXCursor_UnexposedAttr:
3875 return true;
3876 default:
3877 return false;
3878 }
3879}
3880
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003881CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003882 return C.kind;
3883}
3884
Douglas Gregor98258af2010-01-18 22:46:11 +00003885CXSourceLocation clang_getCursorLocation(CXCursor C) {
3886 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003887 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003888 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003889 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3890 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003891 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003892 }
3893
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003894 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003895 std::pair<ObjCProtocolDecl *, SourceLocation> P
3896 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003897 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003898 }
3899
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003900 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003901 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3902 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003903 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003904 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003905
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003906 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003907 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003908 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003909 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003910
3911 case CXCursor_TemplateRef: {
3912 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3913 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3914 }
3915
Douglas Gregor69319002010-08-31 23:48:11 +00003916 case CXCursor_NamespaceRef: {
3917 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3918 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3919 }
3920
Douglas Gregora67e03f2010-09-09 21:42:20 +00003921 case CXCursor_MemberRef: {
3922 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3923 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3924 }
3925
Douglas Gregor011d8b92012-02-15 00:54:55 +00003926 case CXCursor_VariableRef: {
3927 std::pair<VarDecl *, SourceLocation> P = getCursorVariableRef(C);
3928 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3929 }
3930
Ted Kremenek3064ef92010-08-27 21:34:58 +00003931 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003932 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3933 if (!BaseSpec)
3934 return clang_getNullLocation();
3935
3936 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3937 return cxloc::translateSourceLocation(getCursorContext(C),
3938 TSInfo->getTypeLoc().getBeginLoc());
3939
3940 return cxloc::translateSourceLocation(getCursorContext(C),
Daniel Dunbar96a00142012-03-09 18:35:03 +00003941 BaseSpec->getLocStart());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003942 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003943
Douglas Gregor36897b02010-09-10 00:22:18 +00003944 case CXCursor_LabelRef: {
3945 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3946 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3947 }
3948
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003949 case CXCursor_OverloadedDeclRef:
3950 return cxloc::translateSourceLocation(getCursorContext(C),
3951 getCursorOverloadedDeclRef(C).second);
3952
Douglas Gregorf46034a2010-01-18 23:41:10 +00003953 default:
3954 // FIXME: Need a way to enumerate all non-reference cases.
3955 llvm_unreachable("Missed a reference kind");
3956 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003957 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003958
3959 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003960 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003961 getLocationFromExpr(getCursorExpr(C)));
3962
Douglas Gregor36897b02010-09-10 00:22:18 +00003963 if (clang_isStatement(C.kind))
3964 return cxloc::translateSourceLocation(getCursorContext(C),
3965 getCursorStmt(C)->getLocStart());
3966
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003967 if (C.kind == CXCursor_PreprocessingDirective) {
3968 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3969 return cxloc::translateSourceLocation(getCursorContext(C), L);
3970 }
Douglas Gregor48072312010-03-18 15:23:44 +00003971
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003972 if (C.kind == CXCursor_MacroExpansion) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003973 SourceLocation L
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003974 = cxcursor::getCursorMacroExpansion(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003975 return cxloc::translateSourceLocation(getCursorContext(C), L);
3976 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003977
3978 if (C.kind == CXCursor_MacroDefinition) {
3979 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3980 return cxloc::translateSourceLocation(getCursorContext(C), L);
3981 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003982
3983 if (C.kind == CXCursor_InclusionDirective) {
3984 SourceLocation L
3985 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3986 return cxloc::translateSourceLocation(getCursorContext(C), L);
3987 }
3988
Ted Kremenek9a700d22010-05-12 06:16:13 +00003989 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003990 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003991
Douglas Gregorf46034a2010-01-18 23:41:10 +00003992 Decl *D = getCursorDecl(C);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00003993 if (!D)
3994 return clang_getNullLocation();
3995
Douglas Gregorf46034a2010-01-18 23:41:10 +00003996 SourceLocation Loc = D->getLocation();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003997 // FIXME: Multiple variables declared in a single declaration
3998 // currently lack the information needed to correctly determine their
3999 // ranges when accounting for the type-specifier. We use context
4000 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
4001 // and if so, whether it is the first decl.
4002 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4003 if (!cxcursor::isFirstInDeclGroup(C))
4004 Loc = VD->getLocation();
4005 }
4006
Argyrios Kyrtzidisccc6f362012-03-23 03:33:19 +00004007 // For ObjC methods, give the start location of the method name.
4008 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
4009 Loc = MD->getSelectorStartLoc();
4010
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00004011 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00004012}
Douglas Gregora7bde202010-01-19 00:34:46 +00004013
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004014} // end extern "C"
4015
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00004016CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
4017 assert(TU);
4018
4019 // Guard against an invalid SourceLocation, or we may assert in one
4020 // of the following calls.
4021 if (SLoc.isInvalid())
4022 return clang_getNullCursor();
4023
4024 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4025
4026 // Translate the given source location to make it point at the beginning of
4027 // the token under the cursor.
4028 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +00004029 CXXUnit->getASTContext().getLangOpts());
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00004030
4031 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
4032 if (SLoc.isValid()) {
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00004033 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00004034 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
4035 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00004036 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00004037 SourceLocation(SLoc));
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00004038 CursorVis.visitFileRegion();
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00004039 }
4040
4041 return Result;
4042}
4043
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004044static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00004045 if (clang_isReference(C.kind)) {
4046 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004047 case CXCursor_ObjCSuperClassRef:
4048 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004049
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004050 case CXCursor_ObjCProtocolRef:
4051 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004052
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004053 case CXCursor_ObjCClassRef:
4054 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004055
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004056 case CXCursor_TypeRef:
4057 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00004058
4059 case CXCursor_TemplateRef:
4060 return getCursorTemplateRef(C).second;
4061
Douglas Gregor69319002010-08-31 23:48:11 +00004062 case CXCursor_NamespaceRef:
4063 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00004064
4065 case CXCursor_MemberRef:
4066 return getCursorMemberRef(C).second;
4067
Ted Kremenek3064ef92010-08-27 21:34:58 +00004068 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00004069 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00004070
Douglas Gregor36897b02010-09-10 00:22:18 +00004071 case CXCursor_LabelRef:
4072 return getCursorLabelRef(C).second;
4073
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004074 case CXCursor_OverloadedDeclRef:
4075 return getCursorOverloadedDeclRef(C).second;
4076
Douglas Gregor011d8b92012-02-15 00:54:55 +00004077 case CXCursor_VariableRef:
4078 return getCursorVariableRef(C).second;
4079
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004080 default:
4081 // FIXME: Need a way to enumerate all non-reference cases.
4082 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00004083 }
4084 }
Douglas Gregor97b98722010-01-19 23:20:36 +00004085
4086 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004087 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00004088
4089 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004090 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004091
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00004092 if (clang_isAttribute(C.kind))
4093 return getCursorAttr(C)->getRange();
4094
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004095 if (C.kind == CXCursor_PreprocessingDirective)
4096 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00004097
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004098 if (C.kind == CXCursor_MacroExpansion) {
4099 ASTUnit *TU = getCursorASTUnit(C);
4100 SourceRange Range = cxcursor::getCursorMacroExpansion(C)->getSourceRange();
4101 return TU->mapRangeFromPreamble(Range);
4102 }
Douglas Gregor572feb22010-03-18 18:04:21 +00004103
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004104 if (C.kind == CXCursor_MacroDefinition) {
4105 ASTUnit *TU = getCursorASTUnit(C);
4106 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
4107 return TU->mapRangeFromPreamble(Range);
4108 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00004109
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004110 if (C.kind == CXCursor_InclusionDirective) {
4111 ASTUnit *TU = getCursorASTUnit(C);
4112 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
4113 return TU->mapRangeFromPreamble(Range);
4114 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00004115
Argyrios Kyrtzidis0822c5f2012-03-19 23:17:58 +00004116 if (C.kind == CXCursor_TranslationUnit) {
4117 ASTUnit *TU = getCursorASTUnit(C);
4118 FileID MainID = TU->getSourceManager().getMainFileID();
4119 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
4120 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
4121 return SourceRange(Start, End);
4122 }
4123
Ted Kremenek007a7c92010-11-01 23:26:51 +00004124 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
4125 Decl *D = cxcursor::getCursorDecl(C);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00004126 if (!D)
4127 return SourceRange();
4128
Ted Kremenek007a7c92010-11-01 23:26:51 +00004129 SourceRange R = D->getSourceRange();
4130 // FIXME: Multiple variables declared in a single declaration
4131 // currently lack the information needed to correctly determine their
4132 // ranges when accounting for the type-specifier. We use context
4133 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
4134 // and if so, whether it is the first decl.
4135 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4136 if (!cxcursor::isFirstInDeclGroup(C))
4137 R.setBegin(VD->getLocation());
4138 }
4139 return R;
4140 }
Douglas Gregor66537982010-11-17 17:14:07 +00004141 return SourceRange();
4142}
4143
4144/// \brief Retrieves the "raw" cursor extent, which is then extended to include
4145/// the decl-specifier-seq for declarations.
4146static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
4147 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
4148 Decl *D = cxcursor::getCursorDecl(C);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00004149 if (!D)
4150 return SourceRange();
4151
Douglas Gregor66537982010-11-17 17:14:07 +00004152 SourceRange R = D->getSourceRange();
Douglas Gregor66537982010-11-17 17:14:07 +00004153
Douglas Gregor2494dd02011-03-01 01:34:45 +00004154 // Adjust the start of the location for declarations preceded by
4155 // declaration specifiers.
4156 SourceLocation StartLoc;
4157 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
4158 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
Daniel Dunbar96a00142012-03-09 18:35:03 +00004159 StartLoc = TI->getTypeLoc().getLocStart();
Douglas Gregor2494dd02011-03-01 01:34:45 +00004160 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
4161 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
Daniel Dunbar96a00142012-03-09 18:35:03 +00004162 StartLoc = TI->getTypeLoc().getLocStart();
Douglas Gregor2494dd02011-03-01 01:34:45 +00004163 }
4164
4165 if (StartLoc.isValid() && R.getBegin().isValid() &&
4166 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
4167 R.setBegin(StartLoc);
4168
4169 // FIXME: Multiple variables declared in a single declaration
4170 // currently lack the information needed to correctly determine their
4171 // ranges when accounting for the type-specifier. We use context
4172 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
4173 // and if so, whether it is the first decl.
4174 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4175 if (!cxcursor::isFirstInDeclGroup(C))
4176 R.setBegin(VD->getLocation());
Douglas Gregor66537982010-11-17 17:14:07 +00004177 }
4178
4179 return R;
4180 }
4181
4182 return getRawCursorExtent(C);
4183}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004184
4185extern "C" {
4186
4187CXSourceRange clang_getCursorExtent(CXCursor C) {
4188 SourceRange R = getRawCursorExtent(C);
4189 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00004190 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004191
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004192 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00004193}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004194
4195CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00004196 if (clang_isInvalid(C.kind))
4197 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004198
Ted Kremeneka60ed472010-11-16 08:15:36 +00004199 CXTranslationUnit tu = getCursorTU(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004200 if (clang_isDeclaration(C.kind)) {
4201 Decl *D = getCursorDecl(C);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00004202 if (!D)
4203 return clang_getNullCursor();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004204 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004205 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Chris Lattner5f9e2722011-07-23 10:55:15 +00004206 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00004207 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
4208 return MakeCXCursor(Property, tu);
4209
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004210 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004211 }
4212
Douglas Gregor97b98722010-01-19 23:20:36 +00004213 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004214 Expr *E = getCursorExpr(C);
4215 Decl *D = getDeclFromExpr(E);
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00004216 if (D) {
4217 CXCursor declCursor = MakeCXCursor(D, tu);
4218 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
4219 declCursor);
4220 return declCursor;
4221 }
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004222
4223 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004224 return MakeCursorOverloadedDeclRef(Ovl, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004225
Douglas Gregor97b98722010-01-19 23:20:36 +00004226 return clang_getNullCursor();
4227 }
4228
Douglas Gregor36897b02010-09-10 00:22:18 +00004229 if (clang_isStatement(C.kind)) {
4230 Stmt *S = getCursorStmt(C);
4231 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Ted Kremenek37c2e962011-03-15 23:47:49 +00004232 if (LabelDecl *label = Goto->getLabel())
4233 if (LabelStmt *labelS = label->getStmt())
4234 return MakeCXCursor(labelS, getCursorDecl(C), tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00004235
4236 return clang_getNullCursor();
4237 }
4238
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004239 if (C.kind == CXCursor_MacroExpansion) {
Chandler Carruth9e5bb852011-07-14 08:20:46 +00004240 if (MacroDefinition *Def = getCursorMacroExpansion(C)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004241 return MakeMacroDefinitionCursor(Def, tu);
Douglas Gregorbf7efa22010-03-18 18:23:03 +00004242 }
4243
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004244 if (!clang_isReference(C.kind))
4245 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004246
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004247 switch (C.kind) {
4248 case CXCursor_ObjCSuperClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004249 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004250
4251 case CXCursor_ObjCProtocolRef: {
Argyrios Kyrtzidis98c16b82012-01-24 19:40:15 +00004252 ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
4253 if (ObjCProtocolDecl *Def = Prot->getDefinition())
4254 return MakeCXCursor(Def, tu);
4255
Argyrios Kyrtzidisc15707d2012-01-24 21:39:26 +00004256 return MakeCXCursor(Prot, tu);
Argyrios Kyrtzidis98c16b82012-01-24 19:40:15 +00004257 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004258
Douglas Gregor7723fec2011-12-15 20:29:51 +00004259 case CXCursor_ObjCClassRef: {
4260 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
4261 if (ObjCInterfaceDecl *Def = Class->getDefinition())
4262 return MakeCXCursor(Def, tu);
4263
Argyrios Kyrtzidisc15707d2012-01-24 21:39:26 +00004264 return MakeCXCursor(Class, tu);
Douglas Gregor7723fec2011-12-15 20:29:51 +00004265 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00004266
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004267 case CXCursor_TypeRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004268 return MakeCXCursor(getCursorTypeRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00004269
4270 case CXCursor_TemplateRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004271 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00004272
Douglas Gregor69319002010-08-31 23:48:11 +00004273 case CXCursor_NamespaceRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004274 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
Douglas Gregor69319002010-08-31 23:48:11 +00004275
Douglas Gregora67e03f2010-09-09 21:42:20 +00004276 case CXCursor_MemberRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004277 return MakeCXCursor(getCursorMemberRef(C).first, tu );
Douglas Gregora67e03f2010-09-09 21:42:20 +00004278
Ted Kremenek3064ef92010-08-27 21:34:58 +00004279 case CXCursor_CXXBaseSpecifier: {
4280 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
4281 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004282 tu ));
Ted Kremenek3064ef92010-08-27 21:34:58 +00004283 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004284
Douglas Gregor36897b02010-09-10 00:22:18 +00004285 case CXCursor_LabelRef:
4286 // FIXME: We end up faking the "parent" declaration here because we
4287 // don't want to make CXCursor larger.
4288 return MakeCXCursor(getCursorLabelRef(C).first,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004289 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
4290 .getTranslationUnitDecl(),
4291 tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00004292
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004293 case CXCursor_OverloadedDeclRef:
4294 return C;
Douglas Gregor011d8b92012-02-15 00:54:55 +00004295
4296 case CXCursor_VariableRef:
4297 return MakeCXCursor(getCursorVariableRef(C).first, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004298
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004299 default:
4300 // We would prefer to enumerate all non-reference cursor kinds here.
4301 llvm_unreachable("Unhandled reference cursor kind");
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004302 }
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004303}
4304
Douglas Gregorb6998662010-01-19 19:34:47 +00004305CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00004306 if (clang_isInvalid(C.kind))
4307 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004308
Ted Kremeneka60ed472010-11-16 08:15:36 +00004309 CXTranslationUnit TU = getCursorTU(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004310
Douglas Gregorb6998662010-01-19 19:34:47 +00004311 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00004312 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00004313 C = clang_getCursorReferenced(C);
4314 WasReference = true;
4315 }
4316
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004317 if (C.kind == CXCursor_MacroExpansion)
Douglas Gregorbf7efa22010-03-18 18:23:03 +00004318 return clang_getCursorReferenced(C);
4319
Douglas Gregorb6998662010-01-19 19:34:47 +00004320 if (!clang_isDeclaration(C.kind))
4321 return clang_getNullCursor();
4322
4323 Decl *D = getCursorDecl(C);
4324 if (!D)
4325 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004326
Douglas Gregorb6998662010-01-19 19:34:47 +00004327 switch (D->getKind()) {
4328 // Declaration kinds that don't really separate the notions of
4329 // declaration and definition.
4330 case Decl::Namespace:
4331 case Decl::Typedef:
Richard Smith162e1c12011-04-15 14:24:37 +00004332 case Decl::TypeAlias:
Richard Smith3e4c6c42011-05-05 21:57:07 +00004333 case Decl::TypeAliasTemplate:
Douglas Gregorb6998662010-01-19 19:34:47 +00004334 case Decl::TemplateTypeParm:
4335 case Decl::EnumConstant:
4336 case Decl::Field:
Benjamin Kramerd9811462010-11-21 14:11:41 +00004337 case Decl::IndirectField:
Douglas Gregorb6998662010-01-19 19:34:47 +00004338 case Decl::ObjCIvar:
4339 case Decl::ObjCAtDefsField:
4340 case Decl::ImplicitParam:
4341 case Decl::ParmVar:
4342 case Decl::NonTypeTemplateParm:
4343 case Decl::TemplateTemplateParm:
4344 case Decl::ObjCCategoryImpl:
4345 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00004346 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00004347 case Decl::LinkageSpec:
4348 case Decl::ObjCPropertyImpl:
4349 case Decl::FileScopeAsm:
4350 case Decl::StaticAssert:
4351 case Decl::Block:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00004352 case Decl::Label: // FIXME: Is this right??
Francois Pichetaf0f4d02011-08-14 03:52:19 +00004353 case Decl::ClassScopeFunctionSpecialization:
Douglas Gregor15de72c2011-12-02 23:23:56 +00004354 case Decl::Import:
Douglas Gregorb6998662010-01-19 19:34:47 +00004355 return C;
4356
4357 // Declaration kinds that don't make any sense here, but are
4358 // nonetheless harmless.
4359 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00004360 break;
4361
4362 // Declaration kinds for which the definition is not resolvable.
4363 case Decl::UnresolvedUsingTypename:
4364 case Decl::UnresolvedUsingValue:
4365 break;
4366
4367 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00004368 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004369 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004370
4371 case Decl::NamespaceAlias:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004372 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004373
4374 case Decl::Enum:
4375 case Decl::Record:
4376 case Decl::CXXRecord:
4377 case Decl::ClassTemplateSpecialization:
4378 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00004379 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004380 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004381 return clang_getNullCursor();
4382
4383 case Decl::Function:
4384 case Decl::CXXMethod:
4385 case Decl::CXXConstructor:
4386 case Decl::CXXDestructor:
4387 case Decl::CXXConversion: {
4388 const FunctionDecl *Def = 0;
4389 if (cast<FunctionDecl>(D)->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004390 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004391 return clang_getNullCursor();
4392 }
4393
4394 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00004395 // Ask the variable if it has a definition.
4396 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004397 return MakeCXCursor(Def, TU);
Sebastian Redl31310a22010-02-01 20:16:42 +00004398 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00004399 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004400
Douglas Gregorb6998662010-01-19 19:34:47 +00004401 case Decl::FunctionTemplate: {
4402 const FunctionDecl *Def = 0;
4403 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004404 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004405 return clang_getNullCursor();
4406 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004407
Douglas Gregorb6998662010-01-19 19:34:47 +00004408 case Decl::ClassTemplate: {
4409 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00004410 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00004411 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004412 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004413 return clang_getNullCursor();
4414 }
4415
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004416 case Decl::Using:
4417 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004418 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004419
4420 case Decl::UsingShadow:
4421 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004422 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004423 TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004424
4425 case Decl::ObjCMethod: {
4426 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
4427 if (Method->isThisDeclarationADefinition())
4428 return C;
4429
4430 // Dig out the method definition in the associated
4431 // @implementation, if we have it.
4432 // FIXME: The ASTs should make finding the definition easier.
4433 if (ObjCInterfaceDecl *Class
4434 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
4435 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
4436 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
4437 Method->isInstanceMethod()))
4438 if (Def->isThisDeclarationADefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004439 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004440
4441 return clang_getNullCursor();
4442 }
4443
4444 case Decl::ObjCCategory:
4445 if (ObjCCategoryImplDecl *Impl
4446 = cast<ObjCCategoryDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004447 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004448 return clang_getNullCursor();
4449
4450 case Decl::ObjCProtocol:
Douglas Gregor5e2a1ff2012-01-01 19:29:29 +00004451 if (ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
4452 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004453 return clang_getNullCursor();
4454
Douglas Gregor375bb142011-12-27 22:43:10 +00004455 case Decl::ObjCInterface: {
Douglas Gregorb6998662010-01-19 19:34:47 +00004456 // There are two notions of a "definition" for an Objective-C
4457 // class: the interface and its implementation. When we resolved a
4458 // reference to an Objective-C class, produce the @interface as
4459 // the definition; when we were provided with the interface,
4460 // produce the @implementation as the definition.
Douglas Gregor375bb142011-12-27 22:43:10 +00004461 ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
Douglas Gregorb6998662010-01-19 19:34:47 +00004462 if (WasReference) {
Douglas Gregor375bb142011-12-27 22:43:10 +00004463 if (ObjCInterfaceDecl *Def = IFace->getDefinition())
Douglas Gregor7723fec2011-12-15 20:29:51 +00004464 return MakeCXCursor(Def, TU);
Douglas Gregor375bb142011-12-27 22:43:10 +00004465 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004466 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004467 return clang_getNullCursor();
Douglas Gregor375bb142011-12-27 22:43:10 +00004468 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004469
Douglas Gregorb6998662010-01-19 19:34:47 +00004470 case Decl::ObjCProperty:
4471 // FIXME: We don't really know where to find the
4472 // ObjCPropertyImplDecls that implement this property.
4473 return clang_getNullCursor();
4474
4475 case Decl::ObjCCompatibleAlias:
4476 if (ObjCInterfaceDecl *Class
4477 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
Douglas Gregor7723fec2011-12-15 20:29:51 +00004478 if (ObjCInterfaceDecl *Def = Class->getDefinition())
4479 return MakeCXCursor(Def, TU);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004480
Douglas Gregorb6998662010-01-19 19:34:47 +00004481 return clang_getNullCursor();
4482
Douglas Gregorb6998662010-01-19 19:34:47 +00004483 case Decl::Friend:
4484 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004485 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004486 return clang_getNullCursor();
4487
4488 case Decl::FriendTemplate:
4489 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004490 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004491 return clang_getNullCursor();
4492 }
4493
4494 return clang_getNullCursor();
4495}
4496
4497unsigned clang_isCursorDefinition(CXCursor C) {
4498 if (!clang_isDeclaration(C.kind))
4499 return 0;
4500
4501 return clang_getCursorDefinition(C) == C;
4502}
4503
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004504CXCursor clang_getCanonicalCursor(CXCursor C) {
4505 if (!clang_isDeclaration(C.kind))
4506 return C;
4507
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004508 if (Decl *D = getCursorDecl(C)) {
Argyrios Kyrtzidisdebb00f2011-07-15 22:37:58 +00004509 if (ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
4510 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
4511 return MakeCXCursor(CatD, getCursorTU(C));
4512
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004513 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
4514 if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
4515 return MakeCXCursor(IFD, getCursorTU(C));
4516
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004517 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004518 }
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004519
4520 return C;
4521}
Argyrios Kyrtzidis34ebe1e2012-03-30 22:15:48 +00004522
4523int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) {
4524 return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first;
4525}
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004526
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004527unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004528 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004529 return 0;
4530
4531 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
4532 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
4533 return E->getNumDecls();
4534
4535 if (OverloadedTemplateStorage *S
4536 = Storage.dyn_cast<OverloadedTemplateStorage*>())
4537 return S->size();
4538
4539 Decl *D = Storage.get<Decl*>();
4540 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00004541 return Using->shadow_size();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004542
4543 return 0;
4544}
4545
4546CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004547 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004548 return clang_getNullCursor();
4549
4550 if (index >= clang_getNumOverloadedDecls(cursor))
4551 return clang_getNullCursor();
4552
Ted Kremeneka60ed472010-11-16 08:15:36 +00004553 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004554 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
4555 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004556 return MakeCXCursor(E->decls_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004557
4558 if (OverloadedTemplateStorage *S
4559 = Storage.dyn_cast<OverloadedTemplateStorage*>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004560 return MakeCXCursor(S->begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004561
4562 Decl *D = Storage.get<Decl*>();
4563 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
4564 // FIXME: This is, unfortunately, linear time.
4565 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
4566 std::advance(Pos, index);
Ted Kremeneka60ed472010-11-16 08:15:36 +00004567 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004568 }
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004569
4570 return clang_getNullCursor();
4571}
4572
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00004573void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00004574 const char **startBuf,
4575 const char **endBuf,
4576 unsigned *startLine,
4577 unsigned *startColumn,
4578 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00004579 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00004580 assert(getCursorDecl(C) && "CXCursor has null decl");
4581 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00004582 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
4583 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004584
Steve Naroff4ade6d62009-09-23 17:52:52 +00004585 SourceManager &SM = FD->getASTContext().getSourceManager();
4586 *startBuf = SM.getCharacterData(Body->getLBracLoc());
4587 *endBuf = SM.getCharacterData(Body->getRBracLoc());
4588 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
4589 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
4590 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
4591 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
4592}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004593
Douglas Gregor430d7a12011-07-25 17:48:11 +00004594
4595CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
4596 unsigned PieceIndex) {
4597 RefNamePieces Pieces;
4598
4599 switch (C.kind) {
4600 case CXCursor_MemberRefExpr:
4601 if (MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
4602 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
4603 E->getQualifierLoc().getSourceRange());
4604 break;
4605
4606 case CXCursor_DeclRefExpr:
4607 if (DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C)))
4608 Pieces = buildPieces(NameFlags, false, E->getNameInfo(),
4609 E->getQualifierLoc().getSourceRange(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00004610 E->getOptionalExplicitTemplateArgs());
Douglas Gregor430d7a12011-07-25 17:48:11 +00004611 break;
4612
4613 case CXCursor_CallExpr:
4614 if (CXXOperatorCallExpr *OCE =
4615 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
4616 Expr *Callee = OCE->getCallee();
4617 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
4618 Callee = ICE->getSubExpr();
4619
4620 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
4621 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
4622 DRE->getQualifierLoc().getSourceRange());
4623 }
4624 break;
4625
4626 default:
4627 break;
4628 }
4629
4630 if (Pieces.empty()) {
4631 if (PieceIndex == 0)
4632 return clang_getCursorExtent(C);
4633 } else if (PieceIndex < Pieces.size()) {
4634 SourceRange R = Pieces[PieceIndex];
4635 if (R.isValid())
4636 return cxloc::translateSourceRange(getCursorContext(C), R);
4637 }
4638
4639 return clang_getNullRange();
4640}
4641
Douglas Gregor0a812cf2010-02-18 23:07:20 +00004642void clang_enableStackTraces(void) {
4643 llvm::sys::PrintStackTraceOnErrorSignal();
4644}
4645
Daniel Dunbar995aaf92010-11-04 01:26:29 +00004646void clang_executeOnThread(void (*fn)(void*), void *user_data,
4647 unsigned stack_size) {
4648 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
4649}
4650
Ted Kremenekfb480492010-01-13 21:46:36 +00004651} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00004652
Ted Kremenekfb480492010-01-13 21:46:36 +00004653//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004654// Token-based Operations.
4655//===----------------------------------------------------------------------===//
4656
4657/* CXToken layout:
4658 * int_data[0]: a CXTokenKind
4659 * int_data[1]: starting token location
4660 * int_data[2]: token length
4661 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004662 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004663 * otherwise unused.
4664 */
4665extern "C" {
4666
4667CXTokenKind clang_getTokenKind(CXToken CXTok) {
4668 return static_cast<CXTokenKind>(CXTok.int_data[0]);
4669}
4670
4671CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
4672 switch (clang_getTokenKind(CXTok)) {
4673 case CXToken_Identifier:
4674 case CXToken_Keyword:
4675 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004676 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
4677 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004678
4679 case CXToken_Literal: {
4680 // We have stashed the starting pointer in the ptr_data field. Use it.
4681 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Chris Lattner5f9e2722011-07-23 10:55:15 +00004682 return createCXString(StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004683 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004684
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004685 case CXToken_Punctuation:
4686 case CXToken_Comment:
4687 break;
4688 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004689
4690 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004691 // deconstructing the source location.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004692 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004693 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004694 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004695
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004696 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
4697 std::pair<FileID, unsigned> LocInfo
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004698 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00004699 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004700 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004701 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
4702 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00004703 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004704
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004705 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004706}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004707
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004708CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004709 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004710 if (!CXXUnit)
4711 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004712
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004713 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
4714 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4715}
4716
4717CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004718 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor5352ac02010-01-28 00:27:43 +00004719 if (!CXXUnit)
4720 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004721
4722 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004723 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4724}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004725
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004726static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
4727 SmallVectorImpl<CXToken> &CXTokens) {
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004728 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4729 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004730 = SourceMgr.getDecomposedLoc(Range.getBegin());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004731 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004732 = SourceMgr.getDecomposedLoc(Range.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004733
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004734 // Cannot tokenize across files.
4735 if (BeginLocInfo.first != EndLocInfo.first)
4736 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004737
4738 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004739 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004740 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004741 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00004742 if (Invalid)
4743 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00004744
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004745 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
David Blaikie4e4d0842012-03-11 07:00:24 +00004746 CXXUnit->getASTContext().getLangOpts(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004747 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004748 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004749
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004750 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004751 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004752 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00004753 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004754 do {
4755 // Lex the next token
4756 Lex.LexFromRawLexer(Tok);
4757 if (Tok.is(tok::eof))
4758 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004759
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004760 // Initialize the CXToken.
4761 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004762
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004763 // - Common fields
4764 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
4765 CXTok.int_data[2] = Tok.getLength();
4766 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004767
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004768 // - Kind-specific fields
4769 if (Tok.isLiteral()) {
4770 CXTok.int_data[0] = CXToken_Literal;
4771 CXTok.ptr_data = (void *)Tok.getLiteralData();
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004772 } else if (Tok.is(tok::raw_identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00004773 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004774 IdentifierInfo *II
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004775 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004776
David Chisnall096428b2010-10-13 21:44:48 +00004777 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004778 CXTok.int_data[0] = CXToken_Keyword;
4779 }
4780 else {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004781 CXTok.int_data[0] = Tok.is(tok::identifier)
4782 ? CXToken_Identifier
4783 : CXToken_Keyword;
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004784 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004785 CXTok.ptr_data = II;
4786 } else if (Tok.is(tok::comment)) {
4787 CXTok.int_data[0] = CXToken_Comment;
4788 CXTok.ptr_data = 0;
4789 } else {
4790 CXTok.int_data[0] = CXToken_Punctuation;
4791 CXTok.ptr_data = 0;
4792 }
4793 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00004794 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004795 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004796}
4797
4798void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
4799 CXToken **Tokens, unsigned *NumTokens) {
4800 if (Tokens)
4801 *Tokens = 0;
4802 if (NumTokens)
4803 *NumTokens = 0;
4804
4805 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4806 if (!CXXUnit || !Tokens || !NumTokens)
4807 return;
4808
4809 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4810
4811 SourceRange R = cxloc::translateCXSourceRange(Range);
4812 if (R.isInvalid())
4813 return;
4814
4815 SmallVector<CXToken, 32> CXTokens;
4816 getTokens(CXXUnit, R, CXTokens);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004817
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004818 if (CXTokens.empty())
4819 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004820
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004821 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
4822 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
4823 *NumTokens = CXTokens.size();
4824}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004825
Ted Kremenek6db61092010-05-05 00:55:15 +00004826void clang_disposeTokens(CXTranslationUnit TU,
4827 CXToken *Tokens, unsigned NumTokens) {
4828 free(Tokens);
4829}
4830
4831} // end: extern "C"
4832
4833//===----------------------------------------------------------------------===//
4834// Token annotation APIs.
4835//===----------------------------------------------------------------------===//
4836
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004837typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004838static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4839 CXCursor parent,
4840 CXClientData client_data);
Argyrios Kyrtzidisd579dd52012-09-01 18:27:30 +00004841static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
4842 CXClientData client_data);
4843
Ted Kremenek6db61092010-05-05 00:55:15 +00004844namespace {
4845class AnnotateTokensWorker {
4846 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004847 CXToken *Tokens;
4848 CXCursor *Cursors;
4849 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004850 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00004851 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004852 CursorVisitor AnnotateVis;
4853 SourceManager &SrcMgr;
Douglas Gregorf5251602011-03-08 17:10:18 +00004854 bool HasContextSensitiveKeywords;
Argyrios Kyrtzidisd579dd52012-09-01 18:27:30 +00004855
4856 struct PostChildrenInfo {
4857 CXCursor Cursor;
4858 SourceRange CursorRange;
4859 unsigned BeforeChildrenTokenIdx;
4860 };
4861 llvm::SmallVector<PostChildrenInfo, 8> PostChildrenInfos;
Douglas Gregorf5251602011-03-08 17:10:18 +00004862
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004863 bool MoreTokens() const { return TokIdx < NumTokens; }
4864 unsigned NextToken() const { return TokIdx; }
4865 void AdvanceToken() { ++TokIdx; }
4866 SourceLocation GetTokenLoc(unsigned tokI) {
4867 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4868 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004869 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004870 return Tokens[tokI].int_data[3] != 0;
4871 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004872 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004873 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[3]);
4874 }
4875
4876 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004877 void annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
4878 SourceRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004879
Ted Kremenek6db61092010-05-05 00:55:15 +00004880public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00004881 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004882 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004883 CXTranslationUnit tu, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00004884 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00004885 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004886 AnnotateVis(tu,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00004887 AnnotateTokensVisitor, this,
4888 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00004889 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidisd579dd52012-09-01 18:27:30 +00004890 RegionOfInterest,
4891 /*VisitDeclsOnly=*/false,
4892 AnnotateTokensPostChildrenVisitor),
Douglas Gregorf5251602011-03-08 17:10:18 +00004893 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()),
4894 HasContextSensitiveKeywords(false) { }
Ted Kremenek11949cb2010-05-05 00:55:17 +00004895
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004896 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00004897 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Argyrios Kyrtzidisd579dd52012-09-01 18:27:30 +00004898 bool postVisitChildren(CXCursor cursor);
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004899 void AnnotateTokens();
Douglas Gregorf5251602011-03-08 17:10:18 +00004900
4901 /// \brief Determine whether the annotator saw any cursors that have
4902 /// context-sensitive keywords.
4903 bool hasContextSensitiveKeywords() const {
4904 return HasContextSensitiveKeywords;
4905 }
Argyrios Kyrtzidisd579dd52012-09-01 18:27:30 +00004906
4907 ~AnnotateTokensWorker() {
4908 assert(PostChildrenInfos.empty());
4909 }
Ted Kremenek6db61092010-05-05 00:55:15 +00004910};
4911}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004912
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004913void AnnotateTokensWorker::AnnotateTokens() {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004914 // Walk the AST within the region of interest, annotating tokens
4915 // along the way.
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004916 AnnotateVis.visitFileRegion();
Ted Kremenek11949cb2010-05-05 00:55:17 +00004917
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004918 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4919 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004920 if (Pos != Annotated.end() &&
4921 (clang_isInvalid(Cursors[I].kind) ||
4922 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004923 Cursors[I] = Pos->second;
4924 }
4925
4926 // Finish up annotating any tokens left.
4927 if (!MoreTokens())
4928 return;
4929
4930 const CXCursor &C = clang_getNullCursor();
4931 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004932 if (I < PreprocessingTokIdx && clang_isPreprocessing(Cursors[I].kind))
4933 continue;
4934
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004935 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4936 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004937 }
4938}
4939
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004940/// \brief It annotates and advances tokens with a cursor until the comparison
4941//// between the cursor location and the source range is the same as
4942/// \arg compResult.
4943///
4944/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
4945/// Pass RangeOverlap to annotate tokens inside a range.
4946void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
4947 RangeComparisonResult compResult,
4948 SourceRange range) {
4949 while (MoreTokens()) {
4950 const unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004951 if (isFunctionMacroToken(I))
4952 return annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004953
4954 SourceLocation TokLoc = GetTokenLoc(I);
4955 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4956 Cursors[I] = updateC;
4957 AdvanceToken();
4958 continue;
4959 }
4960 break;
4961 }
4962}
4963
4964/// \brief Special annotation handling for macro argument tokens.
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004965void AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
4966 CXCursor updateC,
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004967 RangeComparisonResult compResult,
4968 SourceRange range) {
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004969 assert(MoreTokens());
4970 assert(isFunctionMacroToken(NextToken()) &&
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004971 "Should be called only for macro arg tokens");
4972
4973 // This works differently than annotateAndAdvanceTokens; because expanded
4974 // macro arguments can have arbitrary translation-unit source order, we do not
4975 // advance the token index one by one until a token fails the range test.
4976 // We only advance once past all of the macro arg tokens if all of them
4977 // pass the range test. If one of them fails we keep the token index pointing
4978 // at the start of the macro arg tokens so that the failing token will be
4979 // annotated by a subsequent annotation try.
4980
4981 bool atLeastOneCompFail = false;
4982
4983 unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004984 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
4985 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004986 if (TokLoc.isFileID())
4987 continue; // not macro arg token, it's parens or comma.
4988 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4989 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
4990 Cursors[I] = updateC;
4991 } else
4992 atLeastOneCompFail = true;
4993 }
4994
4995 if (!atLeastOneCompFail)
4996 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
4997}
4998
Ted Kremenek6db61092010-05-05 00:55:15 +00004999enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00005000AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005001 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00005002 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00005003 if (cursorRange.isInvalid())
5004 return CXChildVisit_Recurse;
Douglas Gregorf5251602011-03-08 17:10:18 +00005005
5006 if (!HasContextSensitiveKeywords) {
5007 // Objective-C properties can have context-sensitive keywords.
5008 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
5009 if (ObjCPropertyDecl *Property
5010 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
5011 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
5012 }
5013 // Objective-C methods can have context-sensitive keywords.
5014 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
5015 cursor.kind == CXCursor_ObjCClassMethodDecl) {
5016 if (ObjCMethodDecl *Method
5017 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
5018 if (Method->getObjCDeclQualifier())
5019 HasContextSensitiveKeywords = true;
5020 else {
5021 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
5022 PEnd = Method->param_end();
5023 P != PEnd; ++P) {
5024 if ((*P)->getObjCDeclQualifier()) {
5025 HasContextSensitiveKeywords = true;
5026 break;
5027 }
5028 }
5029 }
5030 }
5031 }
5032 // C++ methods can have context-sensitive keywords.
5033 else if (cursor.kind == CXCursor_CXXMethod) {
5034 if (CXXMethodDecl *Method
5035 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
5036 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
5037 HasContextSensitiveKeywords = true;
5038 }
5039 }
5040 // C++ classes can have context-sensitive keywords.
5041 else if (cursor.kind == CXCursor_StructDecl ||
5042 cursor.kind == CXCursor_ClassDecl ||
5043 cursor.kind == CXCursor_ClassTemplate ||
5044 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
5045 if (Decl *D = getCursorDecl(cursor))
5046 if (D->hasAttr<FinalAttr>())
5047 HasContextSensitiveKeywords = true;
5048 }
5049 }
5050
Douglas Gregor4419b672010-10-21 06:10:04 +00005051 if (clang_isPreprocessing(cursor.kind)) {
Chandler Carruthcea731a2011-07-14 16:07:57 +00005052 // For macro expansions, just note where the beginning of the macro
5053 // expansion occurs.
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00005054 if (cursor.kind == CXCursor_MacroExpansion) {
Douglas Gregor4419b672010-10-21 06:10:04 +00005055 Annotated[Loc.int_data] = cursor;
5056 return CXChildVisit_Recurse;
5057 }
5058
Douglas Gregor4419b672010-10-21 06:10:04 +00005059 // Items in the preprocessing record are kept separate from items in
5060 // declarations, so we keep a separate token index.
5061 unsigned SavedTokIdx = TokIdx;
5062 TokIdx = PreprocessingTokIdx;
5063
5064 // Skip tokens up until we catch up to the beginning of the preprocessing
5065 // entry.
5066 while (MoreTokens()) {
5067 const unsigned I = NextToken();
5068 SourceLocation TokLoc = GetTokenLoc(I);
5069 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
5070 case RangeBefore:
5071 AdvanceToken();
5072 continue;
5073 case RangeAfter:
5074 case RangeOverlap:
5075 break;
5076 }
5077 break;
5078 }
5079
5080 // Look at all of the tokens within this range.
5081 while (MoreTokens()) {
5082 const unsigned I = NextToken();
5083 SourceLocation TokLoc = GetTokenLoc(I);
5084 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
5085 case RangeBefore:
David Blaikieb219cfc2011-09-23 05:06:16 +00005086 llvm_unreachable("Infeasible");
Douglas Gregor4419b672010-10-21 06:10:04 +00005087 case RangeAfter:
5088 break;
5089 case RangeOverlap:
5090 Cursors[I] = cursor;
5091 AdvanceToken();
5092 continue;
5093 }
5094 break;
5095 }
5096
5097 // Save the preprocessing token index; restore the non-preprocessing
5098 // token index.
5099 PreprocessingTokIdx = TokIdx;
5100 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005101 return CXChildVisit_Recurse;
5102 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005103
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005104 if (cursorRange.isInvalid())
5105 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00005106
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005107 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
5108
Ted Kremeneka333c662010-05-12 05:29:33 +00005109 // Adjust the annotated range based specific declarations.
5110 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
5111 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00005112 Decl *D = cxcursor::getCursorDecl(cursor);
Douglas Gregor2494dd02011-03-01 01:34:45 +00005113
5114 SourceLocation StartLoc;
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00005115 if (const DeclaratorDecl *DD = dyn_cast_or_null<DeclaratorDecl>(D)) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00005116 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
Daniel Dunbar96a00142012-03-09 18:35:03 +00005117 StartLoc = TI->getTypeLoc().getLocStart();
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00005118 } else if (TypedefDecl *Typedef = dyn_cast_or_null<TypedefDecl>(D)) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00005119 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
Daniel Dunbar96a00142012-03-09 18:35:03 +00005120 StartLoc = TI->getTypeLoc().getLocStart();
Ted Kremeneka333c662010-05-12 05:29:33 +00005121 }
Douglas Gregor2494dd02011-03-01 01:34:45 +00005122
5123 if (StartLoc.isValid() && L.isValid() &&
5124 SrcMgr.isBeforeInTranslationUnit(StartLoc, L))
5125 cursorRange.setBegin(StartLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00005126 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00005127
Ted Kremenek3f404602010-08-14 01:14:06 +00005128 // If the location of the cursor occurs within a macro instantiation, record
5129 // the spelling location of the cursor in our annotation map. We can then
5130 // paper over the token labelings during a post-processing step to try and
5131 // get cursor mappings for tokens that are the *arguments* of a macro
5132 // instantiation.
5133 if (L.isMacroID()) {
5134 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
5135 // Only invalidate the old annotation if it isn't part of a preprocessing
5136 // directive. Here we assume that the default construction of CXCursor
5137 // results in CXCursor.kind being an initialized value (i.e., 0). If
5138 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00005139
Ted Kremenek3f404602010-08-14 01:14:06 +00005140 CXCursor &oldC = Annotated[rawEncoding];
5141 if (!clang_isPreprocessing(oldC.kind))
5142 oldC = cursor;
5143 }
5144
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005145 const enum CXCursorKind K = clang_getCursorKind(parent);
5146 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00005147 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
5148 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005149
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005150 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005151
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00005152 // Avoid having the cursor of an expression "overwrite" the annotation of the
5153 // variable declaration that it belongs to.
5154 // This can happen for C++ constructor expressions whose range generally
5155 // include the variable declaration, e.g.:
5156 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
5157 if (clang_isExpression(cursorK)) {
5158 Expr *E = getCursorExpr(cursor);
Argyrios Kyrtzidis8ccac3d2011-06-29 22:20:07 +00005159 if (Decl *D = getCursorParentDecl(cursor)) {
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00005160 const unsigned I = NextToken();
5161 if (E->getLocStart().isValid() && D->getLocation().isValid() &&
5162 E->getLocStart() == D->getLocation() &&
5163 E->getLocStart() == GetTokenLoc(I)) {
5164 Cursors[I] = updateC;
5165 AdvanceToken();
5166 }
5167 }
5168 }
5169
Argyrios Kyrtzidisd579dd52012-09-01 18:27:30 +00005170 // Before recursing into the children keep some state that we are going
5171 // to use in the AnnotateTokensWorker::postVisitChildren callback to do some
5172 // extra work after the child nodes are visited.
5173 // Note that we don't call VisitChildren here to avoid traversing statements
5174 // code-recursively which can blow the stack.
5175
5176 PostChildrenInfo Info;
5177 Info.Cursor = cursor;
5178 Info.CursorRange = cursorRange;
5179 Info.BeforeChildrenTokenIdx = NextToken();
5180 PostChildrenInfos.push_back(Info);
5181
5182 return CXChildVisit_Recurse;
5183}
5184
5185bool AnnotateTokensWorker::postVisitChildren(CXCursor cursor) {
5186 if (PostChildrenInfos.empty())
5187 return false;
5188 const PostChildrenInfo &Info = PostChildrenInfos.back();
5189 if (!clang_equalCursors(Info.Cursor, cursor))
5190 return false;
5191
5192 const unsigned BeforeChildren = Info.BeforeChildrenTokenIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005193 const unsigned AfterChildren = NextToken();
Argyrios Kyrtzidisd579dd52012-09-01 18:27:30 +00005194 SourceRange cursorRange = Info.CursorRange;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005195
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005196 // Scan the tokens that are at the end of the cursor, but are not captured
5197 // but the child cursors.
5198 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
Argyrios Kyrtzidisd579dd52012-09-01 18:27:30 +00005199
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005200 // Scan the tokens that are at the beginning of the cursor, but are not
5201 // capture by the child cursors.
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005202 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
5203 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
5204 break;
Argyrios Kyrtzidisd579dd52012-09-01 18:27:30 +00005205
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005206 Cursors[I] = cursor;
5207 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005208
Argyrios Kyrtzidisd579dd52012-09-01 18:27:30 +00005209 PostChildrenInfos.pop_back();
5210 return false;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005211}
5212
Ted Kremenek6db61092010-05-05 00:55:15 +00005213static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
5214 CXCursor parent,
5215 CXClientData client_data) {
5216 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
5217}
5218
Argyrios Kyrtzidisd579dd52012-09-01 18:27:30 +00005219static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
5220 CXClientData client_data) {
5221 return static_cast<AnnotateTokensWorker*>(client_data)->
5222 postVisitChildren(cursor);
5223}
5224
Ted Kremenek6628a612011-03-18 22:51:30 +00005225namespace {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005226
5227/// \brief Uses the macro expansions in the preprocessing record to find
5228/// and mark tokens that are macro arguments. This info is used by the
5229/// AnnotateTokensWorker.
5230class MarkMacroArgTokensVisitor {
5231 SourceManager &SM;
5232 CXToken *Tokens;
5233 unsigned NumTokens;
5234 unsigned CurIdx;
5235
5236public:
5237 MarkMacroArgTokensVisitor(SourceManager &SM,
5238 CXToken *tokens, unsigned numTokens)
5239 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
5240
5241 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
5242 if (cursor.kind != CXCursor_MacroExpansion)
5243 return CXChildVisit_Continue;
5244
5245 SourceRange macroRange = getCursorMacroExpansion(cursor)->getSourceRange();
5246 if (macroRange.getBegin() == macroRange.getEnd())
5247 return CXChildVisit_Continue; // it's not a function macro.
5248
5249 for (; CurIdx < NumTokens; ++CurIdx) {
5250 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
5251 macroRange.getBegin()))
5252 break;
5253 }
5254
5255 if (CurIdx == NumTokens)
5256 return CXChildVisit_Break;
5257
5258 for (; CurIdx < NumTokens; ++CurIdx) {
5259 SourceLocation tokLoc = getTokenLoc(CurIdx);
5260 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
5261 break;
5262
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00005263 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005264 }
5265
5266 if (CurIdx == NumTokens)
5267 return CXChildVisit_Break;
5268
5269 return CXChildVisit_Continue;
5270 }
5271
5272private:
5273 SourceLocation getTokenLoc(unsigned tokI) {
5274 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
5275 }
5276
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00005277 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005278 // The third field is reserved and currently not used. Use it here
5279 // to mark macro arg expanded tokens with their expanded locations.
5280 Tokens[tokI].int_data[3] = loc.getRawEncoding();
5281 }
5282};
5283
5284} // end anonymous namespace
5285
5286static CXChildVisitResult
5287MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
5288 CXClientData client_data) {
5289 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
5290 parent);
5291}
5292
5293namespace {
Ted Kremenek6628a612011-03-18 22:51:30 +00005294 struct clang_annotateTokens_Data {
5295 CXTranslationUnit TU;
5296 ASTUnit *CXXUnit;
5297 CXToken *Tokens;
5298 unsigned NumTokens;
5299 CXCursor *Cursors;
5300 };
5301}
5302
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005303static void annotatePreprocessorTokens(CXTranslationUnit TU,
5304 SourceRange RegionOfInterest,
5305 AnnotateTokensData &Annotated) {
5306 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
5307
5308 SourceManager &SourceMgr = CXXUnit->getSourceManager();
5309 std::pair<FileID, unsigned> BeginLocInfo
5310 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
5311 std::pair<FileID, unsigned> EndLocInfo
5312 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
5313
5314 if (BeginLocInfo.first != EndLocInfo.first)
5315 return;
5316
5317 StringRef Buffer;
5318 bool Invalid = false;
5319 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
5320 if (Buffer.empty() || Invalid)
5321 return;
5322
5323 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
David Blaikie4e4d0842012-03-11 07:00:24 +00005324 CXXUnit->getASTContext().getLangOpts(),
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005325 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
5326 Buffer.end());
5327 Lex.SetCommentRetentionState(true);
5328
5329 // Lex tokens in raw mode until we hit the end of the range, to avoid
5330 // entering #includes or expanding macros.
5331 while (true) {
5332 Token Tok;
5333 Lex.LexFromRawLexer(Tok);
5334
5335 reprocess:
5336 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
5337 // We have found a preprocessing directive. Gobble it up so that we
5338 // don't see it while preprocessing these tokens later, but keep track
5339 // of all of the token locations inside this preprocessing directive so
5340 // that we can annotate them appropriately.
5341 //
5342 // FIXME: Some simple tests here could identify macro definitions and
5343 // #undefs, to provide specific cursor kinds for those.
5344 SmallVector<SourceLocation, 32> Locations;
5345 do {
5346 Locations.push_back(Tok.getLocation());
5347 Lex.LexFromRawLexer(Tok);
5348 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
5349
5350 using namespace cxcursor;
5351 CXCursor Cursor
5352 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
5353 Locations.back()),
5354 TU);
5355 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
5356 Annotated[Locations[I].getRawEncoding()] = Cursor;
5357 }
5358
5359 if (Tok.isAtStartOfLine())
5360 goto reprocess;
5361
5362 continue;
5363 }
5364
5365 if (Tok.is(tok::eof))
5366 break;
5367 }
5368}
5369
Ted Kremenekab979612010-11-11 08:05:23 +00005370// This gets run a separate thread to avoid stack blowout.
Ted Kremenek6628a612011-03-18 22:51:30 +00005371static void clang_annotateTokensImpl(void *UserData) {
5372 CXTranslationUnit TU = ((clang_annotateTokens_Data*)UserData)->TU;
5373 ASTUnit *CXXUnit = ((clang_annotateTokens_Data*)UserData)->CXXUnit;
5374 CXToken *Tokens = ((clang_annotateTokens_Data*)UserData)->Tokens;
5375 const unsigned NumTokens = ((clang_annotateTokens_Data*)UserData)->NumTokens;
5376 CXCursor *Cursors = ((clang_annotateTokens_Data*)UserData)->Cursors;
5377
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00005378 CIndexer *CXXIdx = (CIndexer*)TU->CIdx;
5379 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
Argyrios Kyrtzidis81b5ac32012-03-28 02:49:54 +00005380 setThreadBackgroundPriority();
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00005381
Ted Kremenek6628a612011-03-18 22:51:30 +00005382 // Determine the region of interest, which contains all of the tokens.
5383 SourceRange RegionOfInterest;
5384 RegionOfInterest.setBegin(
5385 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
5386 RegionOfInterest.setEnd(
5387 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
5388 Tokens[NumTokens-1])));
5389
5390 // A mapping from the source locations found when re-lexing or traversing the
5391 // region of interest to the corresponding cursors.
5392 AnnotateTokensData Annotated;
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005393
Ted Kremenek6628a612011-03-18 22:51:30 +00005394 // Relex the tokens within the source range to look for preprocessing
5395 // directives.
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005396 annotatePreprocessorTokens(TU, RegionOfInterest, Annotated);
Ted Kremenek6628a612011-03-18 22:51:30 +00005397
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005398 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
5399 // Search and mark tokens that are macro argument expansions.
5400 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
5401 Tokens, NumTokens);
5402 CursorVisitor MacroArgMarker(TU,
5403 MarkMacroArgTokensVisitorDelegate, &Visitor,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00005404 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00005405 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00005406 RegionOfInterest);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005407 MacroArgMarker.visitPreprocessedEntitiesInRegion();
5408 }
5409
Ted Kremenek6628a612011-03-18 22:51:30 +00005410 // Annotate all of the source locations in the region of interest that map to
5411 // a specific cursor.
5412 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
5413 TU, RegionOfInterest);
5414
5415 // FIXME: We use a ridiculous stack size here because the data-recursion
5416 // algorithm uses a large stack frame than the non-data recursive version,
5417 // and AnnotationTokensWorker currently transforms the data-recursion
5418 // algorithm back into a traditional recursion by explicitly calling
5419 // VisitChildren(). We will need to remove this explicit recursive call.
5420 W.AnnotateTokens();
5421
5422 // If we ran into any entities that involve context-sensitive keywords,
5423 // take another pass through the tokens to mark them as such.
5424 if (W.hasContextSensitiveKeywords()) {
5425 for (unsigned I = 0; I != NumTokens; ++I) {
5426 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
5427 continue;
5428
5429 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
5430 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5431 if (ObjCPropertyDecl *Property
5432 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
5433 if (Property->getPropertyAttributesAsWritten() != 0 &&
5434 llvm::StringSwitch<bool>(II->getName())
5435 .Case("readonly", true)
5436 .Case("assign", true)
John McCallf85e1932011-06-15 23:02:42 +00005437 .Case("unsafe_unretained", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00005438 .Case("readwrite", true)
5439 .Case("retain", true)
5440 .Case("copy", true)
5441 .Case("nonatomic", true)
5442 .Case("atomic", true)
5443 .Case("getter", true)
5444 .Case("setter", true)
John McCallf85e1932011-06-15 23:02:42 +00005445 .Case("strong", true)
5446 .Case("weak", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00005447 .Default(false))
5448 Tokens[I].int_data[0] = CXToken_Keyword;
5449 }
5450 continue;
5451 }
5452
5453 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
5454 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
5455 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5456 if (llvm::StringSwitch<bool>(II->getName())
5457 .Case("in", true)
5458 .Case("out", true)
5459 .Case("inout", true)
5460 .Case("oneway", true)
5461 .Case("bycopy", true)
5462 .Case("byref", true)
5463 .Default(false))
5464 Tokens[I].int_data[0] = CXToken_Keyword;
5465 continue;
5466 }
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00005467
5468 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
5469 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
5470 Tokens[I].int_data[0] = CXToken_Keyword;
Ted Kremenek6628a612011-03-18 22:51:30 +00005471 continue;
5472 }
5473 }
5474 }
Ted Kremenekab979612010-11-11 08:05:23 +00005475}
5476
Ted Kremenek6db61092010-05-05 00:55:15 +00005477extern "C" {
5478
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005479void clang_annotateTokens(CXTranslationUnit TU,
5480 CXToken *Tokens, unsigned NumTokens,
5481 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005482
5483 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005484 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005485
Douglas Gregor4419b672010-10-21 06:10:04 +00005486 // Any token we don't specifically annotate will have a NULL cursor.
5487 CXCursor C = clang_getNullCursor();
5488 for (unsigned I = 0; I != NumTokens; ++I)
5489 Cursors[I] = C;
5490
Ted Kremeneka60ed472010-11-16 08:15:36 +00005491 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor4419b672010-10-21 06:10:04 +00005492 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005493 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005494
Douglas Gregorbdf60622010-03-05 21:16:25 +00005495 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenek6628a612011-03-18 22:51:30 +00005496
5497 clang_annotateTokens_Data data = { TU, CXXUnit, Tokens, NumTokens, Cursors };
Ted Kremenekab979612010-11-11 08:05:23 +00005498 llvm::CrashRecoveryContext CRC;
Ted Kremenek6628a612011-03-18 22:51:30 +00005499 if (!RunSafely(CRC, clang_annotateTokensImpl, &data,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005500 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00005501 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
5502 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005503}
Ted Kremenek6628a612011-03-18 22:51:30 +00005504
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005505} // end: extern "C"
5506
5507//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00005508// Operations for querying linkage of a cursor.
5509//===----------------------------------------------------------------------===//
5510
5511extern "C" {
5512CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00005513 if (!clang_isDeclaration(cursor.kind))
5514 return CXLinkage_Invalid;
5515
Ted Kremenek16b42592010-03-03 06:36:57 +00005516 Decl *D = cxcursor::getCursorDecl(cursor);
5517 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
5518 switch (ND->getLinkage()) {
5519 case NoLinkage: return CXLinkage_NoLinkage;
5520 case InternalLinkage: return CXLinkage_Internal;
5521 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
5522 case ExternalLinkage: return CXLinkage_External;
5523 };
5524
5525 return CXLinkage_Invalid;
5526}
5527} // end: extern "C"
5528
5529//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005530// Operations for querying language of a cursor.
5531//===----------------------------------------------------------------------===//
5532
5533static CXLanguageKind getDeclLanguage(const Decl *D) {
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00005534 if (!D)
5535 return CXLanguage_C;
5536
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005537 switch (D->getKind()) {
5538 default:
5539 break;
5540 case Decl::ImplicitParam:
5541 case Decl::ObjCAtDefsField:
5542 case Decl::ObjCCategory:
5543 case Decl::ObjCCategoryImpl:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005544 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005545 case Decl::ObjCImplementation:
5546 case Decl::ObjCInterface:
5547 case Decl::ObjCIvar:
5548 case Decl::ObjCMethod:
5549 case Decl::ObjCProperty:
5550 case Decl::ObjCPropertyImpl:
5551 case Decl::ObjCProtocol:
5552 return CXLanguage_ObjC;
5553 case Decl::CXXConstructor:
5554 case Decl::CXXConversion:
5555 case Decl::CXXDestructor:
5556 case Decl::CXXMethod:
5557 case Decl::CXXRecord:
5558 case Decl::ClassTemplate:
5559 case Decl::ClassTemplatePartialSpecialization:
5560 case Decl::ClassTemplateSpecialization:
5561 case Decl::Friend:
5562 case Decl::FriendTemplate:
5563 case Decl::FunctionTemplate:
5564 case Decl::LinkageSpec:
5565 case Decl::Namespace:
5566 case Decl::NamespaceAlias:
5567 case Decl::NonTypeTemplateParm:
5568 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005569 case Decl::TemplateTemplateParm:
5570 case Decl::TemplateTypeParm:
5571 case Decl::UnresolvedUsingTypename:
5572 case Decl::UnresolvedUsingValue:
5573 case Decl::Using:
5574 case Decl::UsingDirective:
5575 case Decl::UsingShadow:
5576 return CXLanguage_CPlusPlus;
5577 }
5578
5579 return CXLanguage_C;
5580}
5581
5582extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00005583
5584enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
5585 if (clang_isDeclaration(cursor.kind))
5586 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005587 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Douglas Gregor58ddb602010-08-23 23:00:57 +00005588 return CXAvailability_Available;
5589
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005590 switch (D->getAvailability()) {
5591 case AR_Available:
5592 case AR_NotYetIntroduced:
5593 return CXAvailability_Available;
5594
5595 case AR_Deprecated:
Douglas Gregor58ddb602010-08-23 23:00:57 +00005596 return CXAvailability_Deprecated;
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005597
5598 case AR_Unavailable:
5599 return CXAvailability_NotAvailable;
5600 }
Douglas Gregor58ddb602010-08-23 23:00:57 +00005601 }
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005602
Douglas Gregor58ddb602010-08-23 23:00:57 +00005603 return CXAvailability_Available;
5604}
5605
Douglas Gregorcc889662012-05-08 00:14:45 +00005606static CXVersion convertVersion(VersionTuple In) {
5607 CXVersion Out = { -1, -1, -1 };
5608 if (In.empty())
5609 return Out;
5610
5611 Out.Major = In.getMajor();
5612
5613 if (llvm::Optional<unsigned> Minor = In.getMinor())
5614 Out.Minor = *Minor;
5615 else
5616 return Out;
5617
5618 if (llvm::Optional<unsigned> Subminor = In.getSubminor())
5619 Out.Subminor = *Subminor;
5620
5621 return Out;
5622}
5623
5624int clang_getCursorPlatformAvailability(CXCursor cursor,
5625 int *always_deprecated,
5626 CXString *deprecated_message,
5627 int *always_unavailable,
5628 CXString *unavailable_message,
5629 CXPlatformAvailability *availability,
5630 int availability_size) {
5631 if (always_deprecated)
5632 *always_deprecated = 0;
5633 if (deprecated_message)
5634 *deprecated_message = cxstring::createCXString("", /*DupString=*/false);
5635 if (always_unavailable)
5636 *always_unavailable = 0;
5637 if (unavailable_message)
5638 *unavailable_message = cxstring::createCXString("", /*DupString=*/false);
5639
5640 if (!clang_isDeclaration(cursor.kind))
5641 return 0;
5642
5643 Decl *D = cxcursor::getCursorDecl(cursor);
5644 if (!D)
5645 return 0;
5646
5647 int N = 0;
5648 for (Decl::attr_iterator A = D->attr_begin(), AEnd = D->attr_end(); A != AEnd;
5649 ++A) {
5650 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(*A)) {
5651 if (always_deprecated)
5652 *always_deprecated = 1;
5653 if (deprecated_message)
5654 *deprecated_message = cxstring::createCXString(Deprecated->getMessage());
5655 continue;
5656 }
5657
5658 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(*A)) {
5659 if (always_unavailable)
5660 *always_unavailable = 1;
5661 if (unavailable_message) {
5662 *unavailable_message
5663 = cxstring::createCXString(Unavailable->getMessage());
5664 }
5665 continue;
5666 }
5667
5668 if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(*A)) {
5669 if (N < availability_size) {
5670 availability[N].Platform
5671 = cxstring::createCXString(Avail->getPlatform()->getName());
5672 availability[N].Introduced = convertVersion(Avail->getIntroduced());
5673 availability[N].Deprecated = convertVersion(Avail->getDeprecated());
5674 availability[N].Obsoleted = convertVersion(Avail->getObsoleted());
5675 availability[N].Unavailable = Avail->getUnavailable();
5676 availability[N].Message = cxstring::createCXString(Avail->getMessage());
5677 }
5678 ++N;
5679 }
5680 }
5681
5682 return N;
5683}
5684
5685void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) {
5686 clang_disposeString(availability->Platform);
5687 clang_disposeString(availability->Message);
5688}
5689
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005690CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
5691 if (clang_isDeclaration(cursor.kind))
5692 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
5693
5694 return CXLanguage_Invalid;
5695}
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005696
5697 /// \brief If the given cursor is the "templated" declaration
5698 /// descibing a class or function template, return the class or
5699 /// function template.
5700static Decl *maybeGetTemplateCursor(Decl *D) {
5701 if (!D)
5702 return 0;
5703
5704 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
5705 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
5706 return FunTmpl;
5707
5708 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
5709 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
5710 return ClassTmpl;
5711
5712 return D;
5713}
5714
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005715CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
5716 if (clang_isDeclaration(cursor.kind)) {
5717 if (Decl *D = getCursorDecl(cursor)) {
5718 DeclContext *DC = D->getDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005719 if (!DC)
5720 return clang_getNullCursor();
5721
5722 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5723 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005724 }
5725 }
5726
5727 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
5728 if (Decl *D = getCursorDecl(cursor))
Ted Kremeneka60ed472010-11-16 08:15:36 +00005729 return MakeCXCursor(D, getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005730 }
5731
5732 return clang_getNullCursor();
5733}
5734
5735CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
5736 if (clang_isDeclaration(cursor.kind)) {
5737 if (Decl *D = getCursorDecl(cursor)) {
5738 DeclContext *DC = D->getLexicalDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005739 if (!DC)
5740 return clang_getNullCursor();
5741
5742 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5743 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005744 }
5745 }
5746
5747 // FIXME: Note that we can't easily compute the lexical context of a
5748 // statement or expression, so we return nothing.
5749 return clang_getNullCursor();
5750}
5751
Douglas Gregorecdcb882010-10-20 22:00:55 +00005752CXFile clang_getIncludedFile(CXCursor cursor) {
5753 if (cursor.kind != CXCursor_InclusionDirective)
5754 return 0;
5755
5756 InclusionDirective *ID = getCursorInclusionDirective(cursor);
5757 return (void *)ID->getFile();
5758}
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +00005759
5760CXSourceRange clang_Cursor_getCommentRange(CXCursor C) {
5761 if (!clang_isDeclaration(C.kind))
5762 return clang_getNullRange();
5763
5764 const Decl *D = getCursorDecl(C);
5765 ASTContext &Context = getCursorContext(C);
Dmitri Gribenkof50555e2012-08-11 00:51:43 +00005766 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +00005767 if (!RC)
5768 return clang_getNullRange();
5769
5770 return cxloc::translateSourceRange(Context, RC->getSourceRange());
5771}
5772
5773CXString clang_Cursor_getRawCommentText(CXCursor C) {
5774 if (!clang_isDeclaration(C.kind))
5775 return createCXString((const char *) NULL);
5776
5777 const Decl *D = getCursorDecl(C);
5778 ASTContext &Context = getCursorContext(C);
Dmitri Gribenkof50555e2012-08-11 00:51:43 +00005779 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +00005780 StringRef RawText = RC ? RC->getRawText(Context.getSourceManager()) :
5781 StringRef();
5782
5783 // Don't duplicate the string because RawText points directly into source
5784 // code.
5785 return createCXString(RawText, false);
5786}
5787
Dmitri Gribenko2d44d772012-06-26 20:39:18 +00005788CXString clang_Cursor_getBriefCommentText(CXCursor C) {
5789 if (!clang_isDeclaration(C.kind))
5790 return createCXString((const char *) NULL);
5791
5792 const Decl *D = getCursorDecl(C);
5793 const ASTContext &Context = getCursorContext(C);
Dmitri Gribenkof50555e2012-08-11 00:51:43 +00005794 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
Dmitri Gribenko2d44d772012-06-26 20:39:18 +00005795
Dmitri Gribenko8376f592012-06-28 16:25:36 +00005796 if (RC) {
Dmitri Gribenko2d44d772012-06-26 20:39:18 +00005797 StringRef BriefText = RC->getBriefText(Context);
5798
5799 // Don't duplicate the string because RawComment ensures that this memory
5800 // will not go away.
5801 return createCXString(BriefText, false);
5802 }
5803
5804 return createCXString((const char *) NULL);
5805}
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005806
Dmitri Gribenkoae99b752012-07-20 21:34:34 +00005807CXComment clang_Cursor_getParsedComment(CXCursor C) {
5808 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkoe4330a32012-09-10 20:32:42 +00005809 return cxcomment::createCXComment(NULL, NULL);
Dmitri Gribenkoae99b752012-07-20 21:34:34 +00005810
5811 const Decl *D = getCursorDecl(C);
5812 const ASTContext &Context = getCursorContext(C);
5813 const comments::FullComment *FC = Context.getCommentForDecl(D);
5814
Dmitri Gribenkoe4330a32012-09-10 20:32:42 +00005815 return cxcomment::createCXComment(FC, getCursorTU(C));
Dmitri Gribenkoae99b752012-07-20 21:34:34 +00005816}
5817
Dmitri Gribenkob619e782012-07-17 00:17:45 +00005818} // end: extern "C"
5819
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005820//===----------------------------------------------------------------------===//
5821// C++ AST instrospection.
5822//===----------------------------------------------------------------------===//
5823
5824extern "C" {
5825unsigned clang_CXXMethod_isStatic(CXCursor C) {
5826 if (!clang_isDeclaration(C.kind))
5827 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00005828
5829 CXXMethodDecl *Method = 0;
5830 Decl *D = cxcursor::getCursorDecl(C);
5831 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5832 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5833 else
5834 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5835 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00005836}
Ted Kremenekb12903e2010-05-18 22:32:15 +00005837
Douglas Gregor211924b2011-05-12 15:17:24 +00005838unsigned clang_CXXMethod_isVirtual(CXCursor C) {
5839 if (!clang_isDeclaration(C.kind))
5840 return 0;
5841
5842 CXXMethodDecl *Method = 0;
5843 Decl *D = cxcursor::getCursorDecl(C);
5844 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5845 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5846 else
5847 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5848 return (Method && Method->isVirtual()) ? 1 : 0;
5849}
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005850} // end: extern "C"
5851
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005852//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00005853// Attribute introspection.
5854//===----------------------------------------------------------------------===//
5855
5856extern "C" {
5857CXType clang_getIBOutletCollectionType(CXCursor C) {
5858 if (C.kind != CXCursor_IBOutletCollectionAttr)
Ted Kremeneka60ed472010-11-16 08:15:36 +00005859 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005860
5861 IBOutletCollectionAttr *A =
5862 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
5863
Argyrios Kyrtzidis18aa2ff2011-09-13 18:49:52 +00005864 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005865}
5866} // end: extern "C"
5867
5868//===----------------------------------------------------------------------===//
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005869// Inspecting memory usage.
5870//===----------------------------------------------------------------------===//
5871
Ted Kremenekf7870022011-04-20 16:41:07 +00005872typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005873
Ted Kremenekf7870022011-04-20 16:41:07 +00005874static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
5875 enum CXTUResourceUsageKind k,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005876 unsigned long amount) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005877 CXTUResourceUsageEntry entry = { k, amount };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005878 entries.push_back(entry);
5879}
5880
5881extern "C" {
5882
Ted Kremenekf7870022011-04-20 16:41:07 +00005883const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005884 const char *str = "";
5885 switch (kind) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005886 case CXTUResourceUsage_AST:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005887 str = "ASTContext: expressions, declarations, and types";
5888 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005889 case CXTUResourceUsage_Identifiers:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005890 str = "ASTContext: identifiers";
5891 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005892 case CXTUResourceUsage_Selectors:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005893 str = "ASTContext: selectors";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005894 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005895 case CXTUResourceUsage_GlobalCompletionResults:
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005896 str = "Code completion: cached global results";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005897 break;
Ted Kremenek457aaf02011-04-28 04:10:31 +00005898 case CXTUResourceUsage_SourceManagerContentCache:
5899 str = "SourceManager: content cache allocator";
5900 break;
Ted Kremenekba29bd22011-04-28 04:53:38 +00005901 case CXTUResourceUsage_AST_SideTables:
5902 str = "ASTContext: side tables";
5903 break;
Ted Kremenekf61b8312011-04-28 20:36:42 +00005904 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
5905 str = "SourceManager: malloc'ed memory buffers";
5906 break;
5907 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
5908 str = "SourceManager: mmap'ed memory buffers";
5909 break;
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005910 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
5911 str = "ExternalASTSource: malloc'ed memory buffers";
5912 break;
5913 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
5914 str = "ExternalASTSource: mmap'ed memory buffers";
5915 break;
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005916 case CXTUResourceUsage_Preprocessor:
5917 str = "Preprocessor: malloc'ed memory";
5918 break;
5919 case CXTUResourceUsage_PreprocessingRecord:
5920 str = "Preprocessor: PreprocessingRecord";
5921 break;
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005922 case CXTUResourceUsage_SourceManager_DataStructures:
5923 str = "SourceManager: data structures and tables";
5924 break;
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005925 case CXTUResourceUsage_Preprocessor_HeaderSearch:
5926 str = "Preprocessor: header search tables";
5927 break;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005928 }
5929 return str;
5930}
5931
Ted Kremenekf7870022011-04-20 16:41:07 +00005932CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005933 if (!TU) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005934 CXTUResourceUsage usage = { (void*) 0, 0, 0 };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005935 return usage;
5936 }
5937
5938 ASTUnit *astUnit = static_cast<ASTUnit*>(TU->TUData);
Dylan Noblesmith1e4c01b2012-02-13 12:32:21 +00005939 OwningPtr<MemUsageEntries> entries(new MemUsageEntries());
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005940 ASTContext &astContext = astUnit->getASTContext();
5941
5942 // How much memory is used by AST nodes and types?
Ted Kremenekf7870022011-04-20 16:41:07 +00005943 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005944 (unsigned long) astContext.getASTAllocatedMemory());
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005945
5946 // How much memory is used by identifiers?
Ted Kremenekf7870022011-04-20 16:41:07 +00005947 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005948 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
5949
5950 // How much memory is used for selectors?
Ted Kremenekf7870022011-04-20 16:41:07 +00005951 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005952 (unsigned long) astContext.Selectors.getTotalMemory());
5953
Ted Kremenekba29bd22011-04-28 04:53:38 +00005954 // How much memory is used by ASTContext's side tables?
5955 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
5956 (unsigned long) astContext.getSideTableAllocatedMemory());
5957
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005958 // How much memory is used for caching global code completion results?
5959 unsigned long completionBytes = 0;
5960 if (GlobalCodeCompletionAllocator *completionAllocator =
5961 astUnit->getCachedCompletionAllocator().getPtr()) {
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005962 completionBytes = completionAllocator->getTotalMemory();
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005963 }
Ted Kremenek457aaf02011-04-28 04:10:31 +00005964 createCXTUResourceUsageEntry(*entries,
5965 CXTUResourceUsage_GlobalCompletionResults,
5966 completionBytes);
5967
5968 // How much memory is being used by SourceManager's content cache?
5969 createCXTUResourceUsageEntry(*entries,
5970 CXTUResourceUsage_SourceManagerContentCache,
5971 (unsigned long) astContext.getSourceManager().getContentCacheSize());
Ted Kremenekf61b8312011-04-28 20:36:42 +00005972
5973 // How much memory is being used by the MemoryBuffer's in SourceManager?
5974 const SourceManager::MemoryBufferSizes &srcBufs =
5975 astUnit->getSourceManager().getMemoryBufferSizes();
5976
5977 createCXTUResourceUsageEntry(*entries,
5978 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
5979 (unsigned long) srcBufs.malloc_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005980 createCXTUResourceUsageEntry(*entries,
Ted Kremenekf61b8312011-04-28 20:36:42 +00005981 CXTUResourceUsage_SourceManager_Membuffer_MMap,
5982 (unsigned long) srcBufs.mmap_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005983 createCXTUResourceUsageEntry(*entries,
5984 CXTUResourceUsage_SourceManager_DataStructures,
5985 (unsigned long) astContext.getSourceManager()
5986 .getDataStructureSizes());
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005987
5988 // How much memory is being used by the ExternalASTSource?
5989 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
5990 const ExternalASTSource::MemoryBufferSizes &sizes =
5991 esrc->getMemoryBufferSizes();
5992
5993 createCXTUResourceUsageEntry(*entries,
5994 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
5995 (unsigned long) sizes.malloc_bytes);
5996 createCXTUResourceUsageEntry(*entries,
5997 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
5998 (unsigned long) sizes.mmap_bytes);
5999 }
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00006000
6001 // How much memory is being used by the Preprocessor?
6002 Preprocessor &pp = astUnit->getPreprocessor();
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00006003 createCXTUResourceUsageEntry(*entries,
6004 CXTUResourceUsage_Preprocessor,
Argyrios Kyrtzidisc5c5e922011-06-29 22:20:04 +00006005 pp.getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00006006
6007 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
6008 createCXTUResourceUsageEntry(*entries,
6009 CXTUResourceUsage_PreprocessingRecord,
6010 pRec->getTotalMemory());
6011 }
6012
Ted Kremenekd1194fb2011-07-26 23:46:11 +00006013 createCXTUResourceUsageEntry(*entries,
6014 CXTUResourceUsage_Preprocessor_HeaderSearch,
6015 pp.getHeaderSearchInfo().getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00006016
Ted Kremenekf7870022011-04-20 16:41:07 +00006017 CXTUResourceUsage usage = { (void*) entries.get(),
Ted Kremenek59fc1e52011-04-18 22:47:10 +00006018 (unsigned) entries->size(),
6019 entries->size() ? &(*entries)[0] : 0 };
6020 entries.take();
6021 return usage;
6022}
6023
Ted Kremenekf7870022011-04-20 16:41:07 +00006024void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00006025 if (usage.data)
6026 delete (MemUsageEntries*) usage.data;
6027}
6028
6029} // end extern "C"
6030
Douglas Gregor6df78732011-05-05 20:27:22 +00006031void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
6032 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
6033 for (unsigned I = 0; I != Usage.numEntries; ++I)
6034 fprintf(stderr, " %s: %lu\n",
6035 clang_getTUResourceUsageName(Usage.entries[I].kind),
6036 Usage.entries[I].amount);
6037
6038 clang_disposeCXTUResourceUsage(Usage);
6039}
6040
Ted Kremenek59fc1e52011-04-18 22:47:10 +00006041//===----------------------------------------------------------------------===//
Ted Kremenek04bb7162010-01-22 22:44:15 +00006042// Misc. utility functions.
6043//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00006044
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00006045/// Default to using an 8 MB stack size on "safety" threads.
6046static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00006047
6048namespace clang {
6049
6050bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00006051 void (*Fn)(void*), void *UserData,
6052 unsigned Size) {
6053 if (!Size)
6054 Size = GetSafetyThreadStackSize();
6055 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00006056 return CRC.RunSafelyOnThread(Fn, UserData, Size);
6057 return CRC.RunSafely(Fn, UserData);
6058}
6059
6060unsigned GetSafetyThreadStackSize() {
6061 return SafetyStackThreadSize;
6062}
6063
6064void SetSafetyThreadStackSize(unsigned Value) {
6065 SafetyStackThreadSize = Value;
6066}
6067
Argyrios Kyrtzidis8e7c48a2012-03-28 02:49:50 +00006068}
6069
Argyrios Kyrtzidis81b5ac32012-03-28 02:49:54 +00006070void clang::setThreadBackgroundPriority() {
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00006071 // FIXME: Move to llvm/Support and make it cross-platform.
6072#ifdef __APPLE__
6073 setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG);
6074#endif
6075}
6076
Argyrios Kyrtzidis97934282012-04-11 03:52:18 +00006077void cxindex::printDiagsToStderr(ASTUnit *Unit) {
6078 if (!Unit)
6079 return;
6080
6081 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
6082 DEnd = Unit->stored_diag_end();
6083 D != DEnd; ++D) {
6084 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOpts());
6085 CXString Msg = clang_formatDiagnostic(&Diag,
6086 clang_defaultDiagnosticDisplayOptions());
6087 fprintf(stderr, "%s\n", clang_getCString(Msg));
6088 clang_disposeString(Msg);
6089 }
6090#ifdef LLVM_ON_WIN32
6091 // On Windows, force a flush, since there may be multiple copies of
6092 // stderr and stdout in the file system, all with different buffers
6093 // but writing to the same device.
6094 fflush(stderr);
6095#endif
6096}
6097
Ted Kremenek04bb7162010-01-22 22:44:15 +00006098extern "C" {
6099
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00006100CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00006101 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00006102}
6103
6104} // end: extern "C"
Ted Kremenek59fc1e52011-04-18 22:47:10 +00006105