blob: 9e261de964929b4831c483f085eed967bb988f3a [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
185 case CXChildVisit_Recurse:
186 return VisitChildren(Cursor);
187 }
188
David Blaikie7530c032012-01-17 06:56:22 +0000189 llvm_unreachable("Invalid CXChildVisitResult!");
Douglas Gregorb1373d02010-01-20 20:59:29 +0000190}
191
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000192static bool visitPreprocessedEntitiesInRange(SourceRange R,
193 PreprocessingRecord &PPRec,
194 CursorVisitor &Visitor) {
195 SourceManager &SM = Visitor.getASTUnit()->getSourceManager();
196 FileID FID;
197
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +0000198 if (!Visitor.shouldVisitIncludedEntities()) {
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000199 // If the begin/end of the range lie in the same FileID, do the optimization
200 // where we skip preprocessed entities that do not come from the same FileID.
Argyrios Kyrtzidisacca4112011-12-21 16:56:38 +0000201 FID = SM.getFileID(SM.getFileLoc(R.getBegin()));
202 if (FID != SM.getFileID(SM.getFileLoc(R.getEnd())))
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000203 FID = FileID();
204 }
205
206 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
207 Entities = PPRec.getPreprocessedEntitiesInRange(R);
208 return Visitor.visitPreprocessedEntities(Entities.first, Entities.second,
209 PPRec, FID);
210}
211
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000212void CursorVisitor::visitFileRegion() {
213 if (RegionOfInterest.isInvalid())
214 return;
215
216 ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData);
217 SourceManager &SM = Unit->getSourceManager();
218
219 std::pair<FileID, unsigned>
220 Begin = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getBegin())),
221 End = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getEnd()));
222
223 if (End.first != Begin.first) {
224 // If the end does not reside in the same file, try to recover by
225 // picking the end of the file of begin location.
226 End.first = Begin.first;
227 End.second = SM.getFileIDSize(Begin.first);
228 }
229
230 assert(Begin.first == End.first);
231 if (Begin.second > End.second)
232 return;
233
234 FileID File = Begin.first;
235 unsigned Offset = Begin.second;
236 unsigned Length = End.second - Begin.second;
237
Argyrios Kyrtzidisb49e7282011-11-29 03:14:11 +0000238 if (!VisitDeclsOnly && !VisitPreprocessorLast)
239 if (visitPreprocessedEntitiesInRegion())
240 return; // visitation break.
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000241
242 visitDeclsFromFileRegion(File, Offset, Length);
243
Argyrios Kyrtzidisb49e7282011-11-29 03:14:11 +0000244 if (!VisitDeclsOnly && VisitPreprocessorLast)
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000245 visitPreprocessedEntitiesInRegion();
246}
247
Argyrios Kyrtzidise2079cf2011-11-16 08:58:54 +0000248static bool isInLexicalContext(Decl *D, DeclContext *DC) {
249 if (!DC)
250 return false;
251
252 for (DeclContext *DeclDC = D->getLexicalDeclContext();
253 DeclDC; DeclDC = DeclDC->getLexicalParent()) {
254 if (DeclDC == DC)
255 return true;
256 }
257 return false;
258}
259
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000260void CursorVisitor::visitDeclsFromFileRegion(FileID File,
261 unsigned Offset, unsigned Length) {
262 ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData);
263 SourceManager &SM = Unit->getSourceManager();
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000264 SourceRange Range = RegionOfInterest;
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000265
266 SmallVector<Decl *, 16> Decls;
267 Unit->findFileRegionDecls(File, Offset, Length, Decls);
268
269 // If we didn't find any file level decls for the file, try looking at the
270 // file that it was included from.
Argyrios Kyrtzidisc14a03d2011-11-23 20:27:36 +0000271 while (Decls.empty() || Decls.front()->isTopLevelDeclInObjCContainer()) {
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000272 bool Invalid = false;
273 const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid);
274 if (Invalid)
275 return;
276
277 SourceLocation Outer;
278 if (SLEntry.isFile())
279 Outer = SLEntry.getFile().getIncludeLoc();
280 else
281 Outer = SLEntry.getExpansion().getExpansionLocStart();
282 if (Outer.isInvalid())
283 return;
284
285 llvm::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer);
286 Length = 0;
287 Unit->findFileRegionDecls(File, Offset, Length, Decls);
288 }
289
290 assert(!Decls.empty());
291
292 bool VisitedAtLeastOnce = false;
Argyrios Kyrtzidise2079cf2011-11-16 08:58:54 +0000293 DeclContext *CurDC = 0;
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000294 SmallVector<Decl *, 16>::iterator DIt = Decls.begin();
295 for (SmallVector<Decl *, 16>::iterator DE = Decls.end(); DIt != DE; ++DIt) {
296 Decl *D = *DIt;
Argyrios Kyrtzidised8bef42011-11-28 22:38:07 +0000297 if (D->getSourceRange().isInvalid())
298 continue;
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000299
Argyrios Kyrtzidise2079cf2011-11-16 08:58:54 +0000300 if (isInLexicalContext(D, CurDC))
301 continue;
302
303 CurDC = dyn_cast<DeclContext>(D);
304
Argyrios Kyrtzidise2079cf2011-11-16 08:58:54 +0000305 if (TagDecl *TD = dyn_cast<TagDecl>(D))
306 if (!TD->isFreeStanding())
307 continue;
308
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000309 RangeComparisonResult CompRes = RangeCompare(SM, D->getSourceRange(),Range);
310 if (CompRes == RangeBefore)
311 continue;
312 if (CompRes == RangeAfter)
313 break;
314
315 assert(CompRes == RangeOverlap);
316 VisitedAtLeastOnce = true;
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +0000317
318 if (isa<ObjCContainerDecl>(D)) {
319 FileDI_current = &DIt;
320 FileDE_current = DE;
321 } else {
322 FileDI_current = 0;
323 }
324
Argyrios Kyrtzidisba986172011-11-03 19:02:28 +0000325 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000326 break;
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000327 }
328
329 if (VisitedAtLeastOnce)
330 return;
331
332 // No Decls overlapped with the range. Move up the lexical context until there
333 // is a context that contains the range or we reach the translation unit
334 // level.
335 DeclContext *DC = DIt == Decls.begin() ? (*DIt)->getLexicalDeclContext()
336 : (*(DIt-1))->getLexicalDeclContext();
337
338 while (DC && !DC->isTranslationUnit()) {
339 Decl *D = cast<Decl>(DC);
340 SourceRange CurDeclRange = D->getSourceRange();
341 if (CurDeclRange.isInvalid())
342 break;
343
344 if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) {
Argyrios Kyrtzidisba986172011-11-03 19:02:28 +0000345 Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true);
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000346 break;
347 }
348
349 DC = D->getLexicalDeclContext();
350 }
351}
352
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000353bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
Argyrios Kyrtzidisb49e7282011-11-29 03:14:11 +0000354 if (!AU->getPreprocessor().getPreprocessingRecord())
355 return false;
356
Douglas Gregor788f5a12010-03-20 00:41:21 +0000357 PreprocessingRecord &PPRec
Ted Kremeneka60ed472010-11-16 08:15:36 +0000358 = *AU->getPreprocessor().getPreprocessingRecord();
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000359 SourceManager &SM = AU->getSourceManager();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000360
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000361 if (RegionOfInterest.isValid()) {
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +0000362 SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000363 SourceLocation B = MappedRange.getBegin();
364 SourceLocation E = MappedRange.getEnd();
365
366 if (AU->isInPreambleFileID(B)) {
367 if (SM.isLoadedSourceLocation(E))
368 return visitPreprocessedEntitiesInRange(SourceRange(B, E),
369 PPRec, *this);
370
371 // Beginning of range lies in the preamble but it also extends beyond
372 // it into the main file. Split the range into 2 parts, one covering
373 // the preamble and another covering the main file. This allows subsequent
374 // calls to visitPreprocessedEntitiesInRange to accept a source range that
375 // lies in the same FileID, allowing it to skip preprocessed entities that
376 // do not come from the same FileID.
377 bool breaked =
378 visitPreprocessedEntitiesInRange(
379 SourceRange(B, AU->getEndOfPreambleFileID()),
380 PPRec, *this);
381 if (breaked) return true;
382 return visitPreprocessedEntitiesInRange(
383 SourceRange(AU->getStartOfMainFileID(), E),
384 PPRec, *this);
385 }
386
387 return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this);
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000388 }
389
Douglas Gregor788f5a12010-03-20 00:41:21 +0000390 bool OnlyLocalDecls
Douglas Gregor32038bb2010-12-21 19:07:48 +0000391 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
392
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000393 if (OnlyLocalDecls)
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000394 return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(),
395 PPRec);
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000396
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000397 return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec);
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000398}
399
400template<typename InputIterator>
401bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000402 InputIterator Last,
403 PreprocessingRecord &PPRec,
404 FileID FID) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000405 for (; First != Last; ++First) {
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000406 if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID))
407 continue;
408
409 PreprocessedEntity *PPE = *First;
410 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000411 if (Visit(MakeMacroExpansionCursor(ME, TU)))
412 return true;
413
414 continue;
415 }
416
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000417 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(PPE)) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000418 if (Visit(MakeMacroDefinitionCursor(MD, TU)))
419 return true;
420
421 continue;
422 }
423
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000424 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000425 if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
426 return true;
427
428 continue;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000429 }
430 }
431
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000432 return false;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000433}
434
Douglas Gregorb1373d02010-01-20 20:59:29 +0000435/// \brief Visit the children of the given cursor.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000436///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000437/// \returns true if the visitation should be aborted, false if it
438/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000439bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregorc314aa42011-03-02 19:17:03 +0000440 if (clang_isReference(Cursor.kind) &&
441 Cursor.kind != CXCursor_CXXBaseSpecifier) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000442 // By definition, references have no children.
443 return false;
444 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000445
446 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000447 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000448 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000449
Douglas Gregorb1373d02010-01-20 20:59:29 +0000450 if (clang_isDeclaration(Cursor.kind)) {
451 Decl *D = getCursorDecl(Cursor);
Douglas Gregor06d9b1a2011-04-14 21:41:34 +0000452 if (!D)
453 return false;
454
Ted Kremenek539311e2010-02-18 18:47:01 +0000455 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000456 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000457
Douglas Gregor06d9b1a2011-04-14 21:41:34 +0000458 if (clang_isStatement(Cursor.kind)) {
459 if (Stmt *S = getCursorStmt(Cursor))
460 return Visit(S);
461
462 return false;
463 }
464
465 if (clang_isExpression(Cursor.kind)) {
466 if (Expr *E = getCursorExpr(Cursor))
467 return Visit(E);
468
469 return false;
470 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000471
Douglas Gregorb1373d02010-01-20 20:59:29 +0000472 if (clang_isTranslationUnit(Cursor.kind)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000473 CXTranslationUnit tu = getCursorTU(Cursor);
474 ASTUnit *CXXUnit = static_cast<ASTUnit*>(tu->TUData);
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000475
476 int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
477 for (unsigned I = 0; I != 2; ++I) {
478 if (VisitOrder[I]) {
479 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
480 RegionOfInterest.isInvalid()) {
481 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
482 TLEnd = CXXUnit->top_level_end();
483 TL != TLEnd; ++TL) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000484 if (Visit(MakeCXCursor(*TL, tu, RegionOfInterest), true))
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000485 return true;
486 }
487 } else if (VisitDeclContext(
488 CXXUnit->getASTContext().getTranslationUnitDecl()))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000489 return true;
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000490 continue;
Douglas Gregor7b691f332010-01-20 21:13:59 +0000491 }
Bob Wilson3178cb62010-03-19 03:57:57 +0000492
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000493 // Walk the preprocessing record.
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000494 if (CXXUnit->getPreprocessor().getPreprocessingRecord())
495 visitPreprocessedEntitiesInRegion();
Douglas Gregor0396f462010-03-19 05:22:59 +0000496 }
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000497
Douglas Gregor7b691f332010-01-20 21:13:59 +0000498 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000499 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000500
Douglas Gregorc314aa42011-03-02 19:17:03 +0000501 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
502 if (CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
503 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
504 return Visit(BaseTSInfo->getTypeLoc());
505 }
506 }
507 }
Argyrios Kyrtzidis221d5a52011-09-13 18:49:56 +0000508
509 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
510 IBOutletCollectionAttr *A =
511 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
512 if (const ObjCInterfaceType *InterT = A->getInterface()->getAs<ObjCInterfaceType>())
513 return Visit(cxcursor::MakeCursorObjCClassRef(InterT->getInterface(),
514 A->getInterfaceLoc(), TU));
515 }
516
Douglas Gregorb1373d02010-01-20 20:59:29 +0000517 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000518 return false;
519}
520
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000521bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
Douglas Gregor13c8ccb2011-04-22 23:49:24 +0000522 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
523 if (Visit(TSInfo->getTypeLoc()))
524 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000525
Ted Kremenek664cffd2010-07-22 11:30:19 +0000526 if (Stmt *Body = B->getBody())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000527 return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest));
Ted Kremenek664cffd2010-07-22 11:30:19 +0000528
529 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000530}
531
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000532llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
533 if (RegionOfInterest.isValid()) {
Douglas Gregor66537982010-11-17 17:14:07 +0000534 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000535 if (Range.isInvalid())
536 return llvm::Optional<bool>();
Douglas Gregor66537982010-11-17 17:14:07 +0000537
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000538 switch (CompareRegionOfInterest(Range)) {
539 case RangeBefore:
540 // This declaration comes before the region of interest; skip it.
541 return llvm::Optional<bool>();
542
543 case RangeAfter:
544 // This declaration comes after the region of interest; we're done.
545 return false;
546
547 case RangeOverlap:
548 // This declaration overlaps the region of interest; visit it.
549 break;
550 }
551 }
552 return true;
553}
554
555bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
556 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
557
558 // FIXME: Eventually remove. This part of a hack to support proper
559 // iteration over all Decls contained lexically within an ObjC container.
560 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
561 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
562
563 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000564 Decl *D = *I;
565 if (D->getLexicalDeclContext() != DC)
566 continue;
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000567 CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
Argyrios Kyrtzidis1836db02012-02-04 01:04:58 +0000568
Argyrios Kyrtzidisc178d762012-08-28 00:04:23 +0000569 // Ignore synthesized ivars here, otherwise if we have something like:
570 // @synthesize prop = _prop;
571 // and '_prop' is not declared, we will encounter a '_prop' ivar before
572 // encountering the 'prop' synthesize declaration and we will think that
573 // we passed the region-of-interest.
574 if (ObjCIvarDecl *ivarD = dyn_cast<ObjCIvarDecl>(D)) {
575 if (ivarD->getSynthesize())
576 continue;
577 }
578
Argyrios Kyrtzidis1836db02012-02-04 01:04:58 +0000579 // FIXME: ObjCClassRef/ObjCProtocolRef for forward class/protocol
580 // declarations is a mismatch with the compiler semantics.
581 if (Cursor.kind == CXCursor_ObjCInterfaceDecl) {
582 ObjCInterfaceDecl *ID = cast<ObjCInterfaceDecl>(D);
583 if (!ID->isThisDeclarationADefinition())
584 Cursor = MakeCursorObjCClassRef(ID, ID->getLocation(), TU);
585
586 } else if (Cursor.kind == CXCursor_ObjCProtocolDecl) {
587 ObjCProtocolDecl *PD = cast<ObjCProtocolDecl>(D);
588 if (!PD->isThisDeclarationADefinition())
589 Cursor = MakeCursorObjCProtocolRef(PD, PD->getLocation(), TU);
590 }
591
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000592 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
593 if (!V.hasValue())
594 continue;
595 if (!V.getValue())
596 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000597 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000598 return true;
599 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000600 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000601}
602
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000603bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
604 llvm_unreachable("Translation units are visited directly by Visit()");
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000605}
606
Richard Smith162e1c12011-04-15 14:24:37 +0000607bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
608 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
609 return Visit(TSInfo->getTypeLoc());
610
611 return false;
612}
613
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000614bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
615 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
616 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000617
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000618 return false;
619}
620
621bool CursorVisitor::VisitTagDecl(TagDecl *D) {
622 return VisitDeclContext(D);
623}
624
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000625bool CursorVisitor::VisitClassTemplateSpecializationDecl(
626 ClassTemplateSpecializationDecl *D) {
627 bool ShouldVisitBody = false;
628 switch (D->getSpecializationKind()) {
629 case TSK_Undeclared:
630 case TSK_ImplicitInstantiation:
631 // Nothing to visit
632 return false;
633
634 case TSK_ExplicitInstantiationDeclaration:
635 case TSK_ExplicitInstantiationDefinition:
636 break;
637
638 case TSK_ExplicitSpecialization:
639 ShouldVisitBody = true;
640 break;
641 }
642
643 // Visit the template arguments used in the specialization.
644 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
645 TypeLoc TL = SpecType->getTypeLoc();
646 if (TemplateSpecializationTypeLoc *TSTLoc
647 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
648 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
649 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
650 return true;
651 }
652 }
653
654 if (ShouldVisitBody && VisitCXXRecordDecl(D))
655 return true;
656
657 return false;
658}
659
Douglas Gregor74dbe642010-08-31 19:31:58 +0000660bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
661 ClassTemplatePartialSpecializationDecl *D) {
662 // FIXME: Visit the "outer" template parameter lists on the TagDecl
663 // before visiting these template parameters.
664 if (VisitTemplateParameters(D->getTemplateParameters()))
665 return true;
666
667 // Visit the partial specialization arguments.
668 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
669 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
670 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
671 return true;
672
673 return VisitCXXRecordDecl(D);
674}
675
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000676bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000677 // Visit the default argument.
678 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
679 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
680 if (Visit(DefArg->getTypeLoc()))
681 return true;
682
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000683 return false;
684}
685
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000686bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
687 if (Expr *Init = D->getInitExpr())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000688 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000689 return false;
690}
691
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000692bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
693 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
694 if (Visit(TSInfo->getTypeLoc()))
695 return true;
696
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000697 // Visit the nested-name-specifier, if present.
698 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
699 if (VisitNestedNameSpecifierLoc(QualifierLoc))
700 return true;
701
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000702 return false;
703}
704
Douglas Gregora67e03f2010-09-09 21:42:20 +0000705/// \brief Compare two base or member initializers based on their source order.
Sean Huntcbb67482011-01-08 20:30:50 +0000706static int CompareCXXCtorInitializers(const void* Xp, const void *Yp) {
707 CXXCtorInitializer const * const *X
708 = static_cast<CXXCtorInitializer const * const *>(Xp);
709 CXXCtorInitializer const * const *Y
710 = static_cast<CXXCtorInitializer const * const *>(Yp);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000711
712 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
713 return -1;
714 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
715 return 1;
716 else
717 return 0;
718}
719
Douglas Gregorb1373d02010-01-20 20:59:29 +0000720bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000721 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
722 // Visit the function declaration's syntactic components in the order
723 // written. This requires a bit of work.
Abramo Bagnara723df242010-12-14 22:11:44 +0000724 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
Douglas Gregor01829d32010-08-31 14:41:23 +0000725 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
726
727 // If we have a function declared directly (without the use of a typedef),
728 // visit just the return type. Otherwise, just visit the function's type
729 // now.
730 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
731 (!FTL && Visit(TL)))
732 return true;
733
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000734 // Visit the nested-name-specifier, if present.
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000735 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
736 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000737 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000738
739 // Visit the declaration name.
740 if (VisitDeclarationNameInfo(ND->getNameInfo()))
741 return true;
742
743 // FIXME: Visit explicitly-specified template arguments!
744
745 // Visit the function parameters, if we have a function type.
746 if (FTL && VisitFunctionTypeLoc(*FTL, true))
747 return true;
748
749 // FIXME: Attributes?
750 }
751
Sean Hunt10620eb2011-05-06 20:44:56 +0000752 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
Douglas Gregora67e03f2010-09-09 21:42:20 +0000753 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
754 // Find the initializers that were written in the source.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000755 SmallVector<CXXCtorInitializer *, 4> WrittenInits;
Douglas Gregora67e03f2010-09-09 21:42:20 +0000756 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
757 IEnd = Constructor->init_end();
758 I != IEnd; ++I) {
759 if (!(*I)->isWritten())
760 continue;
761
762 WrittenInits.push_back(*I);
763 }
764
765 // Sort the initializers in source order
766 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
Sean Huntcbb67482011-01-08 20:30:50 +0000767 &CompareCXXCtorInitializers);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000768
769 // Visit the initializers in source order
770 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
Sean Huntcbb67482011-01-08 20:30:50 +0000771 CXXCtorInitializer *Init = WrittenInits[I];
Francois Pichet00eb3f92010-12-04 09:14:42 +0000772 if (Init->isAnyMemberInitializer()) {
773 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
Douglas Gregora67e03f2010-09-09 21:42:20 +0000774 Init->getMemberLocation(), TU)))
775 return true;
Douglas Gregor76852c22011-11-01 01:16:03 +0000776 } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) {
777 if (Visit(TInfo->getTypeLoc()))
Douglas Gregora67e03f2010-09-09 21:42:20 +0000778 return true;
779 }
780
781 // Visit the initializer value.
782 if (Expr *Initializer = Init->getInit())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000783 if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
Douglas Gregora67e03f2010-09-09 21:42:20 +0000784 return true;
785 }
786 }
787
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000788 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
Douglas Gregora67e03f2010-09-09 21:42:20 +0000789 return true;
790 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000791
Douglas Gregorb1373d02010-01-20 20:59:29 +0000792 return false;
793}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000794
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000795bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
796 if (VisitDeclaratorDecl(D))
797 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000798
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000799 if (Expr *BitWidth = D->getBitWidth())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000800 return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000801
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000802 return false;
803}
804
805bool CursorVisitor::VisitVarDecl(VarDecl *D) {
806 if (VisitDeclaratorDecl(D))
807 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000808
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000809 if (Expr *Init = D->getInit())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000810 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000811
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000812 return false;
813}
814
Douglas Gregor84b51d72010-09-01 20:16:53 +0000815bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
816 if (VisitDeclaratorDecl(D))
817 return true;
818
819 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
820 if (Expr *DefArg = D->getDefaultArgument())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000821 return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
Douglas Gregor84b51d72010-09-01 20:16:53 +0000822
823 return false;
824}
825
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000826bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
827 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
828 // before visiting these template parameters.
829 if (VisitTemplateParameters(D->getTemplateParameters()))
830 return true;
831
832 return VisitFunctionDecl(D->getTemplatedDecl());
833}
834
Douglas Gregor39d6f072010-08-31 19:02:00 +0000835bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
836 // FIXME: Visit the "outer" template parameter lists on the TagDecl
837 // before visiting these template parameters.
838 if (VisitTemplateParameters(D->getTemplateParameters()))
839 return true;
840
841 return VisitCXXRecordDecl(D->getTemplatedDecl());
842}
843
Douglas Gregor84b51d72010-09-01 20:16:53 +0000844bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
845 if (VisitTemplateParameters(D->getTemplateParameters()))
846 return true;
847
848 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
849 VisitTemplateArgumentLoc(D->getDefaultArgument()))
850 return true;
851
852 return false;
853}
854
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000855bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000856 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
857 if (Visit(TSInfo->getTypeLoc()))
858 return true;
859
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000860 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000861 PEnd = ND->param_end();
862 P != PEnd; ++P) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000863 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000864 return true;
865 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000866
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000867 if (ND->isThisDeclarationADefinition() &&
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000868 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000869 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000870
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000871 return false;
872}
873
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +0000874template <typename DeclIt>
875static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current,
876 SourceManager &SM, SourceLocation EndLoc,
877 SmallVectorImpl<Decl *> &Decls) {
878 DeclIt next = *DI_current;
879 while (++next != DE_current) {
880 Decl *D_next = *next;
881 if (!D_next)
882 break;
883 SourceLocation L = D_next->getLocStart();
884 if (!L.isValid())
885 break;
886 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
887 *DI_current = next;
888 Decls.push_back(D_next);
889 continue;
890 }
891 break;
892 }
893}
894
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000895namespace {
896 struct ContainerDeclsSort {
897 SourceManager &SM;
898 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
899 bool operator()(Decl *A, Decl *B) {
900 SourceLocation L_A = A->getLocStart();
901 SourceLocation L_B = B->getLocStart();
902 assert(L_A.isValid() && L_B.isValid());
903 return SM.isBeforeInTranslationUnit(L_A, L_B);
904 }
905 };
906}
907
Douglas Gregora59e3902010-01-21 23:27:09 +0000908bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000909 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
910 // an @implementation can lexically contain Decls that are not properly
911 // nested in the AST. When we identify such cases, we need to retrofit
912 // this nesting here.
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +0000913 if (!DI_current && !FileDI_current)
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000914 return VisitDeclContext(D);
915
916 // Scan the Decls that immediately come after the container
917 // in the current DeclContext. If any fall within the
918 // container's lexical region, stash them into a vector
919 // for later processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000920 SmallVector<Decl *, 24> DeclsInContainer;
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000921 SourceLocation EndLoc = D->getSourceRange().getEnd();
Ted Kremeneka60ed472010-11-16 08:15:36 +0000922 SourceManager &SM = AU->getSourceManager();
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000923 if (EndLoc.isValid()) {
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +0000924 if (DI_current) {
925 addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc,
926 DeclsInContainer);
927 } else {
928 addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc,
929 DeclsInContainer);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000930 }
931 }
932
933 // The common case.
934 if (DeclsInContainer.empty())
935 return VisitDeclContext(D);
936
937 // Get all the Decls in the DeclContext, and sort them with the
938 // additional ones we've collected. Then visit them.
939 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
940 I!=E; ++I) {
941 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000942 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
943 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000944 continue;
945 DeclsInContainer.push_back(subDecl);
946 }
947
948 // Now sort the Decls so that they appear in lexical order.
949 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
950 ContainerDeclsSort(SM));
951
952 // Now visit the decls.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000953 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000954 E = DeclsInContainer.end(); I != E; ++I) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000955 CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000956 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
957 if (!V.hasValue())
958 continue;
959 if (!V.getValue())
960 return false;
961 if (Visit(Cursor, true))
962 return true;
963 }
964 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000965}
966
Douglas Gregorb1373d02010-01-20 20:59:29 +0000967bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000968 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
969 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000970 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000971
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000972 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
973 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
974 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000975 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000976 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000977
Douglas Gregora59e3902010-01-21 23:27:09 +0000978 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000979}
980
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000981bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000982 if (!PID->isThisDeclarationADefinition())
983 return Visit(MakeCursorObjCProtocolRef(PID, PID->getLocation(), TU));
984
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000985 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
986 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
987 E = PID->protocol_end(); I != E; ++I, ++PL)
988 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
989 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000990
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000991 return VisitObjCContainerDecl(PID);
992}
993
Ted Kremenek23173d72010-05-18 21:09:07 +0000994bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000995 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000996 return true;
997
Ted Kremenek23173d72010-05-18 21:09:07 +0000998 // FIXME: This implements a workaround with @property declarations also being
999 // installed in the DeclContext for the @interface. Eventually this code
1000 // should be removed.
1001 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
1002 if (!CDecl || !CDecl->IsClassExtension())
1003 return false;
1004
1005 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
1006 if (!ID)
1007 return false;
1008
1009 IdentifierInfo *PropertyId = PD->getIdentifier();
1010 ObjCPropertyDecl *prevDecl =
1011 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
1012
1013 if (!prevDecl)
1014 return false;
1015
1016 // Visit synthesized methods since they will be skipped when visiting
1017 // the @interface.
1018 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +00001019 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001020 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
Ted Kremenek23173d72010-05-18 21:09:07 +00001021 return true;
1022
1023 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
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 return false;
1029}
1030
Douglas Gregorb1373d02010-01-20 20:59:29 +00001031bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Douglas Gregor375bb142011-12-27 22:43:10 +00001032 if (!D->isThisDeclarationADefinition()) {
1033 // Forward declaration is treated like a reference.
1034 return Visit(MakeCursorObjCClassRef(D, D->getLocation(), TU));
1035 }
1036
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001037 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +00001038 if (D->getSuperClass() &&
1039 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001040 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001041 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001042 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001043
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001044 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1045 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1046 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001047 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001048 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001049
Douglas Gregora59e3902010-01-21 23:27:09 +00001050 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001051}
1052
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001053bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1054 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001055}
1056
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001057bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +00001058 // 'ID' could be null when dealing with invalid code.
1059 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1060 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1061 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001062
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001063 return VisitObjCImplDecl(D);
1064}
1065
1066bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1067#if 0
1068 // Issue callbacks for super class.
1069 // FIXME: No source location information!
1070 if (D->getSuperClass() &&
1071 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001072 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001073 TU)))
1074 return true;
1075#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001076
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001077 return VisitObjCImplDecl(D);
1078}
1079
Douglas Gregora4ffd852010-11-17 01:03:52 +00001080bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1081 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
Argyrios Kyrtzidis135bf8e2012-06-09 03:03:02 +00001082 if (PD->isIvarNameSpecified())
1083 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
Douglas Gregora4ffd852010-11-17 01:03:52 +00001084
1085 return false;
1086}
1087
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001088bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1089 return VisitDeclContext(D);
1090}
1091
Douglas Gregor69319002010-08-31 23:48:11 +00001092bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001093 // Visit nested-name-specifier.
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00001094 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1095 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001096 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001097
1098 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1099 D->getTargetNameLoc(), TU));
1100}
1101
Douglas Gregor7e242562010-09-01 19:52:22 +00001102bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001103 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001104 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1105 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001106 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001107 }
Douglas Gregor7e242562010-09-01 19:52:22 +00001108
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001109 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1110 return true;
1111
Douglas Gregor7e242562010-09-01 19:52:22 +00001112 return VisitDeclarationNameInfo(D->getNameInfo());
1113}
1114
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001115bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001116 // Visit nested-name-specifier.
Douglas Gregordb992412011-02-25 16:33:46 +00001117 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1118 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001119 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001120
1121 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1122 D->getIdentLocation(), TU));
1123}
1124
Douglas Gregor7e242562010-09-01 19:52:22 +00001125bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001126 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001127 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1128 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001129 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001130 }
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001131
Douglas Gregor7e242562010-09-01 19:52:22 +00001132 return VisitDeclarationNameInfo(D->getNameInfo());
1133}
1134
1135bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1136 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001137 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001138 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1139 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001140 return true;
1141
Douglas Gregor7e242562010-09-01 19:52:22 +00001142 return false;
1143}
1144
Douglas Gregor01829d32010-08-31 14:41:23 +00001145bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1146 switch (Name.getName().getNameKind()) {
1147 case clang::DeclarationName::Identifier:
1148 case clang::DeclarationName::CXXLiteralOperatorName:
1149 case clang::DeclarationName::CXXOperatorName:
1150 case clang::DeclarationName::CXXUsingDirective:
1151 return false;
1152
1153 case clang::DeclarationName::CXXConstructorName:
1154 case clang::DeclarationName::CXXDestructorName:
1155 case clang::DeclarationName::CXXConversionFunctionName:
1156 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1157 return Visit(TSInfo->getTypeLoc());
1158 return false;
1159
1160 case clang::DeclarationName::ObjCZeroArgSelector:
1161 case clang::DeclarationName::ObjCOneArgSelector:
1162 case clang::DeclarationName::ObjCMultiArgSelector:
1163 // FIXME: Per-identifier location info?
1164 return false;
1165 }
David Blaikie7530c032012-01-17 06:56:22 +00001166
1167 llvm_unreachable("Invalid DeclarationName::Kind!");
Douglas Gregor01829d32010-08-31 14:41:23 +00001168}
1169
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001170bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1171 SourceRange Range) {
1172 // FIXME: This whole routine is a hack to work around the lack of proper
1173 // source information in nested-name-specifiers (PR5791). Since we do have
1174 // a beginning source location, we can visit the first component of the
1175 // nested-name-specifier, if it's a single-token component.
1176 if (!NNS)
1177 return false;
1178
1179 // Get the first component in the nested-name-specifier.
1180 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1181 NNS = Prefix;
1182
1183 switch (NNS->getKind()) {
1184 case NestedNameSpecifier::Namespace:
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001185 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1186 TU));
1187
Douglas Gregor14aba762011-02-24 02:36:08 +00001188 case NestedNameSpecifier::NamespaceAlias:
1189 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1190 Range.getBegin(), TU));
1191
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001192 case NestedNameSpecifier::TypeSpec: {
1193 // If the type has a form where we know that the beginning of the source
1194 // range matches up with a reference cursor. Visit the appropriate reference
1195 // cursor.
John McCallf4c73712011-01-19 06:33:43 +00001196 const Type *T = NNS->getAsType();
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001197 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1198 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1199 if (const TagType *Tag = dyn_cast<TagType>(T))
1200 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1201 if (const TemplateSpecializationType *TST
1202 = dyn_cast<TemplateSpecializationType>(T))
1203 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1204 break;
1205 }
1206
1207 case NestedNameSpecifier::TypeSpecWithTemplate:
1208 case NestedNameSpecifier::Global:
1209 case NestedNameSpecifier::Identifier:
1210 break;
1211 }
1212
1213 return false;
1214}
1215
Douglas Gregordc355712011-02-25 00:36:19 +00001216bool
1217CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001218 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
Douglas Gregordc355712011-02-25 00:36:19 +00001219 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1220 Qualifiers.push_back(Qualifier);
1221
1222 while (!Qualifiers.empty()) {
1223 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1224 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1225 switch (NNS->getKind()) {
1226 case NestedNameSpecifier::Namespace:
1227 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001228 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001229 TU)))
1230 return true;
1231
1232 break;
1233
1234 case NestedNameSpecifier::NamespaceAlias:
1235 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001236 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001237 TU)))
1238 return true;
1239
1240 break;
1241
1242 case NestedNameSpecifier::TypeSpec:
1243 case NestedNameSpecifier::TypeSpecWithTemplate:
1244 if (Visit(Q.getTypeLoc()))
1245 return true;
1246
1247 break;
1248
1249 case NestedNameSpecifier::Global:
1250 case NestedNameSpecifier::Identifier:
1251 break;
1252 }
1253 }
1254
1255 return false;
1256}
1257
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001258bool CursorVisitor::VisitTemplateParameters(
1259 const TemplateParameterList *Params) {
1260 if (!Params)
1261 return false;
1262
1263 for (TemplateParameterList::const_iterator P = Params->begin(),
1264 PEnd = Params->end();
1265 P != PEnd; ++P) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001266 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001267 return true;
1268 }
1269
1270 return false;
1271}
1272
Douglas Gregor0b36e612010-08-31 20:37:03 +00001273bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1274 switch (Name.getKind()) {
1275 case TemplateName::Template:
1276 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1277
1278 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001279 // Visit the overloaded template set.
1280 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1281 return true;
1282
Douglas Gregor0b36e612010-08-31 20:37:03 +00001283 return false;
1284
1285 case TemplateName::DependentTemplate:
1286 // FIXME: Visit nested-name-specifier.
1287 return false;
1288
1289 case TemplateName::QualifiedTemplate:
1290 // FIXME: Visit nested-name-specifier.
1291 return Visit(MakeCursorTemplateRef(
1292 Name.getAsQualifiedTemplateName()->getDecl(),
1293 Loc, TU));
John McCall14606042011-06-30 08:33:18 +00001294
1295 case TemplateName::SubstTemplateTemplateParm:
1296 return Visit(MakeCursorTemplateRef(
1297 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1298 Loc, TU));
Douglas Gregor1aee05d2011-01-15 06:45:20 +00001299
1300 case TemplateName::SubstTemplateTemplateParmPack:
1301 return Visit(MakeCursorTemplateRef(
1302 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1303 Loc, TU));
Douglas Gregor0b36e612010-08-31 20:37:03 +00001304 }
David Blaikie7530c032012-01-17 06:56:22 +00001305
1306 llvm_unreachable("Invalid TemplateName::Kind!");
Douglas Gregor0b36e612010-08-31 20:37:03 +00001307}
1308
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001309bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1310 switch (TAL.getArgument().getKind()) {
1311 case TemplateArgument::Null:
1312 case TemplateArgument::Integral:
Douglas Gregor87dd6972010-12-20 16:52:59 +00001313 case TemplateArgument::Pack:
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001314 return false;
1315
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001316 case TemplateArgument::Type:
1317 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1318 return Visit(TSInfo->getTypeLoc());
1319 return false;
1320
1321 case TemplateArgument::Declaration:
1322 if (Expr *E = TAL.getSourceDeclExpression())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001323 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001324 return false;
1325
1326 case TemplateArgument::Expression:
1327 if (Expr *E = TAL.getSourceExpression())
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;
1330
1331 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001332 case TemplateArgument::TemplateExpansion:
Douglas Gregorb6744ef2011-03-02 17:09:35 +00001333 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1334 return true;
1335
Douglas Gregora7fc9012011-01-05 18:58:31 +00001336 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
Douglas Gregor0b36e612010-08-31 20:37:03 +00001337 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001338 }
David Blaikie7530c032012-01-17 06:56:22 +00001339
1340 llvm_unreachable("Invalid TemplateArgument::Kind!");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001341}
1342
Ted Kremeneka0536d82010-05-07 01:04:29 +00001343bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1344 return VisitDeclContext(D);
1345}
1346
Douglas Gregor01829d32010-08-31 14:41:23 +00001347bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1348 return Visit(TL.getUnqualifiedLoc());
1349}
1350
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001351bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00001352 ASTContext &Context = AU->getASTContext();
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001353
1354 // Some builtin types (such as Objective-C's "id", "sel", and
1355 // "Class") have associated declarations. Create cursors for those.
1356 QualType VisitType;
John McCalle0a22d02011-10-18 21:02:43 +00001357 switch (TL.getTypePtr()->getKind()) {
John McCall2dde35b2011-10-18 22:28:37 +00001358
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001359 case BuiltinType::Void:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001360 case BuiltinType::NullPtr:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001361 case BuiltinType::Dependent:
John McCall2dde35b2011-10-18 22:28:37 +00001362#define BUILTIN_TYPE(Id, SingletonId)
1363#define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1364#define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1365#define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
1366#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
1367#include "clang/AST/BuiltinTypes.def"
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001368 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001369
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001370 case BuiltinType::ObjCId:
1371 VisitType = Context.getObjCIdType();
1372 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001373
1374 case BuiltinType::ObjCClass:
1375 VisitType = Context.getObjCClassType();
1376 break;
1377
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001378 case BuiltinType::ObjCSel:
1379 VisitType = Context.getObjCSelType();
1380 break;
1381 }
1382
1383 if (!VisitType.isNull()) {
1384 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001385 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001386 TU));
1387 }
1388
1389 return false;
1390}
1391
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001392bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
Richard Smith162e1c12011-04-15 14:24:37 +00001393 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001394}
1395
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001396bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1397 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1398}
1399
1400bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
Argyrios Kyrtzidis6f155de2011-08-25 22:24:47 +00001401 if (TL.isDefinition())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001402 return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
Argyrios Kyrtzidis6f155de2011-08-25 22:24:47 +00001403
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001404 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1405}
1406
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001407bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Chandler Carruth960d13d2011-05-01 09:53:37 +00001408 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001409}
1410
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001411bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1412 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1413 return true;
1414
John McCallc12c5bb2010-05-15 11:32:37 +00001415 return false;
1416}
1417
1418bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1419 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1420 return true;
1421
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001422 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1423 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1424 TU)))
1425 return true;
1426 }
1427
1428 return false;
1429}
1430
1431bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001432 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001433}
1434
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001435bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1436 return Visit(TL.getInnerLoc());
1437}
1438
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001439bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1440 return Visit(TL.getPointeeLoc());
1441}
1442
1443bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1444 return Visit(TL.getPointeeLoc());
1445}
1446
1447bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1448 return Visit(TL.getPointeeLoc());
1449}
1450
1451bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001452 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001453}
1454
1455bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001456 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001457}
1458
Argyrios Kyrtzidis3422fbc2011-08-15 18:44:43 +00001459bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1460 return Visit(TL.getModifiedLoc());
1461}
1462
Douglas Gregor01829d32010-08-31 14:41:23 +00001463bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1464 bool SkipResultType) {
1465 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001466 return true;
1467
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001468 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001469 if (Decl *D = TL.getArg(I))
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001470 if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001471 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001472
1473 return false;
1474}
1475
1476bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1477 if (Visit(TL.getElementLoc()))
1478 return true;
1479
1480 if (Expr *Size = TL.getSizeExpr())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001481 return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001482
1483 return false;
1484}
1485
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001486bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1487 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001488 // Visit the template name.
1489 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1490 TL.getTemplateNameLoc()))
1491 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001492
1493 // Visit the template arguments.
1494 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1495 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1496 return true;
1497
1498 return false;
1499}
1500
Douglas Gregor2332c112010-01-21 20:48:56 +00001501bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1502 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1503}
1504
1505bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1506 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1507 return Visit(TSInfo->getTypeLoc());
1508
1509 return false;
1510}
1511
Sean Huntca63c202011-05-24 22:41:36 +00001512bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1513 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1514 return Visit(TSInfo->getTypeLoc());
1515
1516 return false;
1517}
1518
Douglas Gregor2494dd02011-03-01 01:34:45 +00001519bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
1520 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1521 return true;
1522
1523 return false;
1524}
1525
Douglas Gregor94fdffa2011-03-01 20:11:18 +00001526bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1527 DependentTemplateSpecializationTypeLoc TL) {
1528 // Visit the nested-name-specifier, if there is one.
1529 if (TL.getQualifierLoc() &&
1530 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1531 return true;
1532
1533 // Visit the template arguments.
1534 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1535 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1536 return true;
1537
1538 return false;
1539}
1540
Douglas Gregor9e876872011-03-01 18:12:44 +00001541bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1542 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1543 return true;
1544
1545 return Visit(TL.getNamedTypeLoc());
1546}
1547
Douglas Gregor7536dd52010-12-20 02:24:11 +00001548bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1549 return Visit(TL.getPatternLoc());
1550}
1551
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +00001552bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1553 if (Expr *E = TL.getUnderlyingExpr())
1554 return Visit(MakeCXCursor(E, StmtParent, TU));
1555
1556 return false;
1557}
1558
1559bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1560 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1561}
1562
Eli Friedmanb001de72011-10-06 23:00:33 +00001563bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1564 return Visit(TL.getValueLoc());
1565}
1566
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +00001567#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1568bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1569 return Visit##PARENT##Loc(TL); \
1570}
1571
1572DEFAULT_TYPELOC_IMPL(Complex, Type)
1573DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1574DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1575DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1576DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
1577DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1578DEFAULT_TYPELOC_IMPL(Vector, Type)
1579DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1580DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1581DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1582DEFAULT_TYPELOC_IMPL(Record, TagType)
1583DEFAULT_TYPELOC_IMPL(Enum, TagType)
1584DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1585DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1586DEFAULT_TYPELOC_IMPL(Auto, Type)
1587
Ted Kremenek3064ef92010-08-27 21:34:58 +00001588bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001589 // Visit the nested-name-specifier, if present.
1590 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1591 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1592 return true;
1593
John McCall5e1cdac2011-10-07 06:10:15 +00001594 if (D->isCompleteDefinition()) {
Ted Kremenek3064ef92010-08-27 21:34:58 +00001595 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1596 E = D->bases_end(); I != E; ++I) {
1597 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1598 return true;
1599 }
1600 }
1601
1602 return VisitTagDecl(D);
1603}
1604
Ted Kremenek09dfa372010-02-18 05:46:33 +00001605bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001606 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1607 i != e; ++i)
1608 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001609 return true;
1610
1611 return false;
1612}
1613
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001614//===----------------------------------------------------------------------===//
1615// Data-recursive visitor methods.
1616//===----------------------------------------------------------------------===//
1617
Ted Kremenek28a71942010-11-13 00:36:47 +00001618namespace {
Ted Kremenek035dc412010-11-13 00:36:50 +00001619#define DEF_JOB(NAME, DATA, KIND)\
1620class NAME : public VisitorJob {\
1621public:\
1622 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1623 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Ted Kremenekf64d8032010-11-18 00:02:32 +00001624 DATA *get() const { return static_cast<DATA*>(data[0]); }\
Ted Kremenek035dc412010-11-13 00:36:50 +00001625};
1626
1627DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1628DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001629DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001630DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001631DEF_JOB(ExplicitTemplateArgsVisit, ASTTemplateArgumentListInfo,
Ted Kremenek60608ec2010-11-17 00:50:47 +00001632 ExplicitTemplateArgsVisitKind)
Douglas Gregor94d96292011-01-19 20:34:17 +00001633DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
Douglas Gregor011d8b92012-02-15 00:54:55 +00001634DEF_JOB(LambdaExprParts, LambdaExpr, LambdaExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001635#undef DEF_JOB
1636
1637class DeclVisit : public VisitorJob {
1638public:
1639 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1640 VisitorJob(parent, VisitorJob::DeclVisitKind,
1641 d, isFirst ? (void*) 1 : (void*) 0) {}
1642 static bool classof(const VisitorJob *VJ) {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001643 return VJ->getKind() == DeclVisitKind;
Ted Kremenek035dc412010-11-13 00:36:50 +00001644 }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001645 Decl *get() const { return static_cast<Decl*>(data[0]); }
1646 bool isFirst() const { return data[1] ? true : false; }
Ted Kremenek035dc412010-11-13 00:36:50 +00001647};
Ted Kremenek035dc412010-11-13 00:36:50 +00001648class TypeLocVisit : public VisitorJob {
1649public:
1650 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1651 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1652 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1653
1654 static bool classof(const VisitorJob *VJ) {
1655 return VJ->getKind() == TypeLocVisitKind;
1656 }
1657
Ted Kremenek82f3c502010-11-15 22:23:26 +00001658 TypeLoc get() const {
Ted Kremenekf64d8032010-11-18 00:02:32 +00001659 QualType T = QualType::getFromOpaquePtr(data[0]);
1660 return TypeLoc(T, data[1]);
Ted Kremenek035dc412010-11-13 00:36:50 +00001661 }
1662};
1663
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001664class LabelRefVisit : public VisitorJob {
1665public:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001666 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1667 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001668 labelLoc.getPtrEncoding()) {}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001669
1670 static bool classof(const VisitorJob *VJ) {
1671 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1672 }
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001673 LabelDecl *get() const { return static_cast<LabelDecl*>(data[0]); }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001674 SourceLocation getLoc() const {
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001675 return SourceLocation::getFromPtrEncoding(data[1]); }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001676};
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001677
1678class NestedNameSpecifierLocVisit : public VisitorJob {
1679public:
1680 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1681 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1682 Qualifier.getNestedNameSpecifier(),
1683 Qualifier.getOpaqueData()) { }
1684
1685 static bool classof(const VisitorJob *VJ) {
1686 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1687 }
1688
1689 NestedNameSpecifierLoc get() const {
1690 return NestedNameSpecifierLoc(static_cast<NestedNameSpecifier*>(data[0]),
1691 data[1]);
1692 }
1693};
1694
Ted Kremenekf64d8032010-11-18 00:02:32 +00001695class DeclarationNameInfoVisit : public VisitorJob {
1696public:
1697 DeclarationNameInfoVisit(Stmt *S, CXCursor parent)
1698 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
1699 static bool classof(const VisitorJob *VJ) {
1700 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1701 }
1702 DeclarationNameInfo get() const {
1703 Stmt *S = static_cast<Stmt*>(data[0]);
1704 switch (S->getStmtClass()) {
1705 default:
1706 llvm_unreachable("Unhandled Stmt");
Douglas Gregorba0513d2011-10-25 01:33:02 +00001707 case clang::Stmt::MSDependentExistsStmtClass:
1708 return cast<MSDependentExistsStmt>(S)->getNameInfo();
Ted Kremenekf64d8032010-11-18 00:02:32 +00001709 case Stmt::CXXDependentScopeMemberExprClass:
1710 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1711 case Stmt::DependentScopeDeclRefExprClass:
1712 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
1713 }
1714 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001715};
Ted Kremenekcdba6592010-11-18 00:42:18 +00001716class MemberRefVisit : public VisitorJob {
1717public:
1718 MemberRefVisit(FieldDecl *D, SourceLocation L, CXCursor parent)
1719 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001720 L.getPtrEncoding()) {}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001721 static bool classof(const VisitorJob *VJ) {
1722 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1723 }
1724 FieldDecl *get() const {
1725 return static_cast<FieldDecl*>(data[0]);
1726 }
1727 SourceLocation getLoc() const {
1728 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1729 }
1730};
Ted Kremenek28a71942010-11-13 00:36:47 +00001731class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1732 VisitorWorkList &WL;
1733 CXCursor Parent;
1734public:
1735 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1736 : WL(wl), Parent(parent) {}
1737
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001738 void VisitAddrLabelExpr(AddrLabelExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001739 void VisitBlockExpr(BlockExpr *B);
Ted Kremenek28a71942010-11-13 00:36:47 +00001740 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek083c7e22010-11-13 05:38:03 +00001741 void VisitCompoundStmt(CompoundStmt *S);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001742 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
Douglas Gregorba0513d2011-10-25 01:33:02 +00001743 void VisitMSDependentExistsStmt(MSDependentExistsStmt *S);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001744 void VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001745 void VisitCXXNewExpr(CXXNewExpr *E);
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001746 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001747 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001748 void VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001749 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001750 void VisitCXXTypeidExpr(CXXTypeidExpr *E);
Ted Kremenek55b933a2010-11-17 00:50:36 +00001751 void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001752 void VisitCXXUuidofExpr(CXXUuidofExpr *E);
Argyrios Kyrtzidisdcbb2fb2011-12-03 03:49:44 +00001753 void VisitCXXCatchStmt(CXXCatchStmt *S);
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001754 void VisitDeclRefExpr(DeclRefExpr *D);
Ted Kremenek035dc412010-11-13 00:36:50 +00001755 void VisitDeclStmt(DeclStmt *S);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001756 void VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001757 void VisitDesignatedInitExpr(DesignatedInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001758 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1759 void VisitForStmt(ForStmt *FS);
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001760 void VisitGotoStmt(GotoStmt *GS);
Ted Kremenek28a71942010-11-13 00:36:47 +00001761 void VisitIfStmt(IfStmt *If);
1762 void VisitInitListExpr(InitListExpr *IE);
1763 void VisitMemberExpr(MemberExpr *M);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001764 void VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001765 void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001766 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1767 void VisitOverloadExpr(OverloadExpr *E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001768 void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001769 void VisitStmt(Stmt *S);
1770 void VisitSwitchStmt(SwitchStmt *S);
1771 void VisitWhileStmt(WhileStmt *W);
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001772 void VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Francois Pichet6ad6f282010-12-07 00:08:36 +00001773 void VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E);
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00001774 void VisitTypeTraitExpr(TypeTraitExpr *E);
John Wiegley21ff2e52011-04-28 00:16:57 +00001775 void VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E);
John Wiegley55262202011-04-25 06:54:41 +00001776 void VisitExpressionTraitExpr(ExpressionTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001777 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001778 void VisitVAArgExpr(VAArgExpr *E);
Douglas Gregor94d96292011-01-19 20:34:17 +00001779 void VisitSizeOfPackExpr(SizeOfPackExpr *E);
John McCall4b9c2d22011-11-06 09:01:30 +00001780 void VisitPseudoObjectExpr(PseudoObjectExpr *E);
1781 void VisitOpaqueValueExpr(OpaqueValueExpr *E);
Douglas Gregor011d8b92012-02-15 00:54:55 +00001782 void VisitLambdaExpr(LambdaExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00001783
Ted Kremenek28a71942010-11-13 00:36:47 +00001784private:
Ted Kremenekf64d8032010-11-18 00:02:32 +00001785 void AddDeclarationNameInfo(Stmt *S);
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001786 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001787 void AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001788 void AddMemberRef(FieldDecl *D, SourceLocation L);
Ted Kremenek28a71942010-11-13 00:36:47 +00001789 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001790 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001791 void AddTypeLoc(TypeSourceInfo *TI);
1792 void EnqueueChildren(Stmt *S);
1793};
1794} // end anonyous namespace
1795
Ted Kremenekf64d8032010-11-18 00:02:32 +00001796void EnqueueVisitor::AddDeclarationNameInfo(Stmt *S) {
1797 // 'S' should always be non-null, since it comes from the
1798 // statement we are visiting.
1799 WL.push_back(DeclarationNameInfoVisit(S, Parent));
1800}
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001801
1802void
1803EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1804 if (Qualifier)
1805 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
1806}
1807
Ted Kremenek28a71942010-11-13 00:36:47 +00001808void EnqueueVisitor::AddStmt(Stmt *S) {
1809 if (S)
1810 WL.push_back(StmtVisit(S, Parent));
1811}
Ted Kremenek035dc412010-11-13 00:36:50 +00001812void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001813 if (D)
Ted Kremenek035dc412010-11-13 00:36:50 +00001814 WL.push_back(DeclVisit(D, Parent, isFirst));
Ted Kremenek28a71942010-11-13 00:36:47 +00001815}
Ted Kremenek60608ec2010-11-17 00:50:47 +00001816void EnqueueVisitor::
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001817 AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001818 if (A)
1819 WL.push_back(ExplicitTemplateArgsVisit(
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001820 const_cast<ASTTemplateArgumentListInfo*>(A), Parent));
Ted Kremenek60608ec2010-11-17 00:50:47 +00001821}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001822void EnqueueVisitor::AddMemberRef(FieldDecl *D, SourceLocation L) {
1823 if (D)
1824 WL.push_back(MemberRefVisit(D, L, Parent));
1825}
Ted Kremenek28a71942010-11-13 00:36:47 +00001826void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1827 if (TI)
1828 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1829 }
1830void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001831 unsigned size = WL.size();
John McCall7502c1d2011-02-13 04:07:26 +00001832 for (Stmt::child_range Child = S->children(); Child; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001833 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001834 }
1835 if (size == WL.size())
1836 return;
1837 // Now reverse the entries we just added. This will match the DFS
1838 // ordering performed by the worklist.
1839 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1840 std::reverse(I, E);
1841}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001842void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1843 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
1844}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001845void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1846 AddDecl(B->getBlockDecl());
1847}
Ted Kremenek28a71942010-11-13 00:36:47 +00001848void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1849 EnqueueChildren(E);
1850 AddTypeLoc(E->getTypeSourceInfo());
1851}
Ted Kremenek083c7e22010-11-13 05:38:03 +00001852void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1853 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1854 E = S->body_rend(); I != E; ++I) {
1855 AddStmt(*I);
1856 }
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001857}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001858void EnqueueVisitor::
Douglas Gregorba0513d2011-10-25 01:33:02 +00001859VisitMSDependentExistsStmt(MSDependentExistsStmt *S) {
1860 AddStmt(S->getSubStmt());
1861 AddDeclarationNameInfo(S);
1862 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
1863 AddNestedNameSpecifierLoc(QualifierLoc);
1864}
1865
1866void EnqueueVisitor::
Ted Kremenekf64d8032010-11-18 00:02:32 +00001867VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
1868 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1869 AddDeclarationNameInfo(E);
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001870 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1871 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001872 if (!E->isImplicitAccess())
1873 AddStmt(E->getBase());
1874}
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001875void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001876 // Enqueue the initializer , if any.
1877 AddStmt(E->getInitializer());
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001878 // Enqueue the array size, if any.
1879 AddStmt(E->getArraySize());
1880 // Enqueue the allocated type.
1881 AddTypeLoc(E->getAllocatedTypeSourceInfo());
1882 // Enqueue the placement arguments.
1883 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1884 AddStmt(E->getPlacementArg(I-1));
1885}
Ted Kremenek28a71942010-11-13 00:36:47 +00001886void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
Ted Kremenek8b8d8c92010-11-13 05:55:56 +00001887 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1888 AddStmt(CE->getArg(I-1));
Ted Kremenek28a71942010-11-13 00:36:47 +00001889 AddStmt(CE->getCallee());
1890 AddStmt(CE->getArg(0));
1891}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001892void EnqueueVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1893 // Visit the name of the type being destroyed.
1894 AddTypeLoc(E->getDestroyedTypeInfo());
1895 // Visit the scope type that looks disturbingly like the nested-name-specifier
1896 // but isn't.
1897 AddTypeLoc(E->getScopeTypeInfo());
1898 // Visit the nested-name-specifier.
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001899 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1900 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001901 // Visit base expression.
1902 AddStmt(E->getBase());
1903}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001904void EnqueueVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1905 AddTypeLoc(E->getTypeSourceInfo());
1906}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001907void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1908 EnqueueChildren(E);
1909 AddTypeLoc(E->getTypeSourceInfo());
1910}
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001911void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1912 EnqueueChildren(E);
1913 if (E->isTypeOperand())
1914 AddTypeLoc(E->getTypeOperandSourceInfo());
1915}
Ted Kremenek55b933a2010-11-17 00:50:36 +00001916
1917void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
1918 *E) {
1919 EnqueueChildren(E);
1920 AddTypeLoc(E->getTypeSourceInfo());
1921}
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001922void EnqueueVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1923 EnqueueChildren(E);
1924 if (E->isTypeOperand())
1925 AddTypeLoc(E->getTypeOperandSourceInfo());
1926}
Argyrios Kyrtzidisdcbb2fb2011-12-03 03:49:44 +00001927
1928void EnqueueVisitor::VisitCXXCatchStmt(CXXCatchStmt *S) {
1929 EnqueueChildren(S);
1930 AddDecl(S->getExceptionDecl());
1931}
1932
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001933void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001934 if (DR->hasExplicitTemplateArgs()) {
1935 AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
1936 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001937 WL.push_back(DeclRefExprParts(DR, Parent));
1938}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001939void EnqueueVisitor::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
1940 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1941 AddDeclarationNameInfo(E);
Douglas Gregor00cf3cc2011-02-25 20:49:16 +00001942 AddNestedNameSpecifierLoc(E->getQualifierLoc());
Ted Kremenekf64d8032010-11-18 00:02:32 +00001943}
Ted Kremenek035dc412010-11-13 00:36:50 +00001944void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1945 unsigned size = WL.size();
1946 bool isFirst = true;
1947 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1948 D != DEnd; ++D) {
1949 AddDecl(*D, isFirst);
1950 isFirst = false;
1951 }
1952 if (size == WL.size())
1953 return;
1954 // Now reverse the entries we just added. This will match the DFS
1955 // ordering performed by the worklist.
1956 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1957 std::reverse(I, E);
1958}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001959void EnqueueVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1960 AddStmt(E->getInit());
1961 typedef DesignatedInitExpr::Designator Designator;
1962 for (DesignatedInitExpr::reverse_designators_iterator
1963 D = E->designators_rbegin(), DEnd = E->designators_rend();
1964 D != DEnd; ++D) {
1965 if (D->isFieldDesignator()) {
1966 if (FieldDecl *Field = D->getField())
1967 AddMemberRef(Field, D->getFieldLoc());
1968 continue;
1969 }
1970 if (D->isArrayDesignator()) {
1971 AddStmt(E->getArrayIndex(*D));
1972 continue;
1973 }
1974 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1975 AddStmt(E->getArrayRangeEnd(*D));
1976 AddStmt(E->getArrayRangeStart(*D));
1977 }
1978}
Ted Kremenek28a71942010-11-13 00:36:47 +00001979void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1980 EnqueueChildren(E);
1981 AddTypeLoc(E->getTypeInfoAsWritten());
1982}
1983void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1984 AddStmt(FS->getBody());
1985 AddStmt(FS->getInc());
1986 AddStmt(FS->getCond());
1987 AddDecl(FS->getConditionVariable());
1988 AddStmt(FS->getInit());
1989}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001990void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) {
1991 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
1992}
Ted Kremenek28a71942010-11-13 00:36:47 +00001993void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
1994 AddStmt(If->getElse());
1995 AddStmt(If->getThen());
1996 AddStmt(If->getCond());
1997 AddDecl(If->getConditionVariable());
1998}
1999void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
2000 // We care about the syntactic form of the initializer list, only.
2001 if (InitListExpr *Syntactic = IE->getSyntacticForm())
2002 IE = Syntactic;
2003 EnqueueChildren(IE);
2004}
2005void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
Douglas Gregor89629a72010-11-17 17:15:08 +00002006 WL.push_back(MemberExprParts(M, Parent));
2007
2008 // If the base of the member access expression is an implicit 'this', don't
2009 // visit it.
2010 // FIXME: If we ever want to show these implicit accesses, this will be
2011 // unfortunate. However, clang_getCursor() relies on this behavior.
Douglas Gregor75e85042011-03-02 21:06:53 +00002012 if (!M->isImplicitAccess())
2013 AddStmt(M->getBase());
Ted Kremenek28a71942010-11-13 00:36:47 +00002014}
Ted Kremenek73d15c42010-11-13 01:09:29 +00002015void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
2016 AddTypeLoc(E->getEncodedTypeSourceInfo());
2017}
Ted Kremenek28a71942010-11-13 00:36:47 +00002018void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
2019 EnqueueChildren(M);
2020 AddTypeLoc(M->getClassReceiverTypeInfo());
2021}
Ted Kremenekcdba6592010-11-18 00:42:18 +00002022void EnqueueVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
2023 // Visit the components of the offsetof expression.
2024 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
2025 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
2026 const OffsetOfNode &Node = E->getComponent(I-1);
2027 switch (Node.getKind()) {
2028 case OffsetOfNode::Array:
2029 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2030 break;
2031 case OffsetOfNode::Field:
Abramo Bagnara06dec892011-03-12 09:45:03 +00002032 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
Ted Kremenekcdba6592010-11-18 00:42:18 +00002033 break;
2034 case OffsetOfNode::Identifier:
2035 case OffsetOfNode::Base:
2036 continue;
2037 }
2038 }
2039 // Visit the type into which we're computing the offset.
2040 AddTypeLoc(E->getTypeSourceInfo());
2041}
Ted Kremenek28a71942010-11-13 00:36:47 +00002042void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00002043 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
Ted Kremenek60458782010-11-12 21:34:16 +00002044 WL.push_back(OverloadExprParts(E, Parent));
2045}
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002046void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
2047 UnaryExprOrTypeTraitExpr *E) {
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00002048 EnqueueChildren(E);
2049 if (E->isArgumentType())
2050 AddTypeLoc(E->getArgumentTypeInfo());
2051}
Ted Kremenek28a71942010-11-13 00:36:47 +00002052void EnqueueVisitor::VisitStmt(Stmt *S) {
2053 EnqueueChildren(S);
2054}
2055void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
2056 AddStmt(S->getBody());
2057 AddStmt(S->getCond());
2058 AddDecl(S->getConditionVariable());
2059}
Ted Kremenekfafa75a2010-11-17 00:50:39 +00002060
Ted Kremenek28a71942010-11-13 00:36:47 +00002061void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
2062 AddStmt(W->getBody());
2063 AddStmt(W->getCond());
2064 AddDecl(W->getConditionVariable());
2065}
John Wiegley21ff2e52011-04-28 00:16:57 +00002066
Ted Kremenek2939b6f2010-11-17 00:50:50 +00002067void EnqueueVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
2068 AddTypeLoc(E->getQueriedTypeSourceInfo());
2069}
Francois Pichet6ad6f282010-12-07 00:08:36 +00002070
2071void EnqueueVisitor::VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
Francois Pichet6ad6f282010-12-07 00:08:36 +00002072 AddTypeLoc(E->getRhsTypeSourceInfo());
Francois Pichet0a03a3f2010-12-08 09:11:05 +00002073 AddTypeLoc(E->getLhsTypeSourceInfo());
Francois Pichet6ad6f282010-12-07 00:08:36 +00002074}
2075
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00002076void EnqueueVisitor::VisitTypeTraitExpr(TypeTraitExpr *E) {
2077 for (unsigned I = E->getNumArgs(); I > 0; --I)
2078 AddTypeLoc(E->getArg(I-1));
2079}
2080
John Wiegley21ff2e52011-04-28 00:16:57 +00002081void EnqueueVisitor::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
2082 AddTypeLoc(E->getQueriedTypeSourceInfo());
2083}
2084
John Wiegley55262202011-04-25 06:54:41 +00002085void EnqueueVisitor::VisitExpressionTraitExpr(ExpressionTraitExpr *E) {
2086 EnqueueChildren(E);
2087}
2088
Ted Kremenek28a71942010-11-13 00:36:47 +00002089void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
2090 VisitOverloadExpr(U);
2091 if (!U->isImplicitAccess())
2092 AddStmt(U->getBase());
2093}
Ted Kremenek9d3bf792010-11-17 00:50:43 +00002094void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) {
2095 AddStmt(E->getSubExpr());
2096 AddTypeLoc(E->getWrittenTypeInfo());
2097}
Douglas Gregor94d96292011-01-19 20:34:17 +00002098void EnqueueVisitor::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
2099 WL.push_back(SizeOfPackExprParts(E, Parent));
2100}
John McCall4b9c2d22011-11-06 09:01:30 +00002101void EnqueueVisitor::VisitOpaqueValueExpr(OpaqueValueExpr *E) {
2102 // If the opaque value has a source expression, just transparently
2103 // visit that. This is useful for (e.g.) pseudo-object expressions.
2104 if (Expr *SourceExpr = E->getSourceExpr())
2105 return Visit(SourceExpr);
John McCall4b9c2d22011-11-06 09:01:30 +00002106}
Douglas Gregor011d8b92012-02-15 00:54:55 +00002107void EnqueueVisitor::VisitLambdaExpr(LambdaExpr *E) {
2108 AddStmt(E->getBody());
2109 WL.push_back(LambdaExprParts(E, Parent));
2110}
John McCall4b9c2d22011-11-06 09:01:30 +00002111void EnqueueVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *E) {
2112 // Treat the expression like its syntactic form.
2113 Visit(E->getSyntacticForm());
2114}
Ted Kremenek60458782010-11-12 21:34:16 +00002115
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002116void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002117 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002118}
2119
2120bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2121 if (RegionOfInterest.isValid()) {
2122 SourceRange Range = getRawCursorExtent(C);
2123 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2124 return false;
2125 }
2126 return true;
2127}
2128
2129bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2130 while (!WL.empty()) {
2131 // Dequeue the worklist item.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002132 VisitorJob LI = WL.back();
2133 WL.pop_back();
2134
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002135 // Set the Parent field, then back to its old value once we're done.
2136 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2137
2138 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00002139 case VisitorJob::DeclVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002140 Decl *D = cast<DeclVisit>(&LI)->get();
Ted Kremenekf1107452010-11-12 18:26:56 +00002141 if (!D)
2142 continue;
2143
2144 // For now, perform default visitation for Decls.
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002145 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2146 cast<DeclVisit>(&LI)->isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00002147 return true;
2148
2149 continue;
2150 }
Ted Kremenek60608ec2010-11-17 00:50:47 +00002151 case VisitorJob::ExplicitTemplateArgsVisitKind: {
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00002152 const ASTTemplateArgumentListInfo *ArgList =
Ted Kremenek60608ec2010-11-17 00:50:47 +00002153 cast<ExplicitTemplateArgsVisit>(&LI)->get();
2154 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2155 *ArgEnd = Arg + ArgList->NumTemplateArgs;
2156 Arg != ArgEnd; ++Arg) {
2157 if (VisitTemplateArgumentLoc(*Arg))
2158 return true;
2159 }
2160 continue;
2161 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002162 case VisitorJob::TypeLocVisitKind: {
2163 // Perform default visitation for TypeLocs.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002164 if (Visit(cast<TypeLocVisit>(&LI)->get()))
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002165 return true;
2166 continue;
2167 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002168 case VisitorJob::LabelRefVisitKind: {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002169 LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Ted Kremeneke7455012011-02-23 04:54:51 +00002170 if (LabelStmt *stmt = LS->getStmt()) {
2171 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2172 TU))) {
2173 return true;
2174 }
2175 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002176 continue;
2177 }
Ted Kremenek47695c82011-08-18 22:25:21 +00002178
Douglas Gregorf3db29f2011-02-25 18:19:59 +00002179 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2180 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2181 if (VisitNestedNameSpecifierLoc(V->get()))
2182 return true;
2183 continue;
2184 }
2185
Ted Kremenekf64d8032010-11-18 00:02:32 +00002186 case VisitorJob::DeclarationNameInfoVisitKind: {
2187 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2188 ->get()))
2189 return true;
2190 continue;
2191 }
Ted Kremenekcdba6592010-11-18 00:42:18 +00002192 case VisitorJob::MemberRefVisitKind: {
2193 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2194 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2195 return true;
2196 continue;
2197 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002198 case VisitorJob::StmtVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002199 Stmt *S = cast<StmtVisit>(&LI)->get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00002200 if (!S)
2201 continue;
2202
Ted Kremenekf1107452010-11-12 18:26:56 +00002203 // Update the current cursor.
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002204 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
Ted Kremenekcdba6592010-11-18 00:42:18 +00002205 if (!IsInRegionOfInterest(Cursor))
2206 continue;
2207 switch (Visitor(Cursor, Parent, ClientData)) {
2208 case CXChildVisit_Break: return true;
2209 case CXChildVisit_Continue: break;
2210 case CXChildVisit_Recurse:
2211 EnqueueWorkList(WL, S);
Ted Kremenek82f3c502010-11-15 22:23:26 +00002212 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002213 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00002214 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002215 }
2216 case VisitorJob::MemberExprPartsKind: {
2217 // Handle the other pieces in the MemberExpr besides the base.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002218 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002219
2220 // Visit the nested-name-specifier
Douglas Gregor40d96a62011-02-28 21:54:11 +00002221 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
2222 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002223 return true;
2224
2225 // Visit the declaration name.
2226 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2227 return true;
2228
2229 // Visit the explicitly-specified template arguments, if any.
2230 if (M->hasExplicitTemplateArgs()) {
2231 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2232 *ArgEnd = Arg + M->getNumTemplateArgs();
2233 Arg != ArgEnd; ++Arg) {
2234 if (VisitTemplateArgumentLoc(*Arg))
2235 return true;
2236 }
2237 }
2238 continue;
2239 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002240 case VisitorJob::DeclRefExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002241 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002242 // Visit nested-name-specifier, if present.
Douglas Gregor40d96a62011-02-28 21:54:11 +00002243 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
2244 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002245 return true;
2246 // Visit declaration name.
2247 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2248 return true;
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002249 continue;
2250 }
Ted Kremenek60458782010-11-12 21:34:16 +00002251 case VisitorJob::OverloadExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002252 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Ted Kremenek60458782010-11-12 21:34:16 +00002253 // Visit the nested-name-specifier.
Douglas Gregor4c9be892011-02-28 20:01:57 +00002254 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
2255 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenek60458782010-11-12 21:34:16 +00002256 return true;
2257 // Visit the declaration name.
2258 if (VisitDeclarationNameInfo(O->getNameInfo()))
2259 return true;
2260 // Visit the overloaded declaration reference.
2261 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2262 return true;
Ted Kremenek60458782010-11-12 21:34:16 +00002263 continue;
2264 }
Douglas Gregor94d96292011-01-19 20:34:17 +00002265 case VisitorJob::SizeOfPackExprPartsKind: {
2266 SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
2267 NamedDecl *Pack = E->getPack();
2268 if (isa<TemplateTypeParmDecl>(Pack)) {
2269 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
2270 E->getPackLoc(), TU)))
2271 return true;
2272
2273 continue;
2274 }
2275
2276 if (isa<TemplateTemplateParmDecl>(Pack)) {
2277 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
2278 E->getPackLoc(), TU)))
2279 return true;
2280
2281 continue;
2282 }
2283
2284 // Non-type template parameter packs and function parameter packs are
2285 // treated like DeclRefExpr cursors.
2286 continue;
2287 }
Douglas Gregor011d8b92012-02-15 00:54:55 +00002288
2289 case VisitorJob::LambdaExprPartsKind: {
2290 // Visit captures.
2291 LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
2292 for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
2293 CEnd = E->explicit_capture_end();
2294 C != CEnd; ++C) {
2295 if (C->capturesThis())
2296 continue;
2297
2298 if (Visit(MakeCursorVariableRef(C->getCapturedVar(),
2299 C->getLocation(),
2300 TU)))
2301 return true;
2302 }
2303
2304 // Visit parameters and return type, if present.
2305 if (E->hasExplicitParameters() || E->hasExplicitResultType()) {
2306 TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
2307 if (E->hasExplicitParameters() && E->hasExplicitResultType()) {
2308 // Visit the whole type.
2309 if (Visit(TL))
2310 return true;
2311 } else if (isa<FunctionProtoTypeLoc>(TL)) {
2312 FunctionProtoTypeLoc Proto = cast<FunctionProtoTypeLoc>(TL);
2313 if (E->hasExplicitParameters()) {
2314 // Visit parameters.
2315 for (unsigned I = 0, N = Proto.getNumArgs(); I != N; ++I)
2316 if (Visit(MakeCXCursor(Proto.getArg(I), TU)))
2317 return true;
2318 } else {
2319 // Visit result type.
2320 if (Visit(Proto.getResultLoc()))
2321 return true;
2322 }
2323 }
2324 }
2325 break;
2326 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002327 }
2328 }
2329 return false;
2330}
2331
Ted Kremenekcdba6592010-11-18 00:42:18 +00002332bool CursorVisitor::Visit(Stmt *S) {
Ted Kremenekd1ded662010-11-15 23:31:32 +00002333 VisitorWorkList *WL = 0;
2334 if (!WorkListFreeList.empty()) {
2335 WL = WorkListFreeList.back();
2336 WL->clear();
2337 WorkListFreeList.pop_back();
2338 }
2339 else {
2340 WL = new VisitorWorkList();
2341 WorkListCache.push_back(WL);
2342 }
2343 EnqueueWorkList(*WL, S);
2344 bool result = RunVisitorWorkList(*WL);
2345 WorkListFreeList.push_back(WL);
2346 return result;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002347}
2348
Francois Pichet48a8d142011-07-25 22:00:44 +00002349namespace {
2350typedef llvm::SmallVector<SourceRange, 4> RefNamePieces;
2351RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
2352 const DeclarationNameInfo &NI,
2353 const SourceRange &QLoc,
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00002354 const ASTTemplateArgumentListInfo *TemplateArgs = 0){
Francois Pichet48a8d142011-07-25 22:00:44 +00002355 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
2356 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
2357 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
2358
2359 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
2360
2361 RefNamePieces Pieces;
2362
2363 if (WantQualifier && QLoc.isValid())
2364 Pieces.push_back(QLoc);
2365
2366 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
2367 Pieces.push_back(NI.getLoc());
2368
2369 if (WantTemplateArgs && TemplateArgs)
2370 Pieces.push_back(SourceRange(TemplateArgs->LAngleLoc,
2371 TemplateArgs->RAngleLoc));
2372
2373 if (Kind == DeclarationName::CXXOperatorName) {
2374 Pieces.push_back(SourceLocation::getFromRawEncoding(
2375 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
2376 Pieces.push_back(SourceLocation::getFromRawEncoding(
2377 NI.getInfo().CXXOperatorName.EndOpNameLoc));
2378 }
2379
2380 if (WantSinglePiece) {
2381 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
2382 Pieces.clear();
2383 Pieces.push_back(R);
2384 }
2385
2386 return Pieces;
2387}
2388}
2389
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002390//===----------------------------------------------------------------------===//
2391// Misc. API hooks.
2392//===----------------------------------------------------------------------===//
2393
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002394static llvm::sys::Mutex EnableMultithreadingMutex;
2395static bool EnabledMultithreading;
2396
Argyrios Kyrtzidisfa39f5b2011-12-15 04:52:41 +00002397static void fatal_error_handler(void *user_data, const std::string& reason) {
Argyrios Kyrtzidisfa39f5b2011-12-15 04:52:41 +00002398 // Write the result out to stderr avoiding errs() because raw_ostreams can
2399 // call report_fatal_error.
Argyrios Kyrtzidisdb7a8002011-12-15 06:51:30 +00002400 fprintf(stderr, "LIBCLANG FATAL ERROR: %s\n", reason.c_str());
Argyrios Kyrtzidisfa39f5b2011-12-15 04:52:41 +00002401 ::abort();
2402}
2403
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002404extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002405CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2406 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002407 // Disable pretty stack trace functionality, which will otherwise be a very
2408 // poor citizen of the world and set up all sorts of signal handlers.
2409 llvm::DisablePrettyStackTrace = true;
2410
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002411 // We use crash recovery to make some of our APIs more reliable, implicitly
2412 // enable it.
2413 llvm::CrashRecoveryContext::Enable();
2414
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002415 // Enable support for multithreading in LLVM.
2416 {
2417 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2418 if (!EnabledMultithreading) {
Argyrios Kyrtzidisfa39f5b2011-12-15 04:52:41 +00002419 llvm::install_fatal_error_handler(fatal_error_handler, 0);
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002420 llvm::llvm_start_multithreaded();
2421 EnabledMultithreading = true;
2422 }
2423 }
2424
Douglas Gregora030b7c2010-01-22 20:35:53 +00002425 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002426 if (excludeDeclarationsFromPCH)
2427 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002428 if (displayDiagnostics)
2429 CIdxr->setDisplayDiagnostics();
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002430
2431 if (getenv("LIBCLANG_BGPRIO_INDEX"))
2432 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
2433 CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
2434 if (getenv("LIBCLANG_BGPRIO_EDIT"))
2435 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
2436 CXGlobalOpt_ThreadBackgroundPriorityForEditing);
2437
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002438 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002439}
2440
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002441void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002442 if (CIdx)
2443 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002444}
2445
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002446void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
2447 if (CIdx)
2448 static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
2449}
2450
2451unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
2452 if (CIdx)
2453 return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
2454 return 0;
2455}
2456
Ted Kremenekd2427dd2011-03-18 23:05:39 +00002457void clang_toggleCrashRecovery(unsigned isEnabled) {
2458 if (isEnabled)
2459 llvm::CrashRecoveryContext::Enable();
2460 else
2461 llvm::CrashRecoveryContext::Disable();
2462}
2463
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002464CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002465 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002466 if (!CIdx)
2467 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002468
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002469 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002470 FileSystemOptions FileSystemOpts;
2471 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002472
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00002473 IntrusiveRefCntPtr<DiagnosticsEngine> Diags;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002474 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002475 CXXIdx->getOnlyLocalDecls(),
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00002476 0, 0,
2477 /*CaptureDiagnostics=*/true,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00002478 /*AllowPCHWithCompilerErrors=*/true,
2479 /*UserFilesAreVolatile=*/true);
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002480 return MakeCXTranslationUnit(CXXIdx, TU);
Steve Naroff600866c2009-08-27 19:51:58 +00002481}
2482
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002483unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002484 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregorb5af8432011-08-25 22:54:01 +00002485 CXTranslationUnit_CacheCompletionResults;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002486}
2487
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002488CXTranslationUnit
2489clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2490 const char *source_filename,
2491 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002492 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002493 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002494 struct CXUnsavedFile *unsaved_files) {
Argyrios Kyrtzidise1d43302012-02-25 02:41:16 +00002495 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
Douglas Gregor5a430212010-07-21 18:52:53 +00002496 return clang_parseTranslationUnit(CIdx, source_filename,
2497 command_line_args, num_command_line_args,
2498 unsaved_files, num_unsaved_files,
Douglas Gregordca8ee82011-05-06 16:33:08 +00002499 Options);
Douglas Gregor5a430212010-07-21 18:52:53 +00002500}
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00002501
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002502struct ParseTranslationUnitInfo {
2503 CXIndex CIdx;
2504 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002505 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002506 int num_command_line_args;
2507 struct CXUnsavedFile *unsaved_files;
2508 unsigned num_unsaved_files;
2509 unsigned options;
2510 CXTranslationUnit result;
2511};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002512static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002513 ParseTranslationUnitInfo *PTUI =
2514 static_cast<ParseTranslationUnitInfo*>(UserData);
2515 CXIndex CIdx = PTUI->CIdx;
2516 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002517 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002518 int num_command_line_args = PTUI->num_command_line_args;
2519 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2520 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2521 unsigned options = PTUI->options;
2522 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002523
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002524 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002525 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002526
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002527 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2528
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002529 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
Argyrios Kyrtzidis81b5ac32012-03-28 02:49:54 +00002530 setThreadBackgroundPriority();
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002531
Douglas Gregor44c181a2010-07-23 00:33:23 +00002532 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregor467dc882011-08-25 22:30:56 +00002533 // FIXME: Add a flag for modules.
2534 TranslationUnitKind TUKind
2535 = (options & CXTranslationUnit_Incomplete)? TU_Prefix : TU_Complete;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002536 bool CacheCodeCompetionResults
2537 = options & CXTranslationUnit_CacheCompletionResults;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002538 bool IncludeBriefCommentsInCodeCompletion
2539 = options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
Erik Verbruggen6a91d382012-04-12 10:11:59 +00002540 bool SkipFunctionBodies = options & CXTranslationUnit_SkipFunctionBodies;
2541
Douglas Gregor5352ac02010-01-28 00:27:43 +00002542 // Configure the diagnostics.
2543 DiagnosticOptions DiagOpts;
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00002544 IntrusiveRefCntPtr<DiagnosticsEngine>
Ted Kremenek25a11e12011-03-22 01:15:24 +00002545 Diags(CompilerInstance::createDiagnostics(DiagOpts, num_command_line_args,
2546 command_line_args));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002547
Ted Kremenek25a11e12011-03-22 01:15:24 +00002548 // Recover resources if we crash before exiting this function.
David Blaikied6471f72011-09-25 23:23:43 +00002549 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
2550 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00002551 DiagCleanup(Diags.getPtr());
2552
Dylan Noblesmith1e4c01b2012-02-13 12:32:21 +00002553 OwningPtr<std::vector<ASTUnit::RemappedFile> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00002554 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2555
2556 // Recover resources if we crash before exiting this function.
2557 llvm::CrashRecoveryContextCleanupRegistrar<
2558 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2559
Douglas Gregor4db64a42010-01-23 00:14:00 +00002560 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002561 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002562 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002563 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002564 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2565 Buffer));
Douglas Gregor4db64a42010-01-23 00:14:00 +00002566 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002567
Dylan Noblesmith1e4c01b2012-02-13 12:32:21 +00002568 OwningPtr<std::vector<const char *> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00002569 Args(new std::vector<const char*>());
2570
2571 // Recover resources if we crash before exiting this method.
2572 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
2573 ArgsCleanup(Args.get());
2574
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002575 // Since the Clang C library is primarily used by batch tools dealing with
2576 // (often very broken) source code, where spell-checking can have a
2577 // significant negative impact on performance (particularly when
2578 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002579 // Only do this if we haven't found a spell-checking-related argument.
2580 bool FoundSpellCheckingArgument = false;
2581 for (int I = 0; I != num_command_line_args; ++I) {
2582 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2583 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2584 FoundSpellCheckingArgument = true;
2585 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002586 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002587 }
2588 if (!FoundSpellCheckingArgument)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002589 Args->push_back("-fno-spell-checking");
Douglas Gregorb10daed2010-10-11 16:52:23 +00002590
Ted Kremenek25a11e12011-03-22 01:15:24 +00002591 Args->insert(Args->end(), command_line_args,
2592 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002593
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002594 // The 'source_filename' argument is optional. If the caller does not
2595 // specify it then it is assumed that the source file is specified
2596 // in the actual argument list.
2597 // Put the source file after command_line_args otherwise if '-x' flag is
2598 // present it will be unused.
2599 if (source_filename)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002600 Args->push_back(source_filename);
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002601
Douglas Gregor44c181a2010-07-23 00:33:23 +00002602 // Do we need the detailed preprocessing record?
2603 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Ted Kremenek25a11e12011-03-22 01:15:24 +00002604 Args->push_back("-Xclang");
2605 Args->push_back("-detailed-preprocessing-record");
Douglas Gregor44c181a2010-07-23 00:33:23 +00002606 }
2607
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002608 unsigned NumErrors = Diags->getClient()->getNumErrors();
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00002609 OwningPtr<ASTUnit> ErrUnit;
Dylan Noblesmith1e4c01b2012-02-13 12:32:21 +00002610 OwningPtr<ASTUnit> Unit(
Ted Kremenek4ee99262011-03-22 20:16:19 +00002611 ASTUnit::LoadFromCommandLine(Args->size() ? &(*Args)[0] : 0
2612 /* vector::data() not portable */,
2613 Args->size() ? (&(*Args)[0] + Args->size()) :0,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002614 Diags,
2615 CXXIdx->getClangResourcesPath(),
2616 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002617 /*CaptureDiagnostics=*/true,
Ted Kremenek4ee99262011-03-22 20:16:19 +00002618 RemappedFiles->size() ? &(*RemappedFiles)[0]:0,
Ted Kremenek25a11e12011-03-22 01:15:24 +00002619 RemappedFiles->size(),
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00002620 /*RemappedFilesKeepOriginalName=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002621 PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00002622 TUKind,
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00002623 CacheCodeCompetionResults,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002624 IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00002625 /*AllowPCHWithCompilerErrors=*/true,
Erik Verbruggen6a91d382012-04-12 10:11:59 +00002626 SkipFunctionBodies,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00002627 /*UserFilesAreVolatile=*/true,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00002628 &ErrUnit));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002629
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002630 if (NumErrors != Diags->getClient()->getNumErrors()) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002631 // Make sure to check that 'Unit' is non-NULL.
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00002632 if (CXXIdx->getDisplayDiagnostics())
2633 printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
Douglas Gregora88084b2010-02-18 18:08:43 +00002634 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002635
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002636 PTUI->result = MakeCXTranslationUnit(CXXIdx, Unit.take());
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002637}
2638CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2639 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002640 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002641 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002642 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002643 unsigned num_unsaved_files,
2644 unsigned options) {
2645 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002646 num_command_line_args, unsaved_files,
2647 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002648 llvm::CrashRecoveryContext CRC;
2649
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002650 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002651 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2652 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2653 fprintf(stderr, " 'command_line_args' : [");
2654 for (int i = 0; i != num_command_line_args; ++i) {
2655 if (i)
2656 fprintf(stderr, ", ");
2657 fprintf(stderr, "'%s'", command_line_args[i]);
2658 }
2659 fprintf(stderr, "],\n");
2660 fprintf(stderr, " 'unsaved_files' : [");
2661 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2662 if (i)
2663 fprintf(stderr, ", ");
2664 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2665 unsaved_files[i].Length);
2666 }
2667 fprintf(stderr, "],\n");
2668 fprintf(stderr, " 'options' : %d,\n", options);
2669 fprintf(stderr, "}\n");
2670
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002671 return 0;
Douglas Gregor6df78732011-05-05 20:27:22 +00002672 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
2673 PrintLibclangResourceUsage(PTUI.result);
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002674 }
Douglas Gregor6df78732011-05-05 20:27:22 +00002675
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002676 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002677}
2678
Douglas Gregor19998442010-08-13 15:35:05 +00002679unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2680 return CXSaveTranslationUnit_None;
2681}
Argyrios Kyrtzidis142bcb52012-03-28 02:17:59 +00002682
2683namespace {
2684
2685struct SaveTranslationUnitInfo {
2686 CXTranslationUnit TU;
2687 const char *FileName;
2688 unsigned options;
2689 CXSaveError result;
2690};
2691
2692}
2693
2694static void clang_saveTranslationUnit_Impl(void *UserData) {
2695 SaveTranslationUnitInfo *STUI =
2696 static_cast<SaveTranslationUnitInfo*>(UserData);
2697
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002698 CIndexer *CXXIdx = (CIndexer*)STUI->TU->CIdx;
2699 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
Argyrios Kyrtzidis81b5ac32012-03-28 02:49:54 +00002700 setThreadBackgroundPriority();
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002701
Argyrios Kyrtzidis142bcb52012-03-28 02:17:59 +00002702 STUI->result = static_cast<ASTUnit *>(STUI->TU->TUData)->Save(STUI->FileName);
2703}
2704
Douglas Gregor19998442010-08-13 15:35:05 +00002705int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2706 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002707 if (!TU)
Douglas Gregor39c411f2011-07-06 16:43:36 +00002708 return CXSaveError_InvalidTU;
Argyrios Kyrtzidis142bcb52012-03-28 02:17:59 +00002709
2710 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
2711 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Argyrios Kyrtzidis374a00b2012-06-08 05:48:06 +00002712 if (!CXXUnit->hasSema())
2713 return CXSaveError_InvalidTU;
Argyrios Kyrtzidis142bcb52012-03-28 02:17:59 +00002714
2715 SaveTranslationUnitInfo STUI = { TU, FileName, options, CXSaveError_None };
2716
2717 if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred() ||
2718 getenv("LIBCLANG_NOTHREADS")) {
2719 clang_saveTranslationUnit_Impl(&STUI);
2720
2721 if (getenv("LIBCLANG_RESOURCE_USAGE"))
2722 PrintLibclangResourceUsage(TU);
2723
2724 return STUI.result;
2725 }
2726
2727 // We have an AST that has invalid nodes due to compiler errors.
2728 // Use a crash recovery thread for protection.
2729
2730 llvm::CrashRecoveryContext CRC;
2731
2732 if (!RunSafely(CRC, clang_saveTranslationUnit_Impl, &STUI)) {
2733 fprintf(stderr, "libclang: crash detected during AST saving: {\n");
2734 fprintf(stderr, " 'filename' : '%s'\n", FileName);
2735 fprintf(stderr, " 'options' : %d,\n", options);
2736 fprintf(stderr, "}\n");
2737
2738 return CXSaveError_Unknown;
2739
2740 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
Douglas Gregor6df78732011-05-05 20:27:22 +00002741 PrintLibclangResourceUsage(TU);
Argyrios Kyrtzidis142bcb52012-03-28 02:17:59 +00002742 }
2743
2744 return STUI.result;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002745}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002746
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002747void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002748 if (CTUnit) {
2749 // If the translation unit has been marked as unsafe to free, just discard
2750 // it.
Ted Kremeneka60ed472010-11-16 08:15:36 +00002751 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002752 return;
2753
Ted Kremeneka60ed472010-11-16 08:15:36 +00002754 delete static_cast<ASTUnit *>(CTUnit->TUData);
2755 disposeCXStringPool(CTUnit->StringPool);
Ted Kremenek15322172011-11-10 08:43:12 +00002756 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
Ted Kremenekbbf66ca2012-04-30 19:06:49 +00002757 disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002758 delete CTUnit;
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002759 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002760}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002761
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002762unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2763 return CXReparse_None;
2764}
2765
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002766struct ReparseTranslationUnitInfo {
2767 CXTranslationUnit TU;
2768 unsigned num_unsaved_files;
2769 struct CXUnsavedFile *unsaved_files;
2770 unsigned options;
2771 int result;
2772};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002773
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002774static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002775 ReparseTranslationUnitInfo *RTUI =
2776 static_cast<ReparseTranslationUnitInfo*>(UserData);
2777 CXTranslationUnit TU = RTUI->TU;
Ted Kremenek15322172011-11-10 08:43:12 +00002778
2779 // Reset the associated diagnostics.
2780 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
2781 TU->Diagnostics = 0;
2782
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002783 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2784 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2785 unsigned options = RTUI->options;
2786 (void) options;
2787 RTUI->result = 1;
2788
Douglas Gregorabc563f2010-07-19 21:46:24 +00002789 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002790 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002791
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002792 CIndexer *CXXIdx = (CIndexer*)TU->CIdx;
2793 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
Argyrios Kyrtzidis81b5ac32012-03-28 02:49:54 +00002794 setThreadBackgroundPriority();
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002795
Ted Kremeneka60ed472010-11-16 08:15:36 +00002796 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor593b0c12010-09-23 18:47:53 +00002797 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002798
Dylan Noblesmith1e4c01b2012-02-13 12:32:21 +00002799 OwningPtr<std::vector<ASTUnit::RemappedFile> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00002800 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2801
2802 // Recover resources if we crash before exiting this function.
2803 llvm::CrashRecoveryContextCleanupRegistrar<
2804 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2805
Douglas Gregorabc563f2010-07-19 21:46:24 +00002806 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002807 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002808 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002809 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002810 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2811 Buffer));
Douglas Gregorabc563f2010-07-19 21:46:24 +00002812 }
2813
Ted Kremenek4ee99262011-03-22 20:16:19 +00002814 if (!CXXUnit->Reparse(RemappedFiles->size() ? &(*RemappedFiles)[0] : 0,
2815 RemappedFiles->size()))
Douglas Gregor593b0c12010-09-23 18:47:53 +00002816 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002817}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002818
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002819int clang_reparseTranslationUnit(CXTranslationUnit TU,
2820 unsigned num_unsaved_files,
2821 struct CXUnsavedFile *unsaved_files,
2822 unsigned options) {
2823 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2824 options, 0 };
Argyrios Kyrtzidis8c4b47e2011-10-28 22:54:33 +00002825
Argyrios Kyrtzidise7de9b42011-10-29 19:32:39 +00002826 if (getenv("LIBCLANG_NOTHREADS")) {
Argyrios Kyrtzidis8c4b47e2011-10-28 22:54:33 +00002827 clang_reparseTranslationUnit_Impl(&RTUI);
2828 return RTUI.result;
2829 }
2830
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002831 llvm::CrashRecoveryContext CRC;
2832
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002833 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002834 fprintf(stderr, "libclang: crash detected during reparsing\n");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002835 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002836 return 1;
Douglas Gregor6df78732011-05-05 20:27:22 +00002837 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
2838 PrintLibclangResourceUsage(TU);
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002839
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002840 return RTUI.result;
2841}
2842
Douglas Gregordf95a132010-08-09 20:45:32 +00002843
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002844CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002845 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002846 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002847
Ted Kremeneka60ed472010-11-16 08:15:36 +00002848 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002849 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002850}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002851
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002852CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregor8e5900c2012-04-30 23:41:16 +00002853 ASTUnit *CXXUnit = static_cast<ASTUnit*>(TU->TUData);
2854 return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002855}
2856
Ted Kremenekfb480492010-01-13 21:46:36 +00002857} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002858
Ted Kremenekfb480492010-01-13 21:46:36 +00002859//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002860// CXFile Operations.
2861//===----------------------------------------------------------------------===//
2862
2863extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002864CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002865 if (!SFile)
Ted Kremeneka60ed472010-11-16 08:15:36 +00002866 return createCXString((const char*)NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002867
Steve Naroff88145032009-10-27 14:35:18 +00002868 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002869 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002870}
2871
2872time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002873 if (!SFile)
2874 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002875
Steve Naroff88145032009-10-27 14:35:18 +00002876 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2877 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002878}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002879
Douglas Gregorb9790342010-01-22 21:44:22 +00002880CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2881 if (!tu)
2882 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002883
Ted Kremeneka60ed472010-11-16 08:15:36 +00002884 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002885
Douglas Gregorb9790342010-01-22 21:44:22 +00002886 FileManager &FMgr = CXXUnit->getFileManager();
Chris Lattner39b49bc2010-11-23 08:35:12 +00002887 return const_cast<FileEntry *>(FMgr.getFile(file_name));
Douglas Gregorb9790342010-01-22 21:44:22 +00002888}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002889
Douglas Gregordd3e5542011-05-04 00:14:37 +00002890unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit tu, CXFile file) {
2891 if (!tu || !file)
2892 return 0;
2893
2894 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
2895 FileEntry *FEnt = static_cast<FileEntry *>(file);
2896 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
2897 .isFileMultipleIncludeGuarded(FEnt);
2898}
2899
Ted Kremenekfb480492010-01-13 21:46:36 +00002900} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002901
Ted Kremenekfb480492010-01-13 21:46:36 +00002902//===----------------------------------------------------------------------===//
2903// CXCursor Operations.
2904//===----------------------------------------------------------------------===//
2905
Ted Kremenekfb480492010-01-13 21:46:36 +00002906static Decl *getDeclFromExpr(Stmt *E) {
Argyrios Kyrtzidisc2954612011-09-12 22:17:26 +00002907 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Douglas Gregordb1314e2010-10-01 21:11:22 +00002908 return getDeclFromExpr(CE->getSubExpr());
2909
Ted Kremenekfb480492010-01-13 21:46:36 +00002910 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2911 return RefExpr->getDecl();
2912 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2913 return ME->getMemberDecl();
2914 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2915 return RE->getDecl();
Argyrios Kyrtzidisb085d892012-03-30 00:19:18 +00002916 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
2917 if (PRE->isExplicitProperty())
2918 return PRE->getExplicitProperty();
2919 // It could be messaging both getter and setter as in:
2920 // ++myobj.myprop;
2921 // in which case prefer to associate the setter since it is less obvious
2922 // from inspecting the source that the setter is going to get called.
2923 if (PRE->isMessagingSetter())
2924 return PRE->getImplicitPropertySetter();
2925 return PRE->getImplicitPropertyGetter();
2926 }
John McCall4b9c2d22011-11-06 09:01:30 +00002927 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
2928 return getDeclFromExpr(POE->getSyntacticForm());
2929 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
2930 if (Expr *Src = OVE->getSourceExpr())
2931 return getDeclFromExpr(Src);
Douglas Gregordb1314e2010-10-01 21:11:22 +00002932
Ted Kremenekfb480492010-01-13 21:46:36 +00002933 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2934 return getDeclFromExpr(CE->getCallee());
Chris Lattner5f9e2722011-07-23 10:55:15 +00002935 if (CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Douglas Gregor93798e22010-11-05 21:11:19 +00002936 if (!CE->isElidable())
2937 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002938 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2939 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002940
Douglas Gregordb1314e2010-10-01 21:11:22 +00002941 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2942 return PE->getProtocol();
Douglas Gregorc7793c72011-01-15 01:15:58 +00002943 if (SubstNonTypeTemplateParmPackExpr *NTTP
2944 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
2945 return NTTP->getParameterPack();
Douglas Gregor94d96292011-01-19 20:34:17 +00002946 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2947 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
2948 isa<ParmVarDecl>(SizeOfPack->getPack()))
2949 return SizeOfPack->getPack();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002950
Ted Kremenekfb480492010-01-13 21:46:36 +00002951 return 0;
2952}
2953
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002954static SourceLocation getLocationFromExpr(Expr *E) {
Argyrios Kyrtzidisc2954612011-09-12 22:17:26 +00002955 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
2956 return getLocationFromExpr(CE->getSubExpr());
2957
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002958 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2959 return /*FIXME:*/Msg->getLeftLoc();
2960 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2961 return DRE->getLocation();
2962 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2963 return Member->getMemberLoc();
2964 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2965 return Ivar->getLocation();
Douglas Gregor94d96292011-01-19 20:34:17 +00002966 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2967 return SizeOfPack->getPackLoc();
Argyrios Kyrtzidisd0469522012-03-30 00:19:13 +00002968 if (ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
2969 return PropRef->getLocation();
Douglas Gregor94d96292011-01-19 20:34:17 +00002970
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002971 return E->getLocStart();
2972}
2973
Ted Kremenekfb480492010-01-13 21:46:36 +00002974extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002975
2976unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002977 CXCursorVisitor visitor,
2978 CXClientData client_data) {
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00002979 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
2980 /*VisitPreprocessorLast=*/false);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002981 return CursorVis.VisitChildren(parent);
2982}
2983
David Chisnall3387c652010-11-03 14:12:26 +00002984#ifndef __has_feature
2985#define __has_feature(x) 0
2986#endif
2987#if __has_feature(blocks)
2988typedef enum CXChildVisitResult
2989 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2990
2991static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2992 CXClientData client_data) {
2993 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2994 return block(cursor, parent);
2995}
2996#else
2997// If we are compiled with a compiler that doesn't have native blocks support,
2998// define and call the block manually, so the
2999typedef struct _CXChildVisitResult
3000{
3001 void *isa;
3002 int flags;
3003 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003004 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
3005 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00003006} *CXCursorVisitorBlock;
3007
3008static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
3009 CXClientData client_data) {
3010 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
3011 return block->invoke(block, cursor, parent);
3012}
3013#endif
3014
3015
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003016unsigned clang_visitChildrenWithBlock(CXCursor parent,
3017 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00003018 return clang_visitChildren(parent, visitWithBlock, block);
3019}
3020
Douglas Gregor78205d42010-01-20 21:45:58 +00003021static CXString getDeclSpelling(Decl *D) {
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00003022 if (!D)
3023 return createCXString("");
3024
3025 NamedDecl *ND = dyn_cast<NamedDecl>(D);
Douglas Gregore3c60a72010-11-17 00:13:31 +00003026 if (!ND) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003027 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00003028 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3029 return createCXString(Property->getIdentifier()->getName());
3030
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003031 return createCXString("");
Douglas Gregore3c60a72010-11-17 00:13:31 +00003032 }
3033
Douglas Gregor78205d42010-01-20 21:45:58 +00003034 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003035 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003036
Douglas Gregor78205d42010-01-20 21:45:58 +00003037 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
3038 // No, this isn't the same as the code below. getIdentifier() is non-virtual
3039 // and returns different names. NamedDecl returns the class name and
3040 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003041 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003042
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003043 if (isa<UsingDirectiveDecl>(D))
3044 return createCXString("");
3045
Dylan Noblesmith36d59272012-02-13 12:32:26 +00003046 SmallString<1024> S;
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00003047 llvm::raw_svector_ostream os(S);
3048 ND->printName(os);
3049
3050 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00003051}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003052
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003053CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003054 if (clang_isTranslationUnit(C.kind))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003055 return clang_getTranslationUnitSpelling(
3056 static_cast<CXTranslationUnit>(C.data[2]));
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003057
Steve Narofff334b4e2009-09-02 18:26:48 +00003058 if (clang_isReference(C.kind)) {
3059 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00003060 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00003061 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003062 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003063 }
3064 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00003065 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003066 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003067 }
3068 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00003069 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00003070 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003071 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003072 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00003073 case CXCursor_CXXBaseSpecifier: {
3074 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
3075 return createCXString(B->getType().getAsString());
3076 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003077 case CXCursor_TypeRef: {
3078 TypeDecl *Type = getCursorTypeRef(C).first;
3079 assert(Type && "Missing type decl");
3080
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003081 return createCXString(getCursorContext(C).getTypeDeclType(Type).
3082 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003083 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003084 case CXCursor_TemplateRef: {
3085 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00003086 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003087
3088 return createCXString(Template->getNameAsString());
3089 }
Douglas Gregor69319002010-08-31 23:48:11 +00003090
3091 case CXCursor_NamespaceRef: {
3092 NamedDecl *NS = getCursorNamespaceRef(C).first;
3093 assert(NS && "Missing namespace decl");
3094
3095 return createCXString(NS->getNameAsString());
3096 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003097
Douglas Gregora67e03f2010-09-09 21:42:20 +00003098 case CXCursor_MemberRef: {
3099 FieldDecl *Field = getCursorMemberRef(C).first;
3100 assert(Field && "Missing member decl");
3101
3102 return createCXString(Field->getNameAsString());
3103 }
3104
Douglas Gregor36897b02010-09-10 00:22:18 +00003105 case CXCursor_LabelRef: {
3106 LabelStmt *Label = getCursorLabelRef(C).first;
3107 assert(Label && "Missing label");
3108
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003109 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00003110 }
3111
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003112 case CXCursor_OverloadedDeclRef: {
3113 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3114 if (Decl *D = Storage.dyn_cast<Decl *>()) {
3115 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
3116 return createCXString(ND->getNameAsString());
3117 return createCXString("");
3118 }
3119 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3120 return createCXString(E->getName().getAsString());
3121 OverloadedTemplateStorage *Ovl
3122 = Storage.get<OverloadedTemplateStorage*>();
3123 if (Ovl->size() == 0)
3124 return createCXString("");
3125 return createCXString((*Ovl->begin())->getNameAsString());
3126 }
3127
Douglas Gregor011d8b92012-02-15 00:54:55 +00003128 case CXCursor_VariableRef: {
3129 VarDecl *Var = getCursorVariableRef(C).first;
3130 assert(Var && "Missing variable decl");
3131
3132 return createCXString(Var->getNameAsString());
3133 }
3134
Daniel Dunbaracca7252009-11-30 20:42:49 +00003135 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003136 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00003137 }
3138 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003139
3140 if (clang_isExpression(C.kind)) {
3141 Decl *D = getDeclFromExpr(getCursorExpr(C));
3142 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00003143 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003144 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00003145 }
3146
Douglas Gregor36897b02010-09-10 00:22:18 +00003147 if (clang_isStatement(C.kind)) {
3148 Stmt *S = getCursorStmt(C);
3149 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003150 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00003151
3152 return createCXString("");
3153 }
3154
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003155 if (C.kind == CXCursor_MacroExpansion)
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003156 return createCXString(getCursorMacroExpansion(C)->getName()
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003157 ->getNameStart());
3158
Douglas Gregor572feb22010-03-18 18:04:21 +00003159 if (C.kind == CXCursor_MacroDefinition)
3160 return createCXString(getCursorMacroDefinition(C)->getName()
3161 ->getNameStart());
3162
Douglas Gregorecdcb882010-10-20 22:00:55 +00003163 if (C.kind == CXCursor_InclusionDirective)
3164 return createCXString(getCursorInclusionDirective(C)->getFileName());
3165
Douglas Gregor60cbfac2010-01-25 16:56:17 +00003166 if (clang_isDeclaration(C.kind))
3167 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00003168
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00003169 if (C.kind == CXCursor_AnnotateAttr) {
3170 AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
3171 return createCXString(AA->getAnnotation());
3172 }
3173
Argyrios Kyrtzidis84b79642011-12-06 22:05:01 +00003174 if (C.kind == CXCursor_AsmLabelAttr) {
3175 AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
3176 return createCXString(AA->getLabel());
3177 }
3178
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003179 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00003180}
3181
Argyrios Kyrtzidisba1da142012-03-30 20:58:35 +00003182CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C,
3183 unsigned pieceIndex,
3184 unsigned options) {
3185 if (clang_Cursor_isNull(C))
3186 return clang_getNullRange();
3187
3188 ASTContext &Ctx = getCursorContext(C);
3189
3190 if (clang_isStatement(C.kind)) {
3191 Stmt *S = getCursorStmt(C);
3192 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
3193 if (pieceIndex > 0)
3194 return clang_getNullRange();
3195 return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
3196 }
3197
3198 return clang_getNullRange();
3199 }
3200
3201 if (C.kind == CXCursor_ObjCMessageExpr) {
3202 if (ObjCMessageExpr *
3203 ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
3204 if (pieceIndex >= ME->getNumSelectorLocs())
3205 return clang_getNullRange();
3206 return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
3207 }
3208 }
3209
3210 if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
3211 C.kind == CXCursor_ObjCClassMethodDecl) {
3212 if (ObjCMethodDecl *
3213 MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
3214 if (pieceIndex >= MD->getNumSelectorLocs())
3215 return clang_getNullRange();
3216 return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
3217 }
3218 }
3219
Argyrios Kyrtzidis9482a182012-04-16 20:01:28 +00003220 if (C.kind == CXCursor_ObjCCategoryDecl ||
3221 C.kind == CXCursor_ObjCCategoryImplDecl) {
3222 if (pieceIndex > 0)
3223 return clang_getNullRange();
3224 if (ObjCCategoryDecl *
3225 CD = dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
3226 return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
3227 if (ObjCCategoryImplDecl *
3228 CID = dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
3229 return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
3230 }
3231
Argyrios Kyrtzidisba1da142012-03-30 20:58:35 +00003232 // FIXME: A CXCursor_InclusionDirective should give the location of the
3233 // filename, but we don't keep track of this.
3234
3235 // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
3236 // but we don't keep track of this.
3237
3238 // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
3239 // but we don't keep track of this.
3240
3241 // Default handling, give the location of the cursor.
3242
3243 if (pieceIndex > 0)
3244 return clang_getNullRange();
3245
3246 CXSourceLocation CXLoc = clang_getCursorLocation(C);
3247 SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
3248 return cxloc::translateSourceRange(Ctx, Loc);
3249}
3250
Douglas Gregor358559d2010-10-02 22:49:11 +00003251CXString clang_getCursorDisplayName(CXCursor C) {
3252 if (!clang_isDeclaration(C.kind))
3253 return clang_getCursorSpelling(C);
3254
3255 Decl *D = getCursorDecl(C);
3256 if (!D)
3257 return createCXString("");
3258
Douglas Gregor30c42402011-09-27 22:38:19 +00003259 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
Douglas Gregor358559d2010-10-02 22:49:11 +00003260 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
3261 D = FunTmpl->getTemplatedDecl();
3262
3263 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Dylan Noblesmith36d59272012-02-13 12:32:26 +00003264 SmallString<64> Str;
Douglas Gregor358559d2010-10-02 22:49:11 +00003265 llvm::raw_svector_ostream OS(Str);
Benjamin Kramera59d20b2012-02-07 11:57:57 +00003266 OS << *Function;
Douglas Gregor358559d2010-10-02 22:49:11 +00003267 if (Function->getPrimaryTemplate())
3268 OS << "<>";
3269 OS << "(";
3270 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
3271 if (I)
3272 OS << ", ";
3273 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
3274 }
3275
3276 if (Function->isVariadic()) {
3277 if (Function->getNumParams())
3278 OS << ", ";
3279 OS << "...";
3280 }
3281 OS << ")";
3282 return createCXString(OS.str());
3283 }
3284
3285 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
Dylan Noblesmith36d59272012-02-13 12:32:26 +00003286 SmallString<64> Str;
Douglas Gregor358559d2010-10-02 22:49:11 +00003287 llvm::raw_svector_ostream OS(Str);
Benjamin Kramera59d20b2012-02-07 11:57:57 +00003288 OS << *ClassTemplate;
Douglas Gregor358559d2010-10-02 22:49:11 +00003289 OS << "<";
3290 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
3291 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3292 if (I)
3293 OS << ", ";
3294
3295 NamedDecl *Param = Params->getParam(I);
3296 if (Param->getIdentifier()) {
3297 OS << Param->getIdentifier()->getName();
3298 continue;
3299 }
3300
3301 // There is no parameter name, which makes this tricky. Try to come up
3302 // with something useful that isn't too long.
3303 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3304 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
3305 else if (NonTypeTemplateParmDecl *NTTP
3306 = dyn_cast<NonTypeTemplateParmDecl>(Param))
3307 OS << NTTP->getType().getAsString(Policy);
3308 else
3309 OS << "template<...> class";
3310 }
3311
3312 OS << ">";
3313 return createCXString(OS.str());
3314 }
3315
3316 if (ClassTemplateSpecializationDecl *ClassSpec
3317 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
3318 // If the type was explicitly written, use that.
3319 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
3320 return createCXString(TSInfo->getType().getAsString(Policy));
3321
Dylan Noblesmith36d59272012-02-13 12:32:26 +00003322 SmallString<64> Str;
Douglas Gregor358559d2010-10-02 22:49:11 +00003323 llvm::raw_svector_ostream OS(Str);
Benjamin Kramera59d20b2012-02-07 11:57:57 +00003324 OS << *ClassSpec;
Douglas Gregor358559d2010-10-02 22:49:11 +00003325 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00003326 ClassSpec->getTemplateArgs().data(),
3327 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00003328 Policy);
3329 return createCXString(OS.str());
3330 }
3331
3332 return clang_getCursorSpelling(C);
3333}
3334
Ted Kremeneke68fff62010-02-17 00:41:32 +00003335CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00003336 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00003337 case CXCursor_FunctionDecl:
3338 return createCXString("FunctionDecl");
3339 case CXCursor_TypedefDecl:
3340 return createCXString("TypedefDecl");
3341 case CXCursor_EnumDecl:
3342 return createCXString("EnumDecl");
3343 case CXCursor_EnumConstantDecl:
3344 return createCXString("EnumConstantDecl");
3345 case CXCursor_StructDecl:
3346 return createCXString("StructDecl");
3347 case CXCursor_UnionDecl:
3348 return createCXString("UnionDecl");
3349 case CXCursor_ClassDecl:
3350 return createCXString("ClassDecl");
3351 case CXCursor_FieldDecl:
3352 return createCXString("FieldDecl");
3353 case CXCursor_VarDecl:
3354 return createCXString("VarDecl");
3355 case CXCursor_ParmDecl:
3356 return createCXString("ParmDecl");
3357 case CXCursor_ObjCInterfaceDecl:
3358 return createCXString("ObjCInterfaceDecl");
3359 case CXCursor_ObjCCategoryDecl:
3360 return createCXString("ObjCCategoryDecl");
3361 case CXCursor_ObjCProtocolDecl:
3362 return createCXString("ObjCProtocolDecl");
3363 case CXCursor_ObjCPropertyDecl:
3364 return createCXString("ObjCPropertyDecl");
3365 case CXCursor_ObjCIvarDecl:
3366 return createCXString("ObjCIvarDecl");
3367 case CXCursor_ObjCInstanceMethodDecl:
3368 return createCXString("ObjCInstanceMethodDecl");
3369 case CXCursor_ObjCClassMethodDecl:
3370 return createCXString("ObjCClassMethodDecl");
3371 case CXCursor_ObjCImplementationDecl:
3372 return createCXString("ObjCImplementationDecl");
3373 case CXCursor_ObjCCategoryImplDecl:
3374 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00003375 case CXCursor_CXXMethod:
3376 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003377 case CXCursor_UnexposedDecl:
3378 return createCXString("UnexposedDecl");
3379 case CXCursor_ObjCSuperClassRef:
3380 return createCXString("ObjCSuperClassRef");
3381 case CXCursor_ObjCProtocolRef:
3382 return createCXString("ObjCProtocolRef");
3383 case CXCursor_ObjCClassRef:
3384 return createCXString("ObjCClassRef");
3385 case CXCursor_TypeRef:
3386 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003387 case CXCursor_TemplateRef:
3388 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00003389 case CXCursor_NamespaceRef:
3390 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00003391 case CXCursor_MemberRef:
3392 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00003393 case CXCursor_LabelRef:
3394 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003395 case CXCursor_OverloadedDeclRef:
3396 return createCXString("OverloadedDeclRef");
Douglas Gregor011d8b92012-02-15 00:54:55 +00003397 case CXCursor_VariableRef:
3398 return createCXString("VariableRef");
Douglas Gregor42b29842011-10-05 19:00:14 +00003399 case CXCursor_IntegerLiteral:
3400 return createCXString("IntegerLiteral");
3401 case CXCursor_FloatingLiteral:
3402 return createCXString("FloatingLiteral");
3403 case CXCursor_ImaginaryLiteral:
3404 return createCXString("ImaginaryLiteral");
3405 case CXCursor_StringLiteral:
3406 return createCXString("StringLiteral");
3407 case CXCursor_CharacterLiteral:
3408 return createCXString("CharacterLiteral");
3409 case CXCursor_ParenExpr:
3410 return createCXString("ParenExpr");
3411 case CXCursor_UnaryOperator:
3412 return createCXString("UnaryOperator");
3413 case CXCursor_ArraySubscriptExpr:
3414 return createCXString("ArraySubscriptExpr");
3415 case CXCursor_BinaryOperator:
3416 return createCXString("BinaryOperator");
3417 case CXCursor_CompoundAssignOperator:
3418 return createCXString("CompoundAssignOperator");
3419 case CXCursor_ConditionalOperator:
3420 return createCXString("ConditionalOperator");
3421 case CXCursor_CStyleCastExpr:
3422 return createCXString("CStyleCastExpr");
3423 case CXCursor_CompoundLiteralExpr:
3424 return createCXString("CompoundLiteralExpr");
3425 case CXCursor_InitListExpr:
3426 return createCXString("InitListExpr");
3427 case CXCursor_AddrLabelExpr:
3428 return createCXString("AddrLabelExpr");
3429 case CXCursor_StmtExpr:
3430 return createCXString("StmtExpr");
3431 case CXCursor_GenericSelectionExpr:
3432 return createCXString("GenericSelectionExpr");
3433 case CXCursor_GNUNullExpr:
3434 return createCXString("GNUNullExpr");
3435 case CXCursor_CXXStaticCastExpr:
3436 return createCXString("CXXStaticCastExpr");
3437 case CXCursor_CXXDynamicCastExpr:
3438 return createCXString("CXXDynamicCastExpr");
3439 case CXCursor_CXXReinterpretCastExpr:
3440 return createCXString("CXXReinterpretCastExpr");
3441 case CXCursor_CXXConstCastExpr:
3442 return createCXString("CXXConstCastExpr");
3443 case CXCursor_CXXFunctionalCastExpr:
3444 return createCXString("CXXFunctionalCastExpr");
3445 case CXCursor_CXXTypeidExpr:
3446 return createCXString("CXXTypeidExpr");
3447 case CXCursor_CXXBoolLiteralExpr:
3448 return createCXString("CXXBoolLiteralExpr");
3449 case CXCursor_CXXNullPtrLiteralExpr:
3450 return createCXString("CXXNullPtrLiteralExpr");
3451 case CXCursor_CXXThisExpr:
3452 return createCXString("CXXThisExpr");
3453 case CXCursor_CXXThrowExpr:
3454 return createCXString("CXXThrowExpr");
3455 case CXCursor_CXXNewExpr:
3456 return createCXString("CXXNewExpr");
3457 case CXCursor_CXXDeleteExpr:
3458 return createCXString("CXXDeleteExpr");
3459 case CXCursor_UnaryExpr:
3460 return createCXString("UnaryExpr");
3461 case CXCursor_ObjCStringLiteral:
3462 return createCXString("ObjCStringLiteral");
Ted Kremenekb3f75422012-03-06 20:06:06 +00003463 case CXCursor_ObjCBoolLiteralExpr:
3464 return createCXString("ObjCBoolLiteralExpr");
Douglas Gregor42b29842011-10-05 19:00:14 +00003465 case CXCursor_ObjCEncodeExpr:
3466 return createCXString("ObjCEncodeExpr");
3467 case CXCursor_ObjCSelectorExpr:
3468 return createCXString("ObjCSelectorExpr");
3469 case CXCursor_ObjCProtocolExpr:
3470 return createCXString("ObjCProtocolExpr");
3471 case CXCursor_ObjCBridgedCastExpr:
3472 return createCXString("ObjCBridgedCastExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00003473 case CXCursor_BlockExpr:
3474 return createCXString("BlockExpr");
Douglas Gregor42b29842011-10-05 19:00:14 +00003475 case CXCursor_PackExpansionExpr:
3476 return createCXString("PackExpansionExpr");
3477 case CXCursor_SizeOfPackExpr:
3478 return createCXString("SizeOfPackExpr");
Douglas Gregor011d8b92012-02-15 00:54:55 +00003479 case CXCursor_LambdaExpr:
3480 return createCXString("LambdaExpr");
Douglas Gregor42b29842011-10-05 19:00:14 +00003481 case CXCursor_UnexposedExpr:
3482 return createCXString("UnexposedExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003483 case CXCursor_DeclRefExpr:
3484 return createCXString("DeclRefExpr");
3485 case CXCursor_MemberRefExpr:
3486 return createCXString("MemberRefExpr");
3487 case CXCursor_CallExpr:
3488 return createCXString("CallExpr");
3489 case CXCursor_ObjCMessageExpr:
3490 return createCXString("ObjCMessageExpr");
3491 case CXCursor_UnexposedStmt:
3492 return createCXString("UnexposedStmt");
Douglas Gregor42b29842011-10-05 19:00:14 +00003493 case CXCursor_DeclStmt:
3494 return createCXString("DeclStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00003495 case CXCursor_LabelStmt:
3496 return createCXString("LabelStmt");
Douglas Gregor42b29842011-10-05 19:00:14 +00003497 case CXCursor_CompoundStmt:
3498 return createCXString("CompoundStmt");
3499 case CXCursor_CaseStmt:
3500 return createCXString("CaseStmt");
3501 case CXCursor_DefaultStmt:
3502 return createCXString("DefaultStmt");
3503 case CXCursor_IfStmt:
3504 return createCXString("IfStmt");
3505 case CXCursor_SwitchStmt:
3506 return createCXString("SwitchStmt");
3507 case CXCursor_WhileStmt:
3508 return createCXString("WhileStmt");
3509 case CXCursor_DoStmt:
3510 return createCXString("DoStmt");
3511 case CXCursor_ForStmt:
3512 return createCXString("ForStmt");
3513 case CXCursor_GotoStmt:
3514 return createCXString("GotoStmt");
3515 case CXCursor_IndirectGotoStmt:
3516 return createCXString("IndirectGotoStmt");
3517 case CXCursor_ContinueStmt:
3518 return createCXString("ContinueStmt");
3519 case CXCursor_BreakStmt:
3520 return createCXString("BreakStmt");
3521 case CXCursor_ReturnStmt:
3522 return createCXString("ReturnStmt");
Chad Rosierdf5faf52012-08-25 00:11:56 +00003523 case CXCursor_GCCAsmStmt:
3524 return createCXString("GCCAsmStmt");
Chad Rosier8cd64b42012-06-11 20:47:18 +00003525 case CXCursor_MSAsmStmt:
3526 return createCXString("MSAsmStmt");
Douglas Gregor42b29842011-10-05 19:00:14 +00003527 case CXCursor_ObjCAtTryStmt:
3528 return createCXString("ObjCAtTryStmt");
3529 case CXCursor_ObjCAtCatchStmt:
3530 return createCXString("ObjCAtCatchStmt");
3531 case CXCursor_ObjCAtFinallyStmt:
3532 return createCXString("ObjCAtFinallyStmt");
3533 case CXCursor_ObjCAtThrowStmt:
3534 return createCXString("ObjCAtThrowStmt");
3535 case CXCursor_ObjCAtSynchronizedStmt:
3536 return createCXString("ObjCAtSynchronizedStmt");
3537 case CXCursor_ObjCAutoreleasePoolStmt:
3538 return createCXString("ObjCAutoreleasePoolStmt");
3539 case CXCursor_ObjCForCollectionStmt:
3540 return createCXString("ObjCForCollectionStmt");
3541 case CXCursor_CXXCatchStmt:
3542 return createCXString("CXXCatchStmt");
3543 case CXCursor_CXXTryStmt:
3544 return createCXString("CXXTryStmt");
3545 case CXCursor_CXXForRangeStmt:
3546 return createCXString("CXXForRangeStmt");
3547 case CXCursor_SEHTryStmt:
3548 return createCXString("SEHTryStmt");
3549 case CXCursor_SEHExceptStmt:
3550 return createCXString("SEHExceptStmt");
3551 case CXCursor_SEHFinallyStmt:
3552 return createCXString("SEHFinallyStmt");
3553 case CXCursor_NullStmt:
3554 return createCXString("NullStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003555 case CXCursor_InvalidFile:
3556 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00003557 case CXCursor_InvalidCode:
3558 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003559 case CXCursor_NoDeclFound:
3560 return createCXString("NoDeclFound");
3561 case CXCursor_NotImplemented:
3562 return createCXString("NotImplemented");
3563 case CXCursor_TranslationUnit:
3564 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00003565 case CXCursor_UnexposedAttr:
3566 return createCXString("UnexposedAttr");
3567 case CXCursor_IBActionAttr:
3568 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003569 case CXCursor_IBOutletAttr:
3570 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003571 case CXCursor_IBOutletCollectionAttr:
3572 return createCXString("attribute(iboutletcollection)");
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00003573 case CXCursor_CXXFinalAttr:
3574 return createCXString("attribute(final)");
3575 case CXCursor_CXXOverrideAttr:
3576 return createCXString("attribute(override)");
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00003577 case CXCursor_AnnotateAttr:
3578 return createCXString("attribute(annotate)");
Argyrios Kyrtzidis84b79642011-12-06 22:05:01 +00003579 case CXCursor_AsmLabelAttr:
3580 return createCXString("asm label");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003581 case CXCursor_PreprocessingDirective:
3582 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003583 case CXCursor_MacroDefinition:
3584 return createCXString("macro definition");
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003585 case CXCursor_MacroExpansion:
3586 return createCXString("macro expansion");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003587 case CXCursor_InclusionDirective:
3588 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003589 case CXCursor_Namespace:
3590 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003591 case CXCursor_LinkageSpec:
3592 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003593 case CXCursor_CXXBaseSpecifier:
3594 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003595 case CXCursor_Constructor:
3596 return createCXString("CXXConstructor");
3597 case CXCursor_Destructor:
3598 return createCXString("CXXDestructor");
3599 case CXCursor_ConversionFunction:
3600 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003601 case CXCursor_TemplateTypeParameter:
3602 return createCXString("TemplateTypeParameter");
3603 case CXCursor_NonTypeTemplateParameter:
3604 return createCXString("NonTypeTemplateParameter");
3605 case CXCursor_TemplateTemplateParameter:
3606 return createCXString("TemplateTemplateParameter");
3607 case CXCursor_FunctionTemplate:
3608 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003609 case CXCursor_ClassTemplate:
3610 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003611 case CXCursor_ClassTemplatePartialSpecialization:
3612 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003613 case CXCursor_NamespaceAlias:
3614 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003615 case CXCursor_UsingDirective:
3616 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003617 case CXCursor_UsingDeclaration:
3618 return createCXString("UsingDeclaration");
Richard Smith162e1c12011-04-15 14:24:37 +00003619 case CXCursor_TypeAliasDecl:
Douglas Gregor352697a2011-06-03 23:08:58 +00003620 return createCXString("TypeAliasDecl");
3621 case CXCursor_ObjCSynthesizeDecl:
3622 return createCXString("ObjCSynthesizeDecl");
3623 case CXCursor_ObjCDynamicDecl:
3624 return createCXString("ObjCDynamicDecl");
Argyrios Kyrtzidis2dfdb942011-09-30 17:58:23 +00003625 case CXCursor_CXXAccessSpecifier:
3626 return createCXString("CXXAccessSpecifier");
Steve Naroff89922f82009-08-31 00:59:03 +00003627 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003628
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003629 llvm_unreachable("Unhandled CXCursorKind");
Steve Naroff600866c2009-08-27 19:51:58 +00003630}
Steve Naroff89922f82009-08-31 00:59:03 +00003631
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003632struct GetCursorData {
3633 SourceLocation TokenBeginLoc;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003634 bool PointsAtMacroArgExpansion;
Argyrios Kyrtzidis135bf8e2012-06-09 03:03:02 +00003635 bool VisitedObjCPropertyImplDecl;
3636 SourceLocation VisitedDeclaratorDeclStartLoc;
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003637 CXCursor &BestCursor;
3638
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003639 GetCursorData(SourceManager &SM,
3640 SourceLocation tokenBegin, CXCursor &outputCursor)
3641 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
3642 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
Argyrios Kyrtzidis135bf8e2012-06-09 03:03:02 +00003643 VisitedObjCPropertyImplDecl = false;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003644 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003645};
3646
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003647static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3648 CXCursor parent,
3649 CXClientData client_data) {
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003650 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
3651 CXCursor *BestCursor = &Data->BestCursor;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003652
3653 // If we point inside a macro argument we should provide info of what the
3654 // token is so use the actual cursor, don't replace it with a macro expansion
3655 // cursor.
3656 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
3657 return CXChildVisit_Recurse;
Argyrios Kyrtzidis65ab9072011-09-26 19:05:37 +00003658
3659 if (clang_isDeclaration(cursor.kind)) {
3660 // Avoid having the implicit methods override the property decls.
Argyrios Kyrtzidisa9d45a32012-04-16 22:42:01 +00003661 if (ObjCMethodDecl *MD
3662 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
Argyrios Kyrtzidis65ab9072011-09-26 19:05:37 +00003663 if (MD->isImplicit())
3664 return CXChildVisit_Break;
Argyrios Kyrtzidisa9d45a32012-04-16 22:42:01 +00003665
3666 } else if (ObjCInterfaceDecl *ID
3667 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) {
3668 // Check that when we have multiple @class references in the same line,
3669 // that later ones do not override the previous ones.
3670 // If we have:
3671 // @class Foo, Bar;
3672 // source ranges for both start at '@', so 'Bar' will end up overriding
3673 // 'Foo' even though the cursor location was at 'Foo'.
3674 if (BestCursor->kind == CXCursor_ObjCInterfaceDecl ||
3675 BestCursor->kind == CXCursor_ObjCClassRef)
3676 if (ObjCInterfaceDecl *PrevID
3677 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(*BestCursor))){
3678 if (PrevID != ID &&
3679 !PrevID->isThisDeclarationADefinition() &&
3680 !ID->isThisDeclarationADefinition())
3681 return CXChildVisit_Break;
3682 }
Argyrios Kyrtzidis135bf8e2012-06-09 03:03:02 +00003683
3684 } else if (DeclaratorDecl *DD
3685 = dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) {
3686 SourceLocation StartLoc = DD->getSourceRange().getBegin();
3687 // Check that when we have multiple declarators in the same line,
3688 // that later ones do not override the previous ones.
3689 // If we have:
3690 // int Foo, Bar;
3691 // source ranges for both start at 'int', so 'Bar' will end up overriding
3692 // 'Foo' even though the cursor location was at 'Foo'.
3693 if (Data->VisitedDeclaratorDeclStartLoc == StartLoc)
3694 return CXChildVisit_Break;
3695 Data->VisitedDeclaratorDeclStartLoc = StartLoc;
3696
3697 } else if (ObjCPropertyImplDecl *PropImp
3698 = dyn_cast_or_null<ObjCPropertyImplDecl>(getCursorDecl(cursor))) {
3699 (void)PropImp;
3700 // Check that when we have multiple @synthesize in the same line,
3701 // that later ones do not override the previous ones.
3702 // If we have:
3703 // @synthesize Foo, Bar;
3704 // source ranges for both start at '@', so 'Bar' will end up overriding
3705 // 'Foo' even though the cursor location was at 'Foo'.
3706 if (Data->VisitedObjCPropertyImplDecl)
3707 return CXChildVisit_Break;
3708 Data->VisitedObjCPropertyImplDecl = true;
Argyrios Kyrtzidisa9d45a32012-04-16 22:42:01 +00003709 }
Argyrios Kyrtzidis65ab9072011-09-26 19:05:37 +00003710 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003711
3712 if (clang_isExpression(cursor.kind) &&
3713 clang_isDeclaration(BestCursor->kind)) {
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00003714 if (Decl *D = getCursorDecl(*BestCursor)) {
3715 // Avoid having the cursor of an expression replace the declaration cursor
3716 // when the expression source range overlaps the declaration range.
3717 // This can happen for C++ constructor expressions whose range generally
3718 // include the variable declaration, e.g.:
3719 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
3720 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
3721 D->getLocation() == Data->TokenBeginLoc)
3722 return CXChildVisit_Break;
3723 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003724 }
3725
Douglas Gregor93798e22010-11-05 21:11:19 +00003726 // If our current best cursor is the construction of a temporary object,
3727 // don't replace that cursor with a type reference, because we want
3728 // clang_getCursor() to point at the constructor.
3729 if (clang_isExpression(BestCursor->kind) &&
3730 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003731 cursor.kind == CXCursor_TypeRef) {
3732 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
3733 // as having the actual point on the type reference.
3734 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
Douglas Gregor93798e22010-11-05 21:11:19 +00003735 return CXChildVisit_Recurse;
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003736 }
Douglas Gregor93798e22010-11-05 21:11:19 +00003737
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003738 *BestCursor = cursor;
3739 return CXChildVisit_Recurse;
3740}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003741
Douglas Gregorb9790342010-01-22 21:44:22 +00003742CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3743 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003744 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003745
Ted Kremeneka60ed472010-11-16 08:15:36 +00003746 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003747 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3748
Ted Kremeneka297de22010-01-25 22:34:44 +00003749 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003750 CXCursor Result = cxcursor::getCursor(TU, SLoc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003751
Douglas Gregor40749ee2010-11-03 00:35:38 +00003752 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregor40749ee2010-11-03 00:35:38 +00003753 if (Logging) {
3754 CXFile SearchFile;
3755 unsigned SearchLine, SearchColumn;
3756 CXFile ResultFile;
3757 unsigned ResultLine, ResultColumn;
Douglas Gregor66537982010-11-17 17:14:07 +00003758 CXString SearchFileName, ResultFileName, KindSpelling, USR;
3759 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
Douglas Gregor40749ee2010-11-03 00:35:38 +00003760 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3761
Chandler Carruth20174222011-08-31 16:53:37 +00003762 clang_getExpansionLocation(Loc, &SearchFile, &SearchLine, &SearchColumn, 0);
3763 clang_getExpansionLocation(ResultLoc, &ResultFile, &ResultLine,
3764 &ResultColumn, 0);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003765 SearchFileName = clang_getFileName(SearchFile);
3766 ResultFileName = clang_getFileName(ResultFile);
3767 KindSpelling = clang_getCursorKindSpelling(Result.kind);
Douglas Gregor66537982010-11-17 17:14:07 +00003768 USR = clang_getCursorUSR(Result);
3769 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n",
Douglas Gregor40749ee2010-11-03 00:35:38 +00003770 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3771 clang_getCString(KindSpelling),
Douglas Gregor66537982010-11-17 17:14:07 +00003772 clang_getCString(ResultFileName), ResultLine, ResultColumn,
3773 clang_getCString(USR), IsDef);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003774 clang_disposeString(SearchFileName);
3775 clang_disposeString(ResultFileName);
3776 clang_disposeString(KindSpelling);
Douglas Gregor66537982010-11-17 17:14:07 +00003777 clang_disposeString(USR);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003778
3779 CXCursor Definition = clang_getCursorDefinition(Result);
3780 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
3781 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
3782 CXString DefinitionKindSpelling
3783 = clang_getCursorKindSpelling(Definition.kind);
3784 CXFile DefinitionFile;
3785 unsigned DefinitionLine, DefinitionColumn;
Chandler Carruth20174222011-08-31 16:53:37 +00003786 clang_getExpansionLocation(DefinitionLoc, &DefinitionFile,
3787 &DefinitionLine, &DefinitionColumn, 0);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003788 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
3789 fprintf(stderr, " -> %s(%s:%d:%d)\n",
3790 clang_getCString(DefinitionKindSpelling),
3791 clang_getCString(DefinitionFileName),
3792 DefinitionLine, DefinitionColumn);
3793 clang_disposeString(DefinitionFileName);
3794 clang_disposeString(DefinitionKindSpelling);
3795 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003796 }
3797
Ted Kremeneke68fff62010-02-17 00:41:32 +00003798 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003799}
3800
Ted Kremenek73885552009-11-17 19:28:59 +00003801CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003802 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003803}
3804
3805unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003806 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003807}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003808
Douglas Gregor9ce55842010-11-20 00:09:34 +00003809unsigned clang_hashCursor(CXCursor C) {
3810 unsigned Index = 0;
3811 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
3812 Index = 1;
3813
3814 return llvm::DenseMapInfo<std::pair<unsigned, void*> >::getHashValue(
3815 std::make_pair(C.kind, C.data[Index]));
3816}
3817
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003818unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003819 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3820}
3821
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003822unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003823 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3824}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003825
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003826unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003827 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3828}
3829
Douglas Gregor97b98722010-01-19 23:20:36 +00003830unsigned clang_isExpression(enum CXCursorKind K) {
3831 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3832}
3833
3834unsigned clang_isStatement(enum CXCursorKind K) {
3835 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3836}
3837
Douglas Gregor8be80e12011-07-06 03:00:34 +00003838unsigned clang_isAttribute(enum CXCursorKind K) {
3839 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
3840}
3841
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003842unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3843 return K == CXCursor_TranslationUnit;
3844}
3845
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003846unsigned clang_isPreprocessing(enum CXCursorKind K) {
3847 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3848}
3849
Ted Kremenekad6eff62010-03-08 21:17:29 +00003850unsigned clang_isUnexposed(enum CXCursorKind K) {
3851 switch (K) {
3852 case CXCursor_UnexposedDecl:
3853 case CXCursor_UnexposedExpr:
3854 case CXCursor_UnexposedStmt:
3855 case CXCursor_UnexposedAttr:
3856 return true;
3857 default:
3858 return false;
3859 }
3860}
3861
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003862CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003863 return C.kind;
3864}
3865
Douglas Gregor98258af2010-01-18 22:46:11 +00003866CXSourceLocation clang_getCursorLocation(CXCursor C) {
3867 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003868 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003869 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003870 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3871 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003872 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003873 }
3874
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003875 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003876 std::pair<ObjCProtocolDecl *, SourceLocation> P
3877 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003878 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003879 }
3880
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003881 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003882 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3883 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003884 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003885 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003886
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003887 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003888 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003889 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003890 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003891
3892 case CXCursor_TemplateRef: {
3893 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3894 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3895 }
3896
Douglas Gregor69319002010-08-31 23:48:11 +00003897 case CXCursor_NamespaceRef: {
3898 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3899 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3900 }
3901
Douglas Gregora67e03f2010-09-09 21:42:20 +00003902 case CXCursor_MemberRef: {
3903 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3904 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3905 }
3906
Douglas Gregor011d8b92012-02-15 00:54:55 +00003907 case CXCursor_VariableRef: {
3908 std::pair<VarDecl *, SourceLocation> P = getCursorVariableRef(C);
3909 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3910 }
3911
Ted Kremenek3064ef92010-08-27 21:34:58 +00003912 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003913 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3914 if (!BaseSpec)
3915 return clang_getNullLocation();
3916
3917 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3918 return cxloc::translateSourceLocation(getCursorContext(C),
3919 TSInfo->getTypeLoc().getBeginLoc());
3920
3921 return cxloc::translateSourceLocation(getCursorContext(C),
Daniel Dunbar96a00142012-03-09 18:35:03 +00003922 BaseSpec->getLocStart());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003923 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003924
Douglas Gregor36897b02010-09-10 00:22:18 +00003925 case CXCursor_LabelRef: {
3926 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3927 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3928 }
3929
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003930 case CXCursor_OverloadedDeclRef:
3931 return cxloc::translateSourceLocation(getCursorContext(C),
3932 getCursorOverloadedDeclRef(C).second);
3933
Douglas Gregorf46034a2010-01-18 23:41:10 +00003934 default:
3935 // FIXME: Need a way to enumerate all non-reference cases.
3936 llvm_unreachable("Missed a reference kind");
3937 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003938 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003939
3940 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003941 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003942 getLocationFromExpr(getCursorExpr(C)));
3943
Douglas Gregor36897b02010-09-10 00:22:18 +00003944 if (clang_isStatement(C.kind))
3945 return cxloc::translateSourceLocation(getCursorContext(C),
3946 getCursorStmt(C)->getLocStart());
3947
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003948 if (C.kind == CXCursor_PreprocessingDirective) {
3949 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3950 return cxloc::translateSourceLocation(getCursorContext(C), L);
3951 }
Douglas Gregor48072312010-03-18 15:23:44 +00003952
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003953 if (C.kind == CXCursor_MacroExpansion) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003954 SourceLocation L
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003955 = cxcursor::getCursorMacroExpansion(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003956 return cxloc::translateSourceLocation(getCursorContext(C), L);
3957 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003958
3959 if (C.kind == CXCursor_MacroDefinition) {
3960 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3961 return cxloc::translateSourceLocation(getCursorContext(C), L);
3962 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003963
3964 if (C.kind == CXCursor_InclusionDirective) {
3965 SourceLocation L
3966 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3967 return cxloc::translateSourceLocation(getCursorContext(C), L);
3968 }
3969
Ted Kremenek9a700d22010-05-12 06:16:13 +00003970 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003971 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003972
Douglas Gregorf46034a2010-01-18 23:41:10 +00003973 Decl *D = getCursorDecl(C);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00003974 if (!D)
3975 return clang_getNullLocation();
3976
Douglas Gregorf46034a2010-01-18 23:41:10 +00003977 SourceLocation Loc = D->getLocation();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003978 // FIXME: Multiple variables declared in a single declaration
3979 // currently lack the information needed to correctly determine their
3980 // ranges when accounting for the type-specifier. We use context
3981 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3982 // and if so, whether it is the first decl.
3983 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3984 if (!cxcursor::isFirstInDeclGroup(C))
3985 Loc = VD->getLocation();
3986 }
3987
Argyrios Kyrtzidisccc6f362012-03-23 03:33:19 +00003988 // For ObjC methods, give the start location of the method name.
3989 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
3990 Loc = MD->getSelectorStartLoc();
3991
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003992 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003993}
Douglas Gregora7bde202010-01-19 00:34:46 +00003994
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003995} // end extern "C"
3996
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003997CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
3998 assert(TU);
3999
4000 // Guard against an invalid SourceLocation, or we may assert in one
4001 // of the following calls.
4002 if (SLoc.isInvalid())
4003 return clang_getNullCursor();
4004
4005 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4006
4007 // Translate the given source location to make it point at the beginning of
4008 // the token under the cursor.
4009 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +00004010 CXXUnit->getASTContext().getLangOpts());
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00004011
4012 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
4013 if (SLoc.isValid()) {
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00004014 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00004015 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
4016 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00004017 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00004018 SourceLocation(SLoc));
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00004019 CursorVis.visitFileRegion();
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00004020 }
4021
4022 return Result;
4023}
4024
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004025static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00004026 if (clang_isReference(C.kind)) {
4027 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004028 case CXCursor_ObjCSuperClassRef:
4029 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004030
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004031 case CXCursor_ObjCProtocolRef:
4032 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004033
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004034 case CXCursor_ObjCClassRef:
4035 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004036
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004037 case CXCursor_TypeRef:
4038 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00004039
4040 case CXCursor_TemplateRef:
4041 return getCursorTemplateRef(C).second;
4042
Douglas Gregor69319002010-08-31 23:48:11 +00004043 case CXCursor_NamespaceRef:
4044 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00004045
4046 case CXCursor_MemberRef:
4047 return getCursorMemberRef(C).second;
4048
Ted Kremenek3064ef92010-08-27 21:34:58 +00004049 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00004050 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00004051
Douglas Gregor36897b02010-09-10 00:22:18 +00004052 case CXCursor_LabelRef:
4053 return getCursorLabelRef(C).second;
4054
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004055 case CXCursor_OverloadedDeclRef:
4056 return getCursorOverloadedDeclRef(C).second;
4057
Douglas Gregor011d8b92012-02-15 00:54:55 +00004058 case CXCursor_VariableRef:
4059 return getCursorVariableRef(C).second;
4060
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004061 default:
4062 // FIXME: Need a way to enumerate all non-reference cases.
4063 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00004064 }
4065 }
Douglas Gregor97b98722010-01-19 23:20:36 +00004066
4067 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004068 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00004069
4070 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004071 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004072
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00004073 if (clang_isAttribute(C.kind))
4074 return getCursorAttr(C)->getRange();
4075
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004076 if (C.kind == CXCursor_PreprocessingDirective)
4077 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00004078
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004079 if (C.kind == CXCursor_MacroExpansion) {
4080 ASTUnit *TU = getCursorASTUnit(C);
4081 SourceRange Range = cxcursor::getCursorMacroExpansion(C)->getSourceRange();
4082 return TU->mapRangeFromPreamble(Range);
4083 }
Douglas Gregor572feb22010-03-18 18:04:21 +00004084
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004085 if (C.kind == CXCursor_MacroDefinition) {
4086 ASTUnit *TU = getCursorASTUnit(C);
4087 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
4088 return TU->mapRangeFromPreamble(Range);
4089 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00004090
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004091 if (C.kind == CXCursor_InclusionDirective) {
4092 ASTUnit *TU = getCursorASTUnit(C);
4093 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
4094 return TU->mapRangeFromPreamble(Range);
4095 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00004096
Argyrios Kyrtzidis0822c5f2012-03-19 23:17:58 +00004097 if (C.kind == CXCursor_TranslationUnit) {
4098 ASTUnit *TU = getCursorASTUnit(C);
4099 FileID MainID = TU->getSourceManager().getMainFileID();
4100 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
4101 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
4102 return SourceRange(Start, End);
4103 }
4104
Ted Kremenek007a7c92010-11-01 23:26:51 +00004105 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
4106 Decl *D = cxcursor::getCursorDecl(C);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00004107 if (!D)
4108 return SourceRange();
4109
Ted Kremenek007a7c92010-11-01 23:26:51 +00004110 SourceRange R = D->getSourceRange();
4111 // FIXME: Multiple variables declared in a single declaration
4112 // currently lack the information needed to correctly determine their
4113 // ranges when accounting for the type-specifier. We use context
4114 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
4115 // and if so, whether it is the first decl.
4116 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4117 if (!cxcursor::isFirstInDeclGroup(C))
4118 R.setBegin(VD->getLocation());
4119 }
4120 return R;
4121 }
Douglas Gregor66537982010-11-17 17:14:07 +00004122 return SourceRange();
4123}
4124
4125/// \brief Retrieves the "raw" cursor extent, which is then extended to include
4126/// the decl-specifier-seq for declarations.
4127static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
4128 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
4129 Decl *D = cxcursor::getCursorDecl(C);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00004130 if (!D)
4131 return SourceRange();
4132
Douglas Gregor66537982010-11-17 17:14:07 +00004133 SourceRange R = D->getSourceRange();
Douglas Gregor66537982010-11-17 17:14:07 +00004134
Douglas Gregor2494dd02011-03-01 01:34:45 +00004135 // Adjust the start of the location for declarations preceded by
4136 // declaration specifiers.
4137 SourceLocation StartLoc;
4138 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
4139 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
Daniel Dunbar96a00142012-03-09 18:35:03 +00004140 StartLoc = TI->getTypeLoc().getLocStart();
Douglas Gregor2494dd02011-03-01 01:34:45 +00004141 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
4142 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
Daniel Dunbar96a00142012-03-09 18:35:03 +00004143 StartLoc = TI->getTypeLoc().getLocStart();
Douglas Gregor2494dd02011-03-01 01:34:45 +00004144 }
4145
4146 if (StartLoc.isValid() && R.getBegin().isValid() &&
4147 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
4148 R.setBegin(StartLoc);
4149
4150 // FIXME: Multiple variables declared in a single declaration
4151 // currently lack the information needed to correctly determine their
4152 // ranges when accounting for the type-specifier. We use context
4153 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
4154 // and if so, whether it is the first decl.
4155 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4156 if (!cxcursor::isFirstInDeclGroup(C))
4157 R.setBegin(VD->getLocation());
Douglas Gregor66537982010-11-17 17:14:07 +00004158 }
4159
4160 return R;
4161 }
4162
4163 return getRawCursorExtent(C);
4164}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004165
4166extern "C" {
4167
4168CXSourceRange clang_getCursorExtent(CXCursor C) {
4169 SourceRange R = getRawCursorExtent(C);
4170 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00004171 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004172
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004173 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00004174}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004175
4176CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00004177 if (clang_isInvalid(C.kind))
4178 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004179
Ted Kremeneka60ed472010-11-16 08:15:36 +00004180 CXTranslationUnit tu = getCursorTU(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004181 if (clang_isDeclaration(C.kind)) {
4182 Decl *D = getCursorDecl(C);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00004183 if (!D)
4184 return clang_getNullCursor();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004185 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004186 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Chris Lattner5f9e2722011-07-23 10:55:15 +00004187 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00004188 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
4189 return MakeCXCursor(Property, tu);
4190
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004191 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004192 }
4193
Douglas Gregor97b98722010-01-19 23:20:36 +00004194 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004195 Expr *E = getCursorExpr(C);
4196 Decl *D = getDeclFromExpr(E);
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00004197 if (D) {
4198 CXCursor declCursor = MakeCXCursor(D, tu);
4199 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
4200 declCursor);
4201 return declCursor;
4202 }
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004203
4204 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004205 return MakeCursorOverloadedDeclRef(Ovl, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004206
Douglas Gregor97b98722010-01-19 23:20:36 +00004207 return clang_getNullCursor();
4208 }
4209
Douglas Gregor36897b02010-09-10 00:22:18 +00004210 if (clang_isStatement(C.kind)) {
4211 Stmt *S = getCursorStmt(C);
4212 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Ted Kremenek37c2e962011-03-15 23:47:49 +00004213 if (LabelDecl *label = Goto->getLabel())
4214 if (LabelStmt *labelS = label->getStmt())
4215 return MakeCXCursor(labelS, getCursorDecl(C), tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00004216
4217 return clang_getNullCursor();
4218 }
4219
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004220 if (C.kind == CXCursor_MacroExpansion) {
Chandler Carruth9e5bb852011-07-14 08:20:46 +00004221 if (MacroDefinition *Def = getCursorMacroExpansion(C)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004222 return MakeMacroDefinitionCursor(Def, tu);
Douglas Gregorbf7efa22010-03-18 18:23:03 +00004223 }
4224
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004225 if (!clang_isReference(C.kind))
4226 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004227
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004228 switch (C.kind) {
4229 case CXCursor_ObjCSuperClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004230 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004231
4232 case CXCursor_ObjCProtocolRef: {
Argyrios Kyrtzidis98c16b82012-01-24 19:40:15 +00004233 ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
4234 if (ObjCProtocolDecl *Def = Prot->getDefinition())
4235 return MakeCXCursor(Def, tu);
4236
Argyrios Kyrtzidisc15707d2012-01-24 21:39:26 +00004237 return MakeCXCursor(Prot, tu);
Argyrios Kyrtzidis98c16b82012-01-24 19:40:15 +00004238 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004239
Douglas Gregor7723fec2011-12-15 20:29:51 +00004240 case CXCursor_ObjCClassRef: {
4241 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
4242 if (ObjCInterfaceDecl *Def = Class->getDefinition())
4243 return MakeCXCursor(Def, tu);
4244
Argyrios Kyrtzidisc15707d2012-01-24 21:39:26 +00004245 return MakeCXCursor(Class, tu);
Douglas Gregor7723fec2011-12-15 20:29:51 +00004246 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00004247
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004248 case CXCursor_TypeRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004249 return MakeCXCursor(getCursorTypeRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00004250
4251 case CXCursor_TemplateRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004252 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00004253
Douglas Gregor69319002010-08-31 23:48:11 +00004254 case CXCursor_NamespaceRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004255 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
Douglas Gregor69319002010-08-31 23:48:11 +00004256
Douglas Gregora67e03f2010-09-09 21:42:20 +00004257 case CXCursor_MemberRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004258 return MakeCXCursor(getCursorMemberRef(C).first, tu );
Douglas Gregora67e03f2010-09-09 21:42:20 +00004259
Ted Kremenek3064ef92010-08-27 21:34:58 +00004260 case CXCursor_CXXBaseSpecifier: {
4261 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
4262 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004263 tu ));
Ted Kremenek3064ef92010-08-27 21:34:58 +00004264 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004265
Douglas Gregor36897b02010-09-10 00:22:18 +00004266 case CXCursor_LabelRef:
4267 // FIXME: We end up faking the "parent" declaration here because we
4268 // don't want to make CXCursor larger.
4269 return MakeCXCursor(getCursorLabelRef(C).first,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004270 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
4271 .getTranslationUnitDecl(),
4272 tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00004273
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004274 case CXCursor_OverloadedDeclRef:
4275 return C;
Douglas Gregor011d8b92012-02-15 00:54:55 +00004276
4277 case CXCursor_VariableRef:
4278 return MakeCXCursor(getCursorVariableRef(C).first, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004279
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004280 default:
4281 // We would prefer to enumerate all non-reference cursor kinds here.
4282 llvm_unreachable("Unhandled reference cursor kind");
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004283 }
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004284}
4285
Douglas Gregorb6998662010-01-19 19:34:47 +00004286CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00004287 if (clang_isInvalid(C.kind))
4288 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004289
Ted Kremeneka60ed472010-11-16 08:15:36 +00004290 CXTranslationUnit TU = getCursorTU(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004291
Douglas Gregorb6998662010-01-19 19:34:47 +00004292 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00004293 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00004294 C = clang_getCursorReferenced(C);
4295 WasReference = true;
4296 }
4297
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004298 if (C.kind == CXCursor_MacroExpansion)
Douglas Gregorbf7efa22010-03-18 18:23:03 +00004299 return clang_getCursorReferenced(C);
4300
Douglas Gregorb6998662010-01-19 19:34:47 +00004301 if (!clang_isDeclaration(C.kind))
4302 return clang_getNullCursor();
4303
4304 Decl *D = getCursorDecl(C);
4305 if (!D)
4306 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004307
Douglas Gregorb6998662010-01-19 19:34:47 +00004308 switch (D->getKind()) {
4309 // Declaration kinds that don't really separate the notions of
4310 // declaration and definition.
4311 case Decl::Namespace:
4312 case Decl::Typedef:
Richard Smith162e1c12011-04-15 14:24:37 +00004313 case Decl::TypeAlias:
Richard Smith3e4c6c42011-05-05 21:57:07 +00004314 case Decl::TypeAliasTemplate:
Douglas Gregorb6998662010-01-19 19:34:47 +00004315 case Decl::TemplateTypeParm:
4316 case Decl::EnumConstant:
4317 case Decl::Field:
Benjamin Kramerd9811462010-11-21 14:11:41 +00004318 case Decl::IndirectField:
Douglas Gregorb6998662010-01-19 19:34:47 +00004319 case Decl::ObjCIvar:
4320 case Decl::ObjCAtDefsField:
4321 case Decl::ImplicitParam:
4322 case Decl::ParmVar:
4323 case Decl::NonTypeTemplateParm:
4324 case Decl::TemplateTemplateParm:
4325 case Decl::ObjCCategoryImpl:
4326 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00004327 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00004328 case Decl::LinkageSpec:
4329 case Decl::ObjCPropertyImpl:
4330 case Decl::FileScopeAsm:
4331 case Decl::StaticAssert:
4332 case Decl::Block:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00004333 case Decl::Label: // FIXME: Is this right??
Francois Pichetaf0f4d02011-08-14 03:52:19 +00004334 case Decl::ClassScopeFunctionSpecialization:
Douglas Gregor15de72c2011-12-02 23:23:56 +00004335 case Decl::Import:
Douglas Gregorb6998662010-01-19 19:34:47 +00004336 return C;
4337
4338 // Declaration kinds that don't make any sense here, but are
4339 // nonetheless harmless.
4340 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00004341 break;
4342
4343 // Declaration kinds for which the definition is not resolvable.
4344 case Decl::UnresolvedUsingTypename:
4345 case Decl::UnresolvedUsingValue:
4346 break;
4347
4348 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00004349 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004350 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004351
4352 case Decl::NamespaceAlias:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004353 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004354
4355 case Decl::Enum:
4356 case Decl::Record:
4357 case Decl::CXXRecord:
4358 case Decl::ClassTemplateSpecialization:
4359 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00004360 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004361 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004362 return clang_getNullCursor();
4363
4364 case Decl::Function:
4365 case Decl::CXXMethod:
4366 case Decl::CXXConstructor:
4367 case Decl::CXXDestructor:
4368 case Decl::CXXConversion: {
4369 const FunctionDecl *Def = 0;
4370 if (cast<FunctionDecl>(D)->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004371 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004372 return clang_getNullCursor();
4373 }
4374
4375 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00004376 // Ask the variable if it has a definition.
4377 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004378 return MakeCXCursor(Def, TU);
Sebastian Redl31310a22010-02-01 20:16:42 +00004379 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00004380 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004381
Douglas Gregorb6998662010-01-19 19:34:47 +00004382 case Decl::FunctionTemplate: {
4383 const FunctionDecl *Def = 0;
4384 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004385 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004386 return clang_getNullCursor();
4387 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004388
Douglas Gregorb6998662010-01-19 19:34:47 +00004389 case Decl::ClassTemplate: {
4390 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00004391 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00004392 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004393 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004394 return clang_getNullCursor();
4395 }
4396
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004397 case Decl::Using:
4398 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004399 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004400
4401 case Decl::UsingShadow:
4402 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004403 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004404 TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004405
4406 case Decl::ObjCMethod: {
4407 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
4408 if (Method->isThisDeclarationADefinition())
4409 return C;
4410
4411 // Dig out the method definition in the associated
4412 // @implementation, if we have it.
4413 // FIXME: The ASTs should make finding the definition easier.
4414 if (ObjCInterfaceDecl *Class
4415 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
4416 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
4417 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
4418 Method->isInstanceMethod()))
4419 if (Def->isThisDeclarationADefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004420 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004421
4422 return clang_getNullCursor();
4423 }
4424
4425 case Decl::ObjCCategory:
4426 if (ObjCCategoryImplDecl *Impl
4427 = cast<ObjCCategoryDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004428 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004429 return clang_getNullCursor();
4430
4431 case Decl::ObjCProtocol:
Douglas Gregor5e2a1ff2012-01-01 19:29:29 +00004432 if (ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
4433 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004434 return clang_getNullCursor();
4435
Douglas Gregor375bb142011-12-27 22:43:10 +00004436 case Decl::ObjCInterface: {
Douglas Gregorb6998662010-01-19 19:34:47 +00004437 // There are two notions of a "definition" for an Objective-C
4438 // class: the interface and its implementation. When we resolved a
4439 // reference to an Objective-C class, produce the @interface as
4440 // the definition; when we were provided with the interface,
4441 // produce the @implementation as the definition.
Douglas Gregor375bb142011-12-27 22:43:10 +00004442 ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
Douglas Gregorb6998662010-01-19 19:34:47 +00004443 if (WasReference) {
Douglas Gregor375bb142011-12-27 22:43:10 +00004444 if (ObjCInterfaceDecl *Def = IFace->getDefinition())
Douglas Gregor7723fec2011-12-15 20:29:51 +00004445 return MakeCXCursor(Def, TU);
Douglas Gregor375bb142011-12-27 22:43:10 +00004446 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004447 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004448 return clang_getNullCursor();
Douglas Gregor375bb142011-12-27 22:43:10 +00004449 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004450
Douglas Gregorb6998662010-01-19 19:34:47 +00004451 case Decl::ObjCProperty:
4452 // FIXME: We don't really know where to find the
4453 // ObjCPropertyImplDecls that implement this property.
4454 return clang_getNullCursor();
4455
4456 case Decl::ObjCCompatibleAlias:
4457 if (ObjCInterfaceDecl *Class
4458 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
Douglas Gregor7723fec2011-12-15 20:29:51 +00004459 if (ObjCInterfaceDecl *Def = Class->getDefinition())
4460 return MakeCXCursor(Def, TU);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004461
Douglas Gregorb6998662010-01-19 19:34:47 +00004462 return clang_getNullCursor();
4463
Douglas Gregorb6998662010-01-19 19:34:47 +00004464 case Decl::Friend:
4465 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004466 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004467 return clang_getNullCursor();
4468
4469 case Decl::FriendTemplate:
4470 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004471 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004472 return clang_getNullCursor();
4473 }
4474
4475 return clang_getNullCursor();
4476}
4477
4478unsigned clang_isCursorDefinition(CXCursor C) {
4479 if (!clang_isDeclaration(C.kind))
4480 return 0;
4481
4482 return clang_getCursorDefinition(C) == C;
4483}
4484
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004485CXCursor clang_getCanonicalCursor(CXCursor C) {
4486 if (!clang_isDeclaration(C.kind))
4487 return C;
4488
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004489 if (Decl *D = getCursorDecl(C)) {
Argyrios Kyrtzidisdebb00f2011-07-15 22:37:58 +00004490 if (ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
4491 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
4492 return MakeCXCursor(CatD, getCursorTU(C));
4493
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004494 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
4495 if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
4496 return MakeCXCursor(IFD, getCursorTU(C));
4497
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004498 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004499 }
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004500
4501 return C;
4502}
Argyrios Kyrtzidis34ebe1e2012-03-30 22:15:48 +00004503
4504int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) {
4505 return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first;
4506}
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004507
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004508unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004509 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004510 return 0;
4511
4512 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
4513 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
4514 return E->getNumDecls();
4515
4516 if (OverloadedTemplateStorage *S
4517 = Storage.dyn_cast<OverloadedTemplateStorage*>())
4518 return S->size();
4519
4520 Decl *D = Storage.get<Decl*>();
4521 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00004522 return Using->shadow_size();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004523
4524 return 0;
4525}
4526
4527CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004528 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004529 return clang_getNullCursor();
4530
4531 if (index >= clang_getNumOverloadedDecls(cursor))
4532 return clang_getNullCursor();
4533
Ted Kremeneka60ed472010-11-16 08:15:36 +00004534 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004535 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
4536 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004537 return MakeCXCursor(E->decls_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004538
4539 if (OverloadedTemplateStorage *S
4540 = Storage.dyn_cast<OverloadedTemplateStorage*>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004541 return MakeCXCursor(S->begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004542
4543 Decl *D = Storage.get<Decl*>();
4544 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
4545 // FIXME: This is, unfortunately, linear time.
4546 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
4547 std::advance(Pos, index);
Ted Kremeneka60ed472010-11-16 08:15:36 +00004548 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004549 }
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004550
4551 return clang_getNullCursor();
4552}
4553
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00004554void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00004555 const char **startBuf,
4556 const char **endBuf,
4557 unsigned *startLine,
4558 unsigned *startColumn,
4559 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00004560 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00004561 assert(getCursorDecl(C) && "CXCursor has null decl");
4562 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00004563 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
4564 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004565
Steve Naroff4ade6d62009-09-23 17:52:52 +00004566 SourceManager &SM = FD->getASTContext().getSourceManager();
4567 *startBuf = SM.getCharacterData(Body->getLBracLoc());
4568 *endBuf = SM.getCharacterData(Body->getRBracLoc());
4569 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
4570 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
4571 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
4572 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
4573}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004574
Douglas Gregor430d7a12011-07-25 17:48:11 +00004575
4576CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
4577 unsigned PieceIndex) {
4578 RefNamePieces Pieces;
4579
4580 switch (C.kind) {
4581 case CXCursor_MemberRefExpr:
4582 if (MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
4583 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
4584 E->getQualifierLoc().getSourceRange());
4585 break;
4586
4587 case CXCursor_DeclRefExpr:
4588 if (DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C)))
4589 Pieces = buildPieces(NameFlags, false, E->getNameInfo(),
4590 E->getQualifierLoc().getSourceRange(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00004591 E->getOptionalExplicitTemplateArgs());
Douglas Gregor430d7a12011-07-25 17:48:11 +00004592 break;
4593
4594 case CXCursor_CallExpr:
4595 if (CXXOperatorCallExpr *OCE =
4596 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
4597 Expr *Callee = OCE->getCallee();
4598 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
4599 Callee = ICE->getSubExpr();
4600
4601 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
4602 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
4603 DRE->getQualifierLoc().getSourceRange());
4604 }
4605 break;
4606
4607 default:
4608 break;
4609 }
4610
4611 if (Pieces.empty()) {
4612 if (PieceIndex == 0)
4613 return clang_getCursorExtent(C);
4614 } else if (PieceIndex < Pieces.size()) {
4615 SourceRange R = Pieces[PieceIndex];
4616 if (R.isValid())
4617 return cxloc::translateSourceRange(getCursorContext(C), R);
4618 }
4619
4620 return clang_getNullRange();
4621}
4622
Douglas Gregor0a812cf2010-02-18 23:07:20 +00004623void clang_enableStackTraces(void) {
4624 llvm::sys::PrintStackTraceOnErrorSignal();
4625}
4626
Daniel Dunbar995aaf92010-11-04 01:26:29 +00004627void clang_executeOnThread(void (*fn)(void*), void *user_data,
4628 unsigned stack_size) {
4629 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
4630}
4631
Ted Kremenekfb480492010-01-13 21:46:36 +00004632} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00004633
Ted Kremenekfb480492010-01-13 21:46:36 +00004634//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004635// Token-based Operations.
4636//===----------------------------------------------------------------------===//
4637
4638/* CXToken layout:
4639 * int_data[0]: a CXTokenKind
4640 * int_data[1]: starting token location
4641 * int_data[2]: token length
4642 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004643 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004644 * otherwise unused.
4645 */
4646extern "C" {
4647
4648CXTokenKind clang_getTokenKind(CXToken CXTok) {
4649 return static_cast<CXTokenKind>(CXTok.int_data[0]);
4650}
4651
4652CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
4653 switch (clang_getTokenKind(CXTok)) {
4654 case CXToken_Identifier:
4655 case CXToken_Keyword:
4656 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004657 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
4658 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004659
4660 case CXToken_Literal: {
4661 // We have stashed the starting pointer in the ptr_data field. Use it.
4662 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Chris Lattner5f9e2722011-07-23 10:55:15 +00004663 return createCXString(StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004664 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004665
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004666 case CXToken_Punctuation:
4667 case CXToken_Comment:
4668 break;
4669 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004670
4671 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004672 // deconstructing the source location.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004673 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004674 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004675 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004676
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004677 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
4678 std::pair<FileID, unsigned> LocInfo
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004679 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00004680 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004681 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004682 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
4683 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00004684 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004685
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004686 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004687}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004688
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004689CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004690 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004691 if (!CXXUnit)
4692 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004693
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004694 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
4695 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4696}
4697
4698CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004699 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor5352ac02010-01-28 00:27:43 +00004700 if (!CXXUnit)
4701 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004702
4703 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004704 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4705}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004706
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004707static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
4708 SmallVectorImpl<CXToken> &CXTokens) {
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004709 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4710 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004711 = SourceMgr.getDecomposedLoc(Range.getBegin());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004712 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004713 = SourceMgr.getDecomposedLoc(Range.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004714
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004715 // Cannot tokenize across files.
4716 if (BeginLocInfo.first != EndLocInfo.first)
4717 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004718
4719 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004720 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004721 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004722 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00004723 if (Invalid)
4724 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00004725
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004726 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
David Blaikie4e4d0842012-03-11 07:00:24 +00004727 CXXUnit->getASTContext().getLangOpts(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004728 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004729 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004730
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004731 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004732 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004733 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00004734 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004735 do {
4736 // Lex the next token
4737 Lex.LexFromRawLexer(Tok);
4738 if (Tok.is(tok::eof))
4739 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004740
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004741 // Initialize the CXToken.
4742 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004743
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004744 // - Common fields
4745 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
4746 CXTok.int_data[2] = Tok.getLength();
4747 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004748
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004749 // - Kind-specific fields
4750 if (Tok.isLiteral()) {
4751 CXTok.int_data[0] = CXToken_Literal;
4752 CXTok.ptr_data = (void *)Tok.getLiteralData();
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004753 } else if (Tok.is(tok::raw_identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00004754 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004755 IdentifierInfo *II
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004756 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004757
David Chisnall096428b2010-10-13 21:44:48 +00004758 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004759 CXTok.int_data[0] = CXToken_Keyword;
4760 }
4761 else {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004762 CXTok.int_data[0] = Tok.is(tok::identifier)
4763 ? CXToken_Identifier
4764 : CXToken_Keyword;
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004765 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004766 CXTok.ptr_data = II;
4767 } else if (Tok.is(tok::comment)) {
4768 CXTok.int_data[0] = CXToken_Comment;
4769 CXTok.ptr_data = 0;
4770 } else {
4771 CXTok.int_data[0] = CXToken_Punctuation;
4772 CXTok.ptr_data = 0;
4773 }
4774 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00004775 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004776 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004777}
4778
4779void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
4780 CXToken **Tokens, unsigned *NumTokens) {
4781 if (Tokens)
4782 *Tokens = 0;
4783 if (NumTokens)
4784 *NumTokens = 0;
4785
4786 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4787 if (!CXXUnit || !Tokens || !NumTokens)
4788 return;
4789
4790 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4791
4792 SourceRange R = cxloc::translateCXSourceRange(Range);
4793 if (R.isInvalid())
4794 return;
4795
4796 SmallVector<CXToken, 32> CXTokens;
4797 getTokens(CXXUnit, R, CXTokens);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004798
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004799 if (CXTokens.empty())
4800 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004801
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004802 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
4803 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
4804 *NumTokens = CXTokens.size();
4805}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004806
Ted Kremenek6db61092010-05-05 00:55:15 +00004807void clang_disposeTokens(CXTranslationUnit TU,
4808 CXToken *Tokens, unsigned NumTokens) {
4809 free(Tokens);
4810}
4811
4812} // end: extern "C"
4813
4814//===----------------------------------------------------------------------===//
4815// Token annotation APIs.
4816//===----------------------------------------------------------------------===//
4817
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004818typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004819static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4820 CXCursor parent,
4821 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00004822namespace {
4823class AnnotateTokensWorker {
4824 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004825 CXToken *Tokens;
4826 CXCursor *Cursors;
4827 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004828 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00004829 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004830 CursorVisitor AnnotateVis;
4831 SourceManager &SrcMgr;
Douglas Gregorf5251602011-03-08 17:10:18 +00004832 bool HasContextSensitiveKeywords;
4833
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004834 bool MoreTokens() const { return TokIdx < NumTokens; }
4835 unsigned NextToken() const { return TokIdx; }
4836 void AdvanceToken() { ++TokIdx; }
4837 SourceLocation GetTokenLoc(unsigned tokI) {
4838 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4839 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004840 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004841 return Tokens[tokI].int_data[3] != 0;
4842 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004843 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004844 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[3]);
4845 }
4846
4847 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004848 void annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
4849 SourceRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004850
Ted Kremenek6db61092010-05-05 00:55:15 +00004851public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00004852 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004853 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004854 CXTranslationUnit tu, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00004855 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00004856 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004857 AnnotateVis(tu,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00004858 AnnotateTokensVisitor, this,
4859 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00004860 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00004861 RegionOfInterest),
Douglas Gregorf5251602011-03-08 17:10:18 +00004862 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()),
4863 HasContextSensitiveKeywords(false) { }
Ted Kremenek11949cb2010-05-05 00:55:17 +00004864
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004865 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00004866 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004867 void AnnotateTokens();
Douglas Gregorf5251602011-03-08 17:10:18 +00004868
4869 /// \brief Determine whether the annotator saw any cursors that have
4870 /// context-sensitive keywords.
4871 bool hasContextSensitiveKeywords() const {
4872 return HasContextSensitiveKeywords;
4873 }
Ted Kremenek6db61092010-05-05 00:55:15 +00004874};
4875}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004876
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004877void AnnotateTokensWorker::AnnotateTokens() {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004878 // Walk the AST within the region of interest, annotating tokens
4879 // along the way.
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004880 AnnotateVis.visitFileRegion();
Ted Kremenek11949cb2010-05-05 00:55:17 +00004881
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004882 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4883 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004884 if (Pos != Annotated.end() &&
4885 (clang_isInvalid(Cursors[I].kind) ||
4886 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004887 Cursors[I] = Pos->second;
4888 }
4889
4890 // Finish up annotating any tokens left.
4891 if (!MoreTokens())
4892 return;
4893
4894 const CXCursor &C = clang_getNullCursor();
4895 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004896 if (I < PreprocessingTokIdx && clang_isPreprocessing(Cursors[I].kind))
4897 continue;
4898
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004899 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4900 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004901 }
4902}
4903
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004904/// \brief It annotates and advances tokens with a cursor until the comparison
4905//// between the cursor location and the source range is the same as
4906/// \arg compResult.
4907///
4908/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
4909/// Pass RangeOverlap to annotate tokens inside a range.
4910void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
4911 RangeComparisonResult compResult,
4912 SourceRange range) {
4913 while (MoreTokens()) {
4914 const unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004915 if (isFunctionMacroToken(I))
4916 return annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004917
4918 SourceLocation TokLoc = GetTokenLoc(I);
4919 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4920 Cursors[I] = updateC;
4921 AdvanceToken();
4922 continue;
4923 }
4924 break;
4925 }
4926}
4927
4928/// \brief Special annotation handling for macro argument tokens.
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004929void AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
4930 CXCursor updateC,
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004931 RangeComparisonResult compResult,
4932 SourceRange range) {
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004933 assert(MoreTokens());
4934 assert(isFunctionMacroToken(NextToken()) &&
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004935 "Should be called only for macro arg tokens");
4936
4937 // This works differently than annotateAndAdvanceTokens; because expanded
4938 // macro arguments can have arbitrary translation-unit source order, we do not
4939 // advance the token index one by one until a token fails the range test.
4940 // We only advance once past all of the macro arg tokens if all of them
4941 // pass the range test. If one of them fails we keep the token index pointing
4942 // at the start of the macro arg tokens so that the failing token will be
4943 // annotated by a subsequent annotation try.
4944
4945 bool atLeastOneCompFail = false;
4946
4947 unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004948 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
4949 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004950 if (TokLoc.isFileID())
4951 continue; // not macro arg token, it's parens or comma.
4952 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4953 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
4954 Cursors[I] = updateC;
4955 } else
4956 atLeastOneCompFail = true;
4957 }
4958
4959 if (!atLeastOneCompFail)
4960 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
4961}
4962
Ted Kremenek6db61092010-05-05 00:55:15 +00004963enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004964AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004965 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004966 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004967 if (cursorRange.isInvalid())
4968 return CXChildVisit_Recurse;
Douglas Gregorf5251602011-03-08 17:10:18 +00004969
4970 if (!HasContextSensitiveKeywords) {
4971 // Objective-C properties can have context-sensitive keywords.
4972 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
4973 if (ObjCPropertyDecl *Property
4974 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
4975 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
4976 }
4977 // Objective-C methods can have context-sensitive keywords.
4978 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
4979 cursor.kind == CXCursor_ObjCClassMethodDecl) {
4980 if (ObjCMethodDecl *Method
4981 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
4982 if (Method->getObjCDeclQualifier())
4983 HasContextSensitiveKeywords = true;
4984 else {
4985 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
4986 PEnd = Method->param_end();
4987 P != PEnd; ++P) {
4988 if ((*P)->getObjCDeclQualifier()) {
4989 HasContextSensitiveKeywords = true;
4990 break;
4991 }
4992 }
4993 }
4994 }
4995 }
4996 // C++ methods can have context-sensitive keywords.
4997 else if (cursor.kind == CXCursor_CXXMethod) {
4998 if (CXXMethodDecl *Method
4999 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
5000 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
5001 HasContextSensitiveKeywords = true;
5002 }
5003 }
5004 // C++ classes can have context-sensitive keywords.
5005 else if (cursor.kind == CXCursor_StructDecl ||
5006 cursor.kind == CXCursor_ClassDecl ||
5007 cursor.kind == CXCursor_ClassTemplate ||
5008 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
5009 if (Decl *D = getCursorDecl(cursor))
5010 if (D->hasAttr<FinalAttr>())
5011 HasContextSensitiveKeywords = true;
5012 }
5013 }
5014
Douglas Gregor4419b672010-10-21 06:10:04 +00005015 if (clang_isPreprocessing(cursor.kind)) {
Chandler Carruthcea731a2011-07-14 16:07:57 +00005016 // For macro expansions, just note where the beginning of the macro
5017 // expansion occurs.
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00005018 if (cursor.kind == CXCursor_MacroExpansion) {
Douglas Gregor4419b672010-10-21 06:10:04 +00005019 Annotated[Loc.int_data] = cursor;
5020 return CXChildVisit_Recurse;
5021 }
5022
Douglas Gregor4419b672010-10-21 06:10:04 +00005023 // Items in the preprocessing record are kept separate from items in
5024 // declarations, so we keep a separate token index.
5025 unsigned SavedTokIdx = TokIdx;
5026 TokIdx = PreprocessingTokIdx;
5027
5028 // Skip tokens up until we catch up to the beginning of the preprocessing
5029 // entry.
5030 while (MoreTokens()) {
5031 const unsigned I = NextToken();
5032 SourceLocation TokLoc = GetTokenLoc(I);
5033 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
5034 case RangeBefore:
5035 AdvanceToken();
5036 continue;
5037 case RangeAfter:
5038 case RangeOverlap:
5039 break;
5040 }
5041 break;
5042 }
5043
5044 // Look at all of the tokens within this range.
5045 while (MoreTokens()) {
5046 const unsigned I = NextToken();
5047 SourceLocation TokLoc = GetTokenLoc(I);
5048 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
5049 case RangeBefore:
David Blaikieb219cfc2011-09-23 05:06:16 +00005050 llvm_unreachable("Infeasible");
Douglas Gregor4419b672010-10-21 06:10:04 +00005051 case RangeAfter:
5052 break;
5053 case RangeOverlap:
5054 Cursors[I] = cursor;
5055 AdvanceToken();
5056 continue;
5057 }
5058 break;
5059 }
5060
5061 // Save the preprocessing token index; restore the non-preprocessing
5062 // token index.
5063 PreprocessingTokIdx = TokIdx;
5064 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005065 return CXChildVisit_Recurse;
5066 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005067
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005068 if (cursorRange.isInvalid())
5069 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00005070
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005071 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
5072
Ted Kremeneka333c662010-05-12 05:29:33 +00005073 // Adjust the annotated range based specific declarations.
5074 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
5075 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00005076 Decl *D = cxcursor::getCursorDecl(cursor);
Douglas Gregor2494dd02011-03-01 01:34:45 +00005077
5078 SourceLocation StartLoc;
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00005079 if (const DeclaratorDecl *DD = dyn_cast_or_null<DeclaratorDecl>(D)) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00005080 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
Daniel Dunbar96a00142012-03-09 18:35:03 +00005081 StartLoc = TI->getTypeLoc().getLocStart();
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00005082 } else if (TypedefDecl *Typedef = dyn_cast_or_null<TypedefDecl>(D)) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00005083 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
Daniel Dunbar96a00142012-03-09 18:35:03 +00005084 StartLoc = TI->getTypeLoc().getLocStart();
Ted Kremeneka333c662010-05-12 05:29:33 +00005085 }
Douglas Gregor2494dd02011-03-01 01:34:45 +00005086
5087 if (StartLoc.isValid() && L.isValid() &&
5088 SrcMgr.isBeforeInTranslationUnit(StartLoc, L))
5089 cursorRange.setBegin(StartLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00005090 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00005091
Ted Kremenek3f404602010-08-14 01:14:06 +00005092 // If the location of the cursor occurs within a macro instantiation, record
5093 // the spelling location of the cursor in our annotation map. We can then
5094 // paper over the token labelings during a post-processing step to try and
5095 // get cursor mappings for tokens that are the *arguments* of a macro
5096 // instantiation.
5097 if (L.isMacroID()) {
5098 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
5099 // Only invalidate the old annotation if it isn't part of a preprocessing
5100 // directive. Here we assume that the default construction of CXCursor
5101 // results in CXCursor.kind being an initialized value (i.e., 0). If
5102 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00005103
Ted Kremenek3f404602010-08-14 01:14:06 +00005104 CXCursor &oldC = Annotated[rawEncoding];
5105 if (!clang_isPreprocessing(oldC.kind))
5106 oldC = cursor;
5107 }
5108
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005109 const enum CXCursorKind K = clang_getCursorKind(parent);
5110 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00005111 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
5112 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005113
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005114 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005115
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00005116 // Avoid having the cursor of an expression "overwrite" the annotation of the
5117 // variable declaration that it belongs to.
5118 // This can happen for C++ constructor expressions whose range generally
5119 // include the variable declaration, e.g.:
5120 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
5121 if (clang_isExpression(cursorK)) {
5122 Expr *E = getCursorExpr(cursor);
Argyrios Kyrtzidis8ccac3d2011-06-29 22:20:07 +00005123 if (Decl *D = getCursorParentDecl(cursor)) {
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00005124 const unsigned I = NextToken();
5125 if (E->getLocStart().isValid() && D->getLocation().isValid() &&
5126 E->getLocStart() == D->getLocation() &&
5127 E->getLocStart() == GetTokenLoc(I)) {
5128 Cursors[I] = updateC;
5129 AdvanceToken();
5130 }
5131 }
5132 }
5133
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005134 // Visit children to get their cursor information.
5135 const unsigned BeforeChildren = NextToken();
5136 VisitChildren(cursor);
5137 const unsigned AfterChildren = NextToken();
5138
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005139 // Scan the tokens that are at the end of the cursor, but are not captured
5140 // but the child cursors.
5141 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
Ted Kremenek6db61092010-05-05 00:55:15 +00005142
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005143 // Scan the tokens that are at the beginning of the cursor, but are not
5144 // capture by the child cursors.
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005145 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
5146 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
5147 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00005148
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005149 Cursors[I] = cursor;
5150 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005151
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005152 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005153}
5154
Ted Kremenek6db61092010-05-05 00:55:15 +00005155static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
5156 CXCursor parent,
5157 CXClientData client_data) {
5158 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
5159}
5160
Ted Kremenek6628a612011-03-18 22:51:30 +00005161namespace {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005162
5163/// \brief Uses the macro expansions in the preprocessing record to find
5164/// and mark tokens that are macro arguments. This info is used by the
5165/// AnnotateTokensWorker.
5166class MarkMacroArgTokensVisitor {
5167 SourceManager &SM;
5168 CXToken *Tokens;
5169 unsigned NumTokens;
5170 unsigned CurIdx;
5171
5172public:
5173 MarkMacroArgTokensVisitor(SourceManager &SM,
5174 CXToken *tokens, unsigned numTokens)
5175 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
5176
5177 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
5178 if (cursor.kind != CXCursor_MacroExpansion)
5179 return CXChildVisit_Continue;
5180
5181 SourceRange macroRange = getCursorMacroExpansion(cursor)->getSourceRange();
5182 if (macroRange.getBegin() == macroRange.getEnd())
5183 return CXChildVisit_Continue; // it's not a function macro.
5184
5185 for (; CurIdx < NumTokens; ++CurIdx) {
5186 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
5187 macroRange.getBegin()))
5188 break;
5189 }
5190
5191 if (CurIdx == NumTokens)
5192 return CXChildVisit_Break;
5193
5194 for (; CurIdx < NumTokens; ++CurIdx) {
5195 SourceLocation tokLoc = getTokenLoc(CurIdx);
5196 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
5197 break;
5198
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00005199 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005200 }
5201
5202 if (CurIdx == NumTokens)
5203 return CXChildVisit_Break;
5204
5205 return CXChildVisit_Continue;
5206 }
5207
5208private:
5209 SourceLocation getTokenLoc(unsigned tokI) {
5210 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
5211 }
5212
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00005213 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005214 // The third field is reserved and currently not used. Use it here
5215 // to mark macro arg expanded tokens with their expanded locations.
5216 Tokens[tokI].int_data[3] = loc.getRawEncoding();
5217 }
5218};
5219
5220} // end anonymous namespace
5221
5222static CXChildVisitResult
5223MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
5224 CXClientData client_data) {
5225 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
5226 parent);
5227}
5228
5229namespace {
Ted Kremenek6628a612011-03-18 22:51:30 +00005230 struct clang_annotateTokens_Data {
5231 CXTranslationUnit TU;
5232 ASTUnit *CXXUnit;
5233 CXToken *Tokens;
5234 unsigned NumTokens;
5235 CXCursor *Cursors;
5236 };
5237}
5238
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005239static void annotatePreprocessorTokens(CXTranslationUnit TU,
5240 SourceRange RegionOfInterest,
5241 AnnotateTokensData &Annotated) {
5242 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
5243
5244 SourceManager &SourceMgr = CXXUnit->getSourceManager();
5245 std::pair<FileID, unsigned> BeginLocInfo
5246 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
5247 std::pair<FileID, unsigned> EndLocInfo
5248 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
5249
5250 if (BeginLocInfo.first != EndLocInfo.first)
5251 return;
5252
5253 StringRef Buffer;
5254 bool Invalid = false;
5255 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
5256 if (Buffer.empty() || Invalid)
5257 return;
5258
5259 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
David Blaikie4e4d0842012-03-11 07:00:24 +00005260 CXXUnit->getASTContext().getLangOpts(),
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005261 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
5262 Buffer.end());
5263 Lex.SetCommentRetentionState(true);
5264
5265 // Lex tokens in raw mode until we hit the end of the range, to avoid
5266 // entering #includes or expanding macros.
5267 while (true) {
5268 Token Tok;
5269 Lex.LexFromRawLexer(Tok);
5270
5271 reprocess:
5272 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
5273 // We have found a preprocessing directive. Gobble it up so that we
5274 // don't see it while preprocessing these tokens later, but keep track
5275 // of all of the token locations inside this preprocessing directive so
5276 // that we can annotate them appropriately.
5277 //
5278 // FIXME: Some simple tests here could identify macro definitions and
5279 // #undefs, to provide specific cursor kinds for those.
5280 SmallVector<SourceLocation, 32> Locations;
5281 do {
5282 Locations.push_back(Tok.getLocation());
5283 Lex.LexFromRawLexer(Tok);
5284 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
5285
5286 using namespace cxcursor;
5287 CXCursor Cursor
5288 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
5289 Locations.back()),
5290 TU);
5291 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
5292 Annotated[Locations[I].getRawEncoding()] = Cursor;
5293 }
5294
5295 if (Tok.isAtStartOfLine())
5296 goto reprocess;
5297
5298 continue;
5299 }
5300
5301 if (Tok.is(tok::eof))
5302 break;
5303 }
5304}
5305
Ted Kremenekab979612010-11-11 08:05:23 +00005306// This gets run a separate thread to avoid stack blowout.
Ted Kremenek6628a612011-03-18 22:51:30 +00005307static void clang_annotateTokensImpl(void *UserData) {
5308 CXTranslationUnit TU = ((clang_annotateTokens_Data*)UserData)->TU;
5309 ASTUnit *CXXUnit = ((clang_annotateTokens_Data*)UserData)->CXXUnit;
5310 CXToken *Tokens = ((clang_annotateTokens_Data*)UserData)->Tokens;
5311 const unsigned NumTokens = ((clang_annotateTokens_Data*)UserData)->NumTokens;
5312 CXCursor *Cursors = ((clang_annotateTokens_Data*)UserData)->Cursors;
5313
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00005314 CIndexer *CXXIdx = (CIndexer*)TU->CIdx;
5315 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
Argyrios Kyrtzidis81b5ac32012-03-28 02:49:54 +00005316 setThreadBackgroundPriority();
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00005317
Ted Kremenek6628a612011-03-18 22:51:30 +00005318 // Determine the region of interest, which contains all of the tokens.
5319 SourceRange RegionOfInterest;
5320 RegionOfInterest.setBegin(
5321 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
5322 RegionOfInterest.setEnd(
5323 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
5324 Tokens[NumTokens-1])));
5325
5326 // A mapping from the source locations found when re-lexing or traversing the
5327 // region of interest to the corresponding cursors.
5328 AnnotateTokensData Annotated;
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005329
Ted Kremenek6628a612011-03-18 22:51:30 +00005330 // Relex the tokens within the source range to look for preprocessing
5331 // directives.
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005332 annotatePreprocessorTokens(TU, RegionOfInterest, Annotated);
Ted Kremenek6628a612011-03-18 22:51:30 +00005333
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005334 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
5335 // Search and mark tokens that are macro argument expansions.
5336 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
5337 Tokens, NumTokens);
5338 CursorVisitor MacroArgMarker(TU,
5339 MarkMacroArgTokensVisitorDelegate, &Visitor,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00005340 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00005341 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00005342 RegionOfInterest);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005343 MacroArgMarker.visitPreprocessedEntitiesInRegion();
5344 }
5345
Ted Kremenek6628a612011-03-18 22:51:30 +00005346 // Annotate all of the source locations in the region of interest that map to
5347 // a specific cursor.
5348 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
5349 TU, RegionOfInterest);
5350
5351 // FIXME: We use a ridiculous stack size here because the data-recursion
5352 // algorithm uses a large stack frame than the non-data recursive version,
5353 // and AnnotationTokensWorker currently transforms the data-recursion
5354 // algorithm back into a traditional recursion by explicitly calling
5355 // VisitChildren(). We will need to remove this explicit recursive call.
5356 W.AnnotateTokens();
5357
5358 // If we ran into any entities that involve context-sensitive keywords,
5359 // take another pass through the tokens to mark them as such.
5360 if (W.hasContextSensitiveKeywords()) {
5361 for (unsigned I = 0; I != NumTokens; ++I) {
5362 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
5363 continue;
5364
5365 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
5366 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5367 if (ObjCPropertyDecl *Property
5368 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
5369 if (Property->getPropertyAttributesAsWritten() != 0 &&
5370 llvm::StringSwitch<bool>(II->getName())
5371 .Case("readonly", true)
5372 .Case("assign", true)
John McCallf85e1932011-06-15 23:02:42 +00005373 .Case("unsafe_unretained", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00005374 .Case("readwrite", true)
5375 .Case("retain", true)
5376 .Case("copy", true)
5377 .Case("nonatomic", true)
5378 .Case("atomic", true)
5379 .Case("getter", true)
5380 .Case("setter", true)
John McCallf85e1932011-06-15 23:02:42 +00005381 .Case("strong", true)
5382 .Case("weak", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00005383 .Default(false))
5384 Tokens[I].int_data[0] = CXToken_Keyword;
5385 }
5386 continue;
5387 }
5388
5389 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
5390 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
5391 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5392 if (llvm::StringSwitch<bool>(II->getName())
5393 .Case("in", true)
5394 .Case("out", true)
5395 .Case("inout", true)
5396 .Case("oneway", true)
5397 .Case("bycopy", true)
5398 .Case("byref", true)
5399 .Default(false))
5400 Tokens[I].int_data[0] = CXToken_Keyword;
5401 continue;
5402 }
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00005403
5404 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
5405 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
5406 Tokens[I].int_data[0] = CXToken_Keyword;
Ted Kremenek6628a612011-03-18 22:51:30 +00005407 continue;
5408 }
5409 }
5410 }
Ted Kremenekab979612010-11-11 08:05:23 +00005411}
5412
Ted Kremenek6db61092010-05-05 00:55:15 +00005413extern "C" {
5414
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005415void clang_annotateTokens(CXTranslationUnit TU,
5416 CXToken *Tokens, unsigned NumTokens,
5417 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005418
5419 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005420 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005421
Douglas Gregor4419b672010-10-21 06:10:04 +00005422 // Any token we don't specifically annotate will have a NULL cursor.
5423 CXCursor C = clang_getNullCursor();
5424 for (unsigned I = 0; I != NumTokens; ++I)
5425 Cursors[I] = C;
5426
Ted Kremeneka60ed472010-11-16 08:15:36 +00005427 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor4419b672010-10-21 06:10:04 +00005428 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005429 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005430
Douglas Gregorbdf60622010-03-05 21:16:25 +00005431 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenek6628a612011-03-18 22:51:30 +00005432
5433 clang_annotateTokens_Data data = { TU, CXXUnit, Tokens, NumTokens, Cursors };
Ted Kremenekab979612010-11-11 08:05:23 +00005434 llvm::CrashRecoveryContext CRC;
Ted Kremenek6628a612011-03-18 22:51:30 +00005435 if (!RunSafely(CRC, clang_annotateTokensImpl, &data,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005436 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00005437 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
5438 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005439}
Ted Kremenek6628a612011-03-18 22:51:30 +00005440
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005441} // end: extern "C"
5442
5443//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00005444// Operations for querying linkage of a cursor.
5445//===----------------------------------------------------------------------===//
5446
5447extern "C" {
5448CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00005449 if (!clang_isDeclaration(cursor.kind))
5450 return CXLinkage_Invalid;
5451
Ted Kremenek16b42592010-03-03 06:36:57 +00005452 Decl *D = cxcursor::getCursorDecl(cursor);
5453 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
5454 switch (ND->getLinkage()) {
5455 case NoLinkage: return CXLinkage_NoLinkage;
5456 case InternalLinkage: return CXLinkage_Internal;
5457 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
5458 case ExternalLinkage: return CXLinkage_External;
5459 };
5460
5461 return CXLinkage_Invalid;
5462}
5463} // end: extern "C"
5464
5465//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005466// Operations for querying language of a cursor.
5467//===----------------------------------------------------------------------===//
5468
5469static CXLanguageKind getDeclLanguage(const Decl *D) {
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00005470 if (!D)
5471 return CXLanguage_C;
5472
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005473 switch (D->getKind()) {
5474 default:
5475 break;
5476 case Decl::ImplicitParam:
5477 case Decl::ObjCAtDefsField:
5478 case Decl::ObjCCategory:
5479 case Decl::ObjCCategoryImpl:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005480 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005481 case Decl::ObjCImplementation:
5482 case Decl::ObjCInterface:
5483 case Decl::ObjCIvar:
5484 case Decl::ObjCMethod:
5485 case Decl::ObjCProperty:
5486 case Decl::ObjCPropertyImpl:
5487 case Decl::ObjCProtocol:
5488 return CXLanguage_ObjC;
5489 case Decl::CXXConstructor:
5490 case Decl::CXXConversion:
5491 case Decl::CXXDestructor:
5492 case Decl::CXXMethod:
5493 case Decl::CXXRecord:
5494 case Decl::ClassTemplate:
5495 case Decl::ClassTemplatePartialSpecialization:
5496 case Decl::ClassTemplateSpecialization:
5497 case Decl::Friend:
5498 case Decl::FriendTemplate:
5499 case Decl::FunctionTemplate:
5500 case Decl::LinkageSpec:
5501 case Decl::Namespace:
5502 case Decl::NamespaceAlias:
5503 case Decl::NonTypeTemplateParm:
5504 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005505 case Decl::TemplateTemplateParm:
5506 case Decl::TemplateTypeParm:
5507 case Decl::UnresolvedUsingTypename:
5508 case Decl::UnresolvedUsingValue:
5509 case Decl::Using:
5510 case Decl::UsingDirective:
5511 case Decl::UsingShadow:
5512 return CXLanguage_CPlusPlus;
5513 }
5514
5515 return CXLanguage_C;
5516}
5517
5518extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00005519
5520enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
5521 if (clang_isDeclaration(cursor.kind))
5522 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005523 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Douglas Gregor58ddb602010-08-23 23:00:57 +00005524 return CXAvailability_Available;
5525
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005526 switch (D->getAvailability()) {
5527 case AR_Available:
5528 case AR_NotYetIntroduced:
5529 return CXAvailability_Available;
5530
5531 case AR_Deprecated:
Douglas Gregor58ddb602010-08-23 23:00:57 +00005532 return CXAvailability_Deprecated;
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005533
5534 case AR_Unavailable:
5535 return CXAvailability_NotAvailable;
5536 }
Douglas Gregor58ddb602010-08-23 23:00:57 +00005537 }
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005538
Douglas Gregor58ddb602010-08-23 23:00:57 +00005539 return CXAvailability_Available;
5540}
5541
Douglas Gregorcc889662012-05-08 00:14:45 +00005542static CXVersion convertVersion(VersionTuple In) {
5543 CXVersion Out = { -1, -1, -1 };
5544 if (In.empty())
5545 return Out;
5546
5547 Out.Major = In.getMajor();
5548
5549 if (llvm::Optional<unsigned> Minor = In.getMinor())
5550 Out.Minor = *Minor;
5551 else
5552 return Out;
5553
5554 if (llvm::Optional<unsigned> Subminor = In.getSubminor())
5555 Out.Subminor = *Subminor;
5556
5557 return Out;
5558}
5559
5560int clang_getCursorPlatformAvailability(CXCursor cursor,
5561 int *always_deprecated,
5562 CXString *deprecated_message,
5563 int *always_unavailable,
5564 CXString *unavailable_message,
5565 CXPlatformAvailability *availability,
5566 int availability_size) {
5567 if (always_deprecated)
5568 *always_deprecated = 0;
5569 if (deprecated_message)
5570 *deprecated_message = cxstring::createCXString("", /*DupString=*/false);
5571 if (always_unavailable)
5572 *always_unavailable = 0;
5573 if (unavailable_message)
5574 *unavailable_message = cxstring::createCXString("", /*DupString=*/false);
5575
5576 if (!clang_isDeclaration(cursor.kind))
5577 return 0;
5578
5579 Decl *D = cxcursor::getCursorDecl(cursor);
5580 if (!D)
5581 return 0;
5582
5583 int N = 0;
5584 for (Decl::attr_iterator A = D->attr_begin(), AEnd = D->attr_end(); A != AEnd;
5585 ++A) {
5586 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(*A)) {
5587 if (always_deprecated)
5588 *always_deprecated = 1;
5589 if (deprecated_message)
5590 *deprecated_message = cxstring::createCXString(Deprecated->getMessage());
5591 continue;
5592 }
5593
5594 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(*A)) {
5595 if (always_unavailable)
5596 *always_unavailable = 1;
5597 if (unavailable_message) {
5598 *unavailable_message
5599 = cxstring::createCXString(Unavailable->getMessage());
5600 }
5601 continue;
5602 }
5603
5604 if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(*A)) {
5605 if (N < availability_size) {
5606 availability[N].Platform
5607 = cxstring::createCXString(Avail->getPlatform()->getName());
5608 availability[N].Introduced = convertVersion(Avail->getIntroduced());
5609 availability[N].Deprecated = convertVersion(Avail->getDeprecated());
5610 availability[N].Obsoleted = convertVersion(Avail->getObsoleted());
5611 availability[N].Unavailable = Avail->getUnavailable();
5612 availability[N].Message = cxstring::createCXString(Avail->getMessage());
5613 }
5614 ++N;
5615 }
5616 }
5617
5618 return N;
5619}
5620
5621void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) {
5622 clang_disposeString(availability->Platform);
5623 clang_disposeString(availability->Message);
5624}
5625
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005626CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
5627 if (clang_isDeclaration(cursor.kind))
5628 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
5629
5630 return CXLanguage_Invalid;
5631}
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005632
5633 /// \brief If the given cursor is the "templated" declaration
5634 /// descibing a class or function template, return the class or
5635 /// function template.
5636static Decl *maybeGetTemplateCursor(Decl *D) {
5637 if (!D)
5638 return 0;
5639
5640 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
5641 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
5642 return FunTmpl;
5643
5644 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
5645 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
5646 return ClassTmpl;
5647
5648 return D;
5649}
5650
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005651CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
5652 if (clang_isDeclaration(cursor.kind)) {
5653 if (Decl *D = getCursorDecl(cursor)) {
5654 DeclContext *DC = D->getDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005655 if (!DC)
5656 return clang_getNullCursor();
5657
5658 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5659 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005660 }
5661 }
5662
5663 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
5664 if (Decl *D = getCursorDecl(cursor))
Ted Kremeneka60ed472010-11-16 08:15:36 +00005665 return MakeCXCursor(D, getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005666 }
5667
5668 return clang_getNullCursor();
5669}
5670
5671CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
5672 if (clang_isDeclaration(cursor.kind)) {
5673 if (Decl *D = getCursorDecl(cursor)) {
5674 DeclContext *DC = D->getLexicalDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005675 if (!DC)
5676 return clang_getNullCursor();
5677
5678 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5679 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005680 }
5681 }
5682
5683 // FIXME: Note that we can't easily compute the lexical context of a
5684 // statement or expression, so we return nothing.
5685 return clang_getNullCursor();
5686}
5687
Douglas Gregorecdcb882010-10-20 22:00:55 +00005688CXFile clang_getIncludedFile(CXCursor cursor) {
5689 if (cursor.kind != CXCursor_InclusionDirective)
5690 return 0;
5691
5692 InclusionDirective *ID = getCursorInclusionDirective(cursor);
5693 return (void *)ID->getFile();
5694}
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +00005695
5696CXSourceRange clang_Cursor_getCommentRange(CXCursor C) {
5697 if (!clang_isDeclaration(C.kind))
5698 return clang_getNullRange();
5699
5700 const Decl *D = getCursorDecl(C);
5701 ASTContext &Context = getCursorContext(C);
Dmitri Gribenkof50555e2012-08-11 00:51:43 +00005702 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +00005703 if (!RC)
5704 return clang_getNullRange();
5705
5706 return cxloc::translateSourceRange(Context, RC->getSourceRange());
5707}
5708
5709CXString clang_Cursor_getRawCommentText(CXCursor C) {
5710 if (!clang_isDeclaration(C.kind))
5711 return createCXString((const char *) NULL);
5712
5713 const Decl *D = getCursorDecl(C);
5714 ASTContext &Context = getCursorContext(C);
Dmitri Gribenkof50555e2012-08-11 00:51:43 +00005715 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +00005716 StringRef RawText = RC ? RC->getRawText(Context.getSourceManager()) :
5717 StringRef();
5718
5719 // Don't duplicate the string because RawText points directly into source
5720 // code.
5721 return createCXString(RawText, false);
5722}
5723
Dmitri Gribenko2d44d772012-06-26 20:39:18 +00005724CXString clang_Cursor_getBriefCommentText(CXCursor C) {
5725 if (!clang_isDeclaration(C.kind))
5726 return createCXString((const char *) NULL);
5727
5728 const Decl *D = getCursorDecl(C);
5729 const ASTContext &Context = getCursorContext(C);
Dmitri Gribenkof50555e2012-08-11 00:51:43 +00005730 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
Dmitri Gribenko2d44d772012-06-26 20:39:18 +00005731
Dmitri Gribenko8376f592012-06-28 16:25:36 +00005732 if (RC) {
Dmitri Gribenko2d44d772012-06-26 20:39:18 +00005733 StringRef BriefText = RC->getBriefText(Context);
5734
5735 // Don't duplicate the string because RawComment ensures that this memory
5736 // will not go away.
5737 return createCXString(BriefText, false);
5738 }
5739
5740 return createCXString((const char *) NULL);
5741}
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005742
Dmitri Gribenkoae99b752012-07-20 21:34:34 +00005743CXComment clang_Cursor_getParsedComment(CXCursor C) {
5744 if (!clang_isDeclaration(C.kind))
5745 return cxcomment::createCXComment(NULL);
5746
5747 const Decl *D = getCursorDecl(C);
5748 const ASTContext &Context = getCursorContext(C);
5749 const comments::FullComment *FC = Context.getCommentForDecl(D);
5750
5751 return cxcomment::createCXComment(FC);
5752}
5753
Dmitri Gribenkob619e782012-07-17 00:17:45 +00005754} // end: extern "C"
5755
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005756//===----------------------------------------------------------------------===//
5757// C++ AST instrospection.
5758//===----------------------------------------------------------------------===//
5759
5760extern "C" {
5761unsigned clang_CXXMethod_isStatic(CXCursor C) {
5762 if (!clang_isDeclaration(C.kind))
5763 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00005764
5765 CXXMethodDecl *Method = 0;
5766 Decl *D = cxcursor::getCursorDecl(C);
5767 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5768 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5769 else
5770 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5771 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00005772}
Ted Kremenekb12903e2010-05-18 22:32:15 +00005773
Douglas Gregor211924b2011-05-12 15:17:24 +00005774unsigned clang_CXXMethod_isVirtual(CXCursor C) {
5775 if (!clang_isDeclaration(C.kind))
5776 return 0;
5777
5778 CXXMethodDecl *Method = 0;
5779 Decl *D = cxcursor::getCursorDecl(C);
5780 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5781 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5782 else
5783 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5784 return (Method && Method->isVirtual()) ? 1 : 0;
5785}
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005786} // end: extern "C"
5787
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005788//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00005789// Attribute introspection.
5790//===----------------------------------------------------------------------===//
5791
5792extern "C" {
5793CXType clang_getIBOutletCollectionType(CXCursor C) {
5794 if (C.kind != CXCursor_IBOutletCollectionAttr)
Ted Kremeneka60ed472010-11-16 08:15:36 +00005795 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005796
5797 IBOutletCollectionAttr *A =
5798 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
5799
Argyrios Kyrtzidis18aa2ff2011-09-13 18:49:52 +00005800 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005801}
5802} // end: extern "C"
5803
5804//===----------------------------------------------------------------------===//
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005805// Inspecting memory usage.
5806//===----------------------------------------------------------------------===//
5807
Ted Kremenekf7870022011-04-20 16:41:07 +00005808typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005809
Ted Kremenekf7870022011-04-20 16:41:07 +00005810static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
5811 enum CXTUResourceUsageKind k,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005812 unsigned long amount) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005813 CXTUResourceUsageEntry entry = { k, amount };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005814 entries.push_back(entry);
5815}
5816
5817extern "C" {
5818
Ted Kremenekf7870022011-04-20 16:41:07 +00005819const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005820 const char *str = "";
5821 switch (kind) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005822 case CXTUResourceUsage_AST:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005823 str = "ASTContext: expressions, declarations, and types";
5824 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005825 case CXTUResourceUsage_Identifiers:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005826 str = "ASTContext: identifiers";
5827 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005828 case CXTUResourceUsage_Selectors:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005829 str = "ASTContext: selectors";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005830 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005831 case CXTUResourceUsage_GlobalCompletionResults:
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005832 str = "Code completion: cached global results";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005833 break;
Ted Kremenek457aaf02011-04-28 04:10:31 +00005834 case CXTUResourceUsage_SourceManagerContentCache:
5835 str = "SourceManager: content cache allocator";
5836 break;
Ted Kremenekba29bd22011-04-28 04:53:38 +00005837 case CXTUResourceUsage_AST_SideTables:
5838 str = "ASTContext: side tables";
5839 break;
Ted Kremenekf61b8312011-04-28 20:36:42 +00005840 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
5841 str = "SourceManager: malloc'ed memory buffers";
5842 break;
5843 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
5844 str = "SourceManager: mmap'ed memory buffers";
5845 break;
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005846 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
5847 str = "ExternalASTSource: malloc'ed memory buffers";
5848 break;
5849 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
5850 str = "ExternalASTSource: mmap'ed memory buffers";
5851 break;
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005852 case CXTUResourceUsage_Preprocessor:
5853 str = "Preprocessor: malloc'ed memory";
5854 break;
5855 case CXTUResourceUsage_PreprocessingRecord:
5856 str = "Preprocessor: PreprocessingRecord";
5857 break;
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005858 case CXTUResourceUsage_SourceManager_DataStructures:
5859 str = "SourceManager: data structures and tables";
5860 break;
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005861 case CXTUResourceUsage_Preprocessor_HeaderSearch:
5862 str = "Preprocessor: header search tables";
5863 break;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005864 }
5865 return str;
5866}
5867
Ted Kremenekf7870022011-04-20 16:41:07 +00005868CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005869 if (!TU) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005870 CXTUResourceUsage usage = { (void*) 0, 0, 0 };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005871 return usage;
5872 }
5873
5874 ASTUnit *astUnit = static_cast<ASTUnit*>(TU->TUData);
Dylan Noblesmith1e4c01b2012-02-13 12:32:21 +00005875 OwningPtr<MemUsageEntries> entries(new MemUsageEntries());
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005876 ASTContext &astContext = astUnit->getASTContext();
5877
5878 // How much memory is used by AST nodes and types?
Ted Kremenekf7870022011-04-20 16:41:07 +00005879 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005880 (unsigned long) astContext.getASTAllocatedMemory());
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005881
5882 // How much memory is used by identifiers?
Ted Kremenekf7870022011-04-20 16:41:07 +00005883 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005884 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
5885
5886 // How much memory is used for selectors?
Ted Kremenekf7870022011-04-20 16:41:07 +00005887 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005888 (unsigned long) astContext.Selectors.getTotalMemory());
5889
Ted Kremenekba29bd22011-04-28 04:53:38 +00005890 // How much memory is used by ASTContext's side tables?
5891 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
5892 (unsigned long) astContext.getSideTableAllocatedMemory());
5893
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005894 // How much memory is used for caching global code completion results?
5895 unsigned long completionBytes = 0;
5896 if (GlobalCodeCompletionAllocator *completionAllocator =
5897 astUnit->getCachedCompletionAllocator().getPtr()) {
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005898 completionBytes = completionAllocator->getTotalMemory();
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005899 }
Ted Kremenek457aaf02011-04-28 04:10:31 +00005900 createCXTUResourceUsageEntry(*entries,
5901 CXTUResourceUsage_GlobalCompletionResults,
5902 completionBytes);
5903
5904 // How much memory is being used by SourceManager's content cache?
5905 createCXTUResourceUsageEntry(*entries,
5906 CXTUResourceUsage_SourceManagerContentCache,
5907 (unsigned long) astContext.getSourceManager().getContentCacheSize());
Ted Kremenekf61b8312011-04-28 20:36:42 +00005908
5909 // How much memory is being used by the MemoryBuffer's in SourceManager?
5910 const SourceManager::MemoryBufferSizes &srcBufs =
5911 astUnit->getSourceManager().getMemoryBufferSizes();
5912
5913 createCXTUResourceUsageEntry(*entries,
5914 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
5915 (unsigned long) srcBufs.malloc_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005916 createCXTUResourceUsageEntry(*entries,
Ted Kremenekf61b8312011-04-28 20:36:42 +00005917 CXTUResourceUsage_SourceManager_Membuffer_MMap,
5918 (unsigned long) srcBufs.mmap_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005919 createCXTUResourceUsageEntry(*entries,
5920 CXTUResourceUsage_SourceManager_DataStructures,
5921 (unsigned long) astContext.getSourceManager()
5922 .getDataStructureSizes());
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005923
5924 // How much memory is being used by the ExternalASTSource?
5925 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
5926 const ExternalASTSource::MemoryBufferSizes &sizes =
5927 esrc->getMemoryBufferSizes();
5928
5929 createCXTUResourceUsageEntry(*entries,
5930 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
5931 (unsigned long) sizes.malloc_bytes);
5932 createCXTUResourceUsageEntry(*entries,
5933 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
5934 (unsigned long) sizes.mmap_bytes);
5935 }
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005936
5937 // How much memory is being used by the Preprocessor?
5938 Preprocessor &pp = astUnit->getPreprocessor();
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005939 createCXTUResourceUsageEntry(*entries,
5940 CXTUResourceUsage_Preprocessor,
Argyrios Kyrtzidisc5c5e922011-06-29 22:20:04 +00005941 pp.getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005942
5943 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
5944 createCXTUResourceUsageEntry(*entries,
5945 CXTUResourceUsage_PreprocessingRecord,
5946 pRec->getTotalMemory());
5947 }
5948
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005949 createCXTUResourceUsageEntry(*entries,
5950 CXTUResourceUsage_Preprocessor_HeaderSearch,
5951 pp.getHeaderSearchInfo().getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005952
Ted Kremenekf7870022011-04-20 16:41:07 +00005953 CXTUResourceUsage usage = { (void*) entries.get(),
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005954 (unsigned) entries->size(),
5955 entries->size() ? &(*entries)[0] : 0 };
5956 entries.take();
5957 return usage;
5958}
5959
Ted Kremenekf7870022011-04-20 16:41:07 +00005960void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005961 if (usage.data)
5962 delete (MemUsageEntries*) usage.data;
5963}
5964
5965} // end extern "C"
5966
Douglas Gregor6df78732011-05-05 20:27:22 +00005967void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
5968 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
5969 for (unsigned I = 0; I != Usage.numEntries; ++I)
5970 fprintf(stderr, " %s: %lu\n",
5971 clang_getTUResourceUsageName(Usage.entries[I].kind),
5972 Usage.entries[I].amount);
5973
5974 clang_disposeCXTUResourceUsage(Usage);
5975}
5976
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005977//===----------------------------------------------------------------------===//
Ted Kremenek04bb7162010-01-22 22:44:15 +00005978// Misc. utility functions.
5979//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00005980
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00005981/// Default to using an 8 MB stack size on "safety" threads.
5982static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005983
5984namespace clang {
5985
5986bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005987 void (*Fn)(void*), void *UserData,
5988 unsigned Size) {
5989 if (!Size)
5990 Size = GetSafetyThreadStackSize();
5991 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005992 return CRC.RunSafelyOnThread(Fn, UserData, Size);
5993 return CRC.RunSafely(Fn, UserData);
5994}
5995
5996unsigned GetSafetyThreadStackSize() {
5997 return SafetyStackThreadSize;
5998}
5999
6000void SetSafetyThreadStackSize(unsigned Value) {
6001 SafetyStackThreadSize = Value;
6002}
6003
Argyrios Kyrtzidis8e7c48a2012-03-28 02:49:50 +00006004}
6005
Argyrios Kyrtzidis81b5ac32012-03-28 02:49:54 +00006006void clang::setThreadBackgroundPriority() {
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00006007 // FIXME: Move to llvm/Support and make it cross-platform.
6008#ifdef __APPLE__
6009 setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG);
6010#endif
6011}
6012
Argyrios Kyrtzidis97934282012-04-11 03:52:18 +00006013void cxindex::printDiagsToStderr(ASTUnit *Unit) {
6014 if (!Unit)
6015 return;
6016
6017 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
6018 DEnd = Unit->stored_diag_end();
6019 D != DEnd; ++D) {
6020 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOpts());
6021 CXString Msg = clang_formatDiagnostic(&Diag,
6022 clang_defaultDiagnosticDisplayOptions());
6023 fprintf(stderr, "%s\n", clang_getCString(Msg));
6024 clang_disposeString(Msg);
6025 }
6026#ifdef LLVM_ON_WIN32
6027 // On Windows, force a flush, since there may be multiple copies of
6028 // stderr and stdout in the file system, all with different buffers
6029 // but writing to the same device.
6030 fflush(stderr);
6031#endif
6032}
6033
Ted Kremenek04bb7162010-01-22 22:44:15 +00006034extern "C" {
6035
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00006036CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00006037 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00006038}
6039
6040} // end: extern "C"
Ted Kremenek59fc1e52011-04-18 22:47:10 +00006041