blob: 1fb9a70336a144f2da0c472f9c9517fbc0d63500 [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"
Chandler Carruthf59edb92012-12-04 09:25:21 +000016#include "CIndexDiagnostic.h"
Dmitri Gribenkoae99b752012-07-20 21:34:34 +000017#include "CXComment.h"
Ted Kremenek16c440a2010-01-15 20:35:54 +000018#include "CXCursor.h"
Ted Kremeneka297de22010-01-25 22:34:44 +000019#include "CXSourceLocation.h"
Chandler Carruthf59edb92012-12-04 09:25:21 +000020#include "CXString.h"
21#include "CXTranslationUnit.h"
22#include "CXType.h"
Argyrios Kyrtzidise397bf12011-11-03 19:02:34 +000023#include "CursorVisitor.h"
Steve Narofffb570422009-09-22 19:25:29 +000024#include "clang/AST/StmtVisitor.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000025#include "clang/Basic/Diagnostic.h"
Chandler Carruthf59edb92012-12-04 09:25:21 +000026#include "clang/Basic/Version.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000027#include "clang/Frontend/ASTUnit.h"
28#include "clang/Frontend/CompilerInstance.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000029#include "clang/Frontend/FrontendDiagnostic.h"
Douglas Gregordd3e5542011-05-04 00:14:37 +000030#include "clang/Lex/HeaderSearch.h"
Chandler Carruthf59edb92012-12-04 09:25:21 +000031#include "clang/Lex/Lexer.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000032#include "clang/Lex/PreprocessingRecord.h"
Douglas Gregor33e9abd2010-01-22 19:49:59 +000033#include "clang/Lex/Preprocessor.h"
Ted Kremenekd8c370c2010-11-02 23:10:24 +000034#include "llvm/ADT/Optional.h"
Chandler Carruthf59edb92012-12-04 09:25:21 +000035#include "llvm/ADT/STLExtras.h"
Douglas Gregorf5251602011-03-08 17:10:18 +000036#include "llvm/ADT/StringSwitch.h"
Chandler Carruthf59edb92012-12-04 09:25:21 +000037#include "llvm/Support/Compiler.h"
Daniel Dunbarc7df4f32010-08-18 18:43:14 +000038#include "llvm/Support/CrashRecoveryContext.h"
Douglas Gregor02465752009-10-16 21:24:31 +000039#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000040#include "llvm/Support/Mutex.h"
Chandler Carruthf59edb92012-12-04 09:25:21 +000041#include "llvm/Support/PrettyStackTrace.h"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000042#include "llvm/Support/Program.h"
Chandler Carruthf59edb92012-12-04 09:25:21 +000043#include "llvm/Support/SaveAndRestore.h"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000044#include "llvm/Support/Signals.h"
45#include "llvm/Support/Threading.h"
Chandler Carruthf59edb92012-12-04 09:25:21 +000046#include "llvm/Support/Timer.h"
47#include "llvm/Support/raw_ostream.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000048
Steve Naroff50398192009-08-28 15:28:48 +000049using namespace clang;
Ted Kremenek16c440a2010-01-15 20:35:54 +000050using namespace clang::cxcursor;
Ted Kremenekee4db4f2010-02-17 00:41:08 +000051using namespace clang::cxstring;
Argyrios Kyrtzidis9049cf62011-10-12 07:07:33 +000052using namespace clang::cxtu;
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +000053using namespace clang::cxindex;
Steve Naroff50398192009-08-28 15:28:48 +000054
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +000055CXTranslationUnit cxtu::MakeCXTranslationUnit(CIndexer *CIdx, ASTUnit *TU) {
Ted Kremeneka60ed472010-11-16 08:15:36 +000056 if (!TU)
57 return 0;
58 CXTranslationUnit D = new CXTranslationUnitImpl();
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +000059 D->CIdx = CIdx;
Ted Kremeneka60ed472010-11-16 08:15:36 +000060 D->TUData = TU;
61 D->StringPool = createCXStringPool();
Ted Kremenek15322172011-11-10 08:43:12 +000062 D->Diagnostics = 0;
Ted Kremenekbbf66ca2012-04-30 19:06:49 +000063 D->OverridenCursorsPool = createOverridenCXCursorsPool();
Ted Kremeneka60ed472010-11-16 08:15:36 +000064 return D;
65}
66
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +000067cxtu::CXTUOwner::~CXTUOwner() {
68 if (TU)
69 clang_disposeTranslationUnit(TU);
70}
71
Ted Kremenekf0e23e82010-02-17 00:41:40 +000072/// \brief Compare two source ranges to determine their relative position in
Douglas Gregor33e9abd2010-01-22 19:49:59 +000073/// the translation unit.
Ted Kremenekf0e23e82010-02-17 00:41:40 +000074static RangeComparisonResult RangeCompare(SourceManager &SM,
75 SourceRange R1,
Douglas Gregor33e9abd2010-01-22 19:49:59 +000076 SourceRange R2) {
77 assert(R1.isValid() && "First range is invalid?");
78 assert(R2.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000079 if (R1.getEnd() != R2.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000080 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000081 return RangeBefore;
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000082 if (R2.getEnd() != R1.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000083 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000084 return RangeAfter;
85 return RangeOverlap;
86}
87
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000088/// \brief Determine if a source location falls within, before, or after a
89/// a given source range.
90static RangeComparisonResult LocationCompare(SourceManager &SM,
91 SourceLocation L, SourceRange R) {
92 assert(R.isValid() && "First range is invalid?");
93 assert(L.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000094 if (L == R.getBegin() || L == R.getEnd())
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000095 return RangeOverlap;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000096 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
97 return RangeBefore;
98 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
99 return RangeAfter;
100 return RangeOverlap;
101}
102
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000103/// \brief Translate a Clang source range into a CIndex source range.
104///
105/// Clang internally represents ranges where the end location points to the
106/// start of the token at the end. However, for external clients it is more
107/// useful to have a CXSourceRange be a proper half-open interval. This routine
108/// does the appropriate translation.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000109CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000110 const LangOptions &LangOpts,
Chris Lattner0a76aae2010-06-18 22:45:06 +0000111 const CharSourceRange &R) {
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000112 // We want the last character in this location, so we will adjust the
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000113 // location accordingly.
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000114 SourceLocation EndLoc = R.getEnd();
Argyrios Kyrtzidiseba8cd52012-04-11 18:15:01 +0000115 if (EndLoc.isValid() && EndLoc.isMacroID() && !SM.isMacroArgExpansion(EndLoc))
Chandler Carruthedc3dcc2011-07-25 16:56:02 +0000116 EndLoc = SM.getExpansionRange(EndLoc).second;
Argyrios Kyrtzidiseba8cd52012-04-11 18:15:01 +0000117 if (R.isTokenRange() && !EndLoc.isInvalid()) {
118 unsigned Length = Lexer::MeasureTokenLength(SM.getSpellingLoc(EndLoc),
119 SM, LangOpts);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000120 EndLoc = EndLoc.getLocWithOffset(Length);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000121 }
122
123 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
124 R.getBegin().getRawEncoding(),
125 EndLoc.getRawEncoding() };
126 return Result;
127}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000128
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000129//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000130// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000131//===----------------------------------------------------------------------===//
132
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000133static SourceRange getRawCursorExtent(CXCursor C);
Douglas Gregor66537982010-11-17 17:14:07 +0000134static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
135
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000136
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000137RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000138 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000139}
140
Douglas Gregorb1373d02010-01-20 20:59:29 +0000141/// \brief Visit the given cursor and, if requested by the visitor,
142/// its children.
143///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000144/// \param Cursor the cursor to visit.
145///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +0000146/// \param CheckedRegionOfInterest if true, then the caller already checked
147/// that this cursor is within the region of interest.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000148///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000149/// \returns true if the visitation should be aborted, false if it
150/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000151bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000152 if (clang_isInvalid(Cursor.kind))
153 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000154
Douglas Gregorb1373d02010-01-20 20:59:29 +0000155 if (clang_isDeclaration(Cursor.kind)) {
156 Decl *D = getCursorDecl(Cursor);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +0000157 if (!D) {
158 assert(0 && "Invalid declaration cursor");
159 return true; // abort.
160 }
161
Argyrios Kyrtzidis65ab9072011-09-26 19:05:37 +0000162 // Ignore implicit declarations, unless it's an objc method because
163 // currently we should report implicit methods for properties when indexing.
164 if (D->isImplicit() && !isa<ObjCMethodDecl>(D))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000165 return false;
166 }
167
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000168 // If we have a range of interest, and this cursor doesn't intersect with it,
169 // we're done.
170 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000171 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000172 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000173 return false;
174 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000175
Douglas Gregorb1373d02010-01-20 20:59:29 +0000176 switch (Visitor(Cursor, Parent, ClientData)) {
177 case CXChildVisit_Break:
178 return true;
179
180 case CXChildVisit_Continue:
181 return false;
182
Argyrios Kyrtzidisd579dd52012-09-01 18:27:30 +0000183 case CXChildVisit_Recurse: {
184 bool ret = VisitChildren(Cursor);
185 if (PostChildrenVisitor)
186 if (PostChildrenVisitor(Cursor, ClientData))
187 return true;
188 return ret;
189 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000190 }
191
David Blaikie7530c032012-01-17 06:56:22 +0000192 llvm_unreachable("Invalid CXChildVisitResult!");
Douglas Gregorb1373d02010-01-20 20:59:29 +0000193}
194
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000195static bool visitPreprocessedEntitiesInRange(SourceRange R,
196 PreprocessingRecord &PPRec,
197 CursorVisitor &Visitor) {
198 SourceManager &SM = Visitor.getASTUnit()->getSourceManager();
199 FileID FID;
200
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +0000201 if (!Visitor.shouldVisitIncludedEntities()) {
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000202 // If the begin/end of the range lie in the same FileID, do the optimization
203 // where we skip preprocessed entities that do not come from the same FileID.
Argyrios Kyrtzidisacca4112011-12-21 16:56:38 +0000204 FID = SM.getFileID(SM.getFileLoc(R.getBegin()));
205 if (FID != SM.getFileID(SM.getFileLoc(R.getEnd())))
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000206 FID = FileID();
207 }
208
209 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
210 Entities = PPRec.getPreprocessedEntitiesInRange(R);
211 return Visitor.visitPreprocessedEntities(Entities.first, Entities.second,
212 PPRec, FID);
213}
214
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000215void CursorVisitor::visitFileRegion() {
216 if (RegionOfInterest.isInvalid())
217 return;
218
219 ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData);
220 SourceManager &SM = Unit->getSourceManager();
221
222 std::pair<FileID, unsigned>
223 Begin = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getBegin())),
224 End = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getEnd()));
225
226 if (End.first != Begin.first) {
227 // If the end does not reside in the same file, try to recover by
228 // picking the end of the file of begin location.
229 End.first = Begin.first;
230 End.second = SM.getFileIDSize(Begin.first);
231 }
232
233 assert(Begin.first == End.first);
234 if (Begin.second > End.second)
235 return;
236
237 FileID File = Begin.first;
238 unsigned Offset = Begin.second;
239 unsigned Length = End.second - Begin.second;
240
Argyrios Kyrtzidisb49e7282011-11-29 03:14:11 +0000241 if (!VisitDeclsOnly && !VisitPreprocessorLast)
242 if (visitPreprocessedEntitiesInRegion())
243 return; // visitation break.
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000244
245 visitDeclsFromFileRegion(File, Offset, Length);
246
Argyrios Kyrtzidisb49e7282011-11-29 03:14:11 +0000247 if (!VisitDeclsOnly && VisitPreprocessorLast)
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000248 visitPreprocessedEntitiesInRegion();
249}
250
Argyrios Kyrtzidise2079cf2011-11-16 08:58:54 +0000251static bool isInLexicalContext(Decl *D, DeclContext *DC) {
252 if (!DC)
253 return false;
254
255 for (DeclContext *DeclDC = D->getLexicalDeclContext();
256 DeclDC; DeclDC = DeclDC->getLexicalParent()) {
257 if (DeclDC == DC)
258 return true;
259 }
260 return false;
261}
262
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000263void CursorVisitor::visitDeclsFromFileRegion(FileID File,
264 unsigned Offset, unsigned Length) {
265 ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData);
266 SourceManager &SM = Unit->getSourceManager();
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000267 SourceRange Range = RegionOfInterest;
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000268
269 SmallVector<Decl *, 16> Decls;
270 Unit->findFileRegionDecls(File, Offset, Length, Decls);
271
272 // If we didn't find any file level decls for the file, try looking at the
273 // file that it was included from.
Argyrios Kyrtzidisc14a03d2011-11-23 20:27:36 +0000274 while (Decls.empty() || Decls.front()->isTopLevelDeclInObjCContainer()) {
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000275 bool Invalid = false;
276 const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid);
277 if (Invalid)
278 return;
279
280 SourceLocation Outer;
281 if (SLEntry.isFile())
282 Outer = SLEntry.getFile().getIncludeLoc();
283 else
284 Outer = SLEntry.getExpansion().getExpansionLocStart();
285 if (Outer.isInvalid())
286 return;
287
288 llvm::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer);
289 Length = 0;
290 Unit->findFileRegionDecls(File, Offset, Length, Decls);
291 }
292
293 assert(!Decls.empty());
294
295 bool VisitedAtLeastOnce = false;
Argyrios Kyrtzidise2079cf2011-11-16 08:58:54 +0000296 DeclContext *CurDC = 0;
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000297 SmallVector<Decl *, 16>::iterator DIt = Decls.begin();
298 for (SmallVector<Decl *, 16>::iterator DE = Decls.end(); DIt != DE; ++DIt) {
299 Decl *D = *DIt;
Argyrios Kyrtzidised8bef42011-11-28 22:38:07 +0000300 if (D->getSourceRange().isInvalid())
301 continue;
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000302
Argyrios Kyrtzidise2079cf2011-11-16 08:58:54 +0000303 if (isInLexicalContext(D, CurDC))
304 continue;
305
306 CurDC = dyn_cast<DeclContext>(D);
307
Argyrios Kyrtzidise2079cf2011-11-16 08:58:54 +0000308 if (TagDecl *TD = dyn_cast<TagDecl>(D))
309 if (!TD->isFreeStanding())
310 continue;
311
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000312 RangeComparisonResult CompRes = RangeCompare(SM, D->getSourceRange(),Range);
313 if (CompRes == RangeBefore)
314 continue;
315 if (CompRes == RangeAfter)
316 break;
317
318 assert(CompRes == RangeOverlap);
319 VisitedAtLeastOnce = true;
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +0000320
321 if (isa<ObjCContainerDecl>(D)) {
322 FileDI_current = &DIt;
323 FileDE_current = DE;
324 } else {
325 FileDI_current = 0;
326 }
327
Argyrios Kyrtzidisba986172011-11-03 19:02:28 +0000328 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000329 break;
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000330 }
331
332 if (VisitedAtLeastOnce)
333 return;
334
335 // No Decls overlapped with the range. Move up the lexical context until there
336 // is a context that contains the range or we reach the translation unit
337 // level.
338 DeclContext *DC = DIt == Decls.begin() ? (*DIt)->getLexicalDeclContext()
339 : (*(DIt-1))->getLexicalDeclContext();
340
341 while (DC && !DC->isTranslationUnit()) {
342 Decl *D = cast<Decl>(DC);
343 SourceRange CurDeclRange = D->getSourceRange();
344 if (CurDeclRange.isInvalid())
345 break;
346
347 if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) {
Argyrios Kyrtzidisba986172011-11-03 19:02:28 +0000348 Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true);
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000349 break;
350 }
351
352 DC = D->getLexicalDeclContext();
353 }
354}
355
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000356bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
Argyrios Kyrtzidisb49e7282011-11-29 03:14:11 +0000357 if (!AU->getPreprocessor().getPreprocessingRecord())
358 return false;
359
Douglas Gregor788f5a12010-03-20 00:41:21 +0000360 PreprocessingRecord &PPRec
Ted Kremeneka60ed472010-11-16 08:15:36 +0000361 = *AU->getPreprocessor().getPreprocessingRecord();
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000362 SourceManager &SM = AU->getSourceManager();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000363
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000364 if (RegionOfInterest.isValid()) {
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +0000365 SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000366 SourceLocation B = MappedRange.getBegin();
367 SourceLocation E = MappedRange.getEnd();
368
369 if (AU->isInPreambleFileID(B)) {
370 if (SM.isLoadedSourceLocation(E))
371 return visitPreprocessedEntitiesInRange(SourceRange(B, E),
372 PPRec, *this);
373
374 // Beginning of range lies in the preamble but it also extends beyond
375 // it into the main file. Split the range into 2 parts, one covering
376 // the preamble and another covering the main file. This allows subsequent
377 // calls to visitPreprocessedEntitiesInRange to accept a source range that
378 // lies in the same FileID, allowing it to skip preprocessed entities that
379 // do not come from the same FileID.
380 bool breaked =
381 visitPreprocessedEntitiesInRange(
382 SourceRange(B, AU->getEndOfPreambleFileID()),
383 PPRec, *this);
384 if (breaked) return true;
385 return visitPreprocessedEntitiesInRange(
386 SourceRange(AU->getStartOfMainFileID(), E),
387 PPRec, *this);
388 }
389
390 return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this);
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000391 }
392
Douglas Gregor788f5a12010-03-20 00:41:21 +0000393 bool OnlyLocalDecls
Douglas Gregor32038bb2010-12-21 19:07:48 +0000394 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
395
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000396 if (OnlyLocalDecls)
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000397 return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(),
398 PPRec);
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000399
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000400 return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec);
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000401}
402
403template<typename InputIterator>
404bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000405 InputIterator Last,
406 PreprocessingRecord &PPRec,
407 FileID FID) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000408 for (; First != Last; ++First) {
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000409 if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID))
410 continue;
411
412 PreprocessedEntity *PPE = *First;
413 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000414 if (Visit(MakeMacroExpansionCursor(ME, TU)))
415 return true;
416
417 continue;
418 }
419
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000420 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(PPE)) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000421 if (Visit(MakeMacroDefinitionCursor(MD, TU)))
422 return true;
423
424 continue;
425 }
426
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000427 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000428 if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
429 return true;
430
431 continue;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000432 }
433 }
434
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000435 return false;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000436}
437
Douglas Gregorb1373d02010-01-20 20:59:29 +0000438/// \brief Visit the children of the given cursor.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000439///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000440/// \returns true if the visitation should be aborted, false if it
441/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000442bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregorc314aa42011-03-02 19:17:03 +0000443 if (clang_isReference(Cursor.kind) &&
444 Cursor.kind != CXCursor_CXXBaseSpecifier) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000445 // By definition, references have no children.
446 return false;
447 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000448
449 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000450 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000451 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000452
Douglas Gregorb1373d02010-01-20 20:59:29 +0000453 if (clang_isDeclaration(Cursor.kind)) {
454 Decl *D = getCursorDecl(Cursor);
Douglas Gregor06d9b1a2011-04-14 21:41:34 +0000455 if (!D)
456 return false;
457
Ted Kremenek539311e2010-02-18 18:47:01 +0000458 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000459 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000460
Douglas Gregor06d9b1a2011-04-14 21:41:34 +0000461 if (clang_isStatement(Cursor.kind)) {
462 if (Stmt *S = getCursorStmt(Cursor))
463 return Visit(S);
464
465 return false;
466 }
467
468 if (clang_isExpression(Cursor.kind)) {
469 if (Expr *E = getCursorExpr(Cursor))
470 return Visit(E);
471
472 return false;
473 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000474
Douglas Gregorb1373d02010-01-20 20:59:29 +0000475 if (clang_isTranslationUnit(Cursor.kind)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000476 CXTranslationUnit tu = getCursorTU(Cursor);
477 ASTUnit *CXXUnit = static_cast<ASTUnit*>(tu->TUData);
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000478
479 int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
480 for (unsigned I = 0; I != 2; ++I) {
481 if (VisitOrder[I]) {
482 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
483 RegionOfInterest.isInvalid()) {
484 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
485 TLEnd = CXXUnit->top_level_end();
486 TL != TLEnd; ++TL) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000487 if (Visit(MakeCXCursor(*TL, tu, RegionOfInterest), true))
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000488 return true;
489 }
490 } else if (VisitDeclContext(
491 CXXUnit->getASTContext().getTranslationUnitDecl()))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000492 return true;
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000493 continue;
Douglas Gregor7b691f332010-01-20 21:13:59 +0000494 }
Bob Wilson3178cb62010-03-19 03:57:57 +0000495
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000496 // Walk the preprocessing record.
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000497 if (CXXUnit->getPreprocessor().getPreprocessingRecord())
498 visitPreprocessedEntitiesInRegion();
Douglas Gregor0396f462010-03-19 05:22:59 +0000499 }
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000500
Douglas Gregor7b691f332010-01-20 21:13:59 +0000501 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000502 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000503
Douglas Gregorc314aa42011-03-02 19:17:03 +0000504 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
505 if (CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
506 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
507 return Visit(BaseTSInfo->getTypeLoc());
508 }
509 }
510 }
Argyrios Kyrtzidis221d5a52011-09-13 18:49:56 +0000511
512 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
513 IBOutletCollectionAttr *A =
514 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
515 if (const ObjCInterfaceType *InterT = A->getInterface()->getAs<ObjCInterfaceType>())
516 return Visit(cxcursor::MakeCursorObjCClassRef(InterT->getInterface(),
517 A->getInterfaceLoc(), TU));
518 }
519
Douglas Gregorb1373d02010-01-20 20:59:29 +0000520 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000521 return false;
522}
523
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000524bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
Douglas Gregor13c8ccb2011-04-22 23:49:24 +0000525 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
526 if (Visit(TSInfo->getTypeLoc()))
527 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000528
Ted Kremenek664cffd2010-07-22 11:30:19 +0000529 if (Stmt *Body = B->getBody())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000530 return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest));
Ted Kremenek664cffd2010-07-22 11:30:19 +0000531
532 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000533}
534
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000535llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
536 if (RegionOfInterest.isValid()) {
Douglas Gregor66537982010-11-17 17:14:07 +0000537 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000538 if (Range.isInvalid())
539 return llvm::Optional<bool>();
Douglas Gregor66537982010-11-17 17:14:07 +0000540
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000541 switch (CompareRegionOfInterest(Range)) {
542 case RangeBefore:
543 // This declaration comes before the region of interest; skip it.
544 return llvm::Optional<bool>();
545
546 case RangeAfter:
547 // This declaration comes after the region of interest; we're done.
548 return false;
549
550 case RangeOverlap:
551 // This declaration overlaps the region of interest; visit it.
552 break;
553 }
554 }
555 return true;
556}
557
558bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
559 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
560
561 // FIXME: Eventually remove. This part of a hack to support proper
562 // iteration over all Decls contained lexically within an ObjC container.
563 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
564 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
565
566 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000567 Decl *D = *I;
568 if (D->getLexicalDeclContext() != DC)
569 continue;
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000570 CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
Argyrios Kyrtzidis1836db02012-02-04 01:04:58 +0000571
Argyrios Kyrtzidisc178d762012-08-28 00:04:23 +0000572 // Ignore synthesized ivars here, otherwise if we have something like:
573 // @synthesize prop = _prop;
574 // and '_prop' is not declared, we will encounter a '_prop' ivar before
575 // encountering the 'prop' synthesize declaration and we will think that
576 // we passed the region-of-interest.
577 if (ObjCIvarDecl *ivarD = dyn_cast<ObjCIvarDecl>(D)) {
578 if (ivarD->getSynthesize())
579 continue;
580 }
581
Argyrios Kyrtzidis1836db02012-02-04 01:04:58 +0000582 // FIXME: ObjCClassRef/ObjCProtocolRef for forward class/protocol
583 // declarations is a mismatch with the compiler semantics.
584 if (Cursor.kind == CXCursor_ObjCInterfaceDecl) {
585 ObjCInterfaceDecl *ID = cast<ObjCInterfaceDecl>(D);
586 if (!ID->isThisDeclarationADefinition())
587 Cursor = MakeCursorObjCClassRef(ID, ID->getLocation(), TU);
588
589 } else if (Cursor.kind == CXCursor_ObjCProtocolDecl) {
590 ObjCProtocolDecl *PD = cast<ObjCProtocolDecl>(D);
591 if (!PD->isThisDeclarationADefinition())
592 Cursor = MakeCursorObjCProtocolRef(PD, PD->getLocation(), TU);
593 }
594
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000595 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
596 if (!V.hasValue())
597 continue;
598 if (!V.getValue())
599 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000600 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000601 return true;
602 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000603 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000604}
605
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000606bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
607 llvm_unreachable("Translation units are visited directly by Visit()");
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000608}
609
Richard Smith162e1c12011-04-15 14:24:37 +0000610bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
611 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
612 return Visit(TSInfo->getTypeLoc());
613
614 return false;
615}
616
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000617bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
618 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
619 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000620
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000621 return false;
622}
623
624bool CursorVisitor::VisitTagDecl(TagDecl *D) {
625 return VisitDeclContext(D);
626}
627
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000628bool CursorVisitor::VisitClassTemplateSpecializationDecl(
629 ClassTemplateSpecializationDecl *D) {
630 bool ShouldVisitBody = false;
631 switch (D->getSpecializationKind()) {
632 case TSK_Undeclared:
633 case TSK_ImplicitInstantiation:
634 // Nothing to visit
635 return false;
636
637 case TSK_ExplicitInstantiationDeclaration:
638 case TSK_ExplicitInstantiationDefinition:
639 break;
640
641 case TSK_ExplicitSpecialization:
642 ShouldVisitBody = true;
643 break;
644 }
645
646 // Visit the template arguments used in the specialization.
647 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
648 TypeLoc TL = SpecType->getTypeLoc();
649 if (TemplateSpecializationTypeLoc *TSTLoc
650 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
651 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
652 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
653 return true;
654 }
655 }
656
657 if (ShouldVisitBody && VisitCXXRecordDecl(D))
658 return true;
659
660 return false;
661}
662
Douglas Gregor74dbe642010-08-31 19:31:58 +0000663bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
664 ClassTemplatePartialSpecializationDecl *D) {
665 // FIXME: Visit the "outer" template parameter lists on the TagDecl
666 // before visiting these template parameters.
667 if (VisitTemplateParameters(D->getTemplateParameters()))
668 return true;
669
670 // Visit the partial specialization arguments.
671 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
672 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
673 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
674 return true;
675
676 return VisitCXXRecordDecl(D);
677}
678
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000679bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000680 // Visit the default argument.
681 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
682 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
683 if (Visit(DefArg->getTypeLoc()))
684 return true;
685
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000686 return false;
687}
688
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000689bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
690 if (Expr *Init = D->getInitExpr())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000691 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000692 return false;
693}
694
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000695bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
696 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
697 if (Visit(TSInfo->getTypeLoc()))
698 return true;
699
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000700 // Visit the nested-name-specifier, if present.
701 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
702 if (VisitNestedNameSpecifierLoc(QualifierLoc))
703 return true;
704
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000705 return false;
706}
707
Douglas Gregora67e03f2010-09-09 21:42:20 +0000708/// \brief Compare two base or member initializers based on their source order.
Sean Huntcbb67482011-01-08 20:30:50 +0000709static int CompareCXXCtorInitializers(const void* Xp, const void *Yp) {
710 CXXCtorInitializer const * const *X
711 = static_cast<CXXCtorInitializer const * const *>(Xp);
712 CXXCtorInitializer const * const *Y
713 = static_cast<CXXCtorInitializer const * const *>(Yp);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000714
715 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
716 return -1;
717 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
718 return 1;
719 else
720 return 0;
721}
722
Douglas Gregorb1373d02010-01-20 20:59:29 +0000723bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000724 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
725 // Visit the function declaration's syntactic components in the order
726 // written. This requires a bit of work.
Abramo Bagnara723df242010-12-14 22:11:44 +0000727 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
Douglas Gregor01829d32010-08-31 14:41:23 +0000728 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
729
730 // If we have a function declared directly (without the use of a typedef),
731 // visit just the return type. Otherwise, just visit the function's type
732 // now.
733 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
734 (!FTL && Visit(TL)))
735 return true;
736
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000737 // Visit the nested-name-specifier, if present.
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000738 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
739 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000740 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000741
742 // Visit the declaration name.
743 if (VisitDeclarationNameInfo(ND->getNameInfo()))
744 return true;
745
746 // FIXME: Visit explicitly-specified template arguments!
747
748 // Visit the function parameters, if we have a function type.
749 if (FTL && VisitFunctionTypeLoc(*FTL, true))
750 return true;
751
752 // FIXME: Attributes?
753 }
754
Sean Hunt10620eb2011-05-06 20:44:56 +0000755 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
Douglas Gregora67e03f2010-09-09 21:42:20 +0000756 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
757 // Find the initializers that were written in the source.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000758 SmallVector<CXXCtorInitializer *, 4> WrittenInits;
Douglas Gregora67e03f2010-09-09 21:42:20 +0000759 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
760 IEnd = Constructor->init_end();
761 I != IEnd; ++I) {
762 if (!(*I)->isWritten())
763 continue;
764
765 WrittenInits.push_back(*I);
766 }
767
768 // Sort the initializers in source order
769 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
Sean Huntcbb67482011-01-08 20:30:50 +0000770 &CompareCXXCtorInitializers);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000771
772 // Visit the initializers in source order
773 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
Sean Huntcbb67482011-01-08 20:30:50 +0000774 CXXCtorInitializer *Init = WrittenInits[I];
Francois Pichet00eb3f92010-12-04 09:14:42 +0000775 if (Init->isAnyMemberInitializer()) {
776 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
Douglas Gregora67e03f2010-09-09 21:42:20 +0000777 Init->getMemberLocation(), TU)))
778 return true;
Douglas Gregor76852c22011-11-01 01:16:03 +0000779 } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) {
780 if (Visit(TInfo->getTypeLoc()))
Douglas Gregora67e03f2010-09-09 21:42:20 +0000781 return true;
782 }
783
784 // Visit the initializer value.
785 if (Expr *Initializer = Init->getInit())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000786 if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
Douglas Gregora67e03f2010-09-09 21:42:20 +0000787 return true;
788 }
789 }
790
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000791 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
Douglas Gregora67e03f2010-09-09 21:42:20 +0000792 return true;
793 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000794
Douglas Gregorb1373d02010-01-20 20:59:29 +0000795 return false;
796}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000797
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000798bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
799 if (VisitDeclaratorDecl(D))
800 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000801
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000802 if (Expr *BitWidth = D->getBitWidth())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000803 return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000804
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000805 return false;
806}
807
808bool CursorVisitor::VisitVarDecl(VarDecl *D) {
809 if (VisitDeclaratorDecl(D))
810 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000811
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000812 if (Expr *Init = D->getInit())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000813 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000814
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000815 return false;
816}
817
Douglas Gregor84b51d72010-09-01 20:16:53 +0000818bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
819 if (VisitDeclaratorDecl(D))
820 return true;
821
822 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
823 if (Expr *DefArg = D->getDefaultArgument())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000824 return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
Douglas Gregor84b51d72010-09-01 20:16:53 +0000825
826 return false;
827}
828
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000829bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
830 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
831 // before visiting these template parameters.
832 if (VisitTemplateParameters(D->getTemplateParameters()))
833 return true;
834
835 return VisitFunctionDecl(D->getTemplatedDecl());
836}
837
Douglas Gregor39d6f072010-08-31 19:02:00 +0000838bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
839 // FIXME: Visit the "outer" template parameter lists on the TagDecl
840 // before visiting these template parameters.
841 if (VisitTemplateParameters(D->getTemplateParameters()))
842 return true;
843
844 return VisitCXXRecordDecl(D->getTemplatedDecl());
845}
846
Douglas Gregor84b51d72010-09-01 20:16:53 +0000847bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
848 if (VisitTemplateParameters(D->getTemplateParameters()))
849 return true;
850
851 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
852 VisitTemplateArgumentLoc(D->getDefaultArgument()))
853 return true;
854
855 return false;
856}
857
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000858bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000859 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
860 if (Visit(TSInfo->getTypeLoc()))
861 return true;
862
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000863 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000864 PEnd = ND->param_end();
865 P != PEnd; ++P) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000866 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000867 return true;
868 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000869
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000870 if (ND->isThisDeclarationADefinition() &&
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000871 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000872 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000873
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000874 return false;
875}
876
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +0000877template <typename DeclIt>
878static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current,
879 SourceManager &SM, SourceLocation EndLoc,
880 SmallVectorImpl<Decl *> &Decls) {
881 DeclIt next = *DI_current;
882 while (++next != DE_current) {
883 Decl *D_next = *next;
884 if (!D_next)
885 break;
886 SourceLocation L = D_next->getLocStart();
887 if (!L.isValid())
888 break;
889 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
890 *DI_current = next;
891 Decls.push_back(D_next);
892 continue;
893 }
894 break;
895 }
896}
897
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000898namespace {
899 struct ContainerDeclsSort {
900 SourceManager &SM;
901 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
902 bool operator()(Decl *A, Decl *B) {
903 SourceLocation L_A = A->getLocStart();
904 SourceLocation L_B = B->getLocStart();
905 assert(L_A.isValid() && L_B.isValid());
906 return SM.isBeforeInTranslationUnit(L_A, L_B);
907 }
908 };
909}
910
Douglas Gregora59e3902010-01-21 23:27:09 +0000911bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000912 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
913 // an @implementation can lexically contain Decls that are not properly
914 // nested in the AST. When we identify such cases, we need to retrofit
915 // this nesting here.
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +0000916 if (!DI_current && !FileDI_current)
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000917 return VisitDeclContext(D);
918
919 // Scan the Decls that immediately come after the container
920 // in the current DeclContext. If any fall within the
921 // container's lexical region, stash them into a vector
922 // for later processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000923 SmallVector<Decl *, 24> DeclsInContainer;
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000924 SourceLocation EndLoc = D->getSourceRange().getEnd();
Ted Kremeneka60ed472010-11-16 08:15:36 +0000925 SourceManager &SM = AU->getSourceManager();
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000926 if (EndLoc.isValid()) {
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +0000927 if (DI_current) {
928 addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc,
929 DeclsInContainer);
930 } else {
931 addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc,
932 DeclsInContainer);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000933 }
934 }
935
936 // The common case.
937 if (DeclsInContainer.empty())
938 return VisitDeclContext(D);
939
940 // Get all the Decls in the DeclContext, and sort them with the
941 // additional ones we've collected. Then visit them.
942 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
943 I!=E; ++I) {
944 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000945 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
946 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000947 continue;
948 DeclsInContainer.push_back(subDecl);
949 }
950
951 // Now sort the Decls so that they appear in lexical order.
952 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
953 ContainerDeclsSort(SM));
954
955 // Now visit the decls.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000956 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000957 E = DeclsInContainer.end(); I != E; ++I) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000958 CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000959 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
960 if (!V.hasValue())
961 continue;
962 if (!V.getValue())
963 return false;
964 if (Visit(Cursor, true))
965 return true;
966 }
967 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000968}
969
Douglas Gregorb1373d02010-01-20 20:59:29 +0000970bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000971 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
972 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000973 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000974
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000975 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
976 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
977 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000978 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000979 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000980
Douglas Gregora59e3902010-01-21 23:27:09 +0000981 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000982}
983
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000984bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000985 if (!PID->isThisDeclarationADefinition())
986 return Visit(MakeCursorObjCProtocolRef(PID, PID->getLocation(), TU));
987
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000988 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
989 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
990 E = PID->protocol_end(); I != E; ++I, ++PL)
991 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
992 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000993
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000994 return VisitObjCContainerDecl(PID);
995}
996
Ted Kremenek23173d72010-05-18 21:09:07 +0000997bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000998 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000999 return true;
1000
Ted Kremenek23173d72010-05-18 21:09:07 +00001001 // FIXME: This implements a workaround with @property declarations also being
1002 // installed in the DeclContext for the @interface. Eventually this code
1003 // should be removed.
1004 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
1005 if (!CDecl || !CDecl->IsClassExtension())
1006 return false;
1007
1008 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
1009 if (!ID)
1010 return false;
1011
1012 IdentifierInfo *PropertyId = PD->getIdentifier();
1013 ObjCPropertyDecl *prevDecl =
1014 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
1015
1016 if (!prevDecl)
1017 return false;
1018
1019 // Visit synthesized methods since they will be skipped when visiting
1020 // the @interface.
1021 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Jordan Rose1e4691b2012-10-10 16:42:25 +00001022 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001023 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
Ted Kremenek23173d72010-05-18 21:09:07 +00001024 return true;
1025
1026 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Jordan Rose1e4691b2012-10-10 16:42:25 +00001027 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001028 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
Ted Kremenek23173d72010-05-18 21:09:07 +00001029 return true;
1030
1031 return false;
1032}
1033
Douglas Gregorb1373d02010-01-20 20:59:29 +00001034bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Douglas Gregor375bb142011-12-27 22:43:10 +00001035 if (!D->isThisDeclarationADefinition()) {
1036 // Forward declaration is treated like a reference.
1037 return Visit(MakeCursorObjCClassRef(D, D->getLocation(), TU));
1038 }
1039
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001040 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +00001041 if (D->getSuperClass() &&
1042 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001043 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001044 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001045 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001046
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001047 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1048 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1049 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001050 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001051 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001052
Douglas Gregora59e3902010-01-21 23:27:09 +00001053 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001054}
1055
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001056bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1057 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001058}
1059
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001060bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +00001061 // 'ID' could be null when dealing with invalid code.
1062 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1063 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1064 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001065
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001066 return VisitObjCImplDecl(D);
1067}
1068
1069bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1070#if 0
1071 // Issue callbacks for super class.
1072 // FIXME: No source location information!
1073 if (D->getSuperClass() &&
1074 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001075 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001076 TU)))
1077 return true;
1078#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001079
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001080 return VisitObjCImplDecl(D);
1081}
1082
Douglas Gregora4ffd852010-11-17 01:03:52 +00001083bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1084 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
Argyrios Kyrtzidis135bf8e2012-06-09 03:03:02 +00001085 if (PD->isIvarNameSpecified())
1086 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
Douglas Gregora4ffd852010-11-17 01:03:52 +00001087
1088 return false;
1089}
1090
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001091bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1092 return VisitDeclContext(D);
1093}
1094
Douglas Gregor69319002010-08-31 23:48:11 +00001095bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001096 // Visit nested-name-specifier.
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00001097 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1098 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001099 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001100
1101 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1102 D->getTargetNameLoc(), TU));
1103}
1104
Douglas Gregor7e242562010-09-01 19:52:22 +00001105bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001106 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001107 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1108 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001109 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001110 }
Douglas Gregor7e242562010-09-01 19:52:22 +00001111
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001112 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1113 return true;
1114
Douglas Gregor7e242562010-09-01 19:52:22 +00001115 return VisitDeclarationNameInfo(D->getNameInfo());
1116}
1117
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001118bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001119 // Visit nested-name-specifier.
Douglas Gregordb992412011-02-25 16:33:46 +00001120 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1121 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001122 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001123
1124 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1125 D->getIdentLocation(), TU));
1126}
1127
Douglas Gregor7e242562010-09-01 19:52:22 +00001128bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001129 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001130 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1131 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001132 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001133 }
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001134
Douglas Gregor7e242562010-09-01 19:52:22 +00001135 return VisitDeclarationNameInfo(D->getNameInfo());
1136}
1137
1138bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1139 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001140 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001141 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1142 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001143 return true;
1144
Douglas Gregor7e242562010-09-01 19:52:22 +00001145 return false;
1146}
1147
Douglas Gregor01829d32010-08-31 14:41:23 +00001148bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1149 switch (Name.getName().getNameKind()) {
1150 case clang::DeclarationName::Identifier:
1151 case clang::DeclarationName::CXXLiteralOperatorName:
1152 case clang::DeclarationName::CXXOperatorName:
1153 case clang::DeclarationName::CXXUsingDirective:
1154 return false;
1155
1156 case clang::DeclarationName::CXXConstructorName:
1157 case clang::DeclarationName::CXXDestructorName:
1158 case clang::DeclarationName::CXXConversionFunctionName:
1159 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1160 return Visit(TSInfo->getTypeLoc());
1161 return false;
1162
1163 case clang::DeclarationName::ObjCZeroArgSelector:
1164 case clang::DeclarationName::ObjCOneArgSelector:
1165 case clang::DeclarationName::ObjCMultiArgSelector:
1166 // FIXME: Per-identifier location info?
1167 return false;
1168 }
David Blaikie7530c032012-01-17 06:56:22 +00001169
1170 llvm_unreachable("Invalid DeclarationName::Kind!");
Douglas Gregor01829d32010-08-31 14:41:23 +00001171}
1172
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001173bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1174 SourceRange Range) {
1175 // FIXME: This whole routine is a hack to work around the lack of proper
1176 // source information in nested-name-specifiers (PR5791). Since we do have
1177 // a beginning source location, we can visit the first component of the
1178 // nested-name-specifier, if it's a single-token component.
1179 if (!NNS)
1180 return false;
1181
1182 // Get the first component in the nested-name-specifier.
1183 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1184 NNS = Prefix;
1185
1186 switch (NNS->getKind()) {
1187 case NestedNameSpecifier::Namespace:
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001188 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1189 TU));
1190
Douglas Gregor14aba762011-02-24 02:36:08 +00001191 case NestedNameSpecifier::NamespaceAlias:
1192 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1193 Range.getBegin(), TU));
1194
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001195 case NestedNameSpecifier::TypeSpec: {
1196 // If the type has a form where we know that the beginning of the source
1197 // range matches up with a reference cursor. Visit the appropriate reference
1198 // cursor.
John McCallf4c73712011-01-19 06:33:43 +00001199 const Type *T = NNS->getAsType();
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001200 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1201 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1202 if (const TagType *Tag = dyn_cast<TagType>(T))
1203 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1204 if (const TemplateSpecializationType *TST
1205 = dyn_cast<TemplateSpecializationType>(T))
1206 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1207 break;
1208 }
1209
1210 case NestedNameSpecifier::TypeSpecWithTemplate:
1211 case NestedNameSpecifier::Global:
1212 case NestedNameSpecifier::Identifier:
1213 break;
1214 }
1215
1216 return false;
1217}
1218
Douglas Gregordc355712011-02-25 00:36:19 +00001219bool
1220CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001221 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
Douglas Gregordc355712011-02-25 00:36:19 +00001222 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1223 Qualifiers.push_back(Qualifier);
1224
1225 while (!Qualifiers.empty()) {
1226 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1227 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1228 switch (NNS->getKind()) {
1229 case NestedNameSpecifier::Namespace:
1230 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001231 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001232 TU)))
1233 return true;
1234
1235 break;
1236
1237 case NestedNameSpecifier::NamespaceAlias:
1238 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001239 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001240 TU)))
1241 return true;
1242
1243 break;
1244
1245 case NestedNameSpecifier::TypeSpec:
1246 case NestedNameSpecifier::TypeSpecWithTemplate:
1247 if (Visit(Q.getTypeLoc()))
1248 return true;
1249
1250 break;
1251
1252 case NestedNameSpecifier::Global:
1253 case NestedNameSpecifier::Identifier:
1254 break;
1255 }
1256 }
1257
1258 return false;
1259}
1260
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001261bool CursorVisitor::VisitTemplateParameters(
1262 const TemplateParameterList *Params) {
1263 if (!Params)
1264 return false;
1265
1266 for (TemplateParameterList::const_iterator P = Params->begin(),
1267 PEnd = Params->end();
1268 P != PEnd; ++P) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001269 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001270 return true;
1271 }
1272
1273 return false;
1274}
1275
Douglas Gregor0b36e612010-08-31 20:37:03 +00001276bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1277 switch (Name.getKind()) {
1278 case TemplateName::Template:
1279 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1280
1281 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001282 // Visit the overloaded template set.
1283 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1284 return true;
1285
Douglas Gregor0b36e612010-08-31 20:37:03 +00001286 return false;
1287
1288 case TemplateName::DependentTemplate:
1289 // FIXME: Visit nested-name-specifier.
1290 return false;
1291
1292 case TemplateName::QualifiedTemplate:
1293 // FIXME: Visit nested-name-specifier.
1294 return Visit(MakeCursorTemplateRef(
1295 Name.getAsQualifiedTemplateName()->getDecl(),
1296 Loc, TU));
John McCall14606042011-06-30 08:33:18 +00001297
1298 case TemplateName::SubstTemplateTemplateParm:
1299 return Visit(MakeCursorTemplateRef(
1300 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1301 Loc, TU));
Douglas Gregor1aee05d2011-01-15 06:45:20 +00001302
1303 case TemplateName::SubstTemplateTemplateParmPack:
1304 return Visit(MakeCursorTemplateRef(
1305 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1306 Loc, TU));
Douglas Gregor0b36e612010-08-31 20:37:03 +00001307 }
David Blaikie7530c032012-01-17 06:56:22 +00001308
1309 llvm_unreachable("Invalid TemplateName::Kind!");
Douglas Gregor0b36e612010-08-31 20:37:03 +00001310}
1311
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001312bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1313 switch (TAL.getArgument().getKind()) {
1314 case TemplateArgument::Null:
1315 case TemplateArgument::Integral:
Douglas Gregor87dd6972010-12-20 16:52:59 +00001316 case TemplateArgument::Pack:
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001317 return false;
1318
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001319 case TemplateArgument::Type:
1320 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1321 return Visit(TSInfo->getTypeLoc());
1322 return false;
1323
1324 case TemplateArgument::Declaration:
1325 if (Expr *E = TAL.getSourceDeclExpression())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001326 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001327 return false;
Eli Friedmand7a6b162012-09-26 02:36:12 +00001328
1329 case TemplateArgument::NullPtr:
1330 if (Expr *E = TAL.getSourceNullPtrExpression())
1331 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1332 return false;
1333
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001334 case TemplateArgument::Expression:
1335 if (Expr *E = TAL.getSourceExpression())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001336 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001337 return false;
1338
1339 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001340 case TemplateArgument::TemplateExpansion:
Douglas Gregorb6744ef2011-03-02 17:09:35 +00001341 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1342 return true;
1343
Douglas Gregora7fc9012011-01-05 18:58:31 +00001344 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
Douglas Gregor0b36e612010-08-31 20:37:03 +00001345 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001346 }
David Blaikie7530c032012-01-17 06:56:22 +00001347
1348 llvm_unreachable("Invalid TemplateArgument::Kind!");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001349}
1350
Ted Kremeneka0536d82010-05-07 01:04:29 +00001351bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1352 return VisitDeclContext(D);
1353}
1354
Douglas Gregor01829d32010-08-31 14:41:23 +00001355bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1356 return Visit(TL.getUnqualifiedLoc());
1357}
1358
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001359bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00001360 ASTContext &Context = AU->getASTContext();
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001361
1362 // Some builtin types (such as Objective-C's "id", "sel", and
1363 // "Class") have associated declarations. Create cursors for those.
1364 QualType VisitType;
John McCalle0a22d02011-10-18 21:02:43 +00001365 switch (TL.getTypePtr()->getKind()) {
John McCall2dde35b2011-10-18 22:28:37 +00001366
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001367 case BuiltinType::Void:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001368 case BuiltinType::NullPtr:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001369 case BuiltinType::Dependent:
John McCall2dde35b2011-10-18 22:28:37 +00001370#define BUILTIN_TYPE(Id, SingletonId)
1371#define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1372#define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1373#define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
1374#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
1375#include "clang/AST/BuiltinTypes.def"
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001376 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001377
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001378 case BuiltinType::ObjCId:
1379 VisitType = Context.getObjCIdType();
1380 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001381
1382 case BuiltinType::ObjCClass:
1383 VisitType = Context.getObjCClassType();
1384 break;
1385
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001386 case BuiltinType::ObjCSel:
1387 VisitType = Context.getObjCSelType();
1388 break;
1389 }
1390
1391 if (!VisitType.isNull()) {
1392 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001393 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001394 TU));
1395 }
1396
1397 return false;
1398}
1399
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001400bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
Richard Smith162e1c12011-04-15 14:24:37 +00001401 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001402}
1403
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001404bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1405 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1406}
1407
1408bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
Argyrios Kyrtzidis6f155de2011-08-25 22:24:47 +00001409 if (TL.isDefinition())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001410 return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
Argyrios Kyrtzidis6f155de2011-08-25 22:24:47 +00001411
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001412 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1413}
1414
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001415bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Chandler Carruth960d13d2011-05-01 09:53:37 +00001416 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001417}
1418
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001419bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1420 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1421 return true;
1422
John McCallc12c5bb2010-05-15 11:32:37 +00001423 return false;
1424}
1425
1426bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1427 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1428 return true;
1429
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001430 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1431 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1432 TU)))
1433 return true;
1434 }
1435
1436 return false;
1437}
1438
1439bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001440 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001441}
1442
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001443bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1444 return Visit(TL.getInnerLoc());
1445}
1446
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001447bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1448 return Visit(TL.getPointeeLoc());
1449}
1450
1451bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1452 return Visit(TL.getPointeeLoc());
1453}
1454
1455bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1456 return Visit(TL.getPointeeLoc());
1457}
1458
1459bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001460 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001461}
1462
1463bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001464 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001465}
1466
Argyrios Kyrtzidis3422fbc2011-08-15 18:44:43 +00001467bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1468 return Visit(TL.getModifiedLoc());
1469}
1470
Douglas Gregor01829d32010-08-31 14:41:23 +00001471bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1472 bool SkipResultType) {
1473 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001474 return true;
1475
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001476 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001477 if (Decl *D = TL.getArg(I))
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001478 if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001479 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001480
1481 return false;
1482}
1483
1484bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1485 if (Visit(TL.getElementLoc()))
1486 return true;
1487
1488 if (Expr *Size = TL.getSizeExpr())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001489 return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001490
1491 return false;
1492}
1493
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001494bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1495 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001496 // Visit the template name.
1497 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1498 TL.getTemplateNameLoc()))
1499 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001500
1501 // Visit the template arguments.
1502 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1503 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1504 return true;
1505
1506 return false;
1507}
1508
Douglas Gregor2332c112010-01-21 20:48:56 +00001509bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1510 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1511}
1512
1513bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1514 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1515 return Visit(TSInfo->getTypeLoc());
1516
1517 return false;
1518}
1519
Sean Huntca63c202011-05-24 22:41:36 +00001520bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1521 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1522 return Visit(TSInfo->getTypeLoc());
1523
1524 return false;
1525}
1526
Douglas Gregor2494dd02011-03-01 01:34:45 +00001527bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
1528 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1529 return true;
1530
1531 return false;
1532}
1533
Douglas Gregor94fdffa2011-03-01 20:11:18 +00001534bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1535 DependentTemplateSpecializationTypeLoc TL) {
1536 // Visit the nested-name-specifier, if there is one.
1537 if (TL.getQualifierLoc() &&
1538 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1539 return true;
1540
1541 // Visit the template arguments.
1542 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1543 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1544 return true;
1545
1546 return false;
1547}
1548
Douglas Gregor9e876872011-03-01 18:12:44 +00001549bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1550 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1551 return true;
1552
1553 return Visit(TL.getNamedTypeLoc());
1554}
1555
Douglas Gregor7536dd52010-12-20 02:24:11 +00001556bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1557 return Visit(TL.getPatternLoc());
1558}
1559
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +00001560bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1561 if (Expr *E = TL.getUnderlyingExpr())
1562 return Visit(MakeCXCursor(E, StmtParent, TU));
1563
1564 return false;
1565}
1566
1567bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1568 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1569}
1570
Eli Friedmanb001de72011-10-06 23:00:33 +00001571bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1572 return Visit(TL.getValueLoc());
1573}
1574
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +00001575#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1576bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1577 return Visit##PARENT##Loc(TL); \
1578}
1579
1580DEFAULT_TYPELOC_IMPL(Complex, Type)
1581DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1582DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1583DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1584DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
1585DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1586DEFAULT_TYPELOC_IMPL(Vector, Type)
1587DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1588DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1589DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1590DEFAULT_TYPELOC_IMPL(Record, TagType)
1591DEFAULT_TYPELOC_IMPL(Enum, TagType)
1592DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1593DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1594DEFAULT_TYPELOC_IMPL(Auto, Type)
1595
Ted Kremenek3064ef92010-08-27 21:34:58 +00001596bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001597 // Visit the nested-name-specifier, if present.
1598 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1599 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1600 return true;
1601
John McCall5e1cdac2011-10-07 06:10:15 +00001602 if (D->isCompleteDefinition()) {
Ted Kremenek3064ef92010-08-27 21:34:58 +00001603 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1604 E = D->bases_end(); I != E; ++I) {
1605 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1606 return true;
1607 }
1608 }
1609
1610 return VisitTagDecl(D);
1611}
1612
Ted Kremenek09dfa372010-02-18 05:46:33 +00001613bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001614 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1615 i != e; ++i)
1616 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001617 return true;
1618
1619 return false;
1620}
1621
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001622//===----------------------------------------------------------------------===//
1623// Data-recursive visitor methods.
1624//===----------------------------------------------------------------------===//
1625
Ted Kremenek28a71942010-11-13 00:36:47 +00001626namespace {
Ted Kremenek035dc412010-11-13 00:36:50 +00001627#define DEF_JOB(NAME, DATA, KIND)\
1628class NAME : public VisitorJob {\
1629public:\
1630 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1631 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Ted Kremenekf64d8032010-11-18 00:02:32 +00001632 DATA *get() const { return static_cast<DATA*>(data[0]); }\
Ted Kremenek035dc412010-11-13 00:36:50 +00001633};
1634
1635DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1636DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001637DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001638DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001639DEF_JOB(ExplicitTemplateArgsVisit, ASTTemplateArgumentListInfo,
Ted Kremenek60608ec2010-11-17 00:50:47 +00001640 ExplicitTemplateArgsVisitKind)
Douglas Gregor94d96292011-01-19 20:34:17 +00001641DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
Douglas Gregor011d8b92012-02-15 00:54:55 +00001642DEF_JOB(LambdaExprParts, LambdaExpr, LambdaExprPartsKind)
Argyrios Kyrtzidisd579dd52012-09-01 18:27:30 +00001643DEF_JOB(PostChildrenVisit, void, PostChildrenVisitKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001644#undef DEF_JOB
1645
1646class DeclVisit : public VisitorJob {
1647public:
1648 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1649 VisitorJob(parent, VisitorJob::DeclVisitKind,
1650 d, isFirst ? (void*) 1 : (void*) 0) {}
1651 static bool classof(const VisitorJob *VJ) {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001652 return VJ->getKind() == DeclVisitKind;
Ted Kremenek035dc412010-11-13 00:36:50 +00001653 }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001654 Decl *get() const { return static_cast<Decl*>(data[0]); }
1655 bool isFirst() const { return data[1] ? true : false; }
Ted Kremenek035dc412010-11-13 00:36:50 +00001656};
Ted Kremenek035dc412010-11-13 00:36:50 +00001657class TypeLocVisit : public VisitorJob {
1658public:
1659 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1660 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1661 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1662
1663 static bool classof(const VisitorJob *VJ) {
1664 return VJ->getKind() == TypeLocVisitKind;
1665 }
1666
Ted Kremenek82f3c502010-11-15 22:23:26 +00001667 TypeLoc get() const {
Ted Kremenekf64d8032010-11-18 00:02:32 +00001668 QualType T = QualType::getFromOpaquePtr(data[0]);
1669 return TypeLoc(T, data[1]);
Ted Kremenek035dc412010-11-13 00:36:50 +00001670 }
1671};
1672
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001673class LabelRefVisit : public VisitorJob {
1674public:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001675 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1676 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001677 labelLoc.getPtrEncoding()) {}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001678
1679 static bool classof(const VisitorJob *VJ) {
1680 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1681 }
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001682 LabelDecl *get() const { return static_cast<LabelDecl*>(data[0]); }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001683 SourceLocation getLoc() const {
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001684 return SourceLocation::getFromPtrEncoding(data[1]); }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001685};
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001686
1687class NestedNameSpecifierLocVisit : public VisitorJob {
1688public:
1689 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1690 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1691 Qualifier.getNestedNameSpecifier(),
1692 Qualifier.getOpaqueData()) { }
1693
1694 static bool classof(const VisitorJob *VJ) {
1695 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1696 }
1697
1698 NestedNameSpecifierLoc get() const {
1699 return NestedNameSpecifierLoc(static_cast<NestedNameSpecifier*>(data[0]),
1700 data[1]);
1701 }
1702};
1703
Ted Kremenekf64d8032010-11-18 00:02:32 +00001704class DeclarationNameInfoVisit : public VisitorJob {
1705public:
1706 DeclarationNameInfoVisit(Stmt *S, CXCursor parent)
1707 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
1708 static bool classof(const VisitorJob *VJ) {
1709 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1710 }
1711 DeclarationNameInfo get() const {
1712 Stmt *S = static_cast<Stmt*>(data[0]);
1713 switch (S->getStmtClass()) {
1714 default:
1715 llvm_unreachable("Unhandled Stmt");
Douglas Gregorba0513d2011-10-25 01:33:02 +00001716 case clang::Stmt::MSDependentExistsStmtClass:
1717 return cast<MSDependentExistsStmt>(S)->getNameInfo();
Ted Kremenekf64d8032010-11-18 00:02:32 +00001718 case Stmt::CXXDependentScopeMemberExprClass:
1719 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1720 case Stmt::DependentScopeDeclRefExprClass:
1721 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
1722 }
1723 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001724};
Ted Kremenekcdba6592010-11-18 00:42:18 +00001725class MemberRefVisit : public VisitorJob {
1726public:
1727 MemberRefVisit(FieldDecl *D, SourceLocation L, CXCursor parent)
1728 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001729 L.getPtrEncoding()) {}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001730 static bool classof(const VisitorJob *VJ) {
1731 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1732 }
1733 FieldDecl *get() const {
1734 return static_cast<FieldDecl*>(data[0]);
1735 }
1736 SourceLocation getLoc() const {
1737 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1738 }
1739};
Ted Kremenek28a71942010-11-13 00:36:47 +00001740class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1741 VisitorWorkList &WL;
1742 CXCursor Parent;
1743public:
1744 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1745 : WL(wl), Parent(parent) {}
1746
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001747 void VisitAddrLabelExpr(AddrLabelExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001748 void VisitBlockExpr(BlockExpr *B);
Ted Kremenek28a71942010-11-13 00:36:47 +00001749 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek083c7e22010-11-13 05:38:03 +00001750 void VisitCompoundStmt(CompoundStmt *S);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001751 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
Douglas Gregorba0513d2011-10-25 01:33:02 +00001752 void VisitMSDependentExistsStmt(MSDependentExistsStmt *S);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001753 void VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001754 void VisitCXXNewExpr(CXXNewExpr *E);
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001755 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001756 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001757 void VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001758 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001759 void VisitCXXTypeidExpr(CXXTypeidExpr *E);
Ted Kremenek55b933a2010-11-17 00:50:36 +00001760 void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001761 void VisitCXXUuidofExpr(CXXUuidofExpr *E);
Argyrios Kyrtzidisdcbb2fb2011-12-03 03:49:44 +00001762 void VisitCXXCatchStmt(CXXCatchStmt *S);
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001763 void VisitDeclRefExpr(DeclRefExpr *D);
Ted Kremenek035dc412010-11-13 00:36:50 +00001764 void VisitDeclStmt(DeclStmt *S);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001765 void VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001766 void VisitDesignatedInitExpr(DesignatedInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001767 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1768 void VisitForStmt(ForStmt *FS);
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001769 void VisitGotoStmt(GotoStmt *GS);
Ted Kremenek28a71942010-11-13 00:36:47 +00001770 void VisitIfStmt(IfStmt *If);
1771 void VisitInitListExpr(InitListExpr *IE);
1772 void VisitMemberExpr(MemberExpr *M);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001773 void VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001774 void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001775 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1776 void VisitOverloadExpr(OverloadExpr *E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001777 void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001778 void VisitStmt(Stmt *S);
1779 void VisitSwitchStmt(SwitchStmt *S);
1780 void VisitWhileStmt(WhileStmt *W);
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001781 void VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Francois Pichet6ad6f282010-12-07 00:08:36 +00001782 void VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E);
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00001783 void VisitTypeTraitExpr(TypeTraitExpr *E);
John Wiegley21ff2e52011-04-28 00:16:57 +00001784 void VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E);
John Wiegley55262202011-04-25 06:54:41 +00001785 void VisitExpressionTraitExpr(ExpressionTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001786 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001787 void VisitVAArgExpr(VAArgExpr *E);
Douglas Gregor94d96292011-01-19 20:34:17 +00001788 void VisitSizeOfPackExpr(SizeOfPackExpr *E);
John McCall4b9c2d22011-11-06 09:01:30 +00001789 void VisitPseudoObjectExpr(PseudoObjectExpr *E);
1790 void VisitOpaqueValueExpr(OpaqueValueExpr *E);
Douglas Gregor011d8b92012-02-15 00:54:55 +00001791 void VisitLambdaExpr(LambdaExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00001792
Ted Kremenek28a71942010-11-13 00:36:47 +00001793private:
Ted Kremenekf64d8032010-11-18 00:02:32 +00001794 void AddDeclarationNameInfo(Stmt *S);
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001795 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001796 void AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001797 void AddMemberRef(FieldDecl *D, SourceLocation L);
Ted Kremenek28a71942010-11-13 00:36:47 +00001798 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001799 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001800 void AddTypeLoc(TypeSourceInfo *TI);
1801 void EnqueueChildren(Stmt *S);
1802};
1803} // end anonyous namespace
1804
Ted Kremenekf64d8032010-11-18 00:02:32 +00001805void EnqueueVisitor::AddDeclarationNameInfo(Stmt *S) {
1806 // 'S' should always be non-null, since it comes from the
1807 // statement we are visiting.
1808 WL.push_back(DeclarationNameInfoVisit(S, Parent));
1809}
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001810
1811void
1812EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1813 if (Qualifier)
1814 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
1815}
1816
Ted Kremenek28a71942010-11-13 00:36:47 +00001817void EnqueueVisitor::AddStmt(Stmt *S) {
1818 if (S)
1819 WL.push_back(StmtVisit(S, Parent));
1820}
Ted Kremenek035dc412010-11-13 00:36:50 +00001821void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001822 if (D)
Ted Kremenek035dc412010-11-13 00:36:50 +00001823 WL.push_back(DeclVisit(D, Parent, isFirst));
Ted Kremenek28a71942010-11-13 00:36:47 +00001824}
Ted Kremenek60608ec2010-11-17 00:50:47 +00001825void EnqueueVisitor::
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001826 AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001827 if (A)
1828 WL.push_back(ExplicitTemplateArgsVisit(
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001829 const_cast<ASTTemplateArgumentListInfo*>(A), Parent));
Ted Kremenek60608ec2010-11-17 00:50:47 +00001830}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001831void EnqueueVisitor::AddMemberRef(FieldDecl *D, SourceLocation L) {
1832 if (D)
1833 WL.push_back(MemberRefVisit(D, L, Parent));
1834}
Ted Kremenek28a71942010-11-13 00:36:47 +00001835void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1836 if (TI)
1837 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1838 }
1839void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001840 unsigned size = WL.size();
John McCall7502c1d2011-02-13 04:07:26 +00001841 for (Stmt::child_range Child = S->children(); Child; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001842 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001843 }
1844 if (size == WL.size())
1845 return;
1846 // Now reverse the entries we just added. This will match the DFS
1847 // ordering performed by the worklist.
1848 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1849 std::reverse(I, E);
1850}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001851void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1852 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
1853}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001854void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1855 AddDecl(B->getBlockDecl());
1856}
Ted Kremenek28a71942010-11-13 00:36:47 +00001857void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1858 EnqueueChildren(E);
1859 AddTypeLoc(E->getTypeSourceInfo());
1860}
Ted Kremenek083c7e22010-11-13 05:38:03 +00001861void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1862 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1863 E = S->body_rend(); I != E; ++I) {
1864 AddStmt(*I);
1865 }
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001866}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001867void EnqueueVisitor::
Douglas Gregorba0513d2011-10-25 01:33:02 +00001868VisitMSDependentExistsStmt(MSDependentExistsStmt *S) {
1869 AddStmt(S->getSubStmt());
1870 AddDeclarationNameInfo(S);
1871 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
1872 AddNestedNameSpecifierLoc(QualifierLoc);
1873}
1874
1875void EnqueueVisitor::
Ted Kremenekf64d8032010-11-18 00:02:32 +00001876VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
1877 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1878 AddDeclarationNameInfo(E);
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001879 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1880 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001881 if (!E->isImplicitAccess())
1882 AddStmt(E->getBase());
1883}
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001884void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001885 // Enqueue the initializer , if any.
1886 AddStmt(E->getInitializer());
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001887 // Enqueue the array size, if any.
1888 AddStmt(E->getArraySize());
1889 // Enqueue the allocated type.
1890 AddTypeLoc(E->getAllocatedTypeSourceInfo());
1891 // Enqueue the placement arguments.
1892 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1893 AddStmt(E->getPlacementArg(I-1));
1894}
Ted Kremenek28a71942010-11-13 00:36:47 +00001895void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
Ted Kremenek8b8d8c92010-11-13 05:55:56 +00001896 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1897 AddStmt(CE->getArg(I-1));
Ted Kremenek28a71942010-11-13 00:36:47 +00001898 AddStmt(CE->getCallee());
1899 AddStmt(CE->getArg(0));
1900}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001901void EnqueueVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1902 // Visit the name of the type being destroyed.
1903 AddTypeLoc(E->getDestroyedTypeInfo());
1904 // Visit the scope type that looks disturbingly like the nested-name-specifier
1905 // but isn't.
1906 AddTypeLoc(E->getScopeTypeInfo());
1907 // Visit the nested-name-specifier.
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001908 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1909 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001910 // Visit base expression.
1911 AddStmt(E->getBase());
1912}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001913void EnqueueVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1914 AddTypeLoc(E->getTypeSourceInfo());
1915}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001916void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1917 EnqueueChildren(E);
1918 AddTypeLoc(E->getTypeSourceInfo());
1919}
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001920void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1921 EnqueueChildren(E);
1922 if (E->isTypeOperand())
1923 AddTypeLoc(E->getTypeOperandSourceInfo());
1924}
Ted Kremenek55b933a2010-11-17 00:50:36 +00001925
1926void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
1927 *E) {
1928 EnqueueChildren(E);
1929 AddTypeLoc(E->getTypeSourceInfo());
1930}
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001931void EnqueueVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1932 EnqueueChildren(E);
1933 if (E->isTypeOperand())
1934 AddTypeLoc(E->getTypeOperandSourceInfo());
1935}
Argyrios Kyrtzidisdcbb2fb2011-12-03 03:49:44 +00001936
1937void EnqueueVisitor::VisitCXXCatchStmt(CXXCatchStmt *S) {
1938 EnqueueChildren(S);
1939 AddDecl(S->getExceptionDecl());
1940}
1941
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001942void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001943 if (DR->hasExplicitTemplateArgs()) {
1944 AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
1945 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001946 WL.push_back(DeclRefExprParts(DR, Parent));
1947}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001948void EnqueueVisitor::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
1949 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1950 AddDeclarationNameInfo(E);
Douglas Gregor00cf3cc2011-02-25 20:49:16 +00001951 AddNestedNameSpecifierLoc(E->getQualifierLoc());
Ted Kremenekf64d8032010-11-18 00:02:32 +00001952}
Ted Kremenek035dc412010-11-13 00:36:50 +00001953void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1954 unsigned size = WL.size();
1955 bool isFirst = true;
1956 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1957 D != DEnd; ++D) {
1958 AddDecl(*D, isFirst);
1959 isFirst = false;
1960 }
1961 if (size == WL.size())
1962 return;
1963 // Now reverse the entries we just added. This will match the DFS
1964 // ordering performed by the worklist.
1965 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1966 std::reverse(I, E);
1967}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001968void EnqueueVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1969 AddStmt(E->getInit());
1970 typedef DesignatedInitExpr::Designator Designator;
1971 for (DesignatedInitExpr::reverse_designators_iterator
1972 D = E->designators_rbegin(), DEnd = E->designators_rend();
1973 D != DEnd; ++D) {
1974 if (D->isFieldDesignator()) {
1975 if (FieldDecl *Field = D->getField())
1976 AddMemberRef(Field, D->getFieldLoc());
1977 continue;
1978 }
1979 if (D->isArrayDesignator()) {
1980 AddStmt(E->getArrayIndex(*D));
1981 continue;
1982 }
1983 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1984 AddStmt(E->getArrayRangeEnd(*D));
1985 AddStmt(E->getArrayRangeStart(*D));
1986 }
1987}
Ted Kremenek28a71942010-11-13 00:36:47 +00001988void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1989 EnqueueChildren(E);
1990 AddTypeLoc(E->getTypeInfoAsWritten());
1991}
1992void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1993 AddStmt(FS->getBody());
1994 AddStmt(FS->getInc());
1995 AddStmt(FS->getCond());
1996 AddDecl(FS->getConditionVariable());
1997 AddStmt(FS->getInit());
1998}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001999void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) {
2000 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
2001}
Ted Kremenek28a71942010-11-13 00:36:47 +00002002void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
2003 AddStmt(If->getElse());
2004 AddStmt(If->getThen());
2005 AddStmt(If->getCond());
2006 AddDecl(If->getConditionVariable());
2007}
2008void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
2009 // We care about the syntactic form of the initializer list, only.
2010 if (InitListExpr *Syntactic = IE->getSyntacticForm())
2011 IE = Syntactic;
2012 EnqueueChildren(IE);
2013}
2014void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
Douglas Gregor89629a72010-11-17 17:15:08 +00002015 WL.push_back(MemberExprParts(M, Parent));
2016
2017 // If the base of the member access expression is an implicit 'this', don't
2018 // visit it.
2019 // FIXME: If we ever want to show these implicit accesses, this will be
2020 // unfortunate. However, clang_getCursor() relies on this behavior.
Douglas Gregor75e85042011-03-02 21:06:53 +00002021 if (!M->isImplicitAccess())
2022 AddStmt(M->getBase());
Ted Kremenek28a71942010-11-13 00:36:47 +00002023}
Ted Kremenek73d15c42010-11-13 01:09:29 +00002024void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
2025 AddTypeLoc(E->getEncodedTypeSourceInfo());
2026}
Ted Kremenek28a71942010-11-13 00:36:47 +00002027void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
2028 EnqueueChildren(M);
2029 AddTypeLoc(M->getClassReceiverTypeInfo());
2030}
Ted Kremenekcdba6592010-11-18 00:42:18 +00002031void EnqueueVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
2032 // Visit the components of the offsetof expression.
2033 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
2034 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
2035 const OffsetOfNode &Node = E->getComponent(I-1);
2036 switch (Node.getKind()) {
2037 case OffsetOfNode::Array:
2038 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2039 break;
2040 case OffsetOfNode::Field:
Abramo Bagnara06dec892011-03-12 09:45:03 +00002041 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
Ted Kremenekcdba6592010-11-18 00:42:18 +00002042 break;
2043 case OffsetOfNode::Identifier:
2044 case OffsetOfNode::Base:
2045 continue;
2046 }
2047 }
2048 // Visit the type into which we're computing the offset.
2049 AddTypeLoc(E->getTypeSourceInfo());
2050}
Ted Kremenek28a71942010-11-13 00:36:47 +00002051void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00002052 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
Ted Kremenek60458782010-11-12 21:34:16 +00002053 WL.push_back(OverloadExprParts(E, Parent));
2054}
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002055void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
2056 UnaryExprOrTypeTraitExpr *E) {
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00002057 EnqueueChildren(E);
2058 if (E->isArgumentType())
2059 AddTypeLoc(E->getArgumentTypeInfo());
2060}
Ted Kremenek28a71942010-11-13 00:36:47 +00002061void EnqueueVisitor::VisitStmt(Stmt *S) {
2062 EnqueueChildren(S);
2063}
2064void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
2065 AddStmt(S->getBody());
2066 AddStmt(S->getCond());
2067 AddDecl(S->getConditionVariable());
2068}
Ted Kremenekfafa75a2010-11-17 00:50:39 +00002069
Ted Kremenek28a71942010-11-13 00:36:47 +00002070void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
2071 AddStmt(W->getBody());
2072 AddStmt(W->getCond());
2073 AddDecl(W->getConditionVariable());
2074}
John Wiegley21ff2e52011-04-28 00:16:57 +00002075
Ted Kremenek2939b6f2010-11-17 00:50:50 +00002076void EnqueueVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
2077 AddTypeLoc(E->getQueriedTypeSourceInfo());
2078}
Francois Pichet6ad6f282010-12-07 00:08:36 +00002079
2080void EnqueueVisitor::VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
Francois Pichet6ad6f282010-12-07 00:08:36 +00002081 AddTypeLoc(E->getRhsTypeSourceInfo());
Francois Pichet0a03a3f2010-12-08 09:11:05 +00002082 AddTypeLoc(E->getLhsTypeSourceInfo());
Francois Pichet6ad6f282010-12-07 00:08:36 +00002083}
2084
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00002085void EnqueueVisitor::VisitTypeTraitExpr(TypeTraitExpr *E) {
2086 for (unsigned I = E->getNumArgs(); I > 0; --I)
2087 AddTypeLoc(E->getArg(I-1));
2088}
2089
John Wiegley21ff2e52011-04-28 00:16:57 +00002090void EnqueueVisitor::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
2091 AddTypeLoc(E->getQueriedTypeSourceInfo());
2092}
2093
John Wiegley55262202011-04-25 06:54:41 +00002094void EnqueueVisitor::VisitExpressionTraitExpr(ExpressionTraitExpr *E) {
2095 EnqueueChildren(E);
2096}
2097
Ted Kremenek28a71942010-11-13 00:36:47 +00002098void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
2099 VisitOverloadExpr(U);
2100 if (!U->isImplicitAccess())
2101 AddStmt(U->getBase());
2102}
Ted Kremenek9d3bf792010-11-17 00:50:43 +00002103void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) {
2104 AddStmt(E->getSubExpr());
2105 AddTypeLoc(E->getWrittenTypeInfo());
2106}
Douglas Gregor94d96292011-01-19 20:34:17 +00002107void EnqueueVisitor::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
2108 WL.push_back(SizeOfPackExprParts(E, Parent));
2109}
John McCall4b9c2d22011-11-06 09:01:30 +00002110void EnqueueVisitor::VisitOpaqueValueExpr(OpaqueValueExpr *E) {
2111 // If the opaque value has a source expression, just transparently
2112 // visit that. This is useful for (e.g.) pseudo-object expressions.
2113 if (Expr *SourceExpr = E->getSourceExpr())
2114 return Visit(SourceExpr);
John McCall4b9c2d22011-11-06 09:01:30 +00002115}
Douglas Gregor011d8b92012-02-15 00:54:55 +00002116void EnqueueVisitor::VisitLambdaExpr(LambdaExpr *E) {
2117 AddStmt(E->getBody());
2118 WL.push_back(LambdaExprParts(E, Parent));
2119}
John McCall4b9c2d22011-11-06 09:01:30 +00002120void EnqueueVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *E) {
2121 // Treat the expression like its syntactic form.
2122 Visit(E->getSyntacticForm());
2123}
Ted Kremenek60458782010-11-12 21:34:16 +00002124
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002125void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002126 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002127}
2128
2129bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2130 if (RegionOfInterest.isValid()) {
2131 SourceRange Range = getRawCursorExtent(C);
2132 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2133 return false;
2134 }
2135 return true;
2136}
2137
2138bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2139 while (!WL.empty()) {
2140 // Dequeue the worklist item.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002141 VisitorJob LI = WL.back();
2142 WL.pop_back();
2143
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002144 // Set the Parent field, then back to its old value once we're done.
2145 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2146
2147 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00002148 case VisitorJob::DeclVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002149 Decl *D = cast<DeclVisit>(&LI)->get();
Ted Kremenekf1107452010-11-12 18:26:56 +00002150 if (!D)
2151 continue;
2152
2153 // For now, perform default visitation for Decls.
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002154 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2155 cast<DeclVisit>(&LI)->isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00002156 return true;
2157
2158 continue;
2159 }
Ted Kremenek60608ec2010-11-17 00:50:47 +00002160 case VisitorJob::ExplicitTemplateArgsVisitKind: {
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00002161 const ASTTemplateArgumentListInfo *ArgList =
Ted Kremenek60608ec2010-11-17 00:50:47 +00002162 cast<ExplicitTemplateArgsVisit>(&LI)->get();
2163 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2164 *ArgEnd = Arg + ArgList->NumTemplateArgs;
2165 Arg != ArgEnd; ++Arg) {
2166 if (VisitTemplateArgumentLoc(*Arg))
2167 return true;
2168 }
2169 continue;
2170 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002171 case VisitorJob::TypeLocVisitKind: {
2172 // Perform default visitation for TypeLocs.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002173 if (Visit(cast<TypeLocVisit>(&LI)->get()))
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002174 return true;
2175 continue;
2176 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002177 case VisitorJob::LabelRefVisitKind: {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002178 LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Ted Kremeneke7455012011-02-23 04:54:51 +00002179 if (LabelStmt *stmt = LS->getStmt()) {
2180 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2181 TU))) {
2182 return true;
2183 }
2184 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002185 continue;
2186 }
Ted Kremenek47695c82011-08-18 22:25:21 +00002187
Douglas Gregorf3db29f2011-02-25 18:19:59 +00002188 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2189 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2190 if (VisitNestedNameSpecifierLoc(V->get()))
2191 return true;
2192 continue;
2193 }
2194
Ted Kremenekf64d8032010-11-18 00:02:32 +00002195 case VisitorJob::DeclarationNameInfoVisitKind: {
2196 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2197 ->get()))
2198 return true;
2199 continue;
2200 }
Ted Kremenekcdba6592010-11-18 00:42:18 +00002201 case VisitorJob::MemberRefVisitKind: {
2202 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2203 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2204 return true;
2205 continue;
2206 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002207 case VisitorJob::StmtVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002208 Stmt *S = cast<StmtVisit>(&LI)->get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00002209 if (!S)
2210 continue;
2211
Ted Kremenekf1107452010-11-12 18:26:56 +00002212 // Update the current cursor.
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002213 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
Ted Kremenekcdba6592010-11-18 00:42:18 +00002214 if (!IsInRegionOfInterest(Cursor))
2215 continue;
2216 switch (Visitor(Cursor, Parent, ClientData)) {
2217 case CXChildVisit_Break: return true;
2218 case CXChildVisit_Continue: break;
2219 case CXChildVisit_Recurse:
Argyrios Kyrtzidisd579dd52012-09-01 18:27:30 +00002220 if (PostChildrenVisitor)
2221 WL.push_back(PostChildrenVisit(0, Cursor));
Ted Kremenekcdba6592010-11-18 00:42:18 +00002222 EnqueueWorkList(WL, S);
Ted Kremenek82f3c502010-11-15 22:23:26 +00002223 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002224 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00002225 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002226 }
2227 case VisitorJob::MemberExprPartsKind: {
2228 // Handle the other pieces in the MemberExpr besides the base.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002229 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002230
2231 // Visit the nested-name-specifier
Douglas Gregor40d96a62011-02-28 21:54:11 +00002232 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
2233 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002234 return true;
2235
2236 // Visit the declaration name.
2237 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2238 return true;
2239
2240 // Visit the explicitly-specified template arguments, if any.
2241 if (M->hasExplicitTemplateArgs()) {
2242 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2243 *ArgEnd = Arg + M->getNumTemplateArgs();
2244 Arg != ArgEnd; ++Arg) {
2245 if (VisitTemplateArgumentLoc(*Arg))
2246 return true;
2247 }
2248 }
2249 continue;
2250 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002251 case VisitorJob::DeclRefExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002252 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002253 // Visit nested-name-specifier, if present.
Douglas Gregor40d96a62011-02-28 21:54:11 +00002254 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
2255 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002256 return true;
2257 // Visit declaration name.
2258 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2259 return true;
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002260 continue;
2261 }
Ted Kremenek60458782010-11-12 21:34:16 +00002262 case VisitorJob::OverloadExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002263 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Ted Kremenek60458782010-11-12 21:34:16 +00002264 // Visit the nested-name-specifier.
Douglas Gregor4c9be892011-02-28 20:01:57 +00002265 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
2266 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenek60458782010-11-12 21:34:16 +00002267 return true;
2268 // Visit the declaration name.
2269 if (VisitDeclarationNameInfo(O->getNameInfo()))
2270 return true;
2271 // Visit the overloaded declaration reference.
2272 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2273 return true;
Ted Kremenek60458782010-11-12 21:34:16 +00002274 continue;
2275 }
Douglas Gregor94d96292011-01-19 20:34:17 +00002276 case VisitorJob::SizeOfPackExprPartsKind: {
2277 SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
2278 NamedDecl *Pack = E->getPack();
2279 if (isa<TemplateTypeParmDecl>(Pack)) {
2280 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
2281 E->getPackLoc(), TU)))
2282 return true;
2283
2284 continue;
2285 }
2286
2287 if (isa<TemplateTemplateParmDecl>(Pack)) {
2288 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
2289 E->getPackLoc(), TU)))
2290 return true;
2291
2292 continue;
2293 }
2294
2295 // Non-type template parameter packs and function parameter packs are
2296 // treated like DeclRefExpr cursors.
2297 continue;
2298 }
Douglas Gregor011d8b92012-02-15 00:54:55 +00002299
2300 case VisitorJob::LambdaExprPartsKind: {
2301 // Visit captures.
2302 LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
2303 for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
2304 CEnd = E->explicit_capture_end();
2305 C != CEnd; ++C) {
2306 if (C->capturesThis())
2307 continue;
2308
2309 if (Visit(MakeCursorVariableRef(C->getCapturedVar(),
2310 C->getLocation(),
2311 TU)))
2312 return true;
2313 }
2314
2315 // Visit parameters and return type, if present.
2316 if (E->hasExplicitParameters() || E->hasExplicitResultType()) {
2317 TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
2318 if (E->hasExplicitParameters() && E->hasExplicitResultType()) {
2319 // Visit the whole type.
2320 if (Visit(TL))
2321 return true;
2322 } else if (isa<FunctionProtoTypeLoc>(TL)) {
2323 FunctionProtoTypeLoc Proto = cast<FunctionProtoTypeLoc>(TL);
2324 if (E->hasExplicitParameters()) {
2325 // Visit parameters.
2326 for (unsigned I = 0, N = Proto.getNumArgs(); I != N; ++I)
2327 if (Visit(MakeCXCursor(Proto.getArg(I), TU)))
2328 return true;
2329 } else {
2330 // Visit result type.
2331 if (Visit(Proto.getResultLoc()))
2332 return true;
2333 }
2334 }
2335 }
2336 break;
2337 }
Argyrios Kyrtzidisd579dd52012-09-01 18:27:30 +00002338
2339 case VisitorJob::PostChildrenVisitKind:
2340 if (PostChildrenVisitor(Parent, ClientData))
2341 return true;
2342 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002343 }
2344 }
2345 return false;
2346}
2347
Ted Kremenekcdba6592010-11-18 00:42:18 +00002348bool CursorVisitor::Visit(Stmt *S) {
Ted Kremenekd1ded662010-11-15 23:31:32 +00002349 VisitorWorkList *WL = 0;
2350 if (!WorkListFreeList.empty()) {
2351 WL = WorkListFreeList.back();
2352 WL->clear();
2353 WorkListFreeList.pop_back();
2354 }
2355 else {
2356 WL = new VisitorWorkList();
2357 WorkListCache.push_back(WL);
2358 }
2359 EnqueueWorkList(*WL, S);
2360 bool result = RunVisitorWorkList(*WL);
2361 WorkListFreeList.push_back(WL);
2362 return result;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002363}
2364
Francois Pichet48a8d142011-07-25 22:00:44 +00002365namespace {
2366typedef llvm::SmallVector<SourceRange, 4> RefNamePieces;
2367RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
2368 const DeclarationNameInfo &NI,
2369 const SourceRange &QLoc,
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00002370 const ASTTemplateArgumentListInfo *TemplateArgs = 0){
Francois Pichet48a8d142011-07-25 22:00:44 +00002371 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
2372 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
2373 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
2374
2375 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
2376
2377 RefNamePieces Pieces;
2378
2379 if (WantQualifier && QLoc.isValid())
2380 Pieces.push_back(QLoc);
2381
2382 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
2383 Pieces.push_back(NI.getLoc());
2384
2385 if (WantTemplateArgs && TemplateArgs)
2386 Pieces.push_back(SourceRange(TemplateArgs->LAngleLoc,
2387 TemplateArgs->RAngleLoc));
2388
2389 if (Kind == DeclarationName::CXXOperatorName) {
2390 Pieces.push_back(SourceLocation::getFromRawEncoding(
2391 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
2392 Pieces.push_back(SourceLocation::getFromRawEncoding(
2393 NI.getInfo().CXXOperatorName.EndOpNameLoc));
2394 }
2395
2396 if (WantSinglePiece) {
2397 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
2398 Pieces.clear();
2399 Pieces.push_back(R);
2400 }
2401
2402 return Pieces;
2403}
2404}
2405
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002406//===----------------------------------------------------------------------===//
2407// Misc. API hooks.
2408//===----------------------------------------------------------------------===//
2409
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002410static llvm::sys::Mutex EnableMultithreadingMutex;
2411static bool EnabledMultithreading;
2412
Argyrios Kyrtzidisfa39f5b2011-12-15 04:52:41 +00002413static void fatal_error_handler(void *user_data, const std::string& reason) {
Argyrios Kyrtzidisfa39f5b2011-12-15 04:52:41 +00002414 // Write the result out to stderr avoiding errs() because raw_ostreams can
2415 // call report_fatal_error.
Argyrios Kyrtzidisdb7a8002011-12-15 06:51:30 +00002416 fprintf(stderr, "LIBCLANG FATAL ERROR: %s\n", reason.c_str());
Argyrios Kyrtzidisfa39f5b2011-12-15 04:52:41 +00002417 ::abort();
2418}
2419
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002420extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002421CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2422 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002423 // Disable pretty stack trace functionality, which will otherwise be a very
2424 // poor citizen of the world and set up all sorts of signal handlers.
2425 llvm::DisablePrettyStackTrace = true;
2426
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002427 // We use crash recovery to make some of our APIs more reliable, implicitly
2428 // enable it.
2429 llvm::CrashRecoveryContext::Enable();
2430
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002431 // Enable support for multithreading in LLVM.
2432 {
2433 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2434 if (!EnabledMultithreading) {
Argyrios Kyrtzidisfa39f5b2011-12-15 04:52:41 +00002435 llvm::install_fatal_error_handler(fatal_error_handler, 0);
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002436 llvm::llvm_start_multithreaded();
2437 EnabledMultithreading = true;
2438 }
2439 }
2440
Douglas Gregora030b7c2010-01-22 20:35:53 +00002441 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002442 if (excludeDeclarationsFromPCH)
2443 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002444 if (displayDiagnostics)
2445 CIdxr->setDisplayDiagnostics();
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002446
2447 if (getenv("LIBCLANG_BGPRIO_INDEX"))
2448 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
2449 CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
2450 if (getenv("LIBCLANG_BGPRIO_EDIT"))
2451 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
2452 CXGlobalOpt_ThreadBackgroundPriorityForEditing);
2453
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002454 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002455}
2456
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002457void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002458 if (CIdx)
2459 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002460}
2461
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002462void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
2463 if (CIdx)
2464 static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
2465}
2466
2467unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
2468 if (CIdx)
2469 return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
2470 return 0;
2471}
2472
Ted Kremenekd2427dd2011-03-18 23:05:39 +00002473void clang_toggleCrashRecovery(unsigned isEnabled) {
2474 if (isEnabled)
2475 llvm::CrashRecoveryContext::Enable();
2476 else
2477 llvm::CrashRecoveryContext::Disable();
2478}
2479
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002480CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002481 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002482 if (!CIdx)
2483 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002484
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002485 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002486 FileSystemOptions FileSystemOpts;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002487
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00002488 IntrusiveRefCntPtr<DiagnosticsEngine> Diags;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002489 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002490 CXXIdx->getOnlyLocalDecls(),
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00002491 0, 0,
2492 /*CaptureDiagnostics=*/true,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00002493 /*AllowPCHWithCompilerErrors=*/true,
2494 /*UserFilesAreVolatile=*/true);
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002495 return MakeCXTranslationUnit(CXXIdx, TU);
Steve Naroff600866c2009-08-27 19:51:58 +00002496}
2497
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002498unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002499 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregorb5af8432011-08-25 22:54:01 +00002500 CXTranslationUnit_CacheCompletionResults;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002501}
2502
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002503CXTranslationUnit
2504clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2505 const char *source_filename,
2506 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002507 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002508 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002509 struct CXUnsavedFile *unsaved_files) {
Argyrios Kyrtzidise1d43302012-02-25 02:41:16 +00002510 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
Douglas Gregor5a430212010-07-21 18:52:53 +00002511 return clang_parseTranslationUnit(CIdx, source_filename,
2512 command_line_args, num_command_line_args,
2513 unsaved_files, num_unsaved_files,
Douglas Gregordca8ee82011-05-06 16:33:08 +00002514 Options);
Douglas Gregor5a430212010-07-21 18:52:53 +00002515}
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00002516
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002517struct ParseTranslationUnitInfo {
2518 CXIndex CIdx;
2519 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002520 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002521 int num_command_line_args;
2522 struct CXUnsavedFile *unsaved_files;
2523 unsigned num_unsaved_files;
2524 unsigned options;
2525 CXTranslationUnit result;
2526};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002527static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002528 ParseTranslationUnitInfo *PTUI =
2529 static_cast<ParseTranslationUnitInfo*>(UserData);
2530 CXIndex CIdx = PTUI->CIdx;
2531 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002532 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002533 int num_command_line_args = PTUI->num_command_line_args;
2534 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2535 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2536 unsigned options = PTUI->options;
2537 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002538
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002539 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002540 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002541
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002542 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2543
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002544 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
Argyrios Kyrtzidis81b5ac32012-03-28 02:49:54 +00002545 setThreadBackgroundPriority();
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002546
Douglas Gregor44c181a2010-07-23 00:33:23 +00002547 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregor467dc882011-08-25 22:30:56 +00002548 // FIXME: Add a flag for modules.
2549 TranslationUnitKind TUKind
2550 = (options & CXTranslationUnit_Incomplete)? TU_Prefix : TU_Complete;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002551 bool CacheCodeCompetionResults
2552 = options & CXTranslationUnit_CacheCompletionResults;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002553 bool IncludeBriefCommentsInCodeCompletion
2554 = options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
Erik Verbruggen6a91d382012-04-12 10:11:59 +00002555 bool SkipFunctionBodies = options & CXTranslationUnit_SkipFunctionBodies;
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002556 bool ForSerialization = options & CXTranslationUnit_ForSerialization;
Erik Verbruggen6a91d382012-04-12 10:11:59 +00002557
Douglas Gregor5352ac02010-01-28 00:27:43 +00002558 // Configure the diagnostics.
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00002559 IntrusiveRefCntPtr<DiagnosticsEngine>
Douglas Gregor02c23eb2012-10-23 22:26:28 +00002560 Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions,
2561 num_command_line_args,
2562 command_line_args));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002563
Ted Kremenek25a11e12011-03-22 01:15:24 +00002564 // Recover resources if we crash before exiting this function.
David Blaikied6471f72011-09-25 23:23:43 +00002565 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
2566 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00002567 DiagCleanup(Diags.getPtr());
2568
Dylan Noblesmith1e4c01b2012-02-13 12:32:21 +00002569 OwningPtr<std::vector<ASTUnit::RemappedFile> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00002570 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2571
2572 // Recover resources if we crash before exiting this function.
2573 llvm::CrashRecoveryContextCleanupRegistrar<
2574 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2575
Douglas Gregor4db64a42010-01-23 00:14:00 +00002576 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002577 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002578 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002579 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002580 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2581 Buffer));
Douglas Gregor4db64a42010-01-23 00:14:00 +00002582 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002583
Dylan Noblesmith1e4c01b2012-02-13 12:32:21 +00002584 OwningPtr<std::vector<const char *> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00002585 Args(new std::vector<const char*>());
2586
2587 // Recover resources if we crash before exiting this method.
2588 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
2589 ArgsCleanup(Args.get());
2590
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002591 // Since the Clang C library is primarily used by batch tools dealing with
2592 // (often very broken) source code, where spell-checking can have a
2593 // significant negative impact on performance (particularly when
2594 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002595 // Only do this if we haven't found a spell-checking-related argument.
2596 bool FoundSpellCheckingArgument = false;
2597 for (int I = 0; I != num_command_line_args; ++I) {
2598 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2599 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2600 FoundSpellCheckingArgument = true;
2601 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002602 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002603 }
2604 if (!FoundSpellCheckingArgument)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002605 Args->push_back("-fno-spell-checking");
Douglas Gregorb10daed2010-10-11 16:52:23 +00002606
Ted Kremenek25a11e12011-03-22 01:15:24 +00002607 Args->insert(Args->end(), command_line_args,
2608 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002609
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002610 // The 'source_filename' argument is optional. If the caller does not
2611 // specify it then it is assumed that the source file is specified
2612 // in the actual argument list.
2613 // Put the source file after command_line_args otherwise if '-x' flag is
2614 // present it will be unused.
2615 if (source_filename)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002616 Args->push_back(source_filename);
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002617
Douglas Gregor44c181a2010-07-23 00:33:23 +00002618 // Do we need the detailed preprocessing record?
2619 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Ted Kremenek25a11e12011-03-22 01:15:24 +00002620 Args->push_back("-Xclang");
2621 Args->push_back("-detailed-preprocessing-record");
Douglas Gregor44c181a2010-07-23 00:33:23 +00002622 }
2623
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002624 unsigned NumErrors = Diags->getClient()->getNumErrors();
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00002625 OwningPtr<ASTUnit> ErrUnit;
Dylan Noblesmith1e4c01b2012-02-13 12:32:21 +00002626 OwningPtr<ASTUnit> Unit(
Ted Kremenek4ee99262011-03-22 20:16:19 +00002627 ASTUnit::LoadFromCommandLine(Args->size() ? &(*Args)[0] : 0
2628 /* vector::data() not portable */,
2629 Args->size() ? (&(*Args)[0] + Args->size()) :0,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002630 Diags,
2631 CXXIdx->getClangResourcesPath(),
2632 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002633 /*CaptureDiagnostics=*/true,
Ted Kremenek4ee99262011-03-22 20:16:19 +00002634 RemappedFiles->size() ? &(*RemappedFiles)[0]:0,
Ted Kremenek25a11e12011-03-22 01:15:24 +00002635 RemappedFiles->size(),
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00002636 /*RemappedFilesKeepOriginalName=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002637 PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00002638 TUKind,
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00002639 CacheCodeCompetionResults,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002640 IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00002641 /*AllowPCHWithCompilerErrors=*/true,
Erik Verbruggen6a91d382012-04-12 10:11:59 +00002642 SkipFunctionBodies,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00002643 /*UserFilesAreVolatile=*/true,
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002644 ForSerialization,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00002645 &ErrUnit));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002646
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002647 if (NumErrors != Diags->getClient()->getNumErrors()) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002648 // Make sure to check that 'Unit' is non-NULL.
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00002649 if (CXXIdx->getDisplayDiagnostics())
2650 printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
Douglas Gregora88084b2010-02-18 18:08:43 +00002651 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002652
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002653 PTUI->result = MakeCXTranslationUnit(CXXIdx, Unit.take());
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002654}
2655CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2656 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002657 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002658 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002659 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002660 unsigned num_unsaved_files,
2661 unsigned options) {
2662 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002663 num_command_line_args, unsaved_files,
2664 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002665 llvm::CrashRecoveryContext CRC;
2666
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002667 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002668 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2669 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2670 fprintf(stderr, " 'command_line_args' : [");
2671 for (int i = 0; i != num_command_line_args; ++i) {
2672 if (i)
2673 fprintf(stderr, ", ");
2674 fprintf(stderr, "'%s'", command_line_args[i]);
2675 }
2676 fprintf(stderr, "],\n");
2677 fprintf(stderr, " 'unsaved_files' : [");
2678 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2679 if (i)
2680 fprintf(stderr, ", ");
2681 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2682 unsaved_files[i].Length);
2683 }
2684 fprintf(stderr, "],\n");
2685 fprintf(stderr, " 'options' : %d,\n", options);
2686 fprintf(stderr, "}\n");
2687
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002688 return 0;
Douglas Gregor6df78732011-05-05 20:27:22 +00002689 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
2690 PrintLibclangResourceUsage(PTUI.result);
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002691 }
Douglas Gregor6df78732011-05-05 20:27:22 +00002692
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002693 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002694}
2695
Douglas Gregor19998442010-08-13 15:35:05 +00002696unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2697 return CXSaveTranslationUnit_None;
2698}
Argyrios Kyrtzidis142bcb52012-03-28 02:17:59 +00002699
2700namespace {
2701
2702struct SaveTranslationUnitInfo {
2703 CXTranslationUnit TU;
2704 const char *FileName;
2705 unsigned options;
2706 CXSaveError result;
2707};
2708
2709}
2710
2711static void clang_saveTranslationUnit_Impl(void *UserData) {
2712 SaveTranslationUnitInfo *STUI =
2713 static_cast<SaveTranslationUnitInfo*>(UserData);
2714
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002715 CIndexer *CXXIdx = (CIndexer*)STUI->TU->CIdx;
2716 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
Argyrios Kyrtzidis81b5ac32012-03-28 02:49:54 +00002717 setThreadBackgroundPriority();
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002718
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002719 bool hadError = static_cast<ASTUnit *>(STUI->TU->TUData)->Save(STUI->FileName);
2720 STUI->result = hadError ? CXSaveError_Unknown : CXSaveError_None;
Argyrios Kyrtzidis142bcb52012-03-28 02:17:59 +00002721}
2722
Douglas Gregor19998442010-08-13 15:35:05 +00002723int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2724 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002725 if (!TU)
Douglas Gregor39c411f2011-07-06 16:43:36 +00002726 return CXSaveError_InvalidTU;
Argyrios Kyrtzidis142bcb52012-03-28 02:17:59 +00002727
2728 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
2729 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Argyrios Kyrtzidis374a00b2012-06-08 05:48:06 +00002730 if (!CXXUnit->hasSema())
2731 return CXSaveError_InvalidTU;
Argyrios Kyrtzidis142bcb52012-03-28 02:17:59 +00002732
2733 SaveTranslationUnitInfo STUI = { TU, FileName, options, CXSaveError_None };
2734
2735 if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred() ||
2736 getenv("LIBCLANG_NOTHREADS")) {
2737 clang_saveTranslationUnit_Impl(&STUI);
2738
2739 if (getenv("LIBCLANG_RESOURCE_USAGE"))
2740 PrintLibclangResourceUsage(TU);
2741
2742 return STUI.result;
2743 }
2744
2745 // We have an AST that has invalid nodes due to compiler errors.
2746 // Use a crash recovery thread for protection.
2747
2748 llvm::CrashRecoveryContext CRC;
2749
2750 if (!RunSafely(CRC, clang_saveTranslationUnit_Impl, &STUI)) {
2751 fprintf(stderr, "libclang: crash detected during AST saving: {\n");
2752 fprintf(stderr, " 'filename' : '%s'\n", FileName);
2753 fprintf(stderr, " 'options' : %d,\n", options);
2754 fprintf(stderr, "}\n");
2755
2756 return CXSaveError_Unknown;
2757
2758 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
Douglas Gregor6df78732011-05-05 20:27:22 +00002759 PrintLibclangResourceUsage(TU);
Argyrios Kyrtzidis142bcb52012-03-28 02:17:59 +00002760 }
2761
2762 return STUI.result;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002763}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002764
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002765void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002766 if (CTUnit) {
2767 // If the translation unit has been marked as unsafe to free, just discard
2768 // it.
Ted Kremeneka60ed472010-11-16 08:15:36 +00002769 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002770 return;
2771
Ted Kremeneka60ed472010-11-16 08:15:36 +00002772 delete static_cast<ASTUnit *>(CTUnit->TUData);
2773 disposeCXStringPool(CTUnit->StringPool);
Ted Kremenek15322172011-11-10 08:43:12 +00002774 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
Ted Kremenekbbf66ca2012-04-30 19:06:49 +00002775 disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002776 delete CTUnit;
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002777 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002778}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002779
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002780unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2781 return CXReparse_None;
2782}
2783
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002784struct ReparseTranslationUnitInfo {
2785 CXTranslationUnit TU;
2786 unsigned num_unsaved_files;
2787 struct CXUnsavedFile *unsaved_files;
2788 unsigned options;
2789 int result;
2790};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002791
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002792static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002793 ReparseTranslationUnitInfo *RTUI =
2794 static_cast<ReparseTranslationUnitInfo*>(UserData);
2795 CXTranslationUnit TU = RTUI->TU;
Ted Kremenek15322172011-11-10 08:43:12 +00002796
2797 // Reset the associated diagnostics.
2798 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
2799 TU->Diagnostics = 0;
2800
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002801 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2802 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2803 unsigned options = RTUI->options;
2804 (void) options;
2805 RTUI->result = 1;
2806
Douglas Gregorabc563f2010-07-19 21:46:24 +00002807 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002808 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002809
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002810 CIndexer *CXXIdx = (CIndexer*)TU->CIdx;
2811 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
Argyrios Kyrtzidis81b5ac32012-03-28 02:49:54 +00002812 setThreadBackgroundPriority();
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002813
Ted Kremeneka60ed472010-11-16 08:15:36 +00002814 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor593b0c12010-09-23 18:47:53 +00002815 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002816
Dylan Noblesmith1e4c01b2012-02-13 12:32:21 +00002817 OwningPtr<std::vector<ASTUnit::RemappedFile> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00002818 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2819
2820 // Recover resources if we crash before exiting this function.
2821 llvm::CrashRecoveryContextCleanupRegistrar<
2822 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2823
Douglas Gregorabc563f2010-07-19 21:46:24 +00002824 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002825 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002826 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002827 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002828 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2829 Buffer));
Douglas Gregorabc563f2010-07-19 21:46:24 +00002830 }
2831
Ted Kremenek4ee99262011-03-22 20:16:19 +00002832 if (!CXXUnit->Reparse(RemappedFiles->size() ? &(*RemappedFiles)[0] : 0,
2833 RemappedFiles->size()))
Douglas Gregor593b0c12010-09-23 18:47:53 +00002834 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002835}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002836
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002837int clang_reparseTranslationUnit(CXTranslationUnit TU,
2838 unsigned num_unsaved_files,
2839 struct CXUnsavedFile *unsaved_files,
2840 unsigned options) {
2841 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2842 options, 0 };
Argyrios Kyrtzidis8c4b47e2011-10-28 22:54:33 +00002843
Argyrios Kyrtzidise7de9b42011-10-29 19:32:39 +00002844 if (getenv("LIBCLANG_NOTHREADS")) {
Argyrios Kyrtzidis8c4b47e2011-10-28 22:54:33 +00002845 clang_reparseTranslationUnit_Impl(&RTUI);
2846 return RTUI.result;
2847 }
2848
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002849 llvm::CrashRecoveryContext CRC;
2850
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002851 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002852 fprintf(stderr, "libclang: crash detected during reparsing\n");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002853 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002854 return 1;
Douglas Gregor6df78732011-05-05 20:27:22 +00002855 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
2856 PrintLibclangResourceUsage(TU);
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002857
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002858 return RTUI.result;
2859}
2860
Douglas Gregordf95a132010-08-09 20:45:32 +00002861
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002862CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002863 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002864 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002865
Ted Kremeneka60ed472010-11-16 08:15:36 +00002866 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002867 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002868}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002869
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002870CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregor8e5900c2012-04-30 23:41:16 +00002871 ASTUnit *CXXUnit = static_cast<ASTUnit*>(TU->TUData);
2872 return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002873}
2874
Ted Kremenekfb480492010-01-13 21:46:36 +00002875} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002876
Ted Kremenekfb480492010-01-13 21:46:36 +00002877//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002878// CXFile Operations.
2879//===----------------------------------------------------------------------===//
2880
2881extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002882CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002883 if (!SFile)
Ted Kremeneka60ed472010-11-16 08:15:36 +00002884 return createCXString((const char*)NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002885
Steve Naroff88145032009-10-27 14:35:18 +00002886 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002887 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002888}
2889
2890time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002891 if (!SFile)
2892 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002893
Steve Naroff88145032009-10-27 14:35:18 +00002894 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2895 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002896}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002897
Douglas Gregorb9790342010-01-22 21:44:22 +00002898CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2899 if (!tu)
2900 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002901
Ted Kremeneka60ed472010-11-16 08:15:36 +00002902 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002903
Douglas Gregorb9790342010-01-22 21:44:22 +00002904 FileManager &FMgr = CXXUnit->getFileManager();
Chris Lattner39b49bc2010-11-23 08:35:12 +00002905 return const_cast<FileEntry *>(FMgr.getFile(file_name));
Douglas Gregorb9790342010-01-22 21:44:22 +00002906}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002907
Douglas Gregordd3e5542011-05-04 00:14:37 +00002908unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit tu, CXFile file) {
2909 if (!tu || !file)
2910 return 0;
2911
2912 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
2913 FileEntry *FEnt = static_cast<FileEntry *>(file);
2914 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
2915 .isFileMultipleIncludeGuarded(FEnt);
2916}
2917
Ted Kremenekfb480492010-01-13 21:46:36 +00002918} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002919
Ted Kremenekfb480492010-01-13 21:46:36 +00002920//===----------------------------------------------------------------------===//
2921// CXCursor Operations.
2922//===----------------------------------------------------------------------===//
2923
Ted Kremenekfb480492010-01-13 21:46:36 +00002924static Decl *getDeclFromExpr(Stmt *E) {
Argyrios Kyrtzidisc2954612011-09-12 22:17:26 +00002925 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Douglas Gregordb1314e2010-10-01 21:11:22 +00002926 return getDeclFromExpr(CE->getSubExpr());
2927
Ted Kremenekfb480492010-01-13 21:46:36 +00002928 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2929 return RefExpr->getDecl();
2930 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2931 return ME->getMemberDecl();
2932 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2933 return RE->getDecl();
Argyrios Kyrtzidisb085d892012-03-30 00:19:18 +00002934 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
2935 if (PRE->isExplicitProperty())
2936 return PRE->getExplicitProperty();
2937 // It could be messaging both getter and setter as in:
2938 // ++myobj.myprop;
2939 // in which case prefer to associate the setter since it is less obvious
2940 // from inspecting the source that the setter is going to get called.
2941 if (PRE->isMessagingSetter())
2942 return PRE->getImplicitPropertySetter();
2943 return PRE->getImplicitPropertyGetter();
2944 }
John McCall4b9c2d22011-11-06 09:01:30 +00002945 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
2946 return getDeclFromExpr(POE->getSyntacticForm());
2947 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
2948 if (Expr *Src = OVE->getSourceExpr())
2949 return getDeclFromExpr(Src);
Douglas Gregordb1314e2010-10-01 21:11:22 +00002950
Ted Kremenekfb480492010-01-13 21:46:36 +00002951 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2952 return getDeclFromExpr(CE->getCallee());
Chris Lattner5f9e2722011-07-23 10:55:15 +00002953 if (CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Douglas Gregor93798e22010-11-05 21:11:19 +00002954 if (!CE->isElidable())
2955 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002956 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2957 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002958
Douglas Gregordb1314e2010-10-01 21:11:22 +00002959 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2960 return PE->getProtocol();
Douglas Gregorc7793c72011-01-15 01:15:58 +00002961 if (SubstNonTypeTemplateParmPackExpr *NTTP
2962 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
2963 return NTTP->getParameterPack();
Douglas Gregor94d96292011-01-19 20:34:17 +00002964 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2965 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
2966 isa<ParmVarDecl>(SizeOfPack->getPack()))
2967 return SizeOfPack->getPack();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002968
Ted Kremenekfb480492010-01-13 21:46:36 +00002969 return 0;
2970}
2971
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002972static SourceLocation getLocationFromExpr(Expr *E) {
Argyrios Kyrtzidisc2954612011-09-12 22:17:26 +00002973 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
2974 return getLocationFromExpr(CE->getSubExpr());
2975
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002976 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2977 return /*FIXME:*/Msg->getLeftLoc();
2978 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2979 return DRE->getLocation();
2980 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2981 return Member->getMemberLoc();
2982 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2983 return Ivar->getLocation();
Douglas Gregor94d96292011-01-19 20:34:17 +00002984 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2985 return SizeOfPack->getPackLoc();
Argyrios Kyrtzidisd0469522012-03-30 00:19:13 +00002986 if (ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
2987 return PropRef->getLocation();
Douglas Gregor94d96292011-01-19 20:34:17 +00002988
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002989 return E->getLocStart();
2990}
2991
Ted Kremenekfb480492010-01-13 21:46:36 +00002992extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002993
2994unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002995 CXCursorVisitor visitor,
2996 CXClientData client_data) {
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00002997 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
2998 /*VisitPreprocessorLast=*/false);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002999 return CursorVis.VisitChildren(parent);
3000}
3001
David Chisnall3387c652010-11-03 14:12:26 +00003002#ifndef __has_feature
3003#define __has_feature(x) 0
3004#endif
3005#if __has_feature(blocks)
3006typedef enum CXChildVisitResult
3007 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
3008
3009static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
3010 CXClientData client_data) {
3011 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
3012 return block(cursor, parent);
3013}
3014#else
3015// If we are compiled with a compiler that doesn't have native blocks support,
3016// define and call the block manually, so the
3017typedef struct _CXChildVisitResult
3018{
3019 void *isa;
3020 int flags;
3021 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003022 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
3023 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00003024} *CXCursorVisitorBlock;
3025
3026static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
3027 CXClientData client_data) {
3028 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
3029 return block->invoke(block, cursor, parent);
3030}
3031#endif
3032
3033
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003034unsigned clang_visitChildrenWithBlock(CXCursor parent,
3035 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00003036 return clang_visitChildren(parent, visitWithBlock, block);
3037}
3038
Douglas Gregor78205d42010-01-20 21:45:58 +00003039static CXString getDeclSpelling(Decl *D) {
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00003040 if (!D)
3041 return createCXString("");
3042
3043 NamedDecl *ND = dyn_cast<NamedDecl>(D);
Douglas Gregore3c60a72010-11-17 00:13:31 +00003044 if (!ND) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003045 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00003046 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3047 return createCXString(Property->getIdentifier()->getName());
3048
Argyrios Kyrtzidis6a010122012-10-05 00:22:24 +00003049 if (ImportDecl *ImportD = dyn_cast<ImportDecl>(D))
3050 if (Module *Mod = ImportD->getImportedModule())
3051 return createCXString(Mod->getFullModuleName());
3052
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003053 return createCXString("");
Douglas Gregore3c60a72010-11-17 00:13:31 +00003054 }
3055
Douglas Gregor78205d42010-01-20 21:45:58 +00003056 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003057 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003058
Douglas Gregor78205d42010-01-20 21:45:58 +00003059 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
3060 // No, this isn't the same as the code below. getIdentifier() is non-virtual
3061 // and returns different names. NamedDecl returns the class name and
3062 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003063 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003064
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003065 if (isa<UsingDirectiveDecl>(D))
3066 return createCXString("");
3067
Dylan Noblesmith36d59272012-02-13 12:32:26 +00003068 SmallString<1024> S;
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00003069 llvm::raw_svector_ostream os(S);
3070 ND->printName(os);
3071
3072 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00003073}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003074
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003075CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003076 if (clang_isTranslationUnit(C.kind))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003077 return clang_getTranslationUnitSpelling(
3078 static_cast<CXTranslationUnit>(C.data[2]));
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003079
Steve Narofff334b4e2009-09-02 18:26:48 +00003080 if (clang_isReference(C.kind)) {
3081 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00003082 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00003083 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003084 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003085 }
3086 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00003087 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003088 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003089 }
3090 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00003091 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00003092 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003093 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003094 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00003095 case CXCursor_CXXBaseSpecifier: {
3096 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
3097 return createCXString(B->getType().getAsString());
3098 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003099 case CXCursor_TypeRef: {
3100 TypeDecl *Type = getCursorTypeRef(C).first;
3101 assert(Type && "Missing type decl");
3102
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003103 return createCXString(getCursorContext(C).getTypeDeclType(Type).
3104 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003105 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003106 case CXCursor_TemplateRef: {
3107 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00003108 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003109
3110 return createCXString(Template->getNameAsString());
3111 }
Douglas Gregor69319002010-08-31 23:48:11 +00003112
3113 case CXCursor_NamespaceRef: {
3114 NamedDecl *NS = getCursorNamespaceRef(C).first;
3115 assert(NS && "Missing namespace decl");
3116
3117 return createCXString(NS->getNameAsString());
3118 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003119
Douglas Gregora67e03f2010-09-09 21:42:20 +00003120 case CXCursor_MemberRef: {
3121 FieldDecl *Field = getCursorMemberRef(C).first;
3122 assert(Field && "Missing member decl");
3123
3124 return createCXString(Field->getNameAsString());
3125 }
3126
Douglas Gregor36897b02010-09-10 00:22:18 +00003127 case CXCursor_LabelRef: {
3128 LabelStmt *Label = getCursorLabelRef(C).first;
3129 assert(Label && "Missing label");
3130
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003131 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00003132 }
3133
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003134 case CXCursor_OverloadedDeclRef: {
3135 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3136 if (Decl *D = Storage.dyn_cast<Decl *>()) {
3137 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
3138 return createCXString(ND->getNameAsString());
3139 return createCXString("");
3140 }
3141 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3142 return createCXString(E->getName().getAsString());
3143 OverloadedTemplateStorage *Ovl
3144 = Storage.get<OverloadedTemplateStorage*>();
3145 if (Ovl->size() == 0)
3146 return createCXString("");
3147 return createCXString((*Ovl->begin())->getNameAsString());
3148 }
3149
Douglas Gregor011d8b92012-02-15 00:54:55 +00003150 case CXCursor_VariableRef: {
3151 VarDecl *Var = getCursorVariableRef(C).first;
3152 assert(Var && "Missing variable decl");
3153
3154 return createCXString(Var->getNameAsString());
3155 }
3156
Daniel Dunbaracca7252009-11-30 20:42:49 +00003157 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003158 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00003159 }
3160 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003161
3162 if (clang_isExpression(C.kind)) {
3163 Decl *D = getDeclFromExpr(getCursorExpr(C));
3164 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00003165 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003166 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00003167 }
3168
Douglas Gregor36897b02010-09-10 00:22:18 +00003169 if (clang_isStatement(C.kind)) {
3170 Stmt *S = getCursorStmt(C);
3171 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003172 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00003173
3174 return createCXString("");
3175 }
3176
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003177 if (C.kind == CXCursor_MacroExpansion)
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003178 return createCXString(getCursorMacroExpansion(C)->getName()
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003179 ->getNameStart());
3180
Douglas Gregor572feb22010-03-18 18:04:21 +00003181 if (C.kind == CXCursor_MacroDefinition)
3182 return createCXString(getCursorMacroDefinition(C)->getName()
3183 ->getNameStart());
3184
Douglas Gregorecdcb882010-10-20 22:00:55 +00003185 if (C.kind == CXCursor_InclusionDirective)
3186 return createCXString(getCursorInclusionDirective(C)->getFileName());
3187
Douglas Gregor60cbfac2010-01-25 16:56:17 +00003188 if (clang_isDeclaration(C.kind))
3189 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00003190
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00003191 if (C.kind == CXCursor_AnnotateAttr) {
3192 AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
3193 return createCXString(AA->getAnnotation());
3194 }
3195
Argyrios Kyrtzidis84b79642011-12-06 22:05:01 +00003196 if (C.kind == CXCursor_AsmLabelAttr) {
3197 AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
3198 return createCXString(AA->getLabel());
3199 }
3200
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003201 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00003202}
3203
Argyrios Kyrtzidisba1da142012-03-30 20:58:35 +00003204CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C,
3205 unsigned pieceIndex,
3206 unsigned options) {
3207 if (clang_Cursor_isNull(C))
3208 return clang_getNullRange();
3209
3210 ASTContext &Ctx = getCursorContext(C);
3211
3212 if (clang_isStatement(C.kind)) {
3213 Stmt *S = getCursorStmt(C);
3214 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
3215 if (pieceIndex > 0)
3216 return clang_getNullRange();
3217 return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
3218 }
3219
3220 return clang_getNullRange();
3221 }
3222
3223 if (C.kind == CXCursor_ObjCMessageExpr) {
3224 if (ObjCMessageExpr *
3225 ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
3226 if (pieceIndex >= ME->getNumSelectorLocs())
3227 return clang_getNullRange();
3228 return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
3229 }
3230 }
3231
3232 if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
3233 C.kind == CXCursor_ObjCClassMethodDecl) {
3234 if (ObjCMethodDecl *
3235 MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
3236 if (pieceIndex >= MD->getNumSelectorLocs())
3237 return clang_getNullRange();
3238 return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
3239 }
3240 }
3241
Argyrios Kyrtzidis9482a182012-04-16 20:01:28 +00003242 if (C.kind == CXCursor_ObjCCategoryDecl ||
3243 C.kind == CXCursor_ObjCCategoryImplDecl) {
3244 if (pieceIndex > 0)
3245 return clang_getNullRange();
3246 if (ObjCCategoryDecl *
3247 CD = dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
3248 return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
3249 if (ObjCCategoryImplDecl *
3250 CID = dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
3251 return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
3252 }
3253
Argyrios Kyrtzidis6a010122012-10-05 00:22:24 +00003254 if (C.kind == CXCursor_ModuleImportDecl) {
3255 if (pieceIndex > 0)
3256 return clang_getNullRange();
3257 if (ImportDecl *ImportD = dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) {
3258 ArrayRef<SourceLocation> Locs = ImportD->getIdentifierLocs();
3259 if (!Locs.empty())
3260 return cxloc::translateSourceRange(Ctx,
3261 SourceRange(Locs.front(), Locs.back()));
3262 }
3263 return clang_getNullRange();
3264 }
3265
Argyrios Kyrtzidisba1da142012-03-30 20:58:35 +00003266 // FIXME: A CXCursor_InclusionDirective should give the location of the
3267 // filename, but we don't keep track of this.
3268
3269 // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
3270 // but we don't keep track of this.
3271
3272 // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
3273 // but we don't keep track of this.
3274
3275 // Default handling, give the location of the cursor.
3276
3277 if (pieceIndex > 0)
3278 return clang_getNullRange();
3279
3280 CXSourceLocation CXLoc = clang_getCursorLocation(C);
3281 SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
3282 return cxloc::translateSourceRange(Ctx, Loc);
3283}
3284
Douglas Gregor358559d2010-10-02 22:49:11 +00003285CXString clang_getCursorDisplayName(CXCursor C) {
3286 if (!clang_isDeclaration(C.kind))
3287 return clang_getCursorSpelling(C);
3288
3289 Decl *D = getCursorDecl(C);
3290 if (!D)
3291 return createCXString("");
3292
Douglas Gregor30c42402011-09-27 22:38:19 +00003293 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
Douglas Gregor358559d2010-10-02 22:49:11 +00003294 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
3295 D = FunTmpl->getTemplatedDecl();
3296
3297 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Dylan Noblesmith36d59272012-02-13 12:32:26 +00003298 SmallString<64> Str;
Douglas Gregor358559d2010-10-02 22:49:11 +00003299 llvm::raw_svector_ostream OS(Str);
Benjamin Kramera59d20b2012-02-07 11:57:57 +00003300 OS << *Function;
Douglas Gregor358559d2010-10-02 22:49:11 +00003301 if (Function->getPrimaryTemplate())
3302 OS << "<>";
3303 OS << "(";
3304 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
3305 if (I)
3306 OS << ", ";
3307 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
3308 }
3309
3310 if (Function->isVariadic()) {
3311 if (Function->getNumParams())
3312 OS << ", ";
3313 OS << "...";
3314 }
3315 OS << ")";
3316 return createCXString(OS.str());
3317 }
3318
3319 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
Dylan Noblesmith36d59272012-02-13 12:32:26 +00003320 SmallString<64> Str;
Douglas Gregor358559d2010-10-02 22:49:11 +00003321 llvm::raw_svector_ostream OS(Str);
Benjamin Kramera59d20b2012-02-07 11:57:57 +00003322 OS << *ClassTemplate;
Douglas Gregor358559d2010-10-02 22:49:11 +00003323 OS << "<";
3324 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
3325 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3326 if (I)
3327 OS << ", ";
3328
3329 NamedDecl *Param = Params->getParam(I);
3330 if (Param->getIdentifier()) {
3331 OS << Param->getIdentifier()->getName();
3332 continue;
3333 }
3334
3335 // There is no parameter name, which makes this tricky. Try to come up
3336 // with something useful that isn't too long.
3337 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3338 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
3339 else if (NonTypeTemplateParmDecl *NTTP
3340 = dyn_cast<NonTypeTemplateParmDecl>(Param))
3341 OS << NTTP->getType().getAsString(Policy);
3342 else
3343 OS << "template<...> class";
3344 }
3345
3346 OS << ">";
3347 return createCXString(OS.str());
3348 }
3349
3350 if (ClassTemplateSpecializationDecl *ClassSpec
3351 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
3352 // If the type was explicitly written, use that.
3353 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
3354 return createCXString(TSInfo->getType().getAsString(Policy));
3355
Dylan Noblesmith36d59272012-02-13 12:32:26 +00003356 SmallString<64> Str;
Douglas Gregor358559d2010-10-02 22:49:11 +00003357 llvm::raw_svector_ostream OS(Str);
Benjamin Kramera59d20b2012-02-07 11:57:57 +00003358 OS << *ClassSpec;
Douglas Gregor358559d2010-10-02 22:49:11 +00003359 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00003360 ClassSpec->getTemplateArgs().data(),
3361 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00003362 Policy);
3363 return createCXString(OS.str());
3364 }
3365
3366 return clang_getCursorSpelling(C);
3367}
3368
Ted Kremeneke68fff62010-02-17 00:41:32 +00003369CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00003370 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00003371 case CXCursor_FunctionDecl:
3372 return createCXString("FunctionDecl");
3373 case CXCursor_TypedefDecl:
3374 return createCXString("TypedefDecl");
3375 case CXCursor_EnumDecl:
3376 return createCXString("EnumDecl");
3377 case CXCursor_EnumConstantDecl:
3378 return createCXString("EnumConstantDecl");
3379 case CXCursor_StructDecl:
3380 return createCXString("StructDecl");
3381 case CXCursor_UnionDecl:
3382 return createCXString("UnionDecl");
3383 case CXCursor_ClassDecl:
3384 return createCXString("ClassDecl");
3385 case CXCursor_FieldDecl:
3386 return createCXString("FieldDecl");
3387 case CXCursor_VarDecl:
3388 return createCXString("VarDecl");
3389 case CXCursor_ParmDecl:
3390 return createCXString("ParmDecl");
3391 case CXCursor_ObjCInterfaceDecl:
3392 return createCXString("ObjCInterfaceDecl");
3393 case CXCursor_ObjCCategoryDecl:
3394 return createCXString("ObjCCategoryDecl");
3395 case CXCursor_ObjCProtocolDecl:
3396 return createCXString("ObjCProtocolDecl");
3397 case CXCursor_ObjCPropertyDecl:
3398 return createCXString("ObjCPropertyDecl");
3399 case CXCursor_ObjCIvarDecl:
3400 return createCXString("ObjCIvarDecl");
3401 case CXCursor_ObjCInstanceMethodDecl:
3402 return createCXString("ObjCInstanceMethodDecl");
3403 case CXCursor_ObjCClassMethodDecl:
3404 return createCXString("ObjCClassMethodDecl");
3405 case CXCursor_ObjCImplementationDecl:
3406 return createCXString("ObjCImplementationDecl");
3407 case CXCursor_ObjCCategoryImplDecl:
3408 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00003409 case CXCursor_CXXMethod:
3410 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003411 case CXCursor_UnexposedDecl:
3412 return createCXString("UnexposedDecl");
3413 case CXCursor_ObjCSuperClassRef:
3414 return createCXString("ObjCSuperClassRef");
3415 case CXCursor_ObjCProtocolRef:
3416 return createCXString("ObjCProtocolRef");
3417 case CXCursor_ObjCClassRef:
3418 return createCXString("ObjCClassRef");
3419 case CXCursor_TypeRef:
3420 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003421 case CXCursor_TemplateRef:
3422 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00003423 case CXCursor_NamespaceRef:
3424 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00003425 case CXCursor_MemberRef:
3426 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00003427 case CXCursor_LabelRef:
3428 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003429 case CXCursor_OverloadedDeclRef:
3430 return createCXString("OverloadedDeclRef");
Douglas Gregor011d8b92012-02-15 00:54:55 +00003431 case CXCursor_VariableRef:
3432 return createCXString("VariableRef");
Douglas Gregor42b29842011-10-05 19:00:14 +00003433 case CXCursor_IntegerLiteral:
3434 return createCXString("IntegerLiteral");
3435 case CXCursor_FloatingLiteral:
3436 return createCXString("FloatingLiteral");
3437 case CXCursor_ImaginaryLiteral:
3438 return createCXString("ImaginaryLiteral");
3439 case CXCursor_StringLiteral:
3440 return createCXString("StringLiteral");
3441 case CXCursor_CharacterLiteral:
3442 return createCXString("CharacterLiteral");
3443 case CXCursor_ParenExpr:
3444 return createCXString("ParenExpr");
3445 case CXCursor_UnaryOperator:
3446 return createCXString("UnaryOperator");
3447 case CXCursor_ArraySubscriptExpr:
3448 return createCXString("ArraySubscriptExpr");
3449 case CXCursor_BinaryOperator:
3450 return createCXString("BinaryOperator");
3451 case CXCursor_CompoundAssignOperator:
3452 return createCXString("CompoundAssignOperator");
3453 case CXCursor_ConditionalOperator:
3454 return createCXString("ConditionalOperator");
3455 case CXCursor_CStyleCastExpr:
3456 return createCXString("CStyleCastExpr");
3457 case CXCursor_CompoundLiteralExpr:
3458 return createCXString("CompoundLiteralExpr");
3459 case CXCursor_InitListExpr:
3460 return createCXString("InitListExpr");
3461 case CXCursor_AddrLabelExpr:
3462 return createCXString("AddrLabelExpr");
3463 case CXCursor_StmtExpr:
3464 return createCXString("StmtExpr");
3465 case CXCursor_GenericSelectionExpr:
3466 return createCXString("GenericSelectionExpr");
3467 case CXCursor_GNUNullExpr:
3468 return createCXString("GNUNullExpr");
3469 case CXCursor_CXXStaticCastExpr:
3470 return createCXString("CXXStaticCastExpr");
3471 case CXCursor_CXXDynamicCastExpr:
3472 return createCXString("CXXDynamicCastExpr");
3473 case CXCursor_CXXReinterpretCastExpr:
3474 return createCXString("CXXReinterpretCastExpr");
3475 case CXCursor_CXXConstCastExpr:
3476 return createCXString("CXXConstCastExpr");
3477 case CXCursor_CXXFunctionalCastExpr:
3478 return createCXString("CXXFunctionalCastExpr");
3479 case CXCursor_CXXTypeidExpr:
3480 return createCXString("CXXTypeidExpr");
3481 case CXCursor_CXXBoolLiteralExpr:
3482 return createCXString("CXXBoolLiteralExpr");
3483 case CXCursor_CXXNullPtrLiteralExpr:
3484 return createCXString("CXXNullPtrLiteralExpr");
3485 case CXCursor_CXXThisExpr:
3486 return createCXString("CXXThisExpr");
3487 case CXCursor_CXXThrowExpr:
3488 return createCXString("CXXThrowExpr");
3489 case CXCursor_CXXNewExpr:
3490 return createCXString("CXXNewExpr");
3491 case CXCursor_CXXDeleteExpr:
3492 return createCXString("CXXDeleteExpr");
3493 case CXCursor_UnaryExpr:
3494 return createCXString("UnaryExpr");
3495 case CXCursor_ObjCStringLiteral:
3496 return createCXString("ObjCStringLiteral");
Ted Kremenekb3f75422012-03-06 20:06:06 +00003497 case CXCursor_ObjCBoolLiteralExpr:
3498 return createCXString("ObjCBoolLiteralExpr");
Douglas Gregor42b29842011-10-05 19:00:14 +00003499 case CXCursor_ObjCEncodeExpr:
3500 return createCXString("ObjCEncodeExpr");
3501 case CXCursor_ObjCSelectorExpr:
3502 return createCXString("ObjCSelectorExpr");
3503 case CXCursor_ObjCProtocolExpr:
3504 return createCXString("ObjCProtocolExpr");
3505 case CXCursor_ObjCBridgedCastExpr:
3506 return createCXString("ObjCBridgedCastExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00003507 case CXCursor_BlockExpr:
3508 return createCXString("BlockExpr");
Douglas Gregor42b29842011-10-05 19:00:14 +00003509 case CXCursor_PackExpansionExpr:
3510 return createCXString("PackExpansionExpr");
3511 case CXCursor_SizeOfPackExpr:
3512 return createCXString("SizeOfPackExpr");
Douglas Gregor011d8b92012-02-15 00:54:55 +00003513 case CXCursor_LambdaExpr:
3514 return createCXString("LambdaExpr");
Douglas Gregor42b29842011-10-05 19:00:14 +00003515 case CXCursor_UnexposedExpr:
3516 return createCXString("UnexposedExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003517 case CXCursor_DeclRefExpr:
3518 return createCXString("DeclRefExpr");
3519 case CXCursor_MemberRefExpr:
3520 return createCXString("MemberRefExpr");
3521 case CXCursor_CallExpr:
3522 return createCXString("CallExpr");
3523 case CXCursor_ObjCMessageExpr:
3524 return createCXString("ObjCMessageExpr");
3525 case CXCursor_UnexposedStmt:
3526 return createCXString("UnexposedStmt");
Douglas Gregor42b29842011-10-05 19:00:14 +00003527 case CXCursor_DeclStmt:
3528 return createCXString("DeclStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00003529 case CXCursor_LabelStmt:
3530 return createCXString("LabelStmt");
Douglas Gregor42b29842011-10-05 19:00:14 +00003531 case CXCursor_CompoundStmt:
3532 return createCXString("CompoundStmt");
3533 case CXCursor_CaseStmt:
3534 return createCXString("CaseStmt");
3535 case CXCursor_DefaultStmt:
3536 return createCXString("DefaultStmt");
3537 case CXCursor_IfStmt:
3538 return createCXString("IfStmt");
3539 case CXCursor_SwitchStmt:
3540 return createCXString("SwitchStmt");
3541 case CXCursor_WhileStmt:
3542 return createCXString("WhileStmt");
3543 case CXCursor_DoStmt:
3544 return createCXString("DoStmt");
3545 case CXCursor_ForStmt:
3546 return createCXString("ForStmt");
3547 case CXCursor_GotoStmt:
3548 return createCXString("GotoStmt");
3549 case CXCursor_IndirectGotoStmt:
3550 return createCXString("IndirectGotoStmt");
3551 case CXCursor_ContinueStmt:
3552 return createCXString("ContinueStmt");
3553 case CXCursor_BreakStmt:
3554 return createCXString("BreakStmt");
3555 case CXCursor_ReturnStmt:
3556 return createCXString("ReturnStmt");
Chad Rosierdf5faf52012-08-25 00:11:56 +00003557 case CXCursor_GCCAsmStmt:
3558 return createCXString("GCCAsmStmt");
Chad Rosier8cd64b42012-06-11 20:47:18 +00003559 case CXCursor_MSAsmStmt:
3560 return createCXString("MSAsmStmt");
Douglas Gregor42b29842011-10-05 19:00:14 +00003561 case CXCursor_ObjCAtTryStmt:
3562 return createCXString("ObjCAtTryStmt");
3563 case CXCursor_ObjCAtCatchStmt:
3564 return createCXString("ObjCAtCatchStmt");
3565 case CXCursor_ObjCAtFinallyStmt:
3566 return createCXString("ObjCAtFinallyStmt");
3567 case CXCursor_ObjCAtThrowStmt:
3568 return createCXString("ObjCAtThrowStmt");
3569 case CXCursor_ObjCAtSynchronizedStmt:
3570 return createCXString("ObjCAtSynchronizedStmt");
3571 case CXCursor_ObjCAutoreleasePoolStmt:
3572 return createCXString("ObjCAutoreleasePoolStmt");
3573 case CXCursor_ObjCForCollectionStmt:
3574 return createCXString("ObjCForCollectionStmt");
3575 case CXCursor_CXXCatchStmt:
3576 return createCXString("CXXCatchStmt");
3577 case CXCursor_CXXTryStmt:
3578 return createCXString("CXXTryStmt");
3579 case CXCursor_CXXForRangeStmt:
3580 return createCXString("CXXForRangeStmt");
3581 case CXCursor_SEHTryStmt:
3582 return createCXString("SEHTryStmt");
3583 case CXCursor_SEHExceptStmt:
3584 return createCXString("SEHExceptStmt");
3585 case CXCursor_SEHFinallyStmt:
3586 return createCXString("SEHFinallyStmt");
3587 case CXCursor_NullStmt:
3588 return createCXString("NullStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003589 case CXCursor_InvalidFile:
3590 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00003591 case CXCursor_InvalidCode:
3592 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003593 case CXCursor_NoDeclFound:
3594 return createCXString("NoDeclFound");
3595 case CXCursor_NotImplemented:
3596 return createCXString("NotImplemented");
3597 case CXCursor_TranslationUnit:
3598 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00003599 case CXCursor_UnexposedAttr:
3600 return createCXString("UnexposedAttr");
3601 case CXCursor_IBActionAttr:
3602 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003603 case CXCursor_IBOutletAttr:
3604 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003605 case CXCursor_IBOutletCollectionAttr:
3606 return createCXString("attribute(iboutletcollection)");
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00003607 case CXCursor_CXXFinalAttr:
3608 return createCXString("attribute(final)");
3609 case CXCursor_CXXOverrideAttr:
3610 return createCXString("attribute(override)");
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00003611 case CXCursor_AnnotateAttr:
3612 return createCXString("attribute(annotate)");
Argyrios Kyrtzidis84b79642011-12-06 22:05:01 +00003613 case CXCursor_AsmLabelAttr:
3614 return createCXString("asm label");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003615 case CXCursor_PreprocessingDirective:
3616 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003617 case CXCursor_MacroDefinition:
3618 return createCXString("macro definition");
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003619 case CXCursor_MacroExpansion:
3620 return createCXString("macro expansion");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003621 case CXCursor_InclusionDirective:
3622 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003623 case CXCursor_Namespace:
3624 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003625 case CXCursor_LinkageSpec:
3626 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003627 case CXCursor_CXXBaseSpecifier:
3628 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003629 case CXCursor_Constructor:
3630 return createCXString("CXXConstructor");
3631 case CXCursor_Destructor:
3632 return createCXString("CXXDestructor");
3633 case CXCursor_ConversionFunction:
3634 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003635 case CXCursor_TemplateTypeParameter:
3636 return createCXString("TemplateTypeParameter");
3637 case CXCursor_NonTypeTemplateParameter:
3638 return createCXString("NonTypeTemplateParameter");
3639 case CXCursor_TemplateTemplateParameter:
3640 return createCXString("TemplateTemplateParameter");
3641 case CXCursor_FunctionTemplate:
3642 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003643 case CXCursor_ClassTemplate:
3644 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003645 case CXCursor_ClassTemplatePartialSpecialization:
3646 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003647 case CXCursor_NamespaceAlias:
3648 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003649 case CXCursor_UsingDirective:
3650 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003651 case CXCursor_UsingDeclaration:
3652 return createCXString("UsingDeclaration");
Richard Smith162e1c12011-04-15 14:24:37 +00003653 case CXCursor_TypeAliasDecl:
Douglas Gregor352697a2011-06-03 23:08:58 +00003654 return createCXString("TypeAliasDecl");
3655 case CXCursor_ObjCSynthesizeDecl:
3656 return createCXString("ObjCSynthesizeDecl");
3657 case CXCursor_ObjCDynamicDecl:
3658 return createCXString("ObjCDynamicDecl");
Argyrios Kyrtzidis2dfdb942011-09-30 17:58:23 +00003659 case CXCursor_CXXAccessSpecifier:
3660 return createCXString("CXXAccessSpecifier");
Argyrios Kyrtzidis6a010122012-10-05 00:22:24 +00003661 case CXCursor_ModuleImportDecl:
3662 return createCXString("ModuleImport");
Steve Naroff89922f82009-08-31 00:59:03 +00003663 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003664
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003665 llvm_unreachable("Unhandled CXCursorKind");
Steve Naroff600866c2009-08-27 19:51:58 +00003666}
Steve Naroff89922f82009-08-31 00:59:03 +00003667
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003668struct GetCursorData {
3669 SourceLocation TokenBeginLoc;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003670 bool PointsAtMacroArgExpansion;
Argyrios Kyrtzidis135bf8e2012-06-09 03:03:02 +00003671 bool VisitedObjCPropertyImplDecl;
3672 SourceLocation VisitedDeclaratorDeclStartLoc;
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003673 CXCursor &BestCursor;
3674
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003675 GetCursorData(SourceManager &SM,
3676 SourceLocation tokenBegin, CXCursor &outputCursor)
3677 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
3678 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
Argyrios Kyrtzidis135bf8e2012-06-09 03:03:02 +00003679 VisitedObjCPropertyImplDecl = false;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003680 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003681};
3682
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003683static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3684 CXCursor parent,
3685 CXClientData client_data) {
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003686 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
3687 CXCursor *BestCursor = &Data->BestCursor;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003688
3689 // If we point inside a macro argument we should provide info of what the
3690 // token is so use the actual cursor, don't replace it with a macro expansion
3691 // cursor.
3692 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
3693 return CXChildVisit_Recurse;
Argyrios Kyrtzidis65ab9072011-09-26 19:05:37 +00003694
3695 if (clang_isDeclaration(cursor.kind)) {
3696 // Avoid having the implicit methods override the property decls.
Argyrios Kyrtzidisa9d45a32012-04-16 22:42:01 +00003697 if (ObjCMethodDecl *MD
3698 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
Argyrios Kyrtzidis65ab9072011-09-26 19:05:37 +00003699 if (MD->isImplicit())
3700 return CXChildVisit_Break;
Argyrios Kyrtzidisa9d45a32012-04-16 22:42:01 +00003701
3702 } else if (ObjCInterfaceDecl *ID
3703 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) {
3704 // Check that when we have multiple @class references in the same line,
3705 // that later ones do not override the previous ones.
3706 // If we have:
3707 // @class Foo, Bar;
3708 // source ranges for both start at '@', so 'Bar' will end up overriding
3709 // 'Foo' even though the cursor location was at 'Foo'.
3710 if (BestCursor->kind == CXCursor_ObjCInterfaceDecl ||
3711 BestCursor->kind == CXCursor_ObjCClassRef)
3712 if (ObjCInterfaceDecl *PrevID
3713 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(*BestCursor))){
3714 if (PrevID != ID &&
3715 !PrevID->isThisDeclarationADefinition() &&
3716 !ID->isThisDeclarationADefinition())
3717 return CXChildVisit_Break;
3718 }
Argyrios Kyrtzidis135bf8e2012-06-09 03:03:02 +00003719
3720 } else if (DeclaratorDecl *DD
3721 = dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) {
3722 SourceLocation StartLoc = DD->getSourceRange().getBegin();
3723 // Check that when we have multiple declarators in the same line,
3724 // that later ones do not override the previous ones.
3725 // If we have:
3726 // int Foo, Bar;
3727 // source ranges for both start at 'int', so 'Bar' will end up overriding
3728 // 'Foo' even though the cursor location was at 'Foo'.
3729 if (Data->VisitedDeclaratorDeclStartLoc == StartLoc)
3730 return CXChildVisit_Break;
3731 Data->VisitedDeclaratorDeclStartLoc = StartLoc;
3732
3733 } else if (ObjCPropertyImplDecl *PropImp
3734 = dyn_cast_or_null<ObjCPropertyImplDecl>(getCursorDecl(cursor))) {
3735 (void)PropImp;
3736 // Check that when we have multiple @synthesize in the same line,
3737 // that later ones do not override the previous ones.
3738 // If we have:
3739 // @synthesize Foo, Bar;
3740 // source ranges for both start at '@', so 'Bar' will end up overriding
3741 // 'Foo' even though the cursor location was at 'Foo'.
3742 if (Data->VisitedObjCPropertyImplDecl)
3743 return CXChildVisit_Break;
3744 Data->VisitedObjCPropertyImplDecl = true;
Argyrios Kyrtzidisa9d45a32012-04-16 22:42:01 +00003745 }
Argyrios Kyrtzidis65ab9072011-09-26 19:05:37 +00003746 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003747
3748 if (clang_isExpression(cursor.kind) &&
3749 clang_isDeclaration(BestCursor->kind)) {
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00003750 if (Decl *D = getCursorDecl(*BestCursor)) {
3751 // Avoid having the cursor of an expression replace the declaration cursor
3752 // when the expression source range overlaps the declaration range.
3753 // This can happen for C++ constructor expressions whose range generally
3754 // include the variable declaration, e.g.:
3755 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
3756 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
3757 D->getLocation() == Data->TokenBeginLoc)
3758 return CXChildVisit_Break;
3759 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003760 }
3761
Douglas Gregor93798e22010-11-05 21:11:19 +00003762 // If our current best cursor is the construction of a temporary object,
3763 // don't replace that cursor with a type reference, because we want
3764 // clang_getCursor() to point at the constructor.
3765 if (clang_isExpression(BestCursor->kind) &&
3766 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003767 cursor.kind == CXCursor_TypeRef) {
3768 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
3769 // as having the actual point on the type reference.
3770 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
Douglas Gregor93798e22010-11-05 21:11:19 +00003771 return CXChildVisit_Recurse;
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003772 }
Douglas Gregor93798e22010-11-05 21:11:19 +00003773
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003774 *BestCursor = cursor;
3775 return CXChildVisit_Recurse;
3776}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003777
Douglas Gregorb9790342010-01-22 21:44:22 +00003778CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3779 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003780 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003781
Ted Kremeneka60ed472010-11-16 08:15:36 +00003782 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003783 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3784
Ted Kremeneka297de22010-01-25 22:34:44 +00003785 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003786 CXCursor Result = cxcursor::getCursor(TU, SLoc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003787
Douglas Gregor40749ee2010-11-03 00:35:38 +00003788 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregor40749ee2010-11-03 00:35:38 +00003789 if (Logging) {
3790 CXFile SearchFile;
3791 unsigned SearchLine, SearchColumn;
3792 CXFile ResultFile;
3793 unsigned ResultLine, ResultColumn;
Douglas Gregor66537982010-11-17 17:14:07 +00003794 CXString SearchFileName, ResultFileName, KindSpelling, USR;
3795 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
Douglas Gregor40749ee2010-11-03 00:35:38 +00003796 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3797
Chandler Carruth20174222011-08-31 16:53:37 +00003798 clang_getExpansionLocation(Loc, &SearchFile, &SearchLine, &SearchColumn, 0);
3799 clang_getExpansionLocation(ResultLoc, &ResultFile, &ResultLine,
3800 &ResultColumn, 0);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003801 SearchFileName = clang_getFileName(SearchFile);
3802 ResultFileName = clang_getFileName(ResultFile);
3803 KindSpelling = clang_getCursorKindSpelling(Result.kind);
Douglas Gregor66537982010-11-17 17:14:07 +00003804 USR = clang_getCursorUSR(Result);
3805 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n",
Douglas Gregor40749ee2010-11-03 00:35:38 +00003806 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3807 clang_getCString(KindSpelling),
Douglas Gregor66537982010-11-17 17:14:07 +00003808 clang_getCString(ResultFileName), ResultLine, ResultColumn,
3809 clang_getCString(USR), IsDef);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003810 clang_disposeString(SearchFileName);
3811 clang_disposeString(ResultFileName);
3812 clang_disposeString(KindSpelling);
Douglas Gregor66537982010-11-17 17:14:07 +00003813 clang_disposeString(USR);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003814
3815 CXCursor Definition = clang_getCursorDefinition(Result);
3816 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
3817 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
3818 CXString DefinitionKindSpelling
3819 = clang_getCursorKindSpelling(Definition.kind);
3820 CXFile DefinitionFile;
3821 unsigned DefinitionLine, DefinitionColumn;
Chandler Carruth20174222011-08-31 16:53:37 +00003822 clang_getExpansionLocation(DefinitionLoc, &DefinitionFile,
3823 &DefinitionLine, &DefinitionColumn, 0);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003824 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
3825 fprintf(stderr, " -> %s(%s:%d:%d)\n",
3826 clang_getCString(DefinitionKindSpelling),
3827 clang_getCString(DefinitionFileName),
3828 DefinitionLine, DefinitionColumn);
3829 clang_disposeString(DefinitionFileName);
3830 clang_disposeString(DefinitionKindSpelling);
3831 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003832 }
3833
Ted Kremeneke68fff62010-02-17 00:41:32 +00003834 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003835}
3836
Ted Kremenek73885552009-11-17 19:28:59 +00003837CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003838 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003839}
3840
3841unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003842 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003843}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003844
Douglas Gregor9ce55842010-11-20 00:09:34 +00003845unsigned clang_hashCursor(CXCursor C) {
3846 unsigned Index = 0;
3847 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
3848 Index = 1;
3849
3850 return llvm::DenseMapInfo<std::pair<unsigned, void*> >::getHashValue(
3851 std::make_pair(C.kind, C.data[Index]));
3852}
3853
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003854unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003855 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3856}
3857
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003858unsigned clang_isDeclaration(enum CXCursorKind K) {
Argyrios Kyrtzidis6a010122012-10-05 00:22:24 +00003859 return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) ||
3860 (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl);
Steve Naroff89922f82009-08-31 00:59:03 +00003861}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003862
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003863unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003864 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3865}
3866
Douglas Gregor97b98722010-01-19 23:20:36 +00003867unsigned clang_isExpression(enum CXCursorKind K) {
3868 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3869}
3870
3871unsigned clang_isStatement(enum CXCursorKind K) {
3872 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3873}
3874
Douglas Gregor8be80e12011-07-06 03:00:34 +00003875unsigned clang_isAttribute(enum CXCursorKind K) {
3876 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
3877}
3878
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003879unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3880 return K == CXCursor_TranslationUnit;
3881}
3882
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003883unsigned clang_isPreprocessing(enum CXCursorKind K) {
3884 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3885}
3886
Ted Kremenekad6eff62010-03-08 21:17:29 +00003887unsigned clang_isUnexposed(enum CXCursorKind K) {
3888 switch (K) {
3889 case CXCursor_UnexposedDecl:
3890 case CXCursor_UnexposedExpr:
3891 case CXCursor_UnexposedStmt:
3892 case CXCursor_UnexposedAttr:
3893 return true;
3894 default:
3895 return false;
3896 }
3897}
3898
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003899CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003900 return C.kind;
3901}
3902
Douglas Gregor98258af2010-01-18 22:46:11 +00003903CXSourceLocation clang_getCursorLocation(CXCursor C) {
3904 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003905 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003906 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003907 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3908 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003909 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003910 }
3911
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003912 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003913 std::pair<ObjCProtocolDecl *, SourceLocation> P
3914 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003915 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003916 }
3917
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003918 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003919 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3920 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003921 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003922 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003923
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003924 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003925 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003926 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003927 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003928
3929 case CXCursor_TemplateRef: {
3930 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3931 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3932 }
3933
Douglas Gregor69319002010-08-31 23:48:11 +00003934 case CXCursor_NamespaceRef: {
3935 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3936 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3937 }
3938
Douglas Gregora67e03f2010-09-09 21:42:20 +00003939 case CXCursor_MemberRef: {
3940 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3941 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3942 }
3943
Douglas Gregor011d8b92012-02-15 00:54:55 +00003944 case CXCursor_VariableRef: {
3945 std::pair<VarDecl *, SourceLocation> P = getCursorVariableRef(C);
3946 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3947 }
3948
Ted Kremenek3064ef92010-08-27 21:34:58 +00003949 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003950 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3951 if (!BaseSpec)
3952 return clang_getNullLocation();
3953
3954 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3955 return cxloc::translateSourceLocation(getCursorContext(C),
3956 TSInfo->getTypeLoc().getBeginLoc());
3957
3958 return cxloc::translateSourceLocation(getCursorContext(C),
Daniel Dunbar96a00142012-03-09 18:35:03 +00003959 BaseSpec->getLocStart());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003960 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003961
Douglas Gregor36897b02010-09-10 00:22:18 +00003962 case CXCursor_LabelRef: {
3963 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3964 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3965 }
3966
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003967 case CXCursor_OverloadedDeclRef:
3968 return cxloc::translateSourceLocation(getCursorContext(C),
3969 getCursorOverloadedDeclRef(C).second);
3970
Douglas Gregorf46034a2010-01-18 23:41:10 +00003971 default:
3972 // FIXME: Need a way to enumerate all non-reference cases.
3973 llvm_unreachable("Missed a reference kind");
3974 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003975 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003976
3977 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003978 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003979 getLocationFromExpr(getCursorExpr(C)));
3980
Douglas Gregor36897b02010-09-10 00:22:18 +00003981 if (clang_isStatement(C.kind))
3982 return cxloc::translateSourceLocation(getCursorContext(C),
3983 getCursorStmt(C)->getLocStart());
3984
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003985 if (C.kind == CXCursor_PreprocessingDirective) {
3986 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3987 return cxloc::translateSourceLocation(getCursorContext(C), L);
3988 }
Douglas Gregor48072312010-03-18 15:23:44 +00003989
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003990 if (C.kind == CXCursor_MacroExpansion) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003991 SourceLocation L
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003992 = cxcursor::getCursorMacroExpansion(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003993 return cxloc::translateSourceLocation(getCursorContext(C), L);
3994 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003995
3996 if (C.kind == CXCursor_MacroDefinition) {
3997 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3998 return cxloc::translateSourceLocation(getCursorContext(C), L);
3999 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00004000
4001 if (C.kind == CXCursor_InclusionDirective) {
4002 SourceLocation L
4003 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
4004 return cxloc::translateSourceLocation(getCursorContext(C), L);
4005 }
4006
Argyrios Kyrtzidis6a010122012-10-05 00:22:24 +00004007 if (!clang_isDeclaration(C.kind))
Douglas Gregor5352ac02010-01-28 00:27:43 +00004008 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00004009
Douglas Gregorf46034a2010-01-18 23:41:10 +00004010 Decl *D = getCursorDecl(C);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00004011 if (!D)
4012 return clang_getNullLocation();
4013
Douglas Gregorf46034a2010-01-18 23:41:10 +00004014 SourceLocation Loc = D->getLocation();
Ted Kremenek007a7c92010-11-01 23:26:51 +00004015 // FIXME: Multiple variables declared in a single declaration
4016 // currently lack the information needed to correctly determine their
4017 // ranges when accounting for the type-specifier. We use context
4018 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
4019 // and if so, whether it is the first decl.
4020 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4021 if (!cxcursor::isFirstInDeclGroup(C))
4022 Loc = VD->getLocation();
4023 }
4024
Argyrios Kyrtzidisccc6f362012-03-23 03:33:19 +00004025 // For ObjC methods, give the start location of the method name.
4026 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
4027 Loc = MD->getSelectorStartLoc();
4028
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00004029 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00004030}
Douglas Gregora7bde202010-01-19 00:34:46 +00004031
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004032} // end extern "C"
4033
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00004034CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
4035 assert(TU);
4036
4037 // Guard against an invalid SourceLocation, or we may assert in one
4038 // of the following calls.
4039 if (SLoc.isInvalid())
4040 return clang_getNullCursor();
4041
4042 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4043
4044 // Translate the given source location to make it point at the beginning of
4045 // the token under the cursor.
4046 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +00004047 CXXUnit->getASTContext().getLangOpts());
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00004048
4049 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
4050 if (SLoc.isValid()) {
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00004051 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00004052 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
4053 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00004054 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00004055 SourceLocation(SLoc));
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00004056 CursorVis.visitFileRegion();
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00004057 }
4058
4059 return Result;
4060}
4061
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004062static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00004063 if (clang_isReference(C.kind)) {
4064 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004065 case CXCursor_ObjCSuperClassRef:
4066 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004067
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004068 case CXCursor_ObjCProtocolRef:
4069 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004070
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004071 case CXCursor_ObjCClassRef:
4072 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004073
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004074 case CXCursor_TypeRef:
4075 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00004076
4077 case CXCursor_TemplateRef:
4078 return getCursorTemplateRef(C).second;
4079
Douglas Gregor69319002010-08-31 23:48:11 +00004080 case CXCursor_NamespaceRef:
4081 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00004082
4083 case CXCursor_MemberRef:
4084 return getCursorMemberRef(C).second;
4085
Ted Kremenek3064ef92010-08-27 21:34:58 +00004086 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00004087 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00004088
Douglas Gregor36897b02010-09-10 00:22:18 +00004089 case CXCursor_LabelRef:
4090 return getCursorLabelRef(C).second;
4091
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004092 case CXCursor_OverloadedDeclRef:
4093 return getCursorOverloadedDeclRef(C).second;
4094
Douglas Gregor011d8b92012-02-15 00:54:55 +00004095 case CXCursor_VariableRef:
4096 return getCursorVariableRef(C).second;
4097
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004098 default:
4099 // FIXME: Need a way to enumerate all non-reference cases.
4100 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00004101 }
4102 }
Douglas Gregor97b98722010-01-19 23:20:36 +00004103
4104 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004105 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00004106
4107 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004108 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004109
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00004110 if (clang_isAttribute(C.kind))
4111 return getCursorAttr(C)->getRange();
4112
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004113 if (C.kind == CXCursor_PreprocessingDirective)
4114 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00004115
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004116 if (C.kind == CXCursor_MacroExpansion) {
4117 ASTUnit *TU = getCursorASTUnit(C);
4118 SourceRange Range = cxcursor::getCursorMacroExpansion(C)->getSourceRange();
4119 return TU->mapRangeFromPreamble(Range);
4120 }
Douglas Gregor572feb22010-03-18 18:04:21 +00004121
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004122 if (C.kind == CXCursor_MacroDefinition) {
4123 ASTUnit *TU = getCursorASTUnit(C);
4124 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
4125 return TU->mapRangeFromPreamble(Range);
4126 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00004127
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004128 if (C.kind == CXCursor_InclusionDirective) {
4129 ASTUnit *TU = getCursorASTUnit(C);
4130 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
4131 return TU->mapRangeFromPreamble(Range);
4132 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00004133
Argyrios Kyrtzidis0822c5f2012-03-19 23:17:58 +00004134 if (C.kind == CXCursor_TranslationUnit) {
4135 ASTUnit *TU = getCursorASTUnit(C);
4136 FileID MainID = TU->getSourceManager().getMainFileID();
4137 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
4138 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
4139 return SourceRange(Start, End);
4140 }
4141
Argyrios Kyrtzidis6a010122012-10-05 00:22:24 +00004142 if (clang_isDeclaration(C.kind)) {
Ted Kremenek007a7c92010-11-01 23:26:51 +00004143 Decl *D = cxcursor::getCursorDecl(C);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00004144 if (!D)
4145 return SourceRange();
4146
Ted Kremenek007a7c92010-11-01 23:26:51 +00004147 SourceRange R = D->getSourceRange();
4148 // FIXME: Multiple variables declared in a single declaration
4149 // currently lack the information needed to correctly determine their
4150 // ranges when accounting for the type-specifier. We use context
4151 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
4152 // and if so, whether it is the first decl.
4153 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4154 if (!cxcursor::isFirstInDeclGroup(C))
4155 R.setBegin(VD->getLocation());
4156 }
4157 return R;
4158 }
Douglas Gregor66537982010-11-17 17:14:07 +00004159 return SourceRange();
4160}
4161
4162/// \brief Retrieves the "raw" cursor extent, which is then extended to include
4163/// the decl-specifier-seq for declarations.
4164static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
Argyrios Kyrtzidis6a010122012-10-05 00:22:24 +00004165 if (clang_isDeclaration(C.kind)) {
Douglas Gregor66537982010-11-17 17:14:07 +00004166 Decl *D = cxcursor::getCursorDecl(C);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00004167 if (!D)
4168 return SourceRange();
4169
Douglas Gregor66537982010-11-17 17:14:07 +00004170 SourceRange R = D->getSourceRange();
Douglas Gregor66537982010-11-17 17:14:07 +00004171
Douglas Gregor2494dd02011-03-01 01:34:45 +00004172 // Adjust the start of the location for declarations preceded by
4173 // declaration specifiers.
4174 SourceLocation StartLoc;
4175 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
4176 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
Daniel Dunbar96a00142012-03-09 18:35:03 +00004177 StartLoc = TI->getTypeLoc().getLocStart();
Douglas Gregor2494dd02011-03-01 01:34:45 +00004178 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
4179 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
Daniel Dunbar96a00142012-03-09 18:35:03 +00004180 StartLoc = TI->getTypeLoc().getLocStart();
Douglas Gregor2494dd02011-03-01 01:34:45 +00004181 }
4182
4183 if (StartLoc.isValid() && R.getBegin().isValid() &&
4184 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
4185 R.setBegin(StartLoc);
4186
4187 // FIXME: Multiple variables declared in a single declaration
4188 // currently lack the information needed to correctly determine their
4189 // ranges when accounting for the type-specifier. We use context
4190 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
4191 // and if so, whether it is the first decl.
4192 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4193 if (!cxcursor::isFirstInDeclGroup(C))
4194 R.setBegin(VD->getLocation());
Douglas Gregor66537982010-11-17 17:14:07 +00004195 }
4196
4197 return R;
4198 }
4199
4200 return getRawCursorExtent(C);
4201}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004202
4203extern "C" {
4204
4205CXSourceRange clang_getCursorExtent(CXCursor C) {
4206 SourceRange R = getRawCursorExtent(C);
4207 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00004208 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004209
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004210 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00004211}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004212
4213CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00004214 if (clang_isInvalid(C.kind))
4215 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004216
Ted Kremeneka60ed472010-11-16 08:15:36 +00004217 CXTranslationUnit tu = getCursorTU(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004218 if (clang_isDeclaration(C.kind)) {
4219 Decl *D = getCursorDecl(C);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00004220 if (!D)
4221 return clang_getNullCursor();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004222 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004223 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Chris Lattner5f9e2722011-07-23 10:55:15 +00004224 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00004225 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
4226 return MakeCXCursor(Property, tu);
4227
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004228 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004229 }
4230
Douglas Gregor97b98722010-01-19 23:20:36 +00004231 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004232 Expr *E = getCursorExpr(C);
4233 Decl *D = getDeclFromExpr(E);
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00004234 if (D) {
4235 CXCursor declCursor = MakeCXCursor(D, tu);
4236 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
4237 declCursor);
4238 return declCursor;
4239 }
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004240
4241 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004242 return MakeCursorOverloadedDeclRef(Ovl, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004243
Douglas Gregor97b98722010-01-19 23:20:36 +00004244 return clang_getNullCursor();
4245 }
4246
Douglas Gregor36897b02010-09-10 00:22:18 +00004247 if (clang_isStatement(C.kind)) {
4248 Stmt *S = getCursorStmt(C);
4249 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Ted Kremenek37c2e962011-03-15 23:47:49 +00004250 if (LabelDecl *label = Goto->getLabel())
4251 if (LabelStmt *labelS = label->getStmt())
4252 return MakeCXCursor(labelS, getCursorDecl(C), tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00004253
4254 return clang_getNullCursor();
4255 }
4256
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004257 if (C.kind == CXCursor_MacroExpansion) {
Chandler Carruth9e5bb852011-07-14 08:20:46 +00004258 if (MacroDefinition *Def = getCursorMacroExpansion(C)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004259 return MakeMacroDefinitionCursor(Def, tu);
Douglas Gregorbf7efa22010-03-18 18:23:03 +00004260 }
4261
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004262 if (!clang_isReference(C.kind))
4263 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004264
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004265 switch (C.kind) {
4266 case CXCursor_ObjCSuperClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004267 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004268
4269 case CXCursor_ObjCProtocolRef: {
Argyrios Kyrtzidis98c16b82012-01-24 19:40:15 +00004270 ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
4271 if (ObjCProtocolDecl *Def = Prot->getDefinition())
4272 return MakeCXCursor(Def, tu);
4273
Argyrios Kyrtzidisc15707d2012-01-24 21:39:26 +00004274 return MakeCXCursor(Prot, tu);
Argyrios Kyrtzidis98c16b82012-01-24 19:40:15 +00004275 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004276
Douglas Gregor7723fec2011-12-15 20:29:51 +00004277 case CXCursor_ObjCClassRef: {
4278 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
4279 if (ObjCInterfaceDecl *Def = Class->getDefinition())
4280 return MakeCXCursor(Def, tu);
4281
Argyrios Kyrtzidisc15707d2012-01-24 21:39:26 +00004282 return MakeCXCursor(Class, tu);
Douglas Gregor7723fec2011-12-15 20:29:51 +00004283 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00004284
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004285 case CXCursor_TypeRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004286 return MakeCXCursor(getCursorTypeRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00004287
4288 case CXCursor_TemplateRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004289 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00004290
Douglas Gregor69319002010-08-31 23:48:11 +00004291 case CXCursor_NamespaceRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004292 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
Douglas Gregor69319002010-08-31 23:48:11 +00004293
Douglas Gregora67e03f2010-09-09 21:42:20 +00004294 case CXCursor_MemberRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004295 return MakeCXCursor(getCursorMemberRef(C).first, tu );
Douglas Gregora67e03f2010-09-09 21:42:20 +00004296
Ted Kremenek3064ef92010-08-27 21:34:58 +00004297 case CXCursor_CXXBaseSpecifier: {
4298 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
4299 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004300 tu ));
Ted Kremenek3064ef92010-08-27 21:34:58 +00004301 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004302
Douglas Gregor36897b02010-09-10 00:22:18 +00004303 case CXCursor_LabelRef:
4304 // FIXME: We end up faking the "parent" declaration here because we
4305 // don't want to make CXCursor larger.
4306 return MakeCXCursor(getCursorLabelRef(C).first,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004307 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
4308 .getTranslationUnitDecl(),
4309 tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00004310
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004311 case CXCursor_OverloadedDeclRef:
4312 return C;
Douglas Gregor011d8b92012-02-15 00:54:55 +00004313
4314 case CXCursor_VariableRef:
4315 return MakeCXCursor(getCursorVariableRef(C).first, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004316
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004317 default:
4318 // We would prefer to enumerate all non-reference cursor kinds here.
4319 llvm_unreachable("Unhandled reference cursor kind");
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004320 }
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004321}
4322
Douglas Gregorb6998662010-01-19 19:34:47 +00004323CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00004324 if (clang_isInvalid(C.kind))
4325 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004326
Ted Kremeneka60ed472010-11-16 08:15:36 +00004327 CXTranslationUnit TU = getCursorTU(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004328
Douglas Gregorb6998662010-01-19 19:34:47 +00004329 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00004330 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00004331 C = clang_getCursorReferenced(C);
4332 WasReference = true;
4333 }
4334
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004335 if (C.kind == CXCursor_MacroExpansion)
Douglas Gregorbf7efa22010-03-18 18:23:03 +00004336 return clang_getCursorReferenced(C);
4337
Douglas Gregorb6998662010-01-19 19:34:47 +00004338 if (!clang_isDeclaration(C.kind))
4339 return clang_getNullCursor();
4340
4341 Decl *D = getCursorDecl(C);
4342 if (!D)
4343 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004344
Douglas Gregorb6998662010-01-19 19:34:47 +00004345 switch (D->getKind()) {
4346 // Declaration kinds that don't really separate the notions of
4347 // declaration and definition.
4348 case Decl::Namespace:
4349 case Decl::Typedef:
Richard Smith162e1c12011-04-15 14:24:37 +00004350 case Decl::TypeAlias:
Richard Smith3e4c6c42011-05-05 21:57:07 +00004351 case Decl::TypeAliasTemplate:
Douglas Gregorb6998662010-01-19 19:34:47 +00004352 case Decl::TemplateTypeParm:
4353 case Decl::EnumConstant:
4354 case Decl::Field:
Benjamin Kramerd9811462010-11-21 14:11:41 +00004355 case Decl::IndirectField:
Douglas Gregorb6998662010-01-19 19:34:47 +00004356 case Decl::ObjCIvar:
4357 case Decl::ObjCAtDefsField:
4358 case Decl::ImplicitParam:
4359 case Decl::ParmVar:
4360 case Decl::NonTypeTemplateParm:
4361 case Decl::TemplateTemplateParm:
4362 case Decl::ObjCCategoryImpl:
4363 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00004364 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00004365 case Decl::LinkageSpec:
4366 case Decl::ObjCPropertyImpl:
4367 case Decl::FileScopeAsm:
4368 case Decl::StaticAssert:
4369 case Decl::Block:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00004370 case Decl::Label: // FIXME: Is this right??
Francois Pichetaf0f4d02011-08-14 03:52:19 +00004371 case Decl::ClassScopeFunctionSpecialization:
Douglas Gregor15de72c2011-12-02 23:23:56 +00004372 case Decl::Import:
Douglas Gregorb6998662010-01-19 19:34:47 +00004373 return C;
4374
4375 // Declaration kinds that don't make any sense here, but are
4376 // nonetheless harmless.
4377 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00004378 break;
4379
4380 // Declaration kinds for which the definition is not resolvable.
4381 case Decl::UnresolvedUsingTypename:
4382 case Decl::UnresolvedUsingValue:
4383 break;
4384
4385 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00004386 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004387 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004388
4389 case Decl::NamespaceAlias:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004390 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004391
4392 case Decl::Enum:
4393 case Decl::Record:
4394 case Decl::CXXRecord:
4395 case Decl::ClassTemplateSpecialization:
4396 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00004397 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004398 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004399 return clang_getNullCursor();
4400
4401 case Decl::Function:
4402 case Decl::CXXMethod:
4403 case Decl::CXXConstructor:
4404 case Decl::CXXDestructor:
4405 case Decl::CXXConversion: {
4406 const FunctionDecl *Def = 0;
4407 if (cast<FunctionDecl>(D)->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004408 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004409 return clang_getNullCursor();
4410 }
4411
4412 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00004413 // Ask the variable if it has a definition.
4414 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004415 return MakeCXCursor(Def, TU);
Sebastian Redl31310a22010-02-01 20:16:42 +00004416 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00004417 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004418
Douglas Gregorb6998662010-01-19 19:34:47 +00004419 case Decl::FunctionTemplate: {
4420 const FunctionDecl *Def = 0;
4421 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004422 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004423 return clang_getNullCursor();
4424 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004425
Douglas Gregorb6998662010-01-19 19:34:47 +00004426 case Decl::ClassTemplate: {
4427 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00004428 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00004429 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004430 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004431 return clang_getNullCursor();
4432 }
4433
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004434 case Decl::Using:
4435 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004436 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004437
4438 case Decl::UsingShadow:
4439 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004440 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004441 TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004442
4443 case Decl::ObjCMethod: {
4444 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
4445 if (Method->isThisDeclarationADefinition())
4446 return C;
4447
4448 // Dig out the method definition in the associated
4449 // @implementation, if we have it.
4450 // FIXME: The ASTs should make finding the definition easier.
4451 if (ObjCInterfaceDecl *Class
4452 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
4453 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
4454 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
4455 Method->isInstanceMethod()))
4456 if (Def->isThisDeclarationADefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004457 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004458
4459 return clang_getNullCursor();
4460 }
4461
4462 case Decl::ObjCCategory:
4463 if (ObjCCategoryImplDecl *Impl
4464 = cast<ObjCCategoryDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004465 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004466 return clang_getNullCursor();
4467
4468 case Decl::ObjCProtocol:
Douglas Gregor5e2a1ff2012-01-01 19:29:29 +00004469 if (ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
4470 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004471 return clang_getNullCursor();
4472
Douglas Gregor375bb142011-12-27 22:43:10 +00004473 case Decl::ObjCInterface: {
Douglas Gregorb6998662010-01-19 19:34:47 +00004474 // There are two notions of a "definition" for an Objective-C
4475 // class: the interface and its implementation. When we resolved a
4476 // reference to an Objective-C class, produce the @interface as
4477 // the definition; when we were provided with the interface,
4478 // produce the @implementation as the definition.
Douglas Gregor375bb142011-12-27 22:43:10 +00004479 ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
Douglas Gregorb6998662010-01-19 19:34:47 +00004480 if (WasReference) {
Douglas Gregor375bb142011-12-27 22:43:10 +00004481 if (ObjCInterfaceDecl *Def = IFace->getDefinition())
Douglas Gregor7723fec2011-12-15 20:29:51 +00004482 return MakeCXCursor(Def, TU);
Douglas Gregor375bb142011-12-27 22:43:10 +00004483 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004484 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004485 return clang_getNullCursor();
Douglas Gregor375bb142011-12-27 22:43:10 +00004486 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004487
Douglas Gregorb6998662010-01-19 19:34:47 +00004488 case Decl::ObjCProperty:
4489 // FIXME: We don't really know where to find the
4490 // ObjCPropertyImplDecls that implement this property.
4491 return clang_getNullCursor();
4492
4493 case Decl::ObjCCompatibleAlias:
4494 if (ObjCInterfaceDecl *Class
4495 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
Douglas Gregor7723fec2011-12-15 20:29:51 +00004496 if (ObjCInterfaceDecl *Def = Class->getDefinition())
4497 return MakeCXCursor(Def, TU);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004498
Douglas Gregorb6998662010-01-19 19:34:47 +00004499 return clang_getNullCursor();
4500
Douglas Gregorb6998662010-01-19 19:34:47 +00004501 case Decl::Friend:
4502 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004503 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004504 return clang_getNullCursor();
4505
4506 case Decl::FriendTemplate:
4507 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004508 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004509 return clang_getNullCursor();
4510 }
4511
4512 return clang_getNullCursor();
4513}
4514
4515unsigned clang_isCursorDefinition(CXCursor C) {
4516 if (!clang_isDeclaration(C.kind))
4517 return 0;
4518
4519 return clang_getCursorDefinition(C) == C;
4520}
4521
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004522CXCursor clang_getCanonicalCursor(CXCursor C) {
4523 if (!clang_isDeclaration(C.kind))
4524 return C;
4525
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004526 if (Decl *D = getCursorDecl(C)) {
Argyrios Kyrtzidisdebb00f2011-07-15 22:37:58 +00004527 if (ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
4528 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
4529 return MakeCXCursor(CatD, getCursorTU(C));
4530
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004531 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
4532 if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
4533 return MakeCXCursor(IFD, getCursorTU(C));
4534
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004535 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004536 }
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004537
4538 return C;
4539}
Argyrios Kyrtzidis34ebe1e2012-03-30 22:15:48 +00004540
4541int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) {
4542 return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first;
4543}
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004544
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004545unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004546 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004547 return 0;
4548
4549 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
4550 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
4551 return E->getNumDecls();
4552
4553 if (OverloadedTemplateStorage *S
4554 = Storage.dyn_cast<OverloadedTemplateStorage*>())
4555 return S->size();
4556
4557 Decl *D = Storage.get<Decl*>();
4558 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00004559 return Using->shadow_size();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004560
4561 return 0;
4562}
4563
4564CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004565 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004566 return clang_getNullCursor();
4567
4568 if (index >= clang_getNumOverloadedDecls(cursor))
4569 return clang_getNullCursor();
4570
Ted Kremeneka60ed472010-11-16 08:15:36 +00004571 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004572 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
4573 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004574 return MakeCXCursor(E->decls_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004575
4576 if (OverloadedTemplateStorage *S
4577 = Storage.dyn_cast<OverloadedTemplateStorage*>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004578 return MakeCXCursor(S->begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004579
4580 Decl *D = Storage.get<Decl*>();
4581 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
4582 // FIXME: This is, unfortunately, linear time.
4583 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
4584 std::advance(Pos, index);
Ted Kremeneka60ed472010-11-16 08:15:36 +00004585 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004586 }
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004587
4588 return clang_getNullCursor();
4589}
4590
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00004591void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00004592 const char **startBuf,
4593 const char **endBuf,
4594 unsigned *startLine,
4595 unsigned *startColumn,
4596 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00004597 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00004598 assert(getCursorDecl(C) && "CXCursor has null decl");
4599 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00004600 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
4601 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004602
Steve Naroff4ade6d62009-09-23 17:52:52 +00004603 SourceManager &SM = FD->getASTContext().getSourceManager();
4604 *startBuf = SM.getCharacterData(Body->getLBracLoc());
4605 *endBuf = SM.getCharacterData(Body->getRBracLoc());
4606 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
4607 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
4608 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
4609 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
4610}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004611
Douglas Gregor430d7a12011-07-25 17:48:11 +00004612
4613CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
4614 unsigned PieceIndex) {
4615 RefNamePieces Pieces;
4616
4617 switch (C.kind) {
4618 case CXCursor_MemberRefExpr:
4619 if (MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
4620 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
4621 E->getQualifierLoc().getSourceRange());
4622 break;
4623
4624 case CXCursor_DeclRefExpr:
4625 if (DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C)))
4626 Pieces = buildPieces(NameFlags, false, E->getNameInfo(),
4627 E->getQualifierLoc().getSourceRange(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00004628 E->getOptionalExplicitTemplateArgs());
Douglas Gregor430d7a12011-07-25 17:48:11 +00004629 break;
4630
4631 case CXCursor_CallExpr:
4632 if (CXXOperatorCallExpr *OCE =
4633 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
4634 Expr *Callee = OCE->getCallee();
4635 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
4636 Callee = ICE->getSubExpr();
4637
4638 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
4639 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
4640 DRE->getQualifierLoc().getSourceRange());
4641 }
4642 break;
4643
4644 default:
4645 break;
4646 }
4647
4648 if (Pieces.empty()) {
4649 if (PieceIndex == 0)
4650 return clang_getCursorExtent(C);
4651 } else if (PieceIndex < Pieces.size()) {
4652 SourceRange R = Pieces[PieceIndex];
4653 if (R.isValid())
4654 return cxloc::translateSourceRange(getCursorContext(C), R);
4655 }
4656
4657 return clang_getNullRange();
4658}
4659
Douglas Gregor0a812cf2010-02-18 23:07:20 +00004660void clang_enableStackTraces(void) {
4661 llvm::sys::PrintStackTraceOnErrorSignal();
4662}
4663
Daniel Dunbar995aaf92010-11-04 01:26:29 +00004664void clang_executeOnThread(void (*fn)(void*), void *user_data,
4665 unsigned stack_size) {
4666 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
4667}
4668
Ted Kremenekfb480492010-01-13 21:46:36 +00004669} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00004670
Ted Kremenekfb480492010-01-13 21:46:36 +00004671//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004672// Token-based Operations.
4673//===----------------------------------------------------------------------===//
4674
4675/* CXToken layout:
4676 * int_data[0]: a CXTokenKind
4677 * int_data[1]: starting token location
4678 * int_data[2]: token length
4679 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004680 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004681 * otherwise unused.
4682 */
4683extern "C" {
4684
4685CXTokenKind clang_getTokenKind(CXToken CXTok) {
4686 return static_cast<CXTokenKind>(CXTok.int_data[0]);
4687}
4688
4689CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
4690 switch (clang_getTokenKind(CXTok)) {
4691 case CXToken_Identifier:
4692 case CXToken_Keyword:
4693 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004694 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
4695 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004696
4697 case CXToken_Literal: {
4698 // We have stashed the starting pointer in the ptr_data field. Use it.
4699 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Chris Lattner5f9e2722011-07-23 10:55:15 +00004700 return createCXString(StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004701 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004702
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004703 case CXToken_Punctuation:
4704 case CXToken_Comment:
4705 break;
4706 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004707
4708 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004709 // deconstructing the source location.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004710 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004711 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004712 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004713
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004714 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
4715 std::pair<FileID, unsigned> LocInfo
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004716 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00004717 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004718 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004719 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
4720 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00004721 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004722
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004723 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004724}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004725
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004726CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004727 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004728 if (!CXXUnit)
4729 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004730
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004731 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
4732 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4733}
4734
4735CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004736 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor5352ac02010-01-28 00:27:43 +00004737 if (!CXXUnit)
4738 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004739
4740 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004741 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4742}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004743
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004744static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
4745 SmallVectorImpl<CXToken> &CXTokens) {
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004746 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4747 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004748 = SourceMgr.getDecomposedLoc(Range.getBegin());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004749 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004750 = SourceMgr.getDecomposedLoc(Range.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004751
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004752 // Cannot tokenize across files.
4753 if (BeginLocInfo.first != EndLocInfo.first)
4754 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004755
4756 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004757 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004758 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004759 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00004760 if (Invalid)
4761 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00004762
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004763 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
David Blaikie4e4d0842012-03-11 07:00:24 +00004764 CXXUnit->getASTContext().getLangOpts(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004765 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004766 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004767
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004768 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004769 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004770 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00004771 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004772 do {
4773 // Lex the next token
4774 Lex.LexFromRawLexer(Tok);
4775 if (Tok.is(tok::eof))
4776 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004777
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004778 // Initialize the CXToken.
4779 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004780
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004781 // - Common fields
4782 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
4783 CXTok.int_data[2] = Tok.getLength();
4784 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004785
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004786 // - Kind-specific fields
4787 if (Tok.isLiteral()) {
4788 CXTok.int_data[0] = CXToken_Literal;
4789 CXTok.ptr_data = (void *)Tok.getLiteralData();
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004790 } else if (Tok.is(tok::raw_identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00004791 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004792 IdentifierInfo *II
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004793 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004794
David Chisnall096428b2010-10-13 21:44:48 +00004795 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004796 CXTok.int_data[0] = CXToken_Keyword;
4797 }
4798 else {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004799 CXTok.int_data[0] = Tok.is(tok::identifier)
4800 ? CXToken_Identifier
4801 : CXToken_Keyword;
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004802 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004803 CXTok.ptr_data = II;
4804 } else if (Tok.is(tok::comment)) {
4805 CXTok.int_data[0] = CXToken_Comment;
4806 CXTok.ptr_data = 0;
4807 } else {
4808 CXTok.int_data[0] = CXToken_Punctuation;
4809 CXTok.ptr_data = 0;
4810 }
4811 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00004812 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004813 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004814}
4815
4816void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
4817 CXToken **Tokens, unsigned *NumTokens) {
4818 if (Tokens)
4819 *Tokens = 0;
4820 if (NumTokens)
4821 *NumTokens = 0;
4822
4823 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4824 if (!CXXUnit || !Tokens || !NumTokens)
4825 return;
4826
4827 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4828
4829 SourceRange R = cxloc::translateCXSourceRange(Range);
4830 if (R.isInvalid())
4831 return;
4832
4833 SmallVector<CXToken, 32> CXTokens;
4834 getTokens(CXXUnit, R, CXTokens);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004835
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004836 if (CXTokens.empty())
4837 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004838
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004839 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
4840 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
4841 *NumTokens = CXTokens.size();
4842}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004843
Ted Kremenek6db61092010-05-05 00:55:15 +00004844void clang_disposeTokens(CXTranslationUnit TU,
4845 CXToken *Tokens, unsigned NumTokens) {
4846 free(Tokens);
4847}
4848
4849} // end: extern "C"
4850
4851//===----------------------------------------------------------------------===//
4852// Token annotation APIs.
4853//===----------------------------------------------------------------------===//
4854
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004855typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004856static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4857 CXCursor parent,
4858 CXClientData client_data);
Argyrios Kyrtzidisd579dd52012-09-01 18:27:30 +00004859static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
4860 CXClientData client_data);
4861
Ted Kremenek6db61092010-05-05 00:55:15 +00004862namespace {
4863class AnnotateTokensWorker {
4864 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004865 CXToken *Tokens;
4866 CXCursor *Cursors;
4867 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004868 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00004869 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004870 CursorVisitor AnnotateVis;
4871 SourceManager &SrcMgr;
Douglas Gregorf5251602011-03-08 17:10:18 +00004872 bool HasContextSensitiveKeywords;
Argyrios Kyrtzidisd579dd52012-09-01 18:27:30 +00004873
4874 struct PostChildrenInfo {
4875 CXCursor Cursor;
4876 SourceRange CursorRange;
4877 unsigned BeforeChildrenTokenIdx;
4878 };
4879 llvm::SmallVector<PostChildrenInfo, 8> PostChildrenInfos;
Douglas Gregorf5251602011-03-08 17:10:18 +00004880
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004881 bool MoreTokens() const { return TokIdx < NumTokens; }
4882 unsigned NextToken() const { return TokIdx; }
4883 void AdvanceToken() { ++TokIdx; }
4884 SourceLocation GetTokenLoc(unsigned tokI) {
4885 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4886 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004887 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004888 return Tokens[tokI].int_data[3] != 0;
4889 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004890 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004891 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[3]);
4892 }
4893
4894 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004895 void annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
4896 SourceRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004897
Ted Kremenek6db61092010-05-05 00:55:15 +00004898public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00004899 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004900 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004901 CXTranslationUnit tu, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00004902 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00004903 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004904 AnnotateVis(tu,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00004905 AnnotateTokensVisitor, this,
4906 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00004907 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidisd579dd52012-09-01 18:27:30 +00004908 RegionOfInterest,
4909 /*VisitDeclsOnly=*/false,
4910 AnnotateTokensPostChildrenVisitor),
Douglas Gregorf5251602011-03-08 17:10:18 +00004911 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()),
4912 HasContextSensitiveKeywords(false) { }
Ted Kremenek11949cb2010-05-05 00:55:17 +00004913
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004914 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00004915 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Argyrios Kyrtzidisd579dd52012-09-01 18:27:30 +00004916 bool postVisitChildren(CXCursor cursor);
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004917 void AnnotateTokens();
Douglas Gregorf5251602011-03-08 17:10:18 +00004918
4919 /// \brief Determine whether the annotator saw any cursors that have
4920 /// context-sensitive keywords.
4921 bool hasContextSensitiveKeywords() const {
4922 return HasContextSensitiveKeywords;
4923 }
Argyrios Kyrtzidisd579dd52012-09-01 18:27:30 +00004924
4925 ~AnnotateTokensWorker() {
4926 assert(PostChildrenInfos.empty());
4927 }
Ted Kremenek6db61092010-05-05 00:55:15 +00004928};
4929}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004930
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004931void AnnotateTokensWorker::AnnotateTokens() {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004932 // Walk the AST within the region of interest, annotating tokens
4933 // along the way.
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004934 AnnotateVis.visitFileRegion();
Ted Kremenek11949cb2010-05-05 00:55:17 +00004935
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004936 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4937 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Argyrios Kyrtzidisb94b62c2012-12-12 01:05:25 +00004938 if (Pos != Annotated.end() && !clang_isPreprocessing(Cursors[I].kind))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004939 Cursors[I] = Pos->second;
4940 }
4941
4942 // Finish up annotating any tokens left.
4943 if (!MoreTokens())
4944 return;
4945
4946 const CXCursor &C = clang_getNullCursor();
4947 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004948 if (I < PreprocessingTokIdx && clang_isPreprocessing(Cursors[I].kind))
4949 continue;
4950
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004951 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4952 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004953 }
4954}
4955
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004956/// \brief It annotates and advances tokens with a cursor until the comparison
4957//// between the cursor location and the source range is the same as
4958/// \arg compResult.
4959///
4960/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
4961/// Pass RangeOverlap to annotate tokens inside a range.
4962void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
4963 RangeComparisonResult compResult,
4964 SourceRange range) {
4965 while (MoreTokens()) {
4966 const unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004967 if (isFunctionMacroToken(I))
4968 return annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004969
4970 SourceLocation TokLoc = GetTokenLoc(I);
4971 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4972 Cursors[I] = updateC;
4973 AdvanceToken();
4974 continue;
4975 }
4976 break;
4977 }
4978}
4979
4980/// \brief Special annotation handling for macro argument tokens.
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004981void AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
4982 CXCursor updateC,
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004983 RangeComparisonResult compResult,
4984 SourceRange range) {
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004985 assert(MoreTokens());
4986 assert(isFunctionMacroToken(NextToken()) &&
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004987 "Should be called only for macro arg tokens");
4988
4989 // This works differently than annotateAndAdvanceTokens; because expanded
4990 // macro arguments can have arbitrary translation-unit source order, we do not
4991 // advance the token index one by one until a token fails the range test.
4992 // We only advance once past all of the macro arg tokens if all of them
4993 // pass the range test. If one of them fails we keep the token index pointing
4994 // at the start of the macro arg tokens so that the failing token will be
4995 // annotated by a subsequent annotation try.
4996
4997 bool atLeastOneCompFail = false;
4998
4999 unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00005000 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
5001 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005002 if (TokLoc.isFileID())
5003 continue; // not macro arg token, it's parens or comma.
5004 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
5005 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
5006 Cursors[I] = updateC;
5007 } else
5008 atLeastOneCompFail = true;
5009 }
5010
5011 if (!atLeastOneCompFail)
5012 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
5013}
5014
Ted Kremenek6db61092010-05-05 00:55:15 +00005015enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00005016AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005017 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00005018 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00005019 if (cursorRange.isInvalid())
5020 return CXChildVisit_Recurse;
Douglas Gregorf5251602011-03-08 17:10:18 +00005021
5022 if (!HasContextSensitiveKeywords) {
5023 // Objective-C properties can have context-sensitive keywords.
5024 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
5025 if (ObjCPropertyDecl *Property
5026 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
5027 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
5028 }
5029 // Objective-C methods can have context-sensitive keywords.
5030 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
5031 cursor.kind == CXCursor_ObjCClassMethodDecl) {
5032 if (ObjCMethodDecl *Method
5033 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
5034 if (Method->getObjCDeclQualifier())
5035 HasContextSensitiveKeywords = true;
5036 else {
5037 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
5038 PEnd = Method->param_end();
5039 P != PEnd; ++P) {
5040 if ((*P)->getObjCDeclQualifier()) {
5041 HasContextSensitiveKeywords = true;
5042 break;
5043 }
5044 }
5045 }
5046 }
5047 }
5048 // C++ methods can have context-sensitive keywords.
5049 else if (cursor.kind == CXCursor_CXXMethod) {
5050 if (CXXMethodDecl *Method
5051 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
5052 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
5053 HasContextSensitiveKeywords = true;
5054 }
5055 }
5056 // C++ classes can have context-sensitive keywords.
5057 else if (cursor.kind == CXCursor_StructDecl ||
5058 cursor.kind == CXCursor_ClassDecl ||
5059 cursor.kind == CXCursor_ClassTemplate ||
5060 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
5061 if (Decl *D = getCursorDecl(cursor))
5062 if (D->hasAttr<FinalAttr>())
5063 HasContextSensitiveKeywords = true;
5064 }
5065 }
5066
Douglas Gregor4419b672010-10-21 06:10:04 +00005067 if (clang_isPreprocessing(cursor.kind)) {
Douglas Gregor4419b672010-10-21 06:10:04 +00005068 // Items in the preprocessing record are kept separate from items in
5069 // declarations, so we keep a separate token index.
5070 unsigned SavedTokIdx = TokIdx;
5071 TokIdx = PreprocessingTokIdx;
5072
5073 // Skip tokens up until we catch up to the beginning of the preprocessing
5074 // entry.
5075 while (MoreTokens()) {
5076 const unsigned I = NextToken();
5077 SourceLocation TokLoc = GetTokenLoc(I);
5078 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
5079 case RangeBefore:
5080 AdvanceToken();
5081 continue;
5082 case RangeAfter:
5083 case RangeOverlap:
5084 break;
5085 }
5086 break;
5087 }
5088
5089 // Look at all of the tokens within this range.
5090 while (MoreTokens()) {
5091 const unsigned I = NextToken();
5092 SourceLocation TokLoc = GetTokenLoc(I);
5093 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
5094 case RangeBefore:
David Blaikieb219cfc2011-09-23 05:06:16 +00005095 llvm_unreachable("Infeasible");
Douglas Gregor4419b672010-10-21 06:10:04 +00005096 case RangeAfter:
5097 break;
5098 case RangeOverlap:
5099 Cursors[I] = cursor;
5100 AdvanceToken();
Argyrios Kyrtzidisb94b62c2012-12-12 01:05:25 +00005101 // For macro expansions, just note where the beginning of the macro
5102 // expansion occurs.
5103 if (cursor.kind == CXCursor_MacroExpansion)
5104 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00005105 continue;
5106 }
5107 break;
5108 }
5109
5110 // Save the preprocessing token index; restore the non-preprocessing
5111 // token index.
5112 PreprocessingTokIdx = TokIdx;
5113 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005114 return CXChildVisit_Recurse;
5115 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005116
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005117 if (cursorRange.isInvalid())
5118 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00005119
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005120 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
5121
Ted Kremeneka333c662010-05-12 05:29:33 +00005122 // Adjust the annotated range based specific declarations.
5123 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
Argyrios Kyrtzidis6a010122012-10-05 00:22:24 +00005124 if (clang_isDeclaration(cursorK)) {
Ted Kremenek23173d72010-05-18 21:09:07 +00005125 Decl *D = cxcursor::getCursorDecl(cursor);
Douglas Gregor2494dd02011-03-01 01:34:45 +00005126
5127 SourceLocation StartLoc;
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00005128 if (const DeclaratorDecl *DD = dyn_cast_or_null<DeclaratorDecl>(D)) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00005129 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
Daniel Dunbar96a00142012-03-09 18:35:03 +00005130 StartLoc = TI->getTypeLoc().getLocStart();
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00005131 } else if (TypedefDecl *Typedef = dyn_cast_or_null<TypedefDecl>(D)) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00005132 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
Daniel Dunbar96a00142012-03-09 18:35:03 +00005133 StartLoc = TI->getTypeLoc().getLocStart();
Ted Kremeneka333c662010-05-12 05:29:33 +00005134 }
Douglas Gregor2494dd02011-03-01 01:34:45 +00005135
5136 if (StartLoc.isValid() && L.isValid() &&
5137 SrcMgr.isBeforeInTranslationUnit(StartLoc, L))
5138 cursorRange.setBegin(StartLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00005139 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00005140
Ted Kremenek3f404602010-08-14 01:14:06 +00005141 // If the location of the cursor occurs within a macro instantiation, record
5142 // the spelling location of the cursor in our annotation map. We can then
5143 // paper over the token labelings during a post-processing step to try and
5144 // get cursor mappings for tokens that are the *arguments* of a macro
5145 // instantiation.
5146 if (L.isMacroID()) {
5147 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
5148 // Only invalidate the old annotation if it isn't part of a preprocessing
5149 // directive. Here we assume that the default construction of CXCursor
5150 // results in CXCursor.kind being an initialized value (i.e., 0). If
5151 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00005152
Ted Kremenek3f404602010-08-14 01:14:06 +00005153 CXCursor &oldC = Annotated[rawEncoding];
5154 if (!clang_isPreprocessing(oldC.kind))
5155 oldC = cursor;
5156 }
5157
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005158 const enum CXCursorKind K = clang_getCursorKind(parent);
5159 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00005160 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
5161 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005162
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005163 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005164
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00005165 // Avoid having the cursor of an expression "overwrite" the annotation of the
5166 // variable declaration that it belongs to.
5167 // This can happen for C++ constructor expressions whose range generally
5168 // include the variable declaration, e.g.:
5169 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
5170 if (clang_isExpression(cursorK)) {
5171 Expr *E = getCursorExpr(cursor);
Argyrios Kyrtzidis8ccac3d2011-06-29 22:20:07 +00005172 if (Decl *D = getCursorParentDecl(cursor)) {
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00005173 const unsigned I = NextToken();
5174 if (E->getLocStart().isValid() && D->getLocation().isValid() &&
5175 E->getLocStart() == D->getLocation() &&
5176 E->getLocStart() == GetTokenLoc(I)) {
5177 Cursors[I] = updateC;
5178 AdvanceToken();
5179 }
5180 }
5181 }
5182
Argyrios Kyrtzidisd579dd52012-09-01 18:27:30 +00005183 // Before recursing into the children keep some state that we are going
5184 // to use in the AnnotateTokensWorker::postVisitChildren callback to do some
5185 // extra work after the child nodes are visited.
5186 // Note that we don't call VisitChildren here to avoid traversing statements
5187 // code-recursively which can blow the stack.
5188
5189 PostChildrenInfo Info;
5190 Info.Cursor = cursor;
5191 Info.CursorRange = cursorRange;
5192 Info.BeforeChildrenTokenIdx = NextToken();
5193 PostChildrenInfos.push_back(Info);
5194
5195 return CXChildVisit_Recurse;
5196}
5197
5198bool AnnotateTokensWorker::postVisitChildren(CXCursor cursor) {
5199 if (PostChildrenInfos.empty())
5200 return false;
5201 const PostChildrenInfo &Info = PostChildrenInfos.back();
5202 if (!clang_equalCursors(Info.Cursor, cursor))
5203 return false;
5204
5205 const unsigned BeforeChildren = Info.BeforeChildrenTokenIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005206 const unsigned AfterChildren = NextToken();
Argyrios Kyrtzidisd579dd52012-09-01 18:27:30 +00005207 SourceRange cursorRange = Info.CursorRange;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005208
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005209 // Scan the tokens that are at the end of the cursor, but are not captured
5210 // but the child cursors.
5211 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
Argyrios Kyrtzidisd579dd52012-09-01 18:27:30 +00005212
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005213 // Scan the tokens that are at the beginning of the cursor, but are not
5214 // capture by the child cursors.
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005215 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
5216 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
5217 break;
Argyrios Kyrtzidisd579dd52012-09-01 18:27:30 +00005218
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005219 Cursors[I] = cursor;
5220 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005221
Argyrios Kyrtzidisd579dd52012-09-01 18:27:30 +00005222 PostChildrenInfos.pop_back();
5223 return false;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005224}
5225
Ted Kremenek6db61092010-05-05 00:55:15 +00005226static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
5227 CXCursor parent,
5228 CXClientData client_data) {
5229 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
5230}
5231
Argyrios Kyrtzidisd579dd52012-09-01 18:27:30 +00005232static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
5233 CXClientData client_data) {
5234 return static_cast<AnnotateTokensWorker*>(client_data)->
5235 postVisitChildren(cursor);
5236}
5237
Ted Kremenek6628a612011-03-18 22:51:30 +00005238namespace {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005239
5240/// \brief Uses the macro expansions in the preprocessing record to find
5241/// and mark tokens that are macro arguments. This info is used by the
5242/// AnnotateTokensWorker.
5243class MarkMacroArgTokensVisitor {
5244 SourceManager &SM;
5245 CXToken *Tokens;
5246 unsigned NumTokens;
5247 unsigned CurIdx;
5248
5249public:
5250 MarkMacroArgTokensVisitor(SourceManager &SM,
5251 CXToken *tokens, unsigned numTokens)
5252 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
5253
5254 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
5255 if (cursor.kind != CXCursor_MacroExpansion)
5256 return CXChildVisit_Continue;
5257
5258 SourceRange macroRange = getCursorMacroExpansion(cursor)->getSourceRange();
5259 if (macroRange.getBegin() == macroRange.getEnd())
5260 return CXChildVisit_Continue; // it's not a function macro.
5261
5262 for (; CurIdx < NumTokens; ++CurIdx) {
5263 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
5264 macroRange.getBegin()))
5265 break;
5266 }
5267
5268 if (CurIdx == NumTokens)
5269 return CXChildVisit_Break;
5270
5271 for (; CurIdx < NumTokens; ++CurIdx) {
5272 SourceLocation tokLoc = getTokenLoc(CurIdx);
5273 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
5274 break;
5275
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00005276 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005277 }
5278
5279 if (CurIdx == NumTokens)
5280 return CXChildVisit_Break;
5281
5282 return CXChildVisit_Continue;
5283 }
5284
5285private:
5286 SourceLocation getTokenLoc(unsigned tokI) {
5287 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
5288 }
5289
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00005290 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005291 // The third field is reserved and currently not used. Use it here
5292 // to mark macro arg expanded tokens with their expanded locations.
5293 Tokens[tokI].int_data[3] = loc.getRawEncoding();
5294 }
5295};
5296
5297} // end anonymous namespace
5298
5299static CXChildVisitResult
5300MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
5301 CXClientData client_data) {
5302 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
5303 parent);
5304}
5305
5306namespace {
Ted Kremenek6628a612011-03-18 22:51:30 +00005307 struct clang_annotateTokens_Data {
5308 CXTranslationUnit TU;
5309 ASTUnit *CXXUnit;
5310 CXToken *Tokens;
5311 unsigned NumTokens;
5312 CXCursor *Cursors;
5313 };
5314}
5315
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005316static void annotatePreprocessorTokens(CXTranslationUnit TU,
5317 SourceRange RegionOfInterest,
5318 AnnotateTokensData &Annotated) {
5319 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
5320
5321 SourceManager &SourceMgr = CXXUnit->getSourceManager();
5322 std::pair<FileID, unsigned> BeginLocInfo
5323 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
5324 std::pair<FileID, unsigned> EndLocInfo
5325 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
5326
5327 if (BeginLocInfo.first != EndLocInfo.first)
5328 return;
5329
5330 StringRef Buffer;
5331 bool Invalid = false;
5332 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
5333 if (Buffer.empty() || Invalid)
5334 return;
5335
5336 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
David Blaikie4e4d0842012-03-11 07:00:24 +00005337 CXXUnit->getASTContext().getLangOpts(),
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005338 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
5339 Buffer.end());
5340 Lex.SetCommentRetentionState(true);
5341
5342 // Lex tokens in raw mode until we hit the end of the range, to avoid
5343 // entering #includes or expanding macros.
5344 while (true) {
5345 Token Tok;
5346 Lex.LexFromRawLexer(Tok);
5347
5348 reprocess:
5349 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
5350 // We have found a preprocessing directive. Gobble it up so that we
5351 // don't see it while preprocessing these tokens later, but keep track
5352 // of all of the token locations inside this preprocessing directive so
5353 // that we can annotate them appropriately.
5354 //
5355 // FIXME: Some simple tests here could identify macro definitions and
5356 // #undefs, to provide specific cursor kinds for those.
5357 SmallVector<SourceLocation, 32> Locations;
5358 do {
5359 Locations.push_back(Tok.getLocation());
5360 Lex.LexFromRawLexer(Tok);
5361 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
5362
5363 using namespace cxcursor;
5364 CXCursor Cursor
5365 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
5366 Locations.back()),
5367 TU);
5368 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
5369 Annotated[Locations[I].getRawEncoding()] = Cursor;
5370 }
5371
5372 if (Tok.isAtStartOfLine())
5373 goto reprocess;
5374
5375 continue;
5376 }
5377
5378 if (Tok.is(tok::eof))
5379 break;
5380 }
5381}
5382
Ted Kremenekab979612010-11-11 08:05:23 +00005383// This gets run a separate thread to avoid stack blowout.
Ted Kremenek6628a612011-03-18 22:51:30 +00005384static void clang_annotateTokensImpl(void *UserData) {
5385 CXTranslationUnit TU = ((clang_annotateTokens_Data*)UserData)->TU;
5386 ASTUnit *CXXUnit = ((clang_annotateTokens_Data*)UserData)->CXXUnit;
5387 CXToken *Tokens = ((clang_annotateTokens_Data*)UserData)->Tokens;
5388 const unsigned NumTokens = ((clang_annotateTokens_Data*)UserData)->NumTokens;
5389 CXCursor *Cursors = ((clang_annotateTokens_Data*)UserData)->Cursors;
5390
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00005391 CIndexer *CXXIdx = (CIndexer*)TU->CIdx;
5392 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
Argyrios Kyrtzidis81b5ac32012-03-28 02:49:54 +00005393 setThreadBackgroundPriority();
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00005394
Ted Kremenek6628a612011-03-18 22:51:30 +00005395 // Determine the region of interest, which contains all of the tokens.
5396 SourceRange RegionOfInterest;
5397 RegionOfInterest.setBegin(
5398 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
5399 RegionOfInterest.setEnd(
5400 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
5401 Tokens[NumTokens-1])));
5402
5403 // A mapping from the source locations found when re-lexing or traversing the
5404 // region of interest to the corresponding cursors.
5405 AnnotateTokensData Annotated;
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005406
Ted Kremenek6628a612011-03-18 22:51:30 +00005407 // Relex the tokens within the source range to look for preprocessing
5408 // directives.
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005409 annotatePreprocessorTokens(TU, RegionOfInterest, Annotated);
Ted Kremenek6628a612011-03-18 22:51:30 +00005410
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005411 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
5412 // Search and mark tokens that are macro argument expansions.
5413 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
5414 Tokens, NumTokens);
5415 CursorVisitor MacroArgMarker(TU,
5416 MarkMacroArgTokensVisitorDelegate, &Visitor,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00005417 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00005418 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00005419 RegionOfInterest);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005420 MacroArgMarker.visitPreprocessedEntitiesInRegion();
5421 }
5422
Ted Kremenek6628a612011-03-18 22:51:30 +00005423 // Annotate all of the source locations in the region of interest that map to
5424 // a specific cursor.
5425 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
5426 TU, RegionOfInterest);
5427
5428 // FIXME: We use a ridiculous stack size here because the data-recursion
5429 // algorithm uses a large stack frame than the non-data recursive version,
5430 // and AnnotationTokensWorker currently transforms the data-recursion
5431 // algorithm back into a traditional recursion by explicitly calling
5432 // VisitChildren(). We will need to remove this explicit recursive call.
5433 W.AnnotateTokens();
5434
5435 // If we ran into any entities that involve context-sensitive keywords,
5436 // take another pass through the tokens to mark them as such.
5437 if (W.hasContextSensitiveKeywords()) {
5438 for (unsigned I = 0; I != NumTokens; ++I) {
5439 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
5440 continue;
5441
5442 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
5443 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5444 if (ObjCPropertyDecl *Property
5445 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
5446 if (Property->getPropertyAttributesAsWritten() != 0 &&
5447 llvm::StringSwitch<bool>(II->getName())
5448 .Case("readonly", true)
5449 .Case("assign", true)
John McCallf85e1932011-06-15 23:02:42 +00005450 .Case("unsafe_unretained", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00005451 .Case("readwrite", true)
5452 .Case("retain", true)
5453 .Case("copy", true)
5454 .Case("nonatomic", true)
5455 .Case("atomic", true)
5456 .Case("getter", true)
5457 .Case("setter", true)
John McCallf85e1932011-06-15 23:02:42 +00005458 .Case("strong", true)
5459 .Case("weak", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00005460 .Default(false))
5461 Tokens[I].int_data[0] = CXToken_Keyword;
5462 }
5463 continue;
5464 }
5465
5466 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
5467 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
5468 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5469 if (llvm::StringSwitch<bool>(II->getName())
5470 .Case("in", true)
5471 .Case("out", true)
5472 .Case("inout", true)
5473 .Case("oneway", true)
5474 .Case("bycopy", true)
5475 .Case("byref", true)
5476 .Default(false))
5477 Tokens[I].int_data[0] = CXToken_Keyword;
5478 continue;
5479 }
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00005480
5481 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
5482 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
5483 Tokens[I].int_data[0] = CXToken_Keyword;
Ted Kremenek6628a612011-03-18 22:51:30 +00005484 continue;
5485 }
5486 }
5487 }
Ted Kremenekab979612010-11-11 08:05:23 +00005488}
5489
Ted Kremenek6db61092010-05-05 00:55:15 +00005490extern "C" {
5491
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005492void clang_annotateTokens(CXTranslationUnit TU,
5493 CXToken *Tokens, unsigned NumTokens,
5494 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005495
5496 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005497 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005498
Douglas Gregor4419b672010-10-21 06:10:04 +00005499 // Any token we don't specifically annotate will have a NULL cursor.
5500 CXCursor C = clang_getNullCursor();
5501 for (unsigned I = 0; I != NumTokens; ++I)
5502 Cursors[I] = C;
5503
Ted Kremeneka60ed472010-11-16 08:15:36 +00005504 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor4419b672010-10-21 06:10:04 +00005505 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005506 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005507
Douglas Gregorbdf60622010-03-05 21:16:25 +00005508 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenek6628a612011-03-18 22:51:30 +00005509
5510 clang_annotateTokens_Data data = { TU, CXXUnit, Tokens, NumTokens, Cursors };
Ted Kremenekab979612010-11-11 08:05:23 +00005511 llvm::CrashRecoveryContext CRC;
Ted Kremenek6628a612011-03-18 22:51:30 +00005512 if (!RunSafely(CRC, clang_annotateTokensImpl, &data,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005513 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00005514 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
5515 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005516}
Ted Kremenek6628a612011-03-18 22:51:30 +00005517
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005518} // end: extern "C"
5519
5520//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00005521// Operations for querying linkage of a cursor.
5522//===----------------------------------------------------------------------===//
5523
5524extern "C" {
5525CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00005526 if (!clang_isDeclaration(cursor.kind))
5527 return CXLinkage_Invalid;
5528
Ted Kremenek16b42592010-03-03 06:36:57 +00005529 Decl *D = cxcursor::getCursorDecl(cursor);
5530 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
5531 switch (ND->getLinkage()) {
5532 case NoLinkage: return CXLinkage_NoLinkage;
5533 case InternalLinkage: return CXLinkage_Internal;
5534 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
5535 case ExternalLinkage: return CXLinkage_External;
5536 };
5537
5538 return CXLinkage_Invalid;
5539}
5540} // end: extern "C"
5541
5542//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005543// Operations for querying language of a cursor.
5544//===----------------------------------------------------------------------===//
5545
5546static CXLanguageKind getDeclLanguage(const Decl *D) {
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00005547 if (!D)
5548 return CXLanguage_C;
5549
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005550 switch (D->getKind()) {
5551 default:
5552 break;
5553 case Decl::ImplicitParam:
5554 case Decl::ObjCAtDefsField:
5555 case Decl::ObjCCategory:
5556 case Decl::ObjCCategoryImpl:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005557 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005558 case Decl::ObjCImplementation:
5559 case Decl::ObjCInterface:
5560 case Decl::ObjCIvar:
5561 case Decl::ObjCMethod:
5562 case Decl::ObjCProperty:
5563 case Decl::ObjCPropertyImpl:
5564 case Decl::ObjCProtocol:
5565 return CXLanguage_ObjC;
5566 case Decl::CXXConstructor:
5567 case Decl::CXXConversion:
5568 case Decl::CXXDestructor:
5569 case Decl::CXXMethod:
5570 case Decl::CXXRecord:
5571 case Decl::ClassTemplate:
5572 case Decl::ClassTemplatePartialSpecialization:
5573 case Decl::ClassTemplateSpecialization:
5574 case Decl::Friend:
5575 case Decl::FriendTemplate:
5576 case Decl::FunctionTemplate:
5577 case Decl::LinkageSpec:
5578 case Decl::Namespace:
5579 case Decl::NamespaceAlias:
5580 case Decl::NonTypeTemplateParm:
5581 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005582 case Decl::TemplateTemplateParm:
5583 case Decl::TemplateTypeParm:
5584 case Decl::UnresolvedUsingTypename:
5585 case Decl::UnresolvedUsingValue:
5586 case Decl::Using:
5587 case Decl::UsingDirective:
5588 case Decl::UsingShadow:
5589 return CXLanguage_CPlusPlus;
5590 }
5591
5592 return CXLanguage_C;
5593}
5594
5595extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00005596
5597enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
5598 if (clang_isDeclaration(cursor.kind))
5599 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005600 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Douglas Gregor58ddb602010-08-23 23:00:57 +00005601 return CXAvailability_Available;
5602
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005603 switch (D->getAvailability()) {
5604 case AR_Available:
5605 case AR_NotYetIntroduced:
5606 return CXAvailability_Available;
5607
5608 case AR_Deprecated:
Douglas Gregor58ddb602010-08-23 23:00:57 +00005609 return CXAvailability_Deprecated;
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005610
5611 case AR_Unavailable:
5612 return CXAvailability_NotAvailable;
5613 }
Douglas Gregor58ddb602010-08-23 23:00:57 +00005614 }
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005615
Douglas Gregor58ddb602010-08-23 23:00:57 +00005616 return CXAvailability_Available;
5617}
5618
Douglas Gregorcc889662012-05-08 00:14:45 +00005619static CXVersion convertVersion(VersionTuple In) {
5620 CXVersion Out = { -1, -1, -1 };
5621 if (In.empty())
5622 return Out;
5623
5624 Out.Major = In.getMajor();
5625
5626 if (llvm::Optional<unsigned> Minor = In.getMinor())
5627 Out.Minor = *Minor;
5628 else
5629 return Out;
5630
5631 if (llvm::Optional<unsigned> Subminor = In.getSubminor())
5632 Out.Subminor = *Subminor;
5633
5634 return Out;
5635}
5636
5637int clang_getCursorPlatformAvailability(CXCursor cursor,
5638 int *always_deprecated,
5639 CXString *deprecated_message,
5640 int *always_unavailable,
5641 CXString *unavailable_message,
5642 CXPlatformAvailability *availability,
5643 int availability_size) {
5644 if (always_deprecated)
5645 *always_deprecated = 0;
5646 if (deprecated_message)
5647 *deprecated_message = cxstring::createCXString("", /*DupString=*/false);
5648 if (always_unavailable)
5649 *always_unavailable = 0;
5650 if (unavailable_message)
5651 *unavailable_message = cxstring::createCXString("", /*DupString=*/false);
5652
5653 if (!clang_isDeclaration(cursor.kind))
5654 return 0;
5655
5656 Decl *D = cxcursor::getCursorDecl(cursor);
5657 if (!D)
5658 return 0;
5659
5660 int N = 0;
5661 for (Decl::attr_iterator A = D->attr_begin(), AEnd = D->attr_end(); A != AEnd;
5662 ++A) {
5663 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(*A)) {
5664 if (always_deprecated)
5665 *always_deprecated = 1;
5666 if (deprecated_message)
5667 *deprecated_message = cxstring::createCXString(Deprecated->getMessage());
5668 continue;
5669 }
5670
5671 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(*A)) {
5672 if (always_unavailable)
5673 *always_unavailable = 1;
5674 if (unavailable_message) {
5675 *unavailable_message
5676 = cxstring::createCXString(Unavailable->getMessage());
5677 }
5678 continue;
5679 }
5680
5681 if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(*A)) {
5682 if (N < availability_size) {
5683 availability[N].Platform
5684 = cxstring::createCXString(Avail->getPlatform()->getName());
5685 availability[N].Introduced = convertVersion(Avail->getIntroduced());
5686 availability[N].Deprecated = convertVersion(Avail->getDeprecated());
5687 availability[N].Obsoleted = convertVersion(Avail->getObsoleted());
5688 availability[N].Unavailable = Avail->getUnavailable();
5689 availability[N].Message = cxstring::createCXString(Avail->getMessage());
5690 }
5691 ++N;
5692 }
5693 }
5694
5695 return N;
5696}
5697
5698void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) {
5699 clang_disposeString(availability->Platform);
5700 clang_disposeString(availability->Message);
5701}
5702
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005703CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
5704 if (clang_isDeclaration(cursor.kind))
5705 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
5706
5707 return CXLanguage_Invalid;
5708}
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005709
5710 /// \brief If the given cursor is the "templated" declaration
5711 /// descibing a class or function template, return the class or
5712 /// function template.
5713static Decl *maybeGetTemplateCursor(Decl *D) {
5714 if (!D)
5715 return 0;
5716
5717 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
5718 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
5719 return FunTmpl;
5720
5721 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
5722 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
5723 return ClassTmpl;
5724
5725 return D;
5726}
5727
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005728CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
5729 if (clang_isDeclaration(cursor.kind)) {
5730 if (Decl *D = getCursorDecl(cursor)) {
5731 DeclContext *DC = D->getDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005732 if (!DC)
5733 return clang_getNullCursor();
5734
5735 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5736 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005737 }
5738 }
5739
5740 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
5741 if (Decl *D = getCursorDecl(cursor))
Ted Kremeneka60ed472010-11-16 08:15:36 +00005742 return MakeCXCursor(D, getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005743 }
5744
5745 return clang_getNullCursor();
5746}
5747
5748CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
5749 if (clang_isDeclaration(cursor.kind)) {
5750 if (Decl *D = getCursorDecl(cursor)) {
5751 DeclContext *DC = D->getLexicalDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005752 if (!DC)
5753 return clang_getNullCursor();
5754
5755 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5756 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005757 }
5758 }
5759
5760 // FIXME: Note that we can't easily compute the lexical context of a
5761 // statement or expression, so we return nothing.
5762 return clang_getNullCursor();
5763}
5764
Douglas Gregorecdcb882010-10-20 22:00:55 +00005765CXFile clang_getIncludedFile(CXCursor cursor) {
5766 if (cursor.kind != CXCursor_InclusionDirective)
5767 return 0;
5768
5769 InclusionDirective *ID = getCursorInclusionDirective(cursor);
5770 return (void *)ID->getFile();
5771}
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +00005772
5773CXSourceRange clang_Cursor_getCommentRange(CXCursor C) {
5774 if (!clang_isDeclaration(C.kind))
5775 return clang_getNullRange();
5776
5777 const Decl *D = getCursorDecl(C);
5778 ASTContext &Context = getCursorContext(C);
Dmitri Gribenkof50555e2012-08-11 00:51:43 +00005779 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +00005780 if (!RC)
5781 return clang_getNullRange();
5782
5783 return cxloc::translateSourceRange(Context, RC->getSourceRange());
5784}
5785
5786CXString clang_Cursor_getRawCommentText(CXCursor C) {
5787 if (!clang_isDeclaration(C.kind))
5788 return createCXString((const char *) NULL);
5789
5790 const Decl *D = getCursorDecl(C);
5791 ASTContext &Context = getCursorContext(C);
Dmitri Gribenkof50555e2012-08-11 00:51:43 +00005792 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +00005793 StringRef RawText = RC ? RC->getRawText(Context.getSourceManager()) :
5794 StringRef();
5795
5796 // Don't duplicate the string because RawText points directly into source
5797 // code.
5798 return createCXString(RawText, false);
5799}
5800
Dmitri Gribenko2d44d772012-06-26 20:39:18 +00005801CXString clang_Cursor_getBriefCommentText(CXCursor C) {
5802 if (!clang_isDeclaration(C.kind))
5803 return createCXString((const char *) NULL);
5804
5805 const Decl *D = getCursorDecl(C);
5806 const ASTContext &Context = getCursorContext(C);
Dmitri Gribenkof50555e2012-08-11 00:51:43 +00005807 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
Dmitri Gribenko2d44d772012-06-26 20:39:18 +00005808
Dmitri Gribenko8376f592012-06-28 16:25:36 +00005809 if (RC) {
Dmitri Gribenko2d44d772012-06-26 20:39:18 +00005810 StringRef BriefText = RC->getBriefText(Context);
5811
5812 // Don't duplicate the string because RawComment ensures that this memory
5813 // will not go away.
5814 return createCXString(BriefText, false);
5815 }
5816
5817 return createCXString((const char *) NULL);
5818}
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005819
Dmitri Gribenkoae99b752012-07-20 21:34:34 +00005820CXComment clang_Cursor_getParsedComment(CXCursor C) {
5821 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkoe4330a32012-09-10 20:32:42 +00005822 return cxcomment::createCXComment(NULL, NULL);
Dmitri Gribenkoae99b752012-07-20 21:34:34 +00005823
5824 const Decl *D = getCursorDecl(C);
5825 const ASTContext &Context = getCursorContext(C);
Dmitri Gribenko19523542012-09-29 11:40:46 +00005826 const comments::FullComment *FC = Context.getCommentForDecl(D, /*PP=*/ NULL);
Dmitri Gribenkoae99b752012-07-20 21:34:34 +00005827
Dmitri Gribenkoe4330a32012-09-10 20:32:42 +00005828 return cxcomment::createCXComment(FC, getCursorTU(C));
Dmitri Gribenkoae99b752012-07-20 21:34:34 +00005829}
5830
Argyrios Kyrtzidis5d04b1a2012-10-05 00:22:37 +00005831CXModule clang_Cursor_getModule(CXCursor C) {
5832 if (C.kind == CXCursor_ModuleImportDecl) {
5833 if (ImportDecl *ImportD = dyn_cast_or_null<ImportDecl>(getCursorDecl(C)))
5834 return ImportD->getImportedModule();
5835 }
5836
5837 return 0;
5838}
5839
5840CXModule clang_Module_getParent(CXModule CXMod) {
5841 if (!CXMod)
5842 return 0;
5843 Module *Mod = static_cast<Module*>(CXMod);
5844 return Mod->Parent;
5845}
5846
5847CXString clang_Module_getName(CXModule CXMod) {
5848 if (!CXMod)
5849 return createCXString("");
5850 Module *Mod = static_cast<Module*>(CXMod);
5851 return createCXString(Mod->Name);
5852}
5853
5854CXString clang_Module_getFullName(CXModule CXMod) {
5855 if (!CXMod)
5856 return createCXString("");
5857 Module *Mod = static_cast<Module*>(CXMod);
5858 return createCXString(Mod->getFullModuleName());
5859}
5860
5861unsigned clang_Module_getNumTopLevelHeaders(CXModule CXMod) {
5862 if (!CXMod)
5863 return 0;
5864 Module *Mod = static_cast<Module*>(CXMod);
5865 return Mod->TopHeaders.size();
5866}
5867
5868CXFile clang_Module_getTopLevelHeader(CXModule CXMod, unsigned Index) {
5869 if (!CXMod)
5870 return 0;
5871 Module *Mod = static_cast<Module*>(CXMod);
5872
5873 if (Index < Mod->TopHeaders.size())
5874 return const_cast<FileEntry *>(Mod->TopHeaders[Index]);
5875
5876 return 0;
5877}
5878
Dmitri Gribenkob619e782012-07-17 00:17:45 +00005879} // end: extern "C"
5880
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005881//===----------------------------------------------------------------------===//
5882// C++ AST instrospection.
5883//===----------------------------------------------------------------------===//
5884
5885extern "C" {
5886unsigned clang_CXXMethod_isStatic(CXCursor C) {
5887 if (!clang_isDeclaration(C.kind))
5888 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00005889
5890 CXXMethodDecl *Method = 0;
5891 Decl *D = cxcursor::getCursorDecl(C);
5892 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5893 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5894 else
5895 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5896 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00005897}
Ted Kremenekb12903e2010-05-18 22:32:15 +00005898
Douglas Gregor211924b2011-05-12 15:17:24 +00005899unsigned clang_CXXMethod_isVirtual(CXCursor C) {
5900 if (!clang_isDeclaration(C.kind))
5901 return 0;
5902
5903 CXXMethodDecl *Method = 0;
5904 Decl *D = cxcursor::getCursorDecl(C);
5905 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5906 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5907 else
5908 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5909 return (Method && Method->isVirtual()) ? 1 : 0;
5910}
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005911} // end: extern "C"
5912
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005913//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00005914// Attribute introspection.
5915//===----------------------------------------------------------------------===//
5916
5917extern "C" {
5918CXType clang_getIBOutletCollectionType(CXCursor C) {
5919 if (C.kind != CXCursor_IBOutletCollectionAttr)
Ted Kremeneka60ed472010-11-16 08:15:36 +00005920 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005921
5922 IBOutletCollectionAttr *A =
5923 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
5924
Argyrios Kyrtzidis18aa2ff2011-09-13 18:49:52 +00005925 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005926}
5927} // end: extern "C"
5928
5929//===----------------------------------------------------------------------===//
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005930// Inspecting memory usage.
5931//===----------------------------------------------------------------------===//
5932
Ted Kremenekf7870022011-04-20 16:41:07 +00005933typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005934
Ted Kremenekf7870022011-04-20 16:41:07 +00005935static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
5936 enum CXTUResourceUsageKind k,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005937 unsigned long amount) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005938 CXTUResourceUsageEntry entry = { k, amount };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005939 entries.push_back(entry);
5940}
5941
5942extern "C" {
5943
Ted Kremenekf7870022011-04-20 16:41:07 +00005944const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005945 const char *str = "";
5946 switch (kind) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005947 case CXTUResourceUsage_AST:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005948 str = "ASTContext: expressions, declarations, and types";
5949 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005950 case CXTUResourceUsage_Identifiers:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005951 str = "ASTContext: identifiers";
5952 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005953 case CXTUResourceUsage_Selectors:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005954 str = "ASTContext: selectors";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005955 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005956 case CXTUResourceUsage_GlobalCompletionResults:
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005957 str = "Code completion: cached global results";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005958 break;
Ted Kremenek457aaf02011-04-28 04:10:31 +00005959 case CXTUResourceUsage_SourceManagerContentCache:
5960 str = "SourceManager: content cache allocator";
5961 break;
Ted Kremenekba29bd22011-04-28 04:53:38 +00005962 case CXTUResourceUsage_AST_SideTables:
5963 str = "ASTContext: side tables";
5964 break;
Ted Kremenekf61b8312011-04-28 20:36:42 +00005965 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
5966 str = "SourceManager: malloc'ed memory buffers";
5967 break;
5968 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
5969 str = "SourceManager: mmap'ed memory buffers";
5970 break;
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005971 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
5972 str = "ExternalASTSource: malloc'ed memory buffers";
5973 break;
5974 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
5975 str = "ExternalASTSource: mmap'ed memory buffers";
5976 break;
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005977 case CXTUResourceUsage_Preprocessor:
5978 str = "Preprocessor: malloc'ed memory";
5979 break;
5980 case CXTUResourceUsage_PreprocessingRecord:
5981 str = "Preprocessor: PreprocessingRecord";
5982 break;
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005983 case CXTUResourceUsage_SourceManager_DataStructures:
5984 str = "SourceManager: data structures and tables";
5985 break;
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005986 case CXTUResourceUsage_Preprocessor_HeaderSearch:
5987 str = "Preprocessor: header search tables";
5988 break;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005989 }
5990 return str;
5991}
5992
Ted Kremenekf7870022011-04-20 16:41:07 +00005993CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005994 if (!TU) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005995 CXTUResourceUsage usage = { (void*) 0, 0, 0 };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005996 return usage;
5997 }
5998
5999 ASTUnit *astUnit = static_cast<ASTUnit*>(TU->TUData);
Dylan Noblesmith1e4c01b2012-02-13 12:32:21 +00006000 OwningPtr<MemUsageEntries> entries(new MemUsageEntries());
Ted Kremenek59fc1e52011-04-18 22:47:10 +00006001 ASTContext &astContext = astUnit->getASTContext();
6002
6003 // How much memory is used by AST nodes and types?
Ted Kremenekf7870022011-04-20 16:41:07 +00006004 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
Ted Kremenekba29bd22011-04-28 04:53:38 +00006005 (unsigned long) astContext.getASTAllocatedMemory());
Ted Kremenek59fc1e52011-04-18 22:47:10 +00006006
6007 // How much memory is used by identifiers?
Ted Kremenekf7870022011-04-20 16:41:07 +00006008 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00006009 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
6010
6011 // How much memory is used for selectors?
Ted Kremenekf7870022011-04-20 16:41:07 +00006012 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00006013 (unsigned long) astContext.Selectors.getTotalMemory());
6014
Ted Kremenekba29bd22011-04-28 04:53:38 +00006015 // How much memory is used by ASTContext's side tables?
6016 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
6017 (unsigned long) astContext.getSideTableAllocatedMemory());
6018
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00006019 // How much memory is used for caching global code completion results?
6020 unsigned long completionBytes = 0;
6021 if (GlobalCodeCompletionAllocator *completionAllocator =
6022 astUnit->getCachedCompletionAllocator().getPtr()) {
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00006023 completionBytes = completionAllocator->getTotalMemory();
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00006024 }
Ted Kremenek457aaf02011-04-28 04:10:31 +00006025 createCXTUResourceUsageEntry(*entries,
6026 CXTUResourceUsage_GlobalCompletionResults,
6027 completionBytes);
6028
6029 // How much memory is being used by SourceManager's content cache?
6030 createCXTUResourceUsageEntry(*entries,
6031 CXTUResourceUsage_SourceManagerContentCache,
6032 (unsigned long) astContext.getSourceManager().getContentCacheSize());
Ted Kremenekf61b8312011-04-28 20:36:42 +00006033
6034 // How much memory is being used by the MemoryBuffer's in SourceManager?
6035 const SourceManager::MemoryBufferSizes &srcBufs =
6036 astUnit->getSourceManager().getMemoryBufferSizes();
6037
6038 createCXTUResourceUsageEntry(*entries,
6039 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
6040 (unsigned long) srcBufs.malloc_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00006041 createCXTUResourceUsageEntry(*entries,
Ted Kremenekf61b8312011-04-28 20:36:42 +00006042 CXTUResourceUsage_SourceManager_Membuffer_MMap,
6043 (unsigned long) srcBufs.mmap_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00006044 createCXTUResourceUsageEntry(*entries,
6045 CXTUResourceUsage_SourceManager_DataStructures,
6046 (unsigned long) astContext.getSourceManager()
6047 .getDataStructureSizes());
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00006048
6049 // How much memory is being used by the ExternalASTSource?
6050 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
6051 const ExternalASTSource::MemoryBufferSizes &sizes =
6052 esrc->getMemoryBufferSizes();
6053
6054 createCXTUResourceUsageEntry(*entries,
6055 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
6056 (unsigned long) sizes.malloc_bytes);
6057 createCXTUResourceUsageEntry(*entries,
6058 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
6059 (unsigned long) sizes.mmap_bytes);
6060 }
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00006061
6062 // How much memory is being used by the Preprocessor?
6063 Preprocessor &pp = astUnit->getPreprocessor();
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00006064 createCXTUResourceUsageEntry(*entries,
6065 CXTUResourceUsage_Preprocessor,
Argyrios Kyrtzidisc5c5e922011-06-29 22:20:04 +00006066 pp.getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00006067
6068 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
6069 createCXTUResourceUsageEntry(*entries,
6070 CXTUResourceUsage_PreprocessingRecord,
6071 pRec->getTotalMemory());
6072 }
6073
Ted Kremenekd1194fb2011-07-26 23:46:11 +00006074 createCXTUResourceUsageEntry(*entries,
6075 CXTUResourceUsage_Preprocessor_HeaderSearch,
6076 pp.getHeaderSearchInfo().getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00006077
Ted Kremenekf7870022011-04-20 16:41:07 +00006078 CXTUResourceUsage usage = { (void*) entries.get(),
Ted Kremenek59fc1e52011-04-18 22:47:10 +00006079 (unsigned) entries->size(),
6080 entries->size() ? &(*entries)[0] : 0 };
6081 entries.take();
6082 return usage;
6083}
6084
Ted Kremenekf7870022011-04-20 16:41:07 +00006085void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00006086 if (usage.data)
6087 delete (MemUsageEntries*) usage.data;
6088}
6089
6090} // end extern "C"
6091
Douglas Gregor6df78732011-05-05 20:27:22 +00006092void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
6093 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
6094 for (unsigned I = 0; I != Usage.numEntries; ++I)
6095 fprintf(stderr, " %s: %lu\n",
6096 clang_getTUResourceUsageName(Usage.entries[I].kind),
6097 Usage.entries[I].amount);
6098
6099 clang_disposeCXTUResourceUsage(Usage);
6100}
6101
Ted Kremenek59fc1e52011-04-18 22:47:10 +00006102//===----------------------------------------------------------------------===//
Ted Kremenek04bb7162010-01-22 22:44:15 +00006103// Misc. utility functions.
6104//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00006105
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00006106/// Default to using an 8 MB stack size on "safety" threads.
6107static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00006108
6109namespace clang {
6110
6111bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00006112 void (*Fn)(void*), void *UserData,
6113 unsigned Size) {
6114 if (!Size)
6115 Size = GetSafetyThreadStackSize();
6116 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00006117 return CRC.RunSafelyOnThread(Fn, UserData, Size);
6118 return CRC.RunSafely(Fn, UserData);
6119}
6120
6121unsigned GetSafetyThreadStackSize() {
6122 return SafetyStackThreadSize;
6123}
6124
6125void SetSafetyThreadStackSize(unsigned Value) {
6126 SafetyStackThreadSize = Value;
6127}
6128
Argyrios Kyrtzidis8e7c48a2012-03-28 02:49:50 +00006129}
6130
Argyrios Kyrtzidis81b5ac32012-03-28 02:49:54 +00006131void clang::setThreadBackgroundPriority() {
Argyrios Kyrtzidis28f3a0e2012-10-23 04:09:38 +00006132 if (getenv("LIBCLANG_BGPRIO_DISABLE"))
6133 return;
6134
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00006135 // FIXME: Move to llvm/Support and make it cross-platform.
6136#ifdef __APPLE__
6137 setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG);
6138#endif
6139}
6140
Argyrios Kyrtzidis97934282012-04-11 03:52:18 +00006141void cxindex::printDiagsToStderr(ASTUnit *Unit) {
6142 if (!Unit)
6143 return;
6144
6145 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
6146 DEnd = Unit->stored_diag_end();
6147 D != DEnd; ++D) {
6148 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOpts());
6149 CXString Msg = clang_formatDiagnostic(&Diag,
6150 clang_defaultDiagnosticDisplayOptions());
6151 fprintf(stderr, "%s\n", clang_getCString(Msg));
6152 clang_disposeString(Msg);
6153 }
6154#ifdef LLVM_ON_WIN32
6155 // On Windows, force a flush, since there may be multiple copies of
6156 // stderr and stdout in the file system, all with different buffers
6157 // but writing to the same device.
6158 fflush(stderr);
6159#endif
6160}
6161
Ted Kremenek04bb7162010-01-22 22:44:15 +00006162extern "C" {
6163
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00006164CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00006165 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00006166}
6167
6168} // end: extern "C"
Ted Kremenek59fc1e52011-04-18 22:47:10 +00006169