blob: 972beaf9e75ace83980efaa337151b7ed4a6e119 [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"
Ted Kremenek16c440a2010-01-15 20:35:54 +000016#include "CXCursor.h"
Ted Kremenek0a90d322010-11-17 23:24:11 +000017#include "CXTranslationUnit.h"
Ted Kremeneked122732010-11-16 01:56:27 +000018#include "CXString.h"
Ted Kremenek95f33552010-08-26 01:42:22 +000019#include "CXType.h"
Ted Kremeneka297de22010-01-25 22:34:44 +000020#include "CXSourceLocation.h"
Douglas Gregor5352ac02010-01-28 00:27:43 +000021#include "CIndexDiagnostic.h"
Argyrios Kyrtzidise397bf12011-11-03 19:02:34 +000022#include "CursorVisitor.h"
Ted Kremenekab188932010-01-05 19:32:54 +000023
Ted Kremenek04bb7162010-01-22 22:44:15 +000024#include "clang/Basic/Version.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000025
Steve Narofffb570422009-09-22 19:25:29 +000026#include "clang/AST/StmtVisitor.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000027#include "clang/Basic/Diagnostic.h"
28#include "clang/Frontend/ASTUnit.h"
29#include "clang/Frontend/CompilerInstance.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000030#include "clang/Frontend/FrontendDiagnostic.h"
Ted Kremenekd8210652010-01-06 23:43:31 +000031#include "clang/Lex/Lexer.h"
Douglas Gregordd3e5542011-05-04 00:14:37 +000032#include "clang/Lex/HeaderSearch.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000033#include "clang/Lex/PreprocessingRecord.h"
Douglas Gregor33e9abd2010-01-22 19:49:59 +000034#include "clang/Lex/Preprocessor.h"
Douglas Gregora67e03f2010-09-09 21:42:20 +000035#include "llvm/ADT/STLExtras.h"
Ted Kremenekd8c370c2010-11-02 23:10:24 +000036#include "llvm/ADT/Optional.h"
Douglas Gregorf5251602011-03-08 17:10:18 +000037#include "llvm/ADT/StringSwitch.h"
Argyrios Kyrtzidisb2c60b02012-03-01 19:45:56 +000038#include "llvm/Support/SaveAndRestore.h"
Daniel Dunbarc7df4f32010-08-18 18:43:14 +000039#include "llvm/Support/CrashRecoveryContext.h"
Daniel Dunbar48615ff2010-10-08 19:30:33 +000040#include "llvm/Support/PrettyStackTrace.h"
Douglas Gregor02465752009-10-16 21:24:31 +000041#include "llvm/Support/MemoryBuffer.h"
Douglas Gregor358559d2010-10-02 22:49:11 +000042#include "llvm/Support/raw_ostream.h"
Douglas Gregor7a07fcb2010-08-09 21:00:09 +000043#include "llvm/Support/Timer.h"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000044#include "llvm/Support/Mutex.h"
45#include "llvm/Support/Program.h"
46#include "llvm/Support/Signals.h"
47#include "llvm/Support/Threading.h"
Ted Kremenek37f1ea02010-11-15 23:11:54 +000048#include "llvm/Support/Compiler.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000049
Steve Naroff50398192009-08-28 15:28:48 +000050using namespace clang;
Ted Kremenek16c440a2010-01-15 20:35:54 +000051using namespace clang::cxcursor;
Ted Kremenekee4db4f2010-02-17 00:41:08 +000052using namespace clang::cxstring;
Argyrios Kyrtzidis9049cf62011-10-12 07:07:33 +000053using namespace clang::cxtu;
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 Kremeneka60ed472010-11-16 08:15:36 +000063 return D;
64}
65
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +000066cxtu::CXTUOwner::~CXTUOwner() {
67 if (TU)
68 clang_disposeTranslationUnit(TU);
69}
70
Ted Kremenekf0e23e82010-02-17 00:41:40 +000071/// \brief Compare two source ranges to determine their relative position in
Douglas Gregor33e9abd2010-01-22 19:49:59 +000072/// the translation unit.
Ted Kremenekf0e23e82010-02-17 00:41:40 +000073static RangeComparisonResult RangeCompare(SourceManager &SM,
74 SourceRange R1,
Douglas Gregor33e9abd2010-01-22 19:49:59 +000075 SourceRange R2) {
76 assert(R1.isValid() && "First range is invalid?");
77 assert(R2.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000078 if (R1.getEnd() != R2.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000079 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000080 return RangeBefore;
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000081 if (R2.getEnd() != R1.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000082 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000083 return RangeAfter;
84 return RangeOverlap;
85}
86
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000087/// \brief Determine if a source location falls within, before, or after a
88/// a given source range.
89static RangeComparisonResult LocationCompare(SourceManager &SM,
90 SourceLocation L, SourceRange R) {
91 assert(R.isValid() && "First range is invalid?");
92 assert(L.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000093 if (L == R.getBegin() || L == R.getEnd())
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000094 return RangeOverlap;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000095 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
96 return RangeBefore;
97 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
98 return RangeAfter;
99 return RangeOverlap;
100}
101
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000102/// \brief Translate a Clang source range into a CIndex source range.
103///
104/// Clang internally represents ranges where the end location points to the
105/// start of the token at the end. However, for external clients it is more
106/// useful to have a CXSourceRange be a proper half-open interval. This routine
107/// does the appropriate translation.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000108CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000109 const LangOptions &LangOpts,
Chris Lattner0a76aae2010-06-18 22:45:06 +0000110 const CharSourceRange &R) {
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000111 // We want the last character in this location, so we will adjust the
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000112 // location accordingly.
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000113 SourceLocation EndLoc = R.getEnd();
Douglas Gregora9b06d42010-11-09 06:24:54 +0000114 if (EndLoc.isValid() && EndLoc.isMacroID())
Chandler Carruthedc3dcc2011-07-25 16:56:02 +0000115 EndLoc = SM.getExpansionRange(EndLoc).second;
Chris Lattner0a76aae2010-06-18 22:45:06 +0000116 if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) {
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000117 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000118 EndLoc = EndLoc.getLocWithOffset(Length);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000119 }
120
121 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
122 R.getBegin().getRawEncoding(),
123 EndLoc.getRawEncoding() };
124 return Result;
125}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000126
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000127//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000128// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000129//===----------------------------------------------------------------------===//
130
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000131static SourceRange getRawCursorExtent(CXCursor C);
Douglas Gregor66537982010-11-17 17:14:07 +0000132static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
133
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000134
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000135RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000136 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000137}
138
Douglas Gregorb1373d02010-01-20 20:59:29 +0000139/// \brief Visit the given cursor and, if requested by the visitor,
140/// its children.
141///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000142/// \param Cursor the cursor to visit.
143///
144/// \param CheckRegionOfInterest if true, then the caller already checked that
145/// this cursor is within the region of interest.
146///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000147/// \returns true if the visitation should be aborted, false if it
148/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000149bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000150 if (clang_isInvalid(Cursor.kind))
151 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000152
Douglas Gregorb1373d02010-01-20 20:59:29 +0000153 if (clang_isDeclaration(Cursor.kind)) {
154 Decl *D = getCursorDecl(Cursor);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +0000155 if (!D) {
156 assert(0 && "Invalid declaration cursor");
157 return true; // abort.
158 }
159
Argyrios Kyrtzidis65ab9072011-09-26 19:05:37 +0000160 // Ignore implicit declarations, unless it's an objc method because
161 // currently we should report implicit methods for properties when indexing.
162 if (D->isImplicit() && !isa<ObjCMethodDecl>(D))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000163 return false;
164 }
165
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000166 // If we have a range of interest, and this cursor doesn't intersect with it,
167 // we're done.
168 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000169 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000170 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000171 return false;
172 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000173
Douglas Gregorb1373d02010-01-20 20:59:29 +0000174 switch (Visitor(Cursor, Parent, ClientData)) {
175 case CXChildVisit_Break:
176 return true;
177
178 case CXChildVisit_Continue:
179 return false;
180
181 case CXChildVisit_Recurse:
182 return VisitChildren(Cursor);
183 }
184
David Blaikie7530c032012-01-17 06:56:22 +0000185 llvm_unreachable("Invalid CXChildVisitResult!");
Douglas Gregorb1373d02010-01-20 20:59:29 +0000186}
187
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000188static bool visitPreprocessedEntitiesInRange(SourceRange R,
189 PreprocessingRecord &PPRec,
190 CursorVisitor &Visitor) {
191 SourceManager &SM = Visitor.getASTUnit()->getSourceManager();
192 FileID FID;
193
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +0000194 if (!Visitor.shouldVisitIncludedEntities()) {
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000195 // If the begin/end of the range lie in the same FileID, do the optimization
196 // where we skip preprocessed entities that do not come from the same FileID.
Argyrios Kyrtzidisacca4112011-12-21 16:56:38 +0000197 FID = SM.getFileID(SM.getFileLoc(R.getBegin()));
198 if (FID != SM.getFileID(SM.getFileLoc(R.getEnd())))
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000199 FID = FileID();
200 }
201
202 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
203 Entities = PPRec.getPreprocessedEntitiesInRange(R);
204 return Visitor.visitPreprocessedEntities(Entities.first, Entities.second,
205 PPRec, FID);
206}
207
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000208void CursorVisitor::visitFileRegion() {
209 if (RegionOfInterest.isInvalid())
210 return;
211
212 ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData);
213 SourceManager &SM = Unit->getSourceManager();
214
215 std::pair<FileID, unsigned>
216 Begin = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getBegin())),
217 End = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getEnd()));
218
219 if (End.first != Begin.first) {
220 // If the end does not reside in the same file, try to recover by
221 // picking the end of the file of begin location.
222 End.first = Begin.first;
223 End.second = SM.getFileIDSize(Begin.first);
224 }
225
226 assert(Begin.first == End.first);
227 if (Begin.second > End.second)
228 return;
229
230 FileID File = Begin.first;
231 unsigned Offset = Begin.second;
232 unsigned Length = End.second - Begin.second;
233
Argyrios Kyrtzidisb49e7282011-11-29 03:14:11 +0000234 if (!VisitDeclsOnly && !VisitPreprocessorLast)
235 if (visitPreprocessedEntitiesInRegion())
236 return; // visitation break.
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000237
238 visitDeclsFromFileRegion(File, Offset, Length);
239
Argyrios Kyrtzidisb49e7282011-11-29 03:14:11 +0000240 if (!VisitDeclsOnly && VisitPreprocessorLast)
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000241 visitPreprocessedEntitiesInRegion();
242}
243
Argyrios Kyrtzidise2079cf2011-11-16 08:58:54 +0000244static bool isInLexicalContext(Decl *D, DeclContext *DC) {
245 if (!DC)
246 return false;
247
248 for (DeclContext *DeclDC = D->getLexicalDeclContext();
249 DeclDC; DeclDC = DeclDC->getLexicalParent()) {
250 if (DeclDC == DC)
251 return true;
252 }
253 return false;
254}
255
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000256void CursorVisitor::visitDeclsFromFileRegion(FileID File,
257 unsigned Offset, unsigned Length) {
258 ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData);
259 SourceManager &SM = Unit->getSourceManager();
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000260 SourceRange Range = RegionOfInterest;
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000261
262 SmallVector<Decl *, 16> Decls;
263 Unit->findFileRegionDecls(File, Offset, Length, Decls);
264
265 // If we didn't find any file level decls for the file, try looking at the
266 // file that it was included from.
Argyrios Kyrtzidisc14a03d2011-11-23 20:27:36 +0000267 while (Decls.empty() || Decls.front()->isTopLevelDeclInObjCContainer()) {
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000268 bool Invalid = false;
269 const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid);
270 if (Invalid)
271 return;
272
273 SourceLocation Outer;
274 if (SLEntry.isFile())
275 Outer = SLEntry.getFile().getIncludeLoc();
276 else
277 Outer = SLEntry.getExpansion().getExpansionLocStart();
278 if (Outer.isInvalid())
279 return;
280
281 llvm::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer);
282 Length = 0;
283 Unit->findFileRegionDecls(File, Offset, Length, Decls);
284 }
285
286 assert(!Decls.empty());
287
288 bool VisitedAtLeastOnce = false;
Argyrios Kyrtzidise2079cf2011-11-16 08:58:54 +0000289 DeclContext *CurDC = 0;
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000290 SmallVector<Decl *, 16>::iterator DIt = Decls.begin();
291 for (SmallVector<Decl *, 16>::iterator DE = Decls.end(); DIt != DE; ++DIt) {
292 Decl *D = *DIt;
Argyrios Kyrtzidised8bef42011-11-28 22:38:07 +0000293 if (D->getSourceRange().isInvalid())
294 continue;
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000295
Argyrios Kyrtzidise2079cf2011-11-16 08:58:54 +0000296 if (isInLexicalContext(D, CurDC))
297 continue;
298
299 CurDC = dyn_cast<DeclContext>(D);
300
Argyrios Kyrtzidise2079cf2011-11-16 08:58:54 +0000301 if (TagDecl *TD = dyn_cast<TagDecl>(D))
302 if (!TD->isFreeStanding())
303 continue;
304
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000305 RangeComparisonResult CompRes = RangeCompare(SM, D->getSourceRange(),Range);
306 if (CompRes == RangeBefore)
307 continue;
308 if (CompRes == RangeAfter)
309 break;
310
311 assert(CompRes == RangeOverlap);
312 VisitedAtLeastOnce = true;
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +0000313
314 if (isa<ObjCContainerDecl>(D)) {
315 FileDI_current = &DIt;
316 FileDE_current = DE;
317 } else {
318 FileDI_current = 0;
319 }
320
Argyrios Kyrtzidisba986172011-11-03 19:02:28 +0000321 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000322 break;
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000323 }
324
325 if (VisitedAtLeastOnce)
326 return;
327
328 // No Decls overlapped with the range. Move up the lexical context until there
329 // is a context that contains the range or we reach the translation unit
330 // level.
331 DeclContext *DC = DIt == Decls.begin() ? (*DIt)->getLexicalDeclContext()
332 : (*(DIt-1))->getLexicalDeclContext();
333
334 while (DC && !DC->isTranslationUnit()) {
335 Decl *D = cast<Decl>(DC);
336 SourceRange CurDeclRange = D->getSourceRange();
337 if (CurDeclRange.isInvalid())
338 break;
339
340 if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) {
Argyrios Kyrtzidisba986172011-11-03 19:02:28 +0000341 Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true);
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000342 break;
343 }
344
345 DC = D->getLexicalDeclContext();
346 }
347}
348
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000349bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
Argyrios Kyrtzidisb49e7282011-11-29 03:14:11 +0000350 if (!AU->getPreprocessor().getPreprocessingRecord())
351 return false;
352
Douglas Gregor788f5a12010-03-20 00:41:21 +0000353 PreprocessingRecord &PPRec
Ted Kremeneka60ed472010-11-16 08:15:36 +0000354 = *AU->getPreprocessor().getPreprocessingRecord();
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000355 SourceManager &SM = AU->getSourceManager();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000356
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000357 if (RegionOfInterest.isValid()) {
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +0000358 SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000359 SourceLocation B = MappedRange.getBegin();
360 SourceLocation E = MappedRange.getEnd();
361
362 if (AU->isInPreambleFileID(B)) {
363 if (SM.isLoadedSourceLocation(E))
364 return visitPreprocessedEntitiesInRange(SourceRange(B, E),
365 PPRec, *this);
366
367 // Beginning of range lies in the preamble but it also extends beyond
368 // it into the main file. Split the range into 2 parts, one covering
369 // the preamble and another covering the main file. This allows subsequent
370 // calls to visitPreprocessedEntitiesInRange to accept a source range that
371 // lies in the same FileID, allowing it to skip preprocessed entities that
372 // do not come from the same FileID.
373 bool breaked =
374 visitPreprocessedEntitiesInRange(
375 SourceRange(B, AU->getEndOfPreambleFileID()),
376 PPRec, *this);
377 if (breaked) return true;
378 return visitPreprocessedEntitiesInRange(
379 SourceRange(AU->getStartOfMainFileID(), E),
380 PPRec, *this);
381 }
382
383 return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this);
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000384 }
385
Douglas Gregor788f5a12010-03-20 00:41:21 +0000386 bool OnlyLocalDecls
Douglas Gregor32038bb2010-12-21 19:07:48 +0000387 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
388
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000389 if (OnlyLocalDecls)
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000390 return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(),
391 PPRec);
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000392
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000393 return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec);
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000394}
395
396template<typename InputIterator>
397bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000398 InputIterator Last,
399 PreprocessingRecord &PPRec,
400 FileID FID) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000401 for (; First != Last; ++First) {
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000402 if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID))
403 continue;
404
405 PreprocessedEntity *PPE = *First;
406 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000407 if (Visit(MakeMacroExpansionCursor(ME, TU)))
408 return true;
409
410 continue;
411 }
412
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000413 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(PPE)) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000414 if (Visit(MakeMacroDefinitionCursor(MD, TU)))
415 return true;
416
417 continue;
418 }
419
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000420 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000421 if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
422 return true;
423
424 continue;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000425 }
426 }
427
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000428 return false;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000429}
430
Douglas Gregorb1373d02010-01-20 20:59:29 +0000431/// \brief Visit the children of the given cursor.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000432///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000433/// \returns true if the visitation should be aborted, false if it
434/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000435bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregorc314aa42011-03-02 19:17:03 +0000436 if (clang_isReference(Cursor.kind) &&
437 Cursor.kind != CXCursor_CXXBaseSpecifier) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000438 // By definition, references have no children.
439 return false;
440 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000441
442 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000443 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000444 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000445
Douglas Gregorb1373d02010-01-20 20:59:29 +0000446 if (clang_isDeclaration(Cursor.kind)) {
447 Decl *D = getCursorDecl(Cursor);
Douglas Gregor06d9b1a2011-04-14 21:41:34 +0000448 if (!D)
449 return false;
450
Ted Kremenek539311e2010-02-18 18:47:01 +0000451 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000452 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000453
Douglas Gregor06d9b1a2011-04-14 21:41:34 +0000454 if (clang_isStatement(Cursor.kind)) {
455 if (Stmt *S = getCursorStmt(Cursor))
456 return Visit(S);
457
458 return false;
459 }
460
461 if (clang_isExpression(Cursor.kind)) {
462 if (Expr *E = getCursorExpr(Cursor))
463 return Visit(E);
464
465 return false;
466 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000467
Douglas Gregorb1373d02010-01-20 20:59:29 +0000468 if (clang_isTranslationUnit(Cursor.kind)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000469 CXTranslationUnit tu = getCursorTU(Cursor);
470 ASTUnit *CXXUnit = static_cast<ASTUnit*>(tu->TUData);
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000471
472 int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
473 for (unsigned I = 0; I != 2; ++I) {
474 if (VisitOrder[I]) {
475 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
476 RegionOfInterest.isInvalid()) {
477 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
478 TLEnd = CXXUnit->top_level_end();
479 TL != TLEnd; ++TL) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000480 if (Visit(MakeCXCursor(*TL, tu, RegionOfInterest), true))
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000481 return true;
482 }
483 } else if (VisitDeclContext(
484 CXXUnit->getASTContext().getTranslationUnitDecl()))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000485 return true;
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000486 continue;
Douglas Gregor7b691f332010-01-20 21:13:59 +0000487 }
Bob Wilson3178cb62010-03-19 03:57:57 +0000488
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000489 // Walk the preprocessing record.
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000490 if (CXXUnit->getPreprocessor().getPreprocessingRecord())
491 visitPreprocessedEntitiesInRegion();
Douglas Gregor0396f462010-03-19 05:22:59 +0000492 }
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000493
Douglas Gregor7b691f332010-01-20 21:13:59 +0000494 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000495 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000496
Douglas Gregorc314aa42011-03-02 19:17:03 +0000497 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
498 if (CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
499 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
500 return Visit(BaseTSInfo->getTypeLoc());
501 }
502 }
503 }
Argyrios Kyrtzidis221d5a52011-09-13 18:49:56 +0000504
505 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
506 IBOutletCollectionAttr *A =
507 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
508 if (const ObjCInterfaceType *InterT = A->getInterface()->getAs<ObjCInterfaceType>())
509 return Visit(cxcursor::MakeCursorObjCClassRef(InterT->getInterface(),
510 A->getInterfaceLoc(), TU));
511 }
512
Douglas Gregorb1373d02010-01-20 20:59:29 +0000513 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000514 return false;
515}
516
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000517bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
Douglas Gregor13c8ccb2011-04-22 23:49:24 +0000518 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
519 if (Visit(TSInfo->getTypeLoc()))
520 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000521
Ted Kremenek664cffd2010-07-22 11:30:19 +0000522 if (Stmt *Body = B->getBody())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000523 return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest));
Ted Kremenek664cffd2010-07-22 11:30:19 +0000524
525 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000526}
527
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000528llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
529 if (RegionOfInterest.isValid()) {
Douglas Gregor66537982010-11-17 17:14:07 +0000530 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000531 if (Range.isInvalid())
532 return llvm::Optional<bool>();
Douglas Gregor66537982010-11-17 17:14:07 +0000533
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000534 switch (CompareRegionOfInterest(Range)) {
535 case RangeBefore:
536 // This declaration comes before the region of interest; skip it.
537 return llvm::Optional<bool>();
538
539 case RangeAfter:
540 // This declaration comes after the region of interest; we're done.
541 return false;
542
543 case RangeOverlap:
544 // This declaration overlaps the region of interest; visit it.
545 break;
546 }
547 }
548 return true;
549}
550
551bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
552 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
553
554 // FIXME: Eventually remove. This part of a hack to support proper
555 // iteration over all Decls contained lexically within an ObjC container.
556 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
557 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
558
559 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000560 Decl *D = *I;
561 if (D->getLexicalDeclContext() != DC)
562 continue;
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000563 CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
Argyrios Kyrtzidis1836db02012-02-04 01:04:58 +0000564
565 // FIXME: ObjCClassRef/ObjCProtocolRef for forward class/protocol
566 // declarations is a mismatch with the compiler semantics.
567 if (Cursor.kind == CXCursor_ObjCInterfaceDecl) {
568 ObjCInterfaceDecl *ID = cast<ObjCInterfaceDecl>(D);
569 if (!ID->isThisDeclarationADefinition())
570 Cursor = MakeCursorObjCClassRef(ID, ID->getLocation(), TU);
571
572 } else if (Cursor.kind == CXCursor_ObjCProtocolDecl) {
573 ObjCProtocolDecl *PD = cast<ObjCProtocolDecl>(D);
574 if (!PD->isThisDeclarationADefinition())
575 Cursor = MakeCursorObjCProtocolRef(PD, PD->getLocation(), TU);
576 }
577
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000578 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
579 if (!V.hasValue())
580 continue;
581 if (!V.getValue())
582 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000583 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000584 return true;
585 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000586 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000587}
588
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000589bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
590 llvm_unreachable("Translation units are visited directly by Visit()");
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000591}
592
Richard Smith162e1c12011-04-15 14:24:37 +0000593bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
594 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
595 return Visit(TSInfo->getTypeLoc());
596
597 return false;
598}
599
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000600bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
601 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
602 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000603
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000604 return false;
605}
606
607bool CursorVisitor::VisitTagDecl(TagDecl *D) {
608 return VisitDeclContext(D);
609}
610
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000611bool CursorVisitor::VisitClassTemplateSpecializationDecl(
612 ClassTemplateSpecializationDecl *D) {
613 bool ShouldVisitBody = false;
614 switch (D->getSpecializationKind()) {
615 case TSK_Undeclared:
616 case TSK_ImplicitInstantiation:
617 // Nothing to visit
618 return false;
619
620 case TSK_ExplicitInstantiationDeclaration:
621 case TSK_ExplicitInstantiationDefinition:
622 break;
623
624 case TSK_ExplicitSpecialization:
625 ShouldVisitBody = true;
626 break;
627 }
628
629 // Visit the template arguments used in the specialization.
630 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
631 TypeLoc TL = SpecType->getTypeLoc();
632 if (TemplateSpecializationTypeLoc *TSTLoc
633 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
634 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
635 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
636 return true;
637 }
638 }
639
640 if (ShouldVisitBody && VisitCXXRecordDecl(D))
641 return true;
642
643 return false;
644}
645
Douglas Gregor74dbe642010-08-31 19:31:58 +0000646bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
647 ClassTemplatePartialSpecializationDecl *D) {
648 // FIXME: Visit the "outer" template parameter lists on the TagDecl
649 // before visiting these template parameters.
650 if (VisitTemplateParameters(D->getTemplateParameters()))
651 return true;
652
653 // Visit the partial specialization arguments.
654 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
655 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
656 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
657 return true;
658
659 return VisitCXXRecordDecl(D);
660}
661
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000662bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000663 // Visit the default argument.
664 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
665 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
666 if (Visit(DefArg->getTypeLoc()))
667 return true;
668
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000669 return false;
670}
671
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000672bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
673 if (Expr *Init = D->getInitExpr())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000674 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000675 return false;
676}
677
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000678bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
679 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
680 if (Visit(TSInfo->getTypeLoc()))
681 return true;
682
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000683 // Visit the nested-name-specifier, if present.
684 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
685 if (VisitNestedNameSpecifierLoc(QualifierLoc))
686 return true;
687
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000688 return false;
689}
690
Douglas Gregora67e03f2010-09-09 21:42:20 +0000691/// \brief Compare two base or member initializers based on their source order.
Sean Huntcbb67482011-01-08 20:30:50 +0000692static int CompareCXXCtorInitializers(const void* Xp, const void *Yp) {
693 CXXCtorInitializer const * const *X
694 = static_cast<CXXCtorInitializer const * const *>(Xp);
695 CXXCtorInitializer const * const *Y
696 = static_cast<CXXCtorInitializer const * const *>(Yp);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000697
698 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
699 return -1;
700 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
701 return 1;
702 else
703 return 0;
704}
705
Douglas Gregorb1373d02010-01-20 20:59:29 +0000706bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000707 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
708 // Visit the function declaration's syntactic components in the order
709 // written. This requires a bit of work.
Abramo Bagnara723df242010-12-14 22:11:44 +0000710 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
Douglas Gregor01829d32010-08-31 14:41:23 +0000711 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
712
713 // If we have a function declared directly (without the use of a typedef),
714 // visit just the return type. Otherwise, just visit the function's type
715 // now.
716 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
717 (!FTL && Visit(TL)))
718 return true;
719
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000720 // Visit the nested-name-specifier, if present.
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000721 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
722 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000723 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000724
725 // Visit the declaration name.
726 if (VisitDeclarationNameInfo(ND->getNameInfo()))
727 return true;
728
729 // FIXME: Visit explicitly-specified template arguments!
730
731 // Visit the function parameters, if we have a function type.
732 if (FTL && VisitFunctionTypeLoc(*FTL, true))
733 return true;
734
735 // FIXME: Attributes?
736 }
737
Sean Hunt10620eb2011-05-06 20:44:56 +0000738 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
Douglas Gregora67e03f2010-09-09 21:42:20 +0000739 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
740 // Find the initializers that were written in the source.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000741 SmallVector<CXXCtorInitializer *, 4> WrittenInits;
Douglas Gregora67e03f2010-09-09 21:42:20 +0000742 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
743 IEnd = Constructor->init_end();
744 I != IEnd; ++I) {
745 if (!(*I)->isWritten())
746 continue;
747
748 WrittenInits.push_back(*I);
749 }
750
751 // Sort the initializers in source order
752 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
Sean Huntcbb67482011-01-08 20:30:50 +0000753 &CompareCXXCtorInitializers);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000754
755 // Visit the initializers in source order
756 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
Sean Huntcbb67482011-01-08 20:30:50 +0000757 CXXCtorInitializer *Init = WrittenInits[I];
Francois Pichet00eb3f92010-12-04 09:14:42 +0000758 if (Init->isAnyMemberInitializer()) {
759 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
Douglas Gregora67e03f2010-09-09 21:42:20 +0000760 Init->getMemberLocation(), TU)))
761 return true;
Douglas Gregor76852c22011-11-01 01:16:03 +0000762 } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) {
763 if (Visit(TInfo->getTypeLoc()))
Douglas Gregora67e03f2010-09-09 21:42:20 +0000764 return true;
765 }
766
767 // Visit the initializer value.
768 if (Expr *Initializer = Init->getInit())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000769 if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
Douglas Gregora67e03f2010-09-09 21:42:20 +0000770 return true;
771 }
772 }
773
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000774 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
Douglas Gregora67e03f2010-09-09 21:42:20 +0000775 return true;
776 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000777
Douglas Gregorb1373d02010-01-20 20:59:29 +0000778 return false;
779}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000780
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000781bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
782 if (VisitDeclaratorDecl(D))
783 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000784
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000785 if (Expr *BitWidth = D->getBitWidth())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000786 return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000787
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000788 return false;
789}
790
791bool CursorVisitor::VisitVarDecl(VarDecl *D) {
792 if (VisitDeclaratorDecl(D))
793 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000794
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000795 if (Expr *Init = D->getInit())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000796 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000797
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000798 return false;
799}
800
Douglas Gregor84b51d72010-09-01 20:16:53 +0000801bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
802 if (VisitDeclaratorDecl(D))
803 return true;
804
805 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
806 if (Expr *DefArg = D->getDefaultArgument())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000807 return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
Douglas Gregor84b51d72010-09-01 20:16:53 +0000808
809 return false;
810}
811
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000812bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
813 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
814 // before visiting these template parameters.
815 if (VisitTemplateParameters(D->getTemplateParameters()))
816 return true;
817
818 return VisitFunctionDecl(D->getTemplatedDecl());
819}
820
Douglas Gregor39d6f072010-08-31 19:02:00 +0000821bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
822 // FIXME: Visit the "outer" template parameter lists on the TagDecl
823 // before visiting these template parameters.
824 if (VisitTemplateParameters(D->getTemplateParameters()))
825 return true;
826
827 return VisitCXXRecordDecl(D->getTemplatedDecl());
828}
829
Douglas Gregor84b51d72010-09-01 20:16:53 +0000830bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
831 if (VisitTemplateParameters(D->getTemplateParameters()))
832 return true;
833
834 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
835 VisitTemplateArgumentLoc(D->getDefaultArgument()))
836 return true;
837
838 return false;
839}
840
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000841bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000842 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
843 if (Visit(TSInfo->getTypeLoc()))
844 return true;
845
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000846 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000847 PEnd = ND->param_end();
848 P != PEnd; ++P) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000849 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000850 return true;
851 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000852
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000853 if (ND->isThisDeclarationADefinition() &&
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000854 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000855 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000856
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000857 return false;
858}
859
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +0000860template <typename DeclIt>
861static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current,
862 SourceManager &SM, SourceLocation EndLoc,
863 SmallVectorImpl<Decl *> &Decls) {
864 DeclIt next = *DI_current;
865 while (++next != DE_current) {
866 Decl *D_next = *next;
867 if (!D_next)
868 break;
869 SourceLocation L = D_next->getLocStart();
870 if (!L.isValid())
871 break;
872 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
873 *DI_current = next;
874 Decls.push_back(D_next);
875 continue;
876 }
877 break;
878 }
879}
880
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000881namespace {
882 struct ContainerDeclsSort {
883 SourceManager &SM;
884 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
885 bool operator()(Decl *A, Decl *B) {
886 SourceLocation L_A = A->getLocStart();
887 SourceLocation L_B = B->getLocStart();
888 assert(L_A.isValid() && L_B.isValid());
889 return SM.isBeforeInTranslationUnit(L_A, L_B);
890 }
891 };
892}
893
Douglas Gregora59e3902010-01-21 23:27:09 +0000894bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000895 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
896 // an @implementation can lexically contain Decls that are not properly
897 // nested in the AST. When we identify such cases, we need to retrofit
898 // this nesting here.
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +0000899 if (!DI_current && !FileDI_current)
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000900 return VisitDeclContext(D);
901
902 // Scan the Decls that immediately come after the container
903 // in the current DeclContext. If any fall within the
904 // container's lexical region, stash them into a vector
905 // for later processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000906 SmallVector<Decl *, 24> DeclsInContainer;
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000907 SourceLocation EndLoc = D->getSourceRange().getEnd();
Ted Kremeneka60ed472010-11-16 08:15:36 +0000908 SourceManager &SM = AU->getSourceManager();
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000909 if (EndLoc.isValid()) {
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +0000910 if (DI_current) {
911 addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc,
912 DeclsInContainer);
913 } else {
914 addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc,
915 DeclsInContainer);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000916 }
917 }
918
919 // The common case.
920 if (DeclsInContainer.empty())
921 return VisitDeclContext(D);
922
923 // Get all the Decls in the DeclContext, and sort them with the
924 // additional ones we've collected. Then visit them.
925 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
926 I!=E; ++I) {
927 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000928 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
929 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000930 continue;
931 DeclsInContainer.push_back(subDecl);
932 }
933
934 // Now sort the Decls so that they appear in lexical order.
935 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
936 ContainerDeclsSort(SM));
937
938 // Now visit the decls.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000939 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000940 E = DeclsInContainer.end(); I != E; ++I) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000941 CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000942 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
943 if (!V.hasValue())
944 continue;
945 if (!V.getValue())
946 return false;
947 if (Visit(Cursor, true))
948 return true;
949 }
950 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000951}
952
Douglas Gregorb1373d02010-01-20 20:59:29 +0000953bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000954 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
955 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000956 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000957
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000958 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
959 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
960 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000961 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000962 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000963
Douglas Gregora59e3902010-01-21 23:27:09 +0000964 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000965}
966
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000967bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000968 if (!PID->isThisDeclarationADefinition())
969 return Visit(MakeCursorObjCProtocolRef(PID, PID->getLocation(), TU));
970
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000971 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
972 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
973 E = PID->protocol_end(); I != E; ++I, ++PL)
974 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
975 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000976
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000977 return VisitObjCContainerDecl(PID);
978}
979
Ted Kremenek23173d72010-05-18 21:09:07 +0000980bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000981 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000982 return true;
983
Ted Kremenek23173d72010-05-18 21:09:07 +0000984 // FIXME: This implements a workaround with @property declarations also being
985 // installed in the DeclContext for the @interface. Eventually this code
986 // should be removed.
987 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
988 if (!CDecl || !CDecl->IsClassExtension())
989 return false;
990
991 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
992 if (!ID)
993 return false;
994
995 IdentifierInfo *PropertyId = PD->getIdentifier();
996 ObjCPropertyDecl *prevDecl =
997 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
998
999 if (!prevDecl)
1000 return false;
1001
1002 // Visit synthesized methods since they will be skipped when visiting
1003 // the @interface.
1004 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +00001005 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001006 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
Ted Kremenek23173d72010-05-18 21:09:07 +00001007 return true;
1008
1009 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +00001010 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001011 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
Ted Kremenek23173d72010-05-18 21:09:07 +00001012 return true;
1013
1014 return false;
1015}
1016
Douglas Gregorb1373d02010-01-20 20:59:29 +00001017bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Douglas Gregor375bb142011-12-27 22:43:10 +00001018 if (!D->isThisDeclarationADefinition()) {
1019 // Forward declaration is treated like a reference.
1020 return Visit(MakeCursorObjCClassRef(D, D->getLocation(), TU));
1021 }
1022
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001023 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +00001024 if (D->getSuperClass() &&
1025 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001026 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001027 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001028 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001029
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001030 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1031 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1032 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001033 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001034 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001035
Douglas Gregora59e3902010-01-21 23:27:09 +00001036 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001037}
1038
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001039bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1040 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001041}
1042
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001043bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +00001044 // 'ID' could be null when dealing with invalid code.
1045 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1046 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1047 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001048
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001049 return VisitObjCImplDecl(D);
1050}
1051
1052bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1053#if 0
1054 // Issue callbacks for super class.
1055 // FIXME: No source location information!
1056 if (D->getSuperClass() &&
1057 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001058 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001059 TU)))
1060 return true;
1061#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001062
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001063 return VisitObjCImplDecl(D);
1064}
1065
Douglas Gregora4ffd852010-11-17 01:03:52 +00001066bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1067 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1068 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1069
1070 return false;
1071}
1072
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001073bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1074 return VisitDeclContext(D);
1075}
1076
Douglas Gregor69319002010-08-31 23:48:11 +00001077bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001078 // Visit nested-name-specifier.
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00001079 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1080 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001081 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001082
1083 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1084 D->getTargetNameLoc(), TU));
1085}
1086
Douglas Gregor7e242562010-09-01 19:52:22 +00001087bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001088 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001089 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1090 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001091 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001092 }
Douglas Gregor7e242562010-09-01 19:52:22 +00001093
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001094 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1095 return true;
1096
Douglas Gregor7e242562010-09-01 19:52:22 +00001097 return VisitDeclarationNameInfo(D->getNameInfo());
1098}
1099
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001100bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001101 // Visit nested-name-specifier.
Douglas Gregordb992412011-02-25 16:33:46 +00001102 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1103 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001104 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001105
1106 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1107 D->getIdentLocation(), TU));
1108}
1109
Douglas Gregor7e242562010-09-01 19:52:22 +00001110bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001111 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001112 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1113 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001114 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001115 }
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001116
Douglas Gregor7e242562010-09-01 19:52:22 +00001117 return VisitDeclarationNameInfo(D->getNameInfo());
1118}
1119
1120bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1121 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001122 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001123 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1124 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001125 return true;
1126
Douglas Gregor7e242562010-09-01 19:52:22 +00001127 return false;
1128}
1129
Douglas Gregor01829d32010-08-31 14:41:23 +00001130bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1131 switch (Name.getName().getNameKind()) {
1132 case clang::DeclarationName::Identifier:
1133 case clang::DeclarationName::CXXLiteralOperatorName:
1134 case clang::DeclarationName::CXXOperatorName:
1135 case clang::DeclarationName::CXXUsingDirective:
1136 return false;
1137
1138 case clang::DeclarationName::CXXConstructorName:
1139 case clang::DeclarationName::CXXDestructorName:
1140 case clang::DeclarationName::CXXConversionFunctionName:
1141 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1142 return Visit(TSInfo->getTypeLoc());
1143 return false;
1144
1145 case clang::DeclarationName::ObjCZeroArgSelector:
1146 case clang::DeclarationName::ObjCOneArgSelector:
1147 case clang::DeclarationName::ObjCMultiArgSelector:
1148 // FIXME: Per-identifier location info?
1149 return false;
1150 }
David Blaikie7530c032012-01-17 06:56:22 +00001151
1152 llvm_unreachable("Invalid DeclarationName::Kind!");
Douglas Gregor01829d32010-08-31 14:41:23 +00001153}
1154
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001155bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1156 SourceRange Range) {
1157 // FIXME: This whole routine is a hack to work around the lack of proper
1158 // source information in nested-name-specifiers (PR5791). Since we do have
1159 // a beginning source location, we can visit the first component of the
1160 // nested-name-specifier, if it's a single-token component.
1161 if (!NNS)
1162 return false;
1163
1164 // Get the first component in the nested-name-specifier.
1165 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1166 NNS = Prefix;
1167
1168 switch (NNS->getKind()) {
1169 case NestedNameSpecifier::Namespace:
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001170 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1171 TU));
1172
Douglas Gregor14aba762011-02-24 02:36:08 +00001173 case NestedNameSpecifier::NamespaceAlias:
1174 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1175 Range.getBegin(), TU));
1176
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001177 case NestedNameSpecifier::TypeSpec: {
1178 // If the type has a form where we know that the beginning of the source
1179 // range matches up with a reference cursor. Visit the appropriate reference
1180 // cursor.
John McCallf4c73712011-01-19 06:33:43 +00001181 const Type *T = NNS->getAsType();
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001182 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1183 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1184 if (const TagType *Tag = dyn_cast<TagType>(T))
1185 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1186 if (const TemplateSpecializationType *TST
1187 = dyn_cast<TemplateSpecializationType>(T))
1188 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1189 break;
1190 }
1191
1192 case NestedNameSpecifier::TypeSpecWithTemplate:
1193 case NestedNameSpecifier::Global:
1194 case NestedNameSpecifier::Identifier:
1195 break;
1196 }
1197
1198 return false;
1199}
1200
Douglas Gregordc355712011-02-25 00:36:19 +00001201bool
1202CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001203 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
Douglas Gregordc355712011-02-25 00:36:19 +00001204 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1205 Qualifiers.push_back(Qualifier);
1206
1207 while (!Qualifiers.empty()) {
1208 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1209 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1210 switch (NNS->getKind()) {
1211 case NestedNameSpecifier::Namespace:
1212 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001213 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001214 TU)))
1215 return true;
1216
1217 break;
1218
1219 case NestedNameSpecifier::NamespaceAlias:
1220 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001221 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001222 TU)))
1223 return true;
1224
1225 break;
1226
1227 case NestedNameSpecifier::TypeSpec:
1228 case NestedNameSpecifier::TypeSpecWithTemplate:
1229 if (Visit(Q.getTypeLoc()))
1230 return true;
1231
1232 break;
1233
1234 case NestedNameSpecifier::Global:
1235 case NestedNameSpecifier::Identifier:
1236 break;
1237 }
1238 }
1239
1240 return false;
1241}
1242
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001243bool CursorVisitor::VisitTemplateParameters(
1244 const TemplateParameterList *Params) {
1245 if (!Params)
1246 return false;
1247
1248 for (TemplateParameterList::const_iterator P = Params->begin(),
1249 PEnd = Params->end();
1250 P != PEnd; ++P) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001251 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001252 return true;
1253 }
1254
1255 return false;
1256}
1257
Douglas Gregor0b36e612010-08-31 20:37:03 +00001258bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1259 switch (Name.getKind()) {
1260 case TemplateName::Template:
1261 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1262
1263 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001264 // Visit the overloaded template set.
1265 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1266 return true;
1267
Douglas Gregor0b36e612010-08-31 20:37:03 +00001268 return false;
1269
1270 case TemplateName::DependentTemplate:
1271 // FIXME: Visit nested-name-specifier.
1272 return false;
1273
1274 case TemplateName::QualifiedTemplate:
1275 // FIXME: Visit nested-name-specifier.
1276 return Visit(MakeCursorTemplateRef(
1277 Name.getAsQualifiedTemplateName()->getDecl(),
1278 Loc, TU));
John McCall14606042011-06-30 08:33:18 +00001279
1280 case TemplateName::SubstTemplateTemplateParm:
1281 return Visit(MakeCursorTemplateRef(
1282 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1283 Loc, TU));
Douglas Gregor1aee05d2011-01-15 06:45:20 +00001284
1285 case TemplateName::SubstTemplateTemplateParmPack:
1286 return Visit(MakeCursorTemplateRef(
1287 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1288 Loc, TU));
Douglas Gregor0b36e612010-08-31 20:37:03 +00001289 }
David Blaikie7530c032012-01-17 06:56:22 +00001290
1291 llvm_unreachable("Invalid TemplateName::Kind!");
Douglas Gregor0b36e612010-08-31 20:37:03 +00001292}
1293
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001294bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1295 switch (TAL.getArgument().getKind()) {
1296 case TemplateArgument::Null:
1297 case TemplateArgument::Integral:
Douglas Gregor87dd6972010-12-20 16:52:59 +00001298 case TemplateArgument::Pack:
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001299 return false;
1300
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001301 case TemplateArgument::Type:
1302 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1303 return Visit(TSInfo->getTypeLoc());
1304 return false;
1305
1306 case TemplateArgument::Declaration:
1307 if (Expr *E = TAL.getSourceDeclExpression())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001308 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001309 return false;
1310
1311 case TemplateArgument::Expression:
1312 if (Expr *E = TAL.getSourceExpression())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001313 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001314 return false;
1315
1316 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001317 case TemplateArgument::TemplateExpansion:
Douglas Gregorb6744ef2011-03-02 17:09:35 +00001318 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1319 return true;
1320
Douglas Gregora7fc9012011-01-05 18:58:31 +00001321 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
Douglas Gregor0b36e612010-08-31 20:37:03 +00001322 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001323 }
David Blaikie7530c032012-01-17 06:56:22 +00001324
1325 llvm_unreachable("Invalid TemplateArgument::Kind!");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001326}
1327
Ted Kremeneka0536d82010-05-07 01:04:29 +00001328bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1329 return VisitDeclContext(D);
1330}
1331
Douglas Gregor01829d32010-08-31 14:41:23 +00001332bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1333 return Visit(TL.getUnqualifiedLoc());
1334}
1335
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001336bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00001337 ASTContext &Context = AU->getASTContext();
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001338
1339 // Some builtin types (such as Objective-C's "id", "sel", and
1340 // "Class") have associated declarations. Create cursors for those.
1341 QualType VisitType;
John McCalle0a22d02011-10-18 21:02:43 +00001342 switch (TL.getTypePtr()->getKind()) {
John McCall2dde35b2011-10-18 22:28:37 +00001343
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001344 case BuiltinType::Void:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001345 case BuiltinType::NullPtr:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001346 case BuiltinType::Dependent:
John McCall2dde35b2011-10-18 22:28:37 +00001347#define BUILTIN_TYPE(Id, SingletonId)
1348#define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1349#define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1350#define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
1351#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
1352#include "clang/AST/BuiltinTypes.def"
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001353 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001354
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001355 case BuiltinType::ObjCId:
1356 VisitType = Context.getObjCIdType();
1357 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001358
1359 case BuiltinType::ObjCClass:
1360 VisitType = Context.getObjCClassType();
1361 break;
1362
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001363 case BuiltinType::ObjCSel:
1364 VisitType = Context.getObjCSelType();
1365 break;
1366 }
1367
1368 if (!VisitType.isNull()) {
1369 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001370 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001371 TU));
1372 }
1373
1374 return false;
1375}
1376
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001377bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
Richard Smith162e1c12011-04-15 14:24:37 +00001378 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001379}
1380
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001381bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1382 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1383}
1384
1385bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
Argyrios Kyrtzidis6f155de2011-08-25 22:24:47 +00001386 if (TL.isDefinition())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001387 return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
Argyrios Kyrtzidis6f155de2011-08-25 22:24:47 +00001388
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001389 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1390}
1391
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001392bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Chandler Carruth960d13d2011-05-01 09:53:37 +00001393 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001394}
1395
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001396bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1397 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1398 return true;
1399
John McCallc12c5bb2010-05-15 11:32:37 +00001400 return false;
1401}
1402
1403bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1404 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1405 return true;
1406
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001407 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1408 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1409 TU)))
1410 return true;
1411 }
1412
1413 return false;
1414}
1415
1416bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001417 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001418}
1419
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001420bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1421 return Visit(TL.getInnerLoc());
1422}
1423
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001424bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1425 return Visit(TL.getPointeeLoc());
1426}
1427
1428bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1429 return Visit(TL.getPointeeLoc());
1430}
1431
1432bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1433 return Visit(TL.getPointeeLoc());
1434}
1435
1436bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001437 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001438}
1439
1440bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001441 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001442}
1443
Argyrios Kyrtzidis3422fbc2011-08-15 18:44:43 +00001444bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1445 return Visit(TL.getModifiedLoc());
1446}
1447
Douglas Gregor01829d32010-08-31 14:41:23 +00001448bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1449 bool SkipResultType) {
1450 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001451 return true;
1452
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001453 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001454 if (Decl *D = TL.getArg(I))
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001455 if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001456 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001457
1458 return false;
1459}
1460
1461bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1462 if (Visit(TL.getElementLoc()))
1463 return true;
1464
1465 if (Expr *Size = TL.getSizeExpr())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001466 return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001467
1468 return false;
1469}
1470
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001471bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1472 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001473 // Visit the template name.
1474 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1475 TL.getTemplateNameLoc()))
1476 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001477
1478 // Visit the template arguments.
1479 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1480 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1481 return true;
1482
1483 return false;
1484}
1485
Douglas Gregor2332c112010-01-21 20:48:56 +00001486bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1487 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1488}
1489
1490bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1491 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1492 return Visit(TSInfo->getTypeLoc());
1493
1494 return false;
1495}
1496
Sean Huntca63c202011-05-24 22:41:36 +00001497bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1498 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1499 return Visit(TSInfo->getTypeLoc());
1500
1501 return false;
1502}
1503
Douglas Gregor2494dd02011-03-01 01:34:45 +00001504bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
1505 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1506 return true;
1507
1508 return false;
1509}
1510
Douglas Gregor94fdffa2011-03-01 20:11:18 +00001511bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1512 DependentTemplateSpecializationTypeLoc TL) {
1513 // Visit the nested-name-specifier, if there is one.
1514 if (TL.getQualifierLoc() &&
1515 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1516 return true;
1517
1518 // Visit the template arguments.
1519 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1520 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1521 return true;
1522
1523 return false;
1524}
1525
Douglas Gregor9e876872011-03-01 18:12:44 +00001526bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1527 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1528 return true;
1529
1530 return Visit(TL.getNamedTypeLoc());
1531}
1532
Douglas Gregor7536dd52010-12-20 02:24:11 +00001533bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1534 return Visit(TL.getPatternLoc());
1535}
1536
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +00001537bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1538 if (Expr *E = TL.getUnderlyingExpr())
1539 return Visit(MakeCXCursor(E, StmtParent, TU));
1540
1541 return false;
1542}
1543
1544bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1545 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1546}
1547
Eli Friedmanb001de72011-10-06 23:00:33 +00001548bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1549 return Visit(TL.getValueLoc());
1550}
1551
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +00001552#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1553bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1554 return Visit##PARENT##Loc(TL); \
1555}
1556
1557DEFAULT_TYPELOC_IMPL(Complex, Type)
1558DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1559DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1560DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1561DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
1562DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1563DEFAULT_TYPELOC_IMPL(Vector, Type)
1564DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1565DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1566DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1567DEFAULT_TYPELOC_IMPL(Record, TagType)
1568DEFAULT_TYPELOC_IMPL(Enum, TagType)
1569DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1570DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1571DEFAULT_TYPELOC_IMPL(Auto, Type)
1572
Ted Kremenek3064ef92010-08-27 21:34:58 +00001573bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001574 // Visit the nested-name-specifier, if present.
1575 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1576 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1577 return true;
1578
John McCall5e1cdac2011-10-07 06:10:15 +00001579 if (D->isCompleteDefinition()) {
Ted Kremenek3064ef92010-08-27 21:34:58 +00001580 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1581 E = D->bases_end(); I != E; ++I) {
1582 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1583 return true;
1584 }
1585 }
1586
1587 return VisitTagDecl(D);
1588}
1589
Ted Kremenek09dfa372010-02-18 05:46:33 +00001590bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001591 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1592 i != e; ++i)
1593 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001594 return true;
1595
1596 return false;
1597}
1598
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001599//===----------------------------------------------------------------------===//
1600// Data-recursive visitor methods.
1601//===----------------------------------------------------------------------===//
1602
Ted Kremenek28a71942010-11-13 00:36:47 +00001603namespace {
Ted Kremenek035dc412010-11-13 00:36:50 +00001604#define DEF_JOB(NAME, DATA, KIND)\
1605class NAME : public VisitorJob {\
1606public:\
1607 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1608 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Ted Kremenekf64d8032010-11-18 00:02:32 +00001609 DATA *get() const { return static_cast<DATA*>(data[0]); }\
Ted Kremenek035dc412010-11-13 00:36:50 +00001610};
1611
1612DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1613DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001614DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001615DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001616DEF_JOB(ExplicitTemplateArgsVisit, ASTTemplateArgumentListInfo,
Ted Kremenek60608ec2010-11-17 00:50:47 +00001617 ExplicitTemplateArgsVisitKind)
Douglas Gregor94d96292011-01-19 20:34:17 +00001618DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
Douglas Gregor011d8b92012-02-15 00:54:55 +00001619DEF_JOB(LambdaExprParts, LambdaExpr, LambdaExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001620#undef DEF_JOB
1621
1622class DeclVisit : public VisitorJob {
1623public:
1624 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1625 VisitorJob(parent, VisitorJob::DeclVisitKind,
1626 d, isFirst ? (void*) 1 : (void*) 0) {}
1627 static bool classof(const VisitorJob *VJ) {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001628 return VJ->getKind() == DeclVisitKind;
Ted Kremenek035dc412010-11-13 00:36:50 +00001629 }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001630 Decl *get() const { return static_cast<Decl*>(data[0]); }
1631 bool isFirst() const { return data[1] ? true : false; }
Ted Kremenek035dc412010-11-13 00:36:50 +00001632};
Ted Kremenek035dc412010-11-13 00:36:50 +00001633class TypeLocVisit : public VisitorJob {
1634public:
1635 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1636 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1637 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1638
1639 static bool classof(const VisitorJob *VJ) {
1640 return VJ->getKind() == TypeLocVisitKind;
1641 }
1642
Ted Kremenek82f3c502010-11-15 22:23:26 +00001643 TypeLoc get() const {
Ted Kremenekf64d8032010-11-18 00:02:32 +00001644 QualType T = QualType::getFromOpaquePtr(data[0]);
1645 return TypeLoc(T, data[1]);
Ted Kremenek035dc412010-11-13 00:36:50 +00001646 }
1647};
1648
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001649class LabelRefVisit : public VisitorJob {
1650public:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001651 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1652 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001653 labelLoc.getPtrEncoding()) {}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001654
1655 static bool classof(const VisitorJob *VJ) {
1656 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1657 }
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001658 LabelDecl *get() const { return static_cast<LabelDecl*>(data[0]); }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001659 SourceLocation getLoc() const {
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001660 return SourceLocation::getFromPtrEncoding(data[1]); }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001661};
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001662
1663class NestedNameSpecifierLocVisit : public VisitorJob {
1664public:
1665 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1666 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1667 Qualifier.getNestedNameSpecifier(),
1668 Qualifier.getOpaqueData()) { }
1669
1670 static bool classof(const VisitorJob *VJ) {
1671 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1672 }
1673
1674 NestedNameSpecifierLoc get() const {
1675 return NestedNameSpecifierLoc(static_cast<NestedNameSpecifier*>(data[0]),
1676 data[1]);
1677 }
1678};
1679
Ted Kremenekf64d8032010-11-18 00:02:32 +00001680class DeclarationNameInfoVisit : public VisitorJob {
1681public:
1682 DeclarationNameInfoVisit(Stmt *S, CXCursor parent)
1683 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
1684 static bool classof(const VisitorJob *VJ) {
1685 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1686 }
1687 DeclarationNameInfo get() const {
1688 Stmt *S = static_cast<Stmt*>(data[0]);
1689 switch (S->getStmtClass()) {
1690 default:
1691 llvm_unreachable("Unhandled Stmt");
Douglas Gregorba0513d2011-10-25 01:33:02 +00001692 case clang::Stmt::MSDependentExistsStmtClass:
1693 return cast<MSDependentExistsStmt>(S)->getNameInfo();
Ted Kremenekf64d8032010-11-18 00:02:32 +00001694 case Stmt::CXXDependentScopeMemberExprClass:
1695 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1696 case Stmt::DependentScopeDeclRefExprClass:
1697 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
1698 }
1699 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001700};
Ted Kremenekcdba6592010-11-18 00:42:18 +00001701class MemberRefVisit : public VisitorJob {
1702public:
1703 MemberRefVisit(FieldDecl *D, SourceLocation L, CXCursor parent)
1704 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001705 L.getPtrEncoding()) {}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001706 static bool classof(const VisitorJob *VJ) {
1707 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1708 }
1709 FieldDecl *get() const {
1710 return static_cast<FieldDecl*>(data[0]);
1711 }
1712 SourceLocation getLoc() const {
1713 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1714 }
1715};
Ted Kremenek28a71942010-11-13 00:36:47 +00001716class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1717 VisitorWorkList &WL;
1718 CXCursor Parent;
1719public:
1720 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1721 : WL(wl), Parent(parent) {}
1722
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001723 void VisitAddrLabelExpr(AddrLabelExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001724 void VisitBlockExpr(BlockExpr *B);
Ted Kremenek28a71942010-11-13 00:36:47 +00001725 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek083c7e22010-11-13 05:38:03 +00001726 void VisitCompoundStmt(CompoundStmt *S);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001727 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
Douglas Gregorba0513d2011-10-25 01:33:02 +00001728 void VisitMSDependentExistsStmt(MSDependentExistsStmt *S);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001729 void VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001730 void VisitCXXNewExpr(CXXNewExpr *E);
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001731 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001732 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001733 void VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001734 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001735 void VisitCXXTypeidExpr(CXXTypeidExpr *E);
Ted Kremenek55b933a2010-11-17 00:50:36 +00001736 void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001737 void VisitCXXUuidofExpr(CXXUuidofExpr *E);
Argyrios Kyrtzidisdcbb2fb2011-12-03 03:49:44 +00001738 void VisitCXXCatchStmt(CXXCatchStmt *S);
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001739 void VisitDeclRefExpr(DeclRefExpr *D);
Ted Kremenek035dc412010-11-13 00:36:50 +00001740 void VisitDeclStmt(DeclStmt *S);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001741 void VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001742 void VisitDesignatedInitExpr(DesignatedInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001743 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1744 void VisitForStmt(ForStmt *FS);
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001745 void VisitGotoStmt(GotoStmt *GS);
Ted Kremenek28a71942010-11-13 00:36:47 +00001746 void VisitIfStmt(IfStmt *If);
1747 void VisitInitListExpr(InitListExpr *IE);
1748 void VisitMemberExpr(MemberExpr *M);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001749 void VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001750 void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001751 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1752 void VisitOverloadExpr(OverloadExpr *E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001753 void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001754 void VisitStmt(Stmt *S);
1755 void VisitSwitchStmt(SwitchStmt *S);
1756 void VisitWhileStmt(WhileStmt *W);
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001757 void VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Francois Pichet6ad6f282010-12-07 00:08:36 +00001758 void VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E);
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00001759 void VisitTypeTraitExpr(TypeTraitExpr *E);
John Wiegley21ff2e52011-04-28 00:16:57 +00001760 void VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E);
John Wiegley55262202011-04-25 06:54:41 +00001761 void VisitExpressionTraitExpr(ExpressionTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001762 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001763 void VisitVAArgExpr(VAArgExpr *E);
Douglas Gregor94d96292011-01-19 20:34:17 +00001764 void VisitSizeOfPackExpr(SizeOfPackExpr *E);
John McCall4b9c2d22011-11-06 09:01:30 +00001765 void VisitPseudoObjectExpr(PseudoObjectExpr *E);
1766 void VisitOpaqueValueExpr(OpaqueValueExpr *E);
Douglas Gregor011d8b92012-02-15 00:54:55 +00001767 void VisitLambdaExpr(LambdaExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00001768
Ted Kremenek28a71942010-11-13 00:36:47 +00001769private:
Ted Kremenekf64d8032010-11-18 00:02:32 +00001770 void AddDeclarationNameInfo(Stmt *S);
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001771 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001772 void AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001773 void AddMemberRef(FieldDecl *D, SourceLocation L);
Ted Kremenek28a71942010-11-13 00:36:47 +00001774 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001775 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001776 void AddTypeLoc(TypeSourceInfo *TI);
1777 void EnqueueChildren(Stmt *S);
1778};
1779} // end anonyous namespace
1780
Ted Kremenekf64d8032010-11-18 00:02:32 +00001781void EnqueueVisitor::AddDeclarationNameInfo(Stmt *S) {
1782 // 'S' should always be non-null, since it comes from the
1783 // statement we are visiting.
1784 WL.push_back(DeclarationNameInfoVisit(S, Parent));
1785}
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001786
1787void
1788EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1789 if (Qualifier)
1790 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
1791}
1792
Ted Kremenek28a71942010-11-13 00:36:47 +00001793void EnqueueVisitor::AddStmt(Stmt *S) {
1794 if (S)
1795 WL.push_back(StmtVisit(S, Parent));
1796}
Ted Kremenek035dc412010-11-13 00:36:50 +00001797void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001798 if (D)
Ted Kremenek035dc412010-11-13 00:36:50 +00001799 WL.push_back(DeclVisit(D, Parent, isFirst));
Ted Kremenek28a71942010-11-13 00:36:47 +00001800}
Ted Kremenek60608ec2010-11-17 00:50:47 +00001801void EnqueueVisitor::
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001802 AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001803 if (A)
1804 WL.push_back(ExplicitTemplateArgsVisit(
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001805 const_cast<ASTTemplateArgumentListInfo*>(A), Parent));
Ted Kremenek60608ec2010-11-17 00:50:47 +00001806}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001807void EnqueueVisitor::AddMemberRef(FieldDecl *D, SourceLocation L) {
1808 if (D)
1809 WL.push_back(MemberRefVisit(D, L, Parent));
1810}
Ted Kremenek28a71942010-11-13 00:36:47 +00001811void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1812 if (TI)
1813 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1814 }
1815void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001816 unsigned size = WL.size();
John McCall7502c1d2011-02-13 04:07:26 +00001817 for (Stmt::child_range Child = S->children(); Child; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001818 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001819 }
1820 if (size == WL.size())
1821 return;
1822 // Now reverse the entries we just added. This will match the DFS
1823 // ordering performed by the worklist.
1824 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1825 std::reverse(I, E);
1826}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001827void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1828 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
1829}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001830void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1831 AddDecl(B->getBlockDecl());
1832}
Ted Kremenek28a71942010-11-13 00:36:47 +00001833void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1834 EnqueueChildren(E);
1835 AddTypeLoc(E->getTypeSourceInfo());
1836}
Ted Kremenek083c7e22010-11-13 05:38:03 +00001837void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1838 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1839 E = S->body_rend(); I != E; ++I) {
1840 AddStmt(*I);
1841 }
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001842}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001843void EnqueueVisitor::
Douglas Gregorba0513d2011-10-25 01:33:02 +00001844VisitMSDependentExistsStmt(MSDependentExistsStmt *S) {
1845 AddStmt(S->getSubStmt());
1846 AddDeclarationNameInfo(S);
1847 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
1848 AddNestedNameSpecifierLoc(QualifierLoc);
1849}
1850
1851void EnqueueVisitor::
Ted Kremenekf64d8032010-11-18 00:02:32 +00001852VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
1853 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1854 AddDeclarationNameInfo(E);
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001855 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1856 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001857 if (!E->isImplicitAccess())
1858 AddStmt(E->getBase());
1859}
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001860void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001861 // Enqueue the initializer , if any.
1862 AddStmt(E->getInitializer());
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001863 // Enqueue the array size, if any.
1864 AddStmt(E->getArraySize());
1865 // Enqueue the allocated type.
1866 AddTypeLoc(E->getAllocatedTypeSourceInfo());
1867 // Enqueue the placement arguments.
1868 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1869 AddStmt(E->getPlacementArg(I-1));
1870}
Ted Kremenek28a71942010-11-13 00:36:47 +00001871void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
Ted Kremenek8b8d8c92010-11-13 05:55:56 +00001872 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1873 AddStmt(CE->getArg(I-1));
Ted Kremenek28a71942010-11-13 00:36:47 +00001874 AddStmt(CE->getCallee());
1875 AddStmt(CE->getArg(0));
1876}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001877void EnqueueVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1878 // Visit the name of the type being destroyed.
1879 AddTypeLoc(E->getDestroyedTypeInfo());
1880 // Visit the scope type that looks disturbingly like the nested-name-specifier
1881 // but isn't.
1882 AddTypeLoc(E->getScopeTypeInfo());
1883 // Visit the nested-name-specifier.
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001884 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1885 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001886 // Visit base expression.
1887 AddStmt(E->getBase());
1888}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001889void EnqueueVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1890 AddTypeLoc(E->getTypeSourceInfo());
1891}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001892void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1893 EnqueueChildren(E);
1894 AddTypeLoc(E->getTypeSourceInfo());
1895}
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001896void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1897 EnqueueChildren(E);
1898 if (E->isTypeOperand())
1899 AddTypeLoc(E->getTypeOperandSourceInfo());
1900}
Ted Kremenek55b933a2010-11-17 00:50:36 +00001901
1902void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
1903 *E) {
1904 EnqueueChildren(E);
1905 AddTypeLoc(E->getTypeSourceInfo());
1906}
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001907void EnqueueVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1908 EnqueueChildren(E);
1909 if (E->isTypeOperand())
1910 AddTypeLoc(E->getTypeOperandSourceInfo());
1911}
Argyrios Kyrtzidisdcbb2fb2011-12-03 03:49:44 +00001912
1913void EnqueueVisitor::VisitCXXCatchStmt(CXXCatchStmt *S) {
1914 EnqueueChildren(S);
1915 AddDecl(S->getExceptionDecl());
1916}
1917
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001918void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001919 if (DR->hasExplicitTemplateArgs()) {
1920 AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
1921 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001922 WL.push_back(DeclRefExprParts(DR, Parent));
1923}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001924void EnqueueVisitor::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
1925 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1926 AddDeclarationNameInfo(E);
Douglas Gregor00cf3cc2011-02-25 20:49:16 +00001927 AddNestedNameSpecifierLoc(E->getQualifierLoc());
Ted Kremenekf64d8032010-11-18 00:02:32 +00001928}
Ted Kremenek035dc412010-11-13 00:36:50 +00001929void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1930 unsigned size = WL.size();
1931 bool isFirst = true;
1932 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1933 D != DEnd; ++D) {
1934 AddDecl(*D, isFirst);
1935 isFirst = false;
1936 }
1937 if (size == WL.size())
1938 return;
1939 // Now reverse the entries we just added. This will match the DFS
1940 // ordering performed by the worklist.
1941 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1942 std::reverse(I, E);
1943}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001944void EnqueueVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1945 AddStmt(E->getInit());
1946 typedef DesignatedInitExpr::Designator Designator;
1947 for (DesignatedInitExpr::reverse_designators_iterator
1948 D = E->designators_rbegin(), DEnd = E->designators_rend();
1949 D != DEnd; ++D) {
1950 if (D->isFieldDesignator()) {
1951 if (FieldDecl *Field = D->getField())
1952 AddMemberRef(Field, D->getFieldLoc());
1953 continue;
1954 }
1955 if (D->isArrayDesignator()) {
1956 AddStmt(E->getArrayIndex(*D));
1957 continue;
1958 }
1959 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1960 AddStmt(E->getArrayRangeEnd(*D));
1961 AddStmt(E->getArrayRangeStart(*D));
1962 }
1963}
Ted Kremenek28a71942010-11-13 00:36:47 +00001964void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1965 EnqueueChildren(E);
1966 AddTypeLoc(E->getTypeInfoAsWritten());
1967}
1968void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1969 AddStmt(FS->getBody());
1970 AddStmt(FS->getInc());
1971 AddStmt(FS->getCond());
1972 AddDecl(FS->getConditionVariable());
1973 AddStmt(FS->getInit());
1974}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001975void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) {
1976 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
1977}
Ted Kremenek28a71942010-11-13 00:36:47 +00001978void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
1979 AddStmt(If->getElse());
1980 AddStmt(If->getThen());
1981 AddStmt(If->getCond());
1982 AddDecl(If->getConditionVariable());
1983}
1984void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
1985 // We care about the syntactic form of the initializer list, only.
1986 if (InitListExpr *Syntactic = IE->getSyntacticForm())
1987 IE = Syntactic;
1988 EnqueueChildren(IE);
1989}
1990void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
Douglas Gregor89629a72010-11-17 17:15:08 +00001991 WL.push_back(MemberExprParts(M, Parent));
1992
1993 // If the base of the member access expression is an implicit 'this', don't
1994 // visit it.
1995 // FIXME: If we ever want to show these implicit accesses, this will be
1996 // unfortunate. However, clang_getCursor() relies on this behavior.
Douglas Gregor75e85042011-03-02 21:06:53 +00001997 if (!M->isImplicitAccess())
1998 AddStmt(M->getBase());
Ted Kremenek28a71942010-11-13 00:36:47 +00001999}
Ted Kremenek73d15c42010-11-13 01:09:29 +00002000void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
2001 AddTypeLoc(E->getEncodedTypeSourceInfo());
2002}
Ted Kremenek28a71942010-11-13 00:36:47 +00002003void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
2004 EnqueueChildren(M);
2005 AddTypeLoc(M->getClassReceiverTypeInfo());
2006}
Ted Kremenekcdba6592010-11-18 00:42:18 +00002007void EnqueueVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
2008 // Visit the components of the offsetof expression.
2009 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
2010 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
2011 const OffsetOfNode &Node = E->getComponent(I-1);
2012 switch (Node.getKind()) {
2013 case OffsetOfNode::Array:
2014 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2015 break;
2016 case OffsetOfNode::Field:
Abramo Bagnara06dec892011-03-12 09:45:03 +00002017 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
Ted Kremenekcdba6592010-11-18 00:42:18 +00002018 break;
2019 case OffsetOfNode::Identifier:
2020 case OffsetOfNode::Base:
2021 continue;
2022 }
2023 }
2024 // Visit the type into which we're computing the offset.
2025 AddTypeLoc(E->getTypeSourceInfo());
2026}
Ted Kremenek28a71942010-11-13 00:36:47 +00002027void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00002028 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
Ted Kremenek60458782010-11-12 21:34:16 +00002029 WL.push_back(OverloadExprParts(E, Parent));
2030}
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002031void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
2032 UnaryExprOrTypeTraitExpr *E) {
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00002033 EnqueueChildren(E);
2034 if (E->isArgumentType())
2035 AddTypeLoc(E->getArgumentTypeInfo());
2036}
Ted Kremenek28a71942010-11-13 00:36:47 +00002037void EnqueueVisitor::VisitStmt(Stmt *S) {
2038 EnqueueChildren(S);
2039}
2040void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
2041 AddStmt(S->getBody());
2042 AddStmt(S->getCond());
2043 AddDecl(S->getConditionVariable());
2044}
Ted Kremenekfafa75a2010-11-17 00:50:39 +00002045
Ted Kremenek28a71942010-11-13 00:36:47 +00002046void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
2047 AddStmt(W->getBody());
2048 AddStmt(W->getCond());
2049 AddDecl(W->getConditionVariable());
2050}
John Wiegley21ff2e52011-04-28 00:16:57 +00002051
Ted Kremenek2939b6f2010-11-17 00:50:50 +00002052void EnqueueVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
2053 AddTypeLoc(E->getQueriedTypeSourceInfo());
2054}
Francois Pichet6ad6f282010-12-07 00:08:36 +00002055
2056void EnqueueVisitor::VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
Francois Pichet6ad6f282010-12-07 00:08:36 +00002057 AddTypeLoc(E->getRhsTypeSourceInfo());
Francois Pichet0a03a3f2010-12-08 09:11:05 +00002058 AddTypeLoc(E->getLhsTypeSourceInfo());
Francois Pichet6ad6f282010-12-07 00:08:36 +00002059}
2060
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00002061void EnqueueVisitor::VisitTypeTraitExpr(TypeTraitExpr *E) {
2062 for (unsigned I = E->getNumArgs(); I > 0; --I)
2063 AddTypeLoc(E->getArg(I-1));
2064}
2065
John Wiegley21ff2e52011-04-28 00:16:57 +00002066void EnqueueVisitor::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
2067 AddTypeLoc(E->getQueriedTypeSourceInfo());
2068}
2069
John Wiegley55262202011-04-25 06:54:41 +00002070void EnqueueVisitor::VisitExpressionTraitExpr(ExpressionTraitExpr *E) {
2071 EnqueueChildren(E);
2072}
2073
Ted Kremenek28a71942010-11-13 00:36:47 +00002074void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
2075 VisitOverloadExpr(U);
2076 if (!U->isImplicitAccess())
2077 AddStmt(U->getBase());
2078}
Ted Kremenek9d3bf792010-11-17 00:50:43 +00002079void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) {
2080 AddStmt(E->getSubExpr());
2081 AddTypeLoc(E->getWrittenTypeInfo());
2082}
Douglas Gregor94d96292011-01-19 20:34:17 +00002083void EnqueueVisitor::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
2084 WL.push_back(SizeOfPackExprParts(E, Parent));
2085}
John McCall4b9c2d22011-11-06 09:01:30 +00002086void EnqueueVisitor::VisitOpaqueValueExpr(OpaqueValueExpr *E) {
2087 // If the opaque value has a source expression, just transparently
2088 // visit that. This is useful for (e.g.) pseudo-object expressions.
2089 if (Expr *SourceExpr = E->getSourceExpr())
2090 return Visit(SourceExpr);
John McCall4b9c2d22011-11-06 09:01:30 +00002091}
Douglas Gregor011d8b92012-02-15 00:54:55 +00002092void EnqueueVisitor::VisitLambdaExpr(LambdaExpr *E) {
2093 AddStmt(E->getBody());
2094 WL.push_back(LambdaExprParts(E, Parent));
2095}
John McCall4b9c2d22011-11-06 09:01:30 +00002096void EnqueueVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *E) {
2097 // Treat the expression like its syntactic form.
2098 Visit(E->getSyntacticForm());
2099}
Ted Kremenek60458782010-11-12 21:34:16 +00002100
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002101void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002102 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002103}
2104
2105bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2106 if (RegionOfInterest.isValid()) {
2107 SourceRange Range = getRawCursorExtent(C);
2108 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2109 return false;
2110 }
2111 return true;
2112}
2113
2114bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2115 while (!WL.empty()) {
2116 // Dequeue the worklist item.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002117 VisitorJob LI = WL.back();
2118 WL.pop_back();
2119
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002120 // Set the Parent field, then back to its old value once we're done.
2121 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2122
2123 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00002124 case VisitorJob::DeclVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002125 Decl *D = cast<DeclVisit>(&LI)->get();
Ted Kremenekf1107452010-11-12 18:26:56 +00002126 if (!D)
2127 continue;
2128
2129 // For now, perform default visitation for Decls.
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002130 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2131 cast<DeclVisit>(&LI)->isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00002132 return true;
2133
2134 continue;
2135 }
Ted Kremenek60608ec2010-11-17 00:50:47 +00002136 case VisitorJob::ExplicitTemplateArgsVisitKind: {
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00002137 const ASTTemplateArgumentListInfo *ArgList =
Ted Kremenek60608ec2010-11-17 00:50:47 +00002138 cast<ExplicitTemplateArgsVisit>(&LI)->get();
2139 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2140 *ArgEnd = Arg + ArgList->NumTemplateArgs;
2141 Arg != ArgEnd; ++Arg) {
2142 if (VisitTemplateArgumentLoc(*Arg))
2143 return true;
2144 }
2145 continue;
2146 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002147 case VisitorJob::TypeLocVisitKind: {
2148 // Perform default visitation for TypeLocs.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002149 if (Visit(cast<TypeLocVisit>(&LI)->get()))
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002150 return true;
2151 continue;
2152 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002153 case VisitorJob::LabelRefVisitKind: {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002154 LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Ted Kremeneke7455012011-02-23 04:54:51 +00002155 if (LabelStmt *stmt = LS->getStmt()) {
2156 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2157 TU))) {
2158 return true;
2159 }
2160 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002161 continue;
2162 }
Ted Kremenek47695c82011-08-18 22:25:21 +00002163
Douglas Gregorf3db29f2011-02-25 18:19:59 +00002164 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2165 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2166 if (VisitNestedNameSpecifierLoc(V->get()))
2167 return true;
2168 continue;
2169 }
2170
Ted Kremenekf64d8032010-11-18 00:02:32 +00002171 case VisitorJob::DeclarationNameInfoVisitKind: {
2172 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2173 ->get()))
2174 return true;
2175 continue;
2176 }
Ted Kremenekcdba6592010-11-18 00:42:18 +00002177 case VisitorJob::MemberRefVisitKind: {
2178 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2179 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2180 return true;
2181 continue;
2182 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002183 case VisitorJob::StmtVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002184 Stmt *S = cast<StmtVisit>(&LI)->get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00002185 if (!S)
2186 continue;
2187
Ted Kremenekf1107452010-11-12 18:26:56 +00002188 // Update the current cursor.
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002189 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
Ted Kremenekcdba6592010-11-18 00:42:18 +00002190 if (!IsInRegionOfInterest(Cursor))
2191 continue;
2192 switch (Visitor(Cursor, Parent, ClientData)) {
2193 case CXChildVisit_Break: return true;
2194 case CXChildVisit_Continue: break;
2195 case CXChildVisit_Recurse:
2196 EnqueueWorkList(WL, S);
Ted Kremenek82f3c502010-11-15 22:23:26 +00002197 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002198 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00002199 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002200 }
2201 case VisitorJob::MemberExprPartsKind: {
2202 // Handle the other pieces in the MemberExpr besides the base.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002203 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002204
2205 // Visit the nested-name-specifier
Douglas Gregor40d96a62011-02-28 21:54:11 +00002206 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
2207 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002208 return true;
2209
2210 // Visit the declaration name.
2211 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2212 return true;
2213
2214 // Visit the explicitly-specified template arguments, if any.
2215 if (M->hasExplicitTemplateArgs()) {
2216 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2217 *ArgEnd = Arg + M->getNumTemplateArgs();
2218 Arg != ArgEnd; ++Arg) {
2219 if (VisitTemplateArgumentLoc(*Arg))
2220 return true;
2221 }
2222 }
2223 continue;
2224 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002225 case VisitorJob::DeclRefExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002226 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002227 // Visit nested-name-specifier, if present.
Douglas Gregor40d96a62011-02-28 21:54:11 +00002228 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
2229 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002230 return true;
2231 // Visit declaration name.
2232 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2233 return true;
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002234 continue;
2235 }
Ted Kremenek60458782010-11-12 21:34:16 +00002236 case VisitorJob::OverloadExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002237 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Ted Kremenek60458782010-11-12 21:34:16 +00002238 // Visit the nested-name-specifier.
Douglas Gregor4c9be892011-02-28 20:01:57 +00002239 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
2240 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenek60458782010-11-12 21:34:16 +00002241 return true;
2242 // Visit the declaration name.
2243 if (VisitDeclarationNameInfo(O->getNameInfo()))
2244 return true;
2245 // Visit the overloaded declaration reference.
2246 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2247 return true;
Ted Kremenek60458782010-11-12 21:34:16 +00002248 continue;
2249 }
Douglas Gregor94d96292011-01-19 20:34:17 +00002250 case VisitorJob::SizeOfPackExprPartsKind: {
2251 SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
2252 NamedDecl *Pack = E->getPack();
2253 if (isa<TemplateTypeParmDecl>(Pack)) {
2254 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
2255 E->getPackLoc(), TU)))
2256 return true;
2257
2258 continue;
2259 }
2260
2261 if (isa<TemplateTemplateParmDecl>(Pack)) {
2262 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
2263 E->getPackLoc(), TU)))
2264 return true;
2265
2266 continue;
2267 }
2268
2269 // Non-type template parameter packs and function parameter packs are
2270 // treated like DeclRefExpr cursors.
2271 continue;
2272 }
Douglas Gregor011d8b92012-02-15 00:54:55 +00002273
2274 case VisitorJob::LambdaExprPartsKind: {
2275 // Visit captures.
2276 LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
2277 for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
2278 CEnd = E->explicit_capture_end();
2279 C != CEnd; ++C) {
2280 if (C->capturesThis())
2281 continue;
2282
2283 if (Visit(MakeCursorVariableRef(C->getCapturedVar(),
2284 C->getLocation(),
2285 TU)))
2286 return true;
2287 }
2288
2289 // Visit parameters and return type, if present.
2290 if (E->hasExplicitParameters() || E->hasExplicitResultType()) {
2291 TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
2292 if (E->hasExplicitParameters() && E->hasExplicitResultType()) {
2293 // Visit the whole type.
2294 if (Visit(TL))
2295 return true;
2296 } else if (isa<FunctionProtoTypeLoc>(TL)) {
2297 FunctionProtoTypeLoc Proto = cast<FunctionProtoTypeLoc>(TL);
2298 if (E->hasExplicitParameters()) {
2299 // Visit parameters.
2300 for (unsigned I = 0, N = Proto.getNumArgs(); I != N; ++I)
2301 if (Visit(MakeCXCursor(Proto.getArg(I), TU)))
2302 return true;
2303 } else {
2304 // Visit result type.
2305 if (Visit(Proto.getResultLoc()))
2306 return true;
2307 }
2308 }
2309 }
2310 break;
2311 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002312 }
2313 }
2314 return false;
2315}
2316
Ted Kremenekcdba6592010-11-18 00:42:18 +00002317bool CursorVisitor::Visit(Stmt *S) {
Ted Kremenekd1ded662010-11-15 23:31:32 +00002318 VisitorWorkList *WL = 0;
2319 if (!WorkListFreeList.empty()) {
2320 WL = WorkListFreeList.back();
2321 WL->clear();
2322 WorkListFreeList.pop_back();
2323 }
2324 else {
2325 WL = new VisitorWorkList();
2326 WorkListCache.push_back(WL);
2327 }
2328 EnqueueWorkList(*WL, S);
2329 bool result = RunVisitorWorkList(*WL);
2330 WorkListFreeList.push_back(WL);
2331 return result;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002332}
2333
Francois Pichet48a8d142011-07-25 22:00:44 +00002334namespace {
2335typedef llvm::SmallVector<SourceRange, 4> RefNamePieces;
2336RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
2337 const DeclarationNameInfo &NI,
2338 const SourceRange &QLoc,
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00002339 const ASTTemplateArgumentListInfo *TemplateArgs = 0){
Francois Pichet48a8d142011-07-25 22:00:44 +00002340 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
2341 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
2342 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
2343
2344 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
2345
2346 RefNamePieces Pieces;
2347
2348 if (WantQualifier && QLoc.isValid())
2349 Pieces.push_back(QLoc);
2350
2351 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
2352 Pieces.push_back(NI.getLoc());
2353
2354 if (WantTemplateArgs && TemplateArgs)
2355 Pieces.push_back(SourceRange(TemplateArgs->LAngleLoc,
2356 TemplateArgs->RAngleLoc));
2357
2358 if (Kind == DeclarationName::CXXOperatorName) {
2359 Pieces.push_back(SourceLocation::getFromRawEncoding(
2360 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
2361 Pieces.push_back(SourceLocation::getFromRawEncoding(
2362 NI.getInfo().CXXOperatorName.EndOpNameLoc));
2363 }
2364
2365 if (WantSinglePiece) {
2366 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
2367 Pieces.clear();
2368 Pieces.push_back(R);
2369 }
2370
2371 return Pieces;
2372}
2373}
2374
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002375//===----------------------------------------------------------------------===//
2376// Misc. API hooks.
2377//===----------------------------------------------------------------------===//
2378
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002379static llvm::sys::Mutex EnableMultithreadingMutex;
2380static bool EnabledMultithreading;
2381
Argyrios Kyrtzidisfa39f5b2011-12-15 04:52:41 +00002382static void fatal_error_handler(void *user_data, const std::string& reason) {
Argyrios Kyrtzidisfa39f5b2011-12-15 04:52:41 +00002383 // Write the result out to stderr avoiding errs() because raw_ostreams can
2384 // call report_fatal_error.
Argyrios Kyrtzidisdb7a8002011-12-15 06:51:30 +00002385 fprintf(stderr, "LIBCLANG FATAL ERROR: %s\n", reason.c_str());
Argyrios Kyrtzidisfa39f5b2011-12-15 04:52:41 +00002386 ::abort();
2387}
2388
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002389extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002390CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2391 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002392 // Disable pretty stack trace functionality, which will otherwise be a very
2393 // poor citizen of the world and set up all sorts of signal handlers.
2394 llvm::DisablePrettyStackTrace = true;
2395
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002396 // We use crash recovery to make some of our APIs more reliable, implicitly
2397 // enable it.
2398 llvm::CrashRecoveryContext::Enable();
2399
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002400 // Enable support for multithreading in LLVM.
2401 {
2402 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2403 if (!EnabledMultithreading) {
Argyrios Kyrtzidisfa39f5b2011-12-15 04:52:41 +00002404 llvm::install_fatal_error_handler(fatal_error_handler, 0);
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002405 llvm::llvm_start_multithreaded();
2406 EnabledMultithreading = true;
2407 }
2408 }
2409
Douglas Gregora030b7c2010-01-22 20:35:53 +00002410 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002411 if (excludeDeclarationsFromPCH)
2412 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002413 if (displayDiagnostics)
2414 CIdxr->setDisplayDiagnostics();
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002415
2416 if (getenv("LIBCLANG_BGPRIO_INDEX"))
2417 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
2418 CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
2419 if (getenv("LIBCLANG_BGPRIO_EDIT"))
2420 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
2421 CXGlobalOpt_ThreadBackgroundPriorityForEditing);
2422
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002423 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002424}
2425
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002426void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002427 if (CIdx)
2428 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002429}
2430
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002431void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
2432 if (CIdx)
2433 static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
2434}
2435
2436unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
2437 if (CIdx)
2438 return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
2439 return 0;
2440}
2441
Ted Kremenekd2427dd2011-03-18 23:05:39 +00002442void clang_toggleCrashRecovery(unsigned isEnabled) {
2443 if (isEnabled)
2444 llvm::CrashRecoveryContext::Enable();
2445 else
2446 llvm::CrashRecoveryContext::Disable();
2447}
2448
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002449CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002450 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002451 if (!CIdx)
2452 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002453
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002454 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002455 FileSystemOptions FileSystemOpts;
2456 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002457
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00002458 IntrusiveRefCntPtr<DiagnosticsEngine> Diags;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002459 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002460 CXXIdx->getOnlyLocalDecls(),
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00002461 0, 0,
2462 /*CaptureDiagnostics=*/true,
2463 /*AllowPCHWithCompilerErrors=*/true);
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002464 return MakeCXTranslationUnit(CXXIdx, TU);
Steve Naroff600866c2009-08-27 19:51:58 +00002465}
2466
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002467unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002468 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregorb5af8432011-08-25 22:54:01 +00002469 CXTranslationUnit_CacheCompletionResults;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002470}
2471
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002472CXTranslationUnit
2473clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2474 const char *source_filename,
2475 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002476 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002477 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002478 struct CXUnsavedFile *unsaved_files) {
Argyrios Kyrtzidise1d43302012-02-25 02:41:16 +00002479 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
Douglas Gregor5a430212010-07-21 18:52:53 +00002480 return clang_parseTranslationUnit(CIdx, source_filename,
2481 command_line_args, num_command_line_args,
2482 unsaved_files, num_unsaved_files,
Douglas Gregordca8ee82011-05-06 16:33:08 +00002483 Options);
Douglas Gregor5a430212010-07-21 18:52:53 +00002484}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002485
2486struct ParseTranslationUnitInfo {
2487 CXIndex CIdx;
2488 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002489 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002490 int num_command_line_args;
2491 struct CXUnsavedFile *unsaved_files;
2492 unsigned num_unsaved_files;
2493 unsigned options;
2494 CXTranslationUnit result;
2495};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002496static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002497 ParseTranslationUnitInfo *PTUI =
2498 static_cast<ParseTranslationUnitInfo*>(UserData);
2499 CXIndex CIdx = PTUI->CIdx;
2500 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002501 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002502 int num_command_line_args = PTUI->num_command_line_args;
2503 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2504 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2505 unsigned options = PTUI->options;
2506 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002507
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002508 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002509 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002510
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002511 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2512
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002513 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
Argyrios Kyrtzidis81b5ac32012-03-28 02:49:54 +00002514 setThreadBackgroundPriority();
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002515
Douglas Gregor44c181a2010-07-23 00:33:23 +00002516 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregor467dc882011-08-25 22:30:56 +00002517 // FIXME: Add a flag for modules.
2518 TranslationUnitKind TUKind
2519 = (options & CXTranslationUnit_Incomplete)? TU_Prefix : TU_Complete;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002520 bool CacheCodeCompetionResults
2521 = options & CXTranslationUnit_CacheCompletionResults;
2522
Douglas Gregor5352ac02010-01-28 00:27:43 +00002523 // Configure the diagnostics.
2524 DiagnosticOptions DiagOpts;
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00002525 IntrusiveRefCntPtr<DiagnosticsEngine>
Ted Kremenek25a11e12011-03-22 01:15:24 +00002526 Diags(CompilerInstance::createDiagnostics(DiagOpts, num_command_line_args,
2527 command_line_args));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002528
Ted Kremenek25a11e12011-03-22 01:15:24 +00002529 // Recover resources if we crash before exiting this function.
David Blaikied6471f72011-09-25 23:23:43 +00002530 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
2531 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00002532 DiagCleanup(Diags.getPtr());
2533
Dylan Noblesmith1e4c01b2012-02-13 12:32:21 +00002534 OwningPtr<std::vector<ASTUnit::RemappedFile> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00002535 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2536
2537 // Recover resources if we crash before exiting this function.
2538 llvm::CrashRecoveryContextCleanupRegistrar<
2539 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2540
Douglas Gregor4db64a42010-01-23 00:14:00 +00002541 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002542 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002543 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002544 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002545 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2546 Buffer));
Douglas Gregor4db64a42010-01-23 00:14:00 +00002547 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002548
Dylan Noblesmith1e4c01b2012-02-13 12:32:21 +00002549 OwningPtr<std::vector<const char *> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00002550 Args(new std::vector<const char*>());
2551
2552 // Recover resources if we crash before exiting this method.
2553 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
2554 ArgsCleanup(Args.get());
2555
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002556 // Since the Clang C library is primarily used by batch tools dealing with
2557 // (often very broken) source code, where spell-checking can have a
2558 // significant negative impact on performance (particularly when
2559 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002560 // Only do this if we haven't found a spell-checking-related argument.
2561 bool FoundSpellCheckingArgument = false;
2562 for (int I = 0; I != num_command_line_args; ++I) {
2563 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2564 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2565 FoundSpellCheckingArgument = true;
2566 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002567 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002568 }
2569 if (!FoundSpellCheckingArgument)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002570 Args->push_back("-fno-spell-checking");
Douglas Gregorb10daed2010-10-11 16:52:23 +00002571
Ted Kremenek25a11e12011-03-22 01:15:24 +00002572 Args->insert(Args->end(), command_line_args,
2573 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002574
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002575 // The 'source_filename' argument is optional. If the caller does not
2576 // specify it then it is assumed that the source file is specified
2577 // in the actual argument list.
2578 // Put the source file after command_line_args otherwise if '-x' flag is
2579 // present it will be unused.
2580 if (source_filename)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002581 Args->push_back(source_filename);
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002582
Douglas Gregor44c181a2010-07-23 00:33:23 +00002583 // Do we need the detailed preprocessing record?
2584 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Ted Kremenek25a11e12011-03-22 01:15:24 +00002585 Args->push_back("-Xclang");
2586 Args->push_back("-detailed-preprocessing-record");
Douglas Gregor44c181a2010-07-23 00:33:23 +00002587 }
2588
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002589 unsigned NumErrors = Diags->getClient()->getNumErrors();
Dylan Noblesmith1e4c01b2012-02-13 12:32:21 +00002590 OwningPtr<ASTUnit> Unit(
Ted Kremenek4ee99262011-03-22 20:16:19 +00002591 ASTUnit::LoadFromCommandLine(Args->size() ? &(*Args)[0] : 0
2592 /* vector::data() not portable */,
2593 Args->size() ? (&(*Args)[0] + Args->size()) :0,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002594 Diags,
2595 CXXIdx->getClangResourcesPath(),
2596 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002597 /*CaptureDiagnostics=*/true,
Ted Kremenek4ee99262011-03-22 20:16:19 +00002598 RemappedFiles->size() ? &(*RemappedFiles)[0]:0,
Ted Kremenek25a11e12011-03-22 01:15:24 +00002599 RemappedFiles->size(),
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00002600 /*RemappedFilesKeepOriginalName=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002601 PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00002602 TUKind,
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00002603 CacheCodeCompetionResults,
2604 /*AllowPCHWithCompilerErrors=*/true));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002605
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002606 if (NumErrors != Diags->getClient()->getNumErrors()) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002607 // Make sure to check that 'Unit' is non-NULL.
2608 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2609 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2610 DEnd = Unit->stored_diag_end();
2611 D != DEnd; ++D) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002612 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOpts());
Douglas Gregorb10daed2010-10-11 16:52:23 +00002613 CXString Msg = clang_formatDiagnostic(&Diag,
2614 clang_defaultDiagnosticDisplayOptions());
2615 fprintf(stderr, "%s\n", clang_getCString(Msg));
2616 clang_disposeString(Msg);
2617 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002618#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002619 // On Windows, force a flush, since there may be multiple copies of
2620 // stderr and stdout in the file system, all with different buffers
2621 // but writing to the same device.
2622 fflush(stderr);
2623#endif
2624 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002625 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002626
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002627 PTUI->result = MakeCXTranslationUnit(CXXIdx, Unit.take());
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002628}
2629CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2630 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002631 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002632 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002633 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002634 unsigned num_unsaved_files,
2635 unsigned options) {
2636 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002637 num_command_line_args, unsaved_files,
2638 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002639 llvm::CrashRecoveryContext CRC;
2640
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002641 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002642 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2643 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2644 fprintf(stderr, " 'command_line_args' : [");
2645 for (int i = 0; i != num_command_line_args; ++i) {
2646 if (i)
2647 fprintf(stderr, ", ");
2648 fprintf(stderr, "'%s'", command_line_args[i]);
2649 }
2650 fprintf(stderr, "],\n");
2651 fprintf(stderr, " 'unsaved_files' : [");
2652 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2653 if (i)
2654 fprintf(stderr, ", ");
2655 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2656 unsaved_files[i].Length);
2657 }
2658 fprintf(stderr, "],\n");
2659 fprintf(stderr, " 'options' : %d,\n", options);
2660 fprintf(stderr, "}\n");
2661
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002662 return 0;
Douglas Gregor6df78732011-05-05 20:27:22 +00002663 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
2664 PrintLibclangResourceUsage(PTUI.result);
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002665 }
Douglas Gregor6df78732011-05-05 20:27:22 +00002666
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002667 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002668}
2669
Douglas Gregor19998442010-08-13 15:35:05 +00002670unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2671 return CXSaveTranslationUnit_None;
2672}
Argyrios Kyrtzidis142bcb52012-03-28 02:17:59 +00002673
2674namespace {
2675
2676struct SaveTranslationUnitInfo {
2677 CXTranslationUnit TU;
2678 const char *FileName;
2679 unsigned options;
2680 CXSaveError result;
2681};
2682
2683}
2684
2685static void clang_saveTranslationUnit_Impl(void *UserData) {
2686 SaveTranslationUnitInfo *STUI =
2687 static_cast<SaveTranslationUnitInfo*>(UserData);
2688
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002689 CIndexer *CXXIdx = (CIndexer*)STUI->TU->CIdx;
2690 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
Argyrios Kyrtzidis81b5ac32012-03-28 02:49:54 +00002691 setThreadBackgroundPriority();
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002692
Argyrios Kyrtzidis142bcb52012-03-28 02:17:59 +00002693 STUI->result = static_cast<ASTUnit *>(STUI->TU->TUData)->Save(STUI->FileName);
2694}
2695
Douglas Gregor19998442010-08-13 15:35:05 +00002696int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2697 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002698 if (!TU)
Douglas Gregor39c411f2011-07-06 16:43:36 +00002699 return CXSaveError_InvalidTU;
Argyrios Kyrtzidis142bcb52012-03-28 02:17:59 +00002700
2701 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
2702 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2703
2704 SaveTranslationUnitInfo STUI = { TU, FileName, options, CXSaveError_None };
2705
2706 if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred() ||
2707 getenv("LIBCLANG_NOTHREADS")) {
2708 clang_saveTranslationUnit_Impl(&STUI);
2709
2710 if (getenv("LIBCLANG_RESOURCE_USAGE"))
2711 PrintLibclangResourceUsage(TU);
2712
2713 return STUI.result;
2714 }
2715
2716 // We have an AST that has invalid nodes due to compiler errors.
2717 // Use a crash recovery thread for protection.
2718
2719 llvm::CrashRecoveryContext CRC;
2720
2721 if (!RunSafely(CRC, clang_saveTranslationUnit_Impl, &STUI)) {
2722 fprintf(stderr, "libclang: crash detected during AST saving: {\n");
2723 fprintf(stderr, " 'filename' : '%s'\n", FileName);
2724 fprintf(stderr, " 'options' : %d,\n", options);
2725 fprintf(stderr, "}\n");
2726
2727 return CXSaveError_Unknown;
2728
2729 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
Douglas Gregor6df78732011-05-05 20:27:22 +00002730 PrintLibclangResourceUsage(TU);
Argyrios Kyrtzidis142bcb52012-03-28 02:17:59 +00002731 }
2732
2733 return STUI.result;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002734}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002735
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002736void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002737 if (CTUnit) {
2738 // If the translation unit has been marked as unsafe to free, just discard
2739 // it.
Ted Kremeneka60ed472010-11-16 08:15:36 +00002740 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002741 return;
2742
Ted Kremeneka60ed472010-11-16 08:15:36 +00002743 delete static_cast<ASTUnit *>(CTUnit->TUData);
2744 disposeCXStringPool(CTUnit->StringPool);
Ted Kremenek15322172011-11-10 08:43:12 +00002745 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002746 delete CTUnit;
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002747 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002748}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002749
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002750unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2751 return CXReparse_None;
2752}
2753
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002754struct ReparseTranslationUnitInfo {
2755 CXTranslationUnit TU;
2756 unsigned num_unsaved_files;
2757 struct CXUnsavedFile *unsaved_files;
2758 unsigned options;
2759 int result;
2760};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002761
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002762static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002763 ReparseTranslationUnitInfo *RTUI =
2764 static_cast<ReparseTranslationUnitInfo*>(UserData);
2765 CXTranslationUnit TU = RTUI->TU;
Ted Kremenek15322172011-11-10 08:43:12 +00002766
2767 // Reset the associated diagnostics.
2768 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
2769 TU->Diagnostics = 0;
2770
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002771 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2772 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2773 unsigned options = RTUI->options;
2774 (void) options;
2775 RTUI->result = 1;
2776
Douglas Gregorabc563f2010-07-19 21:46:24 +00002777 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002778 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002779
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002780 CIndexer *CXXIdx = (CIndexer*)TU->CIdx;
2781 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
Argyrios Kyrtzidis81b5ac32012-03-28 02:49:54 +00002782 setThreadBackgroundPriority();
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00002783
Ted Kremeneka60ed472010-11-16 08:15:36 +00002784 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor593b0c12010-09-23 18:47:53 +00002785 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002786
Dylan Noblesmith1e4c01b2012-02-13 12:32:21 +00002787 OwningPtr<std::vector<ASTUnit::RemappedFile> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00002788 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2789
2790 // Recover resources if we crash before exiting this function.
2791 llvm::CrashRecoveryContextCleanupRegistrar<
2792 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2793
Douglas Gregorabc563f2010-07-19 21:46:24 +00002794 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002795 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002796 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002797 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002798 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2799 Buffer));
Douglas Gregorabc563f2010-07-19 21:46:24 +00002800 }
2801
Ted Kremenek4ee99262011-03-22 20:16:19 +00002802 if (!CXXUnit->Reparse(RemappedFiles->size() ? &(*RemappedFiles)[0] : 0,
2803 RemappedFiles->size()))
Douglas Gregor593b0c12010-09-23 18:47:53 +00002804 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002805}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002806
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002807int clang_reparseTranslationUnit(CXTranslationUnit TU,
2808 unsigned num_unsaved_files,
2809 struct CXUnsavedFile *unsaved_files,
2810 unsigned options) {
2811 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2812 options, 0 };
Argyrios Kyrtzidis8c4b47e2011-10-28 22:54:33 +00002813
Argyrios Kyrtzidise7de9b42011-10-29 19:32:39 +00002814 if (getenv("LIBCLANG_NOTHREADS")) {
Argyrios Kyrtzidis8c4b47e2011-10-28 22:54:33 +00002815 clang_reparseTranslationUnit_Impl(&RTUI);
2816 return RTUI.result;
2817 }
2818
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002819 llvm::CrashRecoveryContext CRC;
2820
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002821 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002822 fprintf(stderr, "libclang: crash detected during reparsing\n");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002823 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002824 return 1;
Douglas Gregor6df78732011-05-05 20:27:22 +00002825 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
2826 PrintLibclangResourceUsage(TU);
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002827
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002828 return RTUI.result;
2829}
2830
Douglas Gregordf95a132010-08-09 20:45:32 +00002831
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002832CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002833 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002834 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002835
Ted Kremeneka60ed472010-11-16 08:15:36 +00002836 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002837 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002838}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002839
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002840CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002841 CXCursor Result = { CXCursor_TranslationUnit, 0, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002842 return Result;
2843}
2844
Ted Kremenekfb480492010-01-13 21:46:36 +00002845} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002846
Ted Kremenekfb480492010-01-13 21:46:36 +00002847//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002848// CXFile Operations.
2849//===----------------------------------------------------------------------===//
2850
2851extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002852CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002853 if (!SFile)
Ted Kremeneka60ed472010-11-16 08:15:36 +00002854 return createCXString((const char*)NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002855
Steve Naroff88145032009-10-27 14:35:18 +00002856 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002857 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002858}
2859
2860time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002861 if (!SFile)
2862 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002863
Steve Naroff88145032009-10-27 14:35:18 +00002864 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2865 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002866}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002867
Douglas Gregorb9790342010-01-22 21:44:22 +00002868CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2869 if (!tu)
2870 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002871
Ted Kremeneka60ed472010-11-16 08:15:36 +00002872 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002873
Douglas Gregorb9790342010-01-22 21:44:22 +00002874 FileManager &FMgr = CXXUnit->getFileManager();
Chris Lattner39b49bc2010-11-23 08:35:12 +00002875 return const_cast<FileEntry *>(FMgr.getFile(file_name));
Douglas Gregorb9790342010-01-22 21:44:22 +00002876}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002877
Douglas Gregordd3e5542011-05-04 00:14:37 +00002878unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit tu, CXFile file) {
2879 if (!tu || !file)
2880 return 0;
2881
2882 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
2883 FileEntry *FEnt = static_cast<FileEntry *>(file);
2884 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
2885 .isFileMultipleIncludeGuarded(FEnt);
2886}
2887
Ted Kremenekfb480492010-01-13 21:46:36 +00002888} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002889
Ted Kremenekfb480492010-01-13 21:46:36 +00002890//===----------------------------------------------------------------------===//
2891// CXCursor Operations.
2892//===----------------------------------------------------------------------===//
2893
Ted Kremenekfb480492010-01-13 21:46:36 +00002894static Decl *getDeclFromExpr(Stmt *E) {
Argyrios Kyrtzidisc2954612011-09-12 22:17:26 +00002895 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Douglas Gregordb1314e2010-10-01 21:11:22 +00002896 return getDeclFromExpr(CE->getSubExpr());
2897
Ted Kremenekfb480492010-01-13 21:46:36 +00002898 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2899 return RefExpr->getDecl();
2900 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2901 return ME->getMemberDecl();
2902 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2903 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002904 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
John McCall12f78a62010-12-02 01:19:52 +00002905 return PRE->isExplicitProperty() ? PRE->getExplicitProperty() : 0;
John McCall4b9c2d22011-11-06 09:01:30 +00002906 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
2907 return getDeclFromExpr(POE->getSyntacticForm());
2908 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
2909 if (Expr *Src = OVE->getSourceExpr())
2910 return getDeclFromExpr(Src);
Douglas Gregordb1314e2010-10-01 21:11:22 +00002911
Ted Kremenekfb480492010-01-13 21:46:36 +00002912 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2913 return getDeclFromExpr(CE->getCallee());
Chris Lattner5f9e2722011-07-23 10:55:15 +00002914 if (CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Douglas Gregor93798e22010-11-05 21:11:19 +00002915 if (!CE->isElidable())
2916 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002917 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2918 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002919
Douglas Gregordb1314e2010-10-01 21:11:22 +00002920 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2921 return PE->getProtocol();
Douglas Gregorc7793c72011-01-15 01:15:58 +00002922 if (SubstNonTypeTemplateParmPackExpr *NTTP
2923 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
2924 return NTTP->getParameterPack();
Douglas Gregor94d96292011-01-19 20:34:17 +00002925 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2926 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
2927 isa<ParmVarDecl>(SizeOfPack->getPack()))
2928 return SizeOfPack->getPack();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002929
Ted Kremenekfb480492010-01-13 21:46:36 +00002930 return 0;
2931}
2932
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002933static SourceLocation getLocationFromExpr(Expr *E) {
Argyrios Kyrtzidisc2954612011-09-12 22:17:26 +00002934 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
2935 return getLocationFromExpr(CE->getSubExpr());
2936
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002937 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2938 return /*FIXME:*/Msg->getLeftLoc();
2939 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2940 return DRE->getLocation();
2941 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2942 return Member->getMemberLoc();
2943 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2944 return Ivar->getLocation();
Douglas Gregor94d96292011-01-19 20:34:17 +00002945 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2946 return SizeOfPack->getPackLoc();
Argyrios Kyrtzidisd0469522012-03-30 00:19:13 +00002947 if (ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
2948 return PropRef->getLocation();
Douglas Gregor94d96292011-01-19 20:34:17 +00002949
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002950 return E->getLocStart();
2951}
2952
Ted Kremenekfb480492010-01-13 21:46:36 +00002953extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002954
2955unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002956 CXCursorVisitor visitor,
2957 CXClientData client_data) {
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00002958 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
2959 /*VisitPreprocessorLast=*/false);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002960 return CursorVis.VisitChildren(parent);
2961}
2962
David Chisnall3387c652010-11-03 14:12:26 +00002963#ifndef __has_feature
2964#define __has_feature(x) 0
2965#endif
2966#if __has_feature(blocks)
2967typedef enum CXChildVisitResult
2968 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2969
2970static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2971 CXClientData client_data) {
2972 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2973 return block(cursor, parent);
2974}
2975#else
2976// If we are compiled with a compiler that doesn't have native blocks support,
2977// define and call the block manually, so the
2978typedef struct _CXChildVisitResult
2979{
2980 void *isa;
2981 int flags;
2982 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002983 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2984 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00002985} *CXCursorVisitorBlock;
2986
2987static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2988 CXClientData client_data) {
2989 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2990 return block->invoke(block, cursor, parent);
2991}
2992#endif
2993
2994
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002995unsigned clang_visitChildrenWithBlock(CXCursor parent,
2996 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00002997 return clang_visitChildren(parent, visitWithBlock, block);
2998}
2999
Douglas Gregor78205d42010-01-20 21:45:58 +00003000static CXString getDeclSpelling(Decl *D) {
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00003001 if (!D)
3002 return createCXString("");
3003
3004 NamedDecl *ND = dyn_cast<NamedDecl>(D);
Douglas Gregore3c60a72010-11-17 00:13:31 +00003005 if (!ND) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003006 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00003007 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3008 return createCXString(Property->getIdentifier()->getName());
3009
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003010 return createCXString("");
Douglas Gregore3c60a72010-11-17 00:13:31 +00003011 }
3012
Douglas Gregor78205d42010-01-20 21:45:58 +00003013 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003014 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003015
Douglas Gregor78205d42010-01-20 21:45:58 +00003016 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
3017 // No, this isn't the same as the code below. getIdentifier() is non-virtual
3018 // and returns different names. NamedDecl returns the class name and
3019 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003020 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003021
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003022 if (isa<UsingDirectiveDecl>(D))
3023 return createCXString("");
3024
Dylan Noblesmith36d59272012-02-13 12:32:26 +00003025 SmallString<1024> S;
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00003026 llvm::raw_svector_ostream os(S);
3027 ND->printName(os);
3028
3029 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00003030}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003031
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003032CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003033 if (clang_isTranslationUnit(C.kind))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003034 return clang_getTranslationUnitSpelling(
3035 static_cast<CXTranslationUnit>(C.data[2]));
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003036
Steve Narofff334b4e2009-09-02 18:26:48 +00003037 if (clang_isReference(C.kind)) {
3038 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00003039 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00003040 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003041 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003042 }
3043 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00003044 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003045 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003046 }
3047 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00003048 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00003049 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003050 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003051 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00003052 case CXCursor_CXXBaseSpecifier: {
3053 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
3054 return createCXString(B->getType().getAsString());
3055 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003056 case CXCursor_TypeRef: {
3057 TypeDecl *Type = getCursorTypeRef(C).first;
3058 assert(Type && "Missing type decl");
3059
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003060 return createCXString(getCursorContext(C).getTypeDeclType(Type).
3061 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003062 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003063 case CXCursor_TemplateRef: {
3064 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00003065 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003066
3067 return createCXString(Template->getNameAsString());
3068 }
Douglas Gregor69319002010-08-31 23:48:11 +00003069
3070 case CXCursor_NamespaceRef: {
3071 NamedDecl *NS = getCursorNamespaceRef(C).first;
3072 assert(NS && "Missing namespace decl");
3073
3074 return createCXString(NS->getNameAsString());
3075 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003076
Douglas Gregora67e03f2010-09-09 21:42:20 +00003077 case CXCursor_MemberRef: {
3078 FieldDecl *Field = getCursorMemberRef(C).first;
3079 assert(Field && "Missing member decl");
3080
3081 return createCXString(Field->getNameAsString());
3082 }
3083
Douglas Gregor36897b02010-09-10 00:22:18 +00003084 case CXCursor_LabelRef: {
3085 LabelStmt *Label = getCursorLabelRef(C).first;
3086 assert(Label && "Missing label");
3087
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003088 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00003089 }
3090
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003091 case CXCursor_OverloadedDeclRef: {
3092 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3093 if (Decl *D = Storage.dyn_cast<Decl *>()) {
3094 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
3095 return createCXString(ND->getNameAsString());
3096 return createCXString("");
3097 }
3098 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3099 return createCXString(E->getName().getAsString());
3100 OverloadedTemplateStorage *Ovl
3101 = Storage.get<OverloadedTemplateStorage*>();
3102 if (Ovl->size() == 0)
3103 return createCXString("");
3104 return createCXString((*Ovl->begin())->getNameAsString());
3105 }
3106
Douglas Gregor011d8b92012-02-15 00:54:55 +00003107 case CXCursor_VariableRef: {
3108 VarDecl *Var = getCursorVariableRef(C).first;
3109 assert(Var && "Missing variable decl");
3110
3111 return createCXString(Var->getNameAsString());
3112 }
3113
Daniel Dunbaracca7252009-11-30 20:42:49 +00003114 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003115 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00003116 }
3117 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003118
3119 if (clang_isExpression(C.kind)) {
3120 Decl *D = getDeclFromExpr(getCursorExpr(C));
3121 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00003122 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003123 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00003124 }
3125
Douglas Gregor36897b02010-09-10 00:22:18 +00003126 if (clang_isStatement(C.kind)) {
3127 Stmt *S = getCursorStmt(C);
3128 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003129 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00003130
3131 return createCXString("");
3132 }
3133
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003134 if (C.kind == CXCursor_MacroExpansion)
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003135 return createCXString(getCursorMacroExpansion(C)->getName()
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003136 ->getNameStart());
3137
Douglas Gregor572feb22010-03-18 18:04:21 +00003138 if (C.kind == CXCursor_MacroDefinition)
3139 return createCXString(getCursorMacroDefinition(C)->getName()
3140 ->getNameStart());
3141
Douglas Gregorecdcb882010-10-20 22:00:55 +00003142 if (C.kind == CXCursor_InclusionDirective)
3143 return createCXString(getCursorInclusionDirective(C)->getFileName());
3144
Douglas Gregor60cbfac2010-01-25 16:56:17 +00003145 if (clang_isDeclaration(C.kind))
3146 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00003147
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00003148 if (C.kind == CXCursor_AnnotateAttr) {
3149 AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
3150 return createCXString(AA->getAnnotation());
3151 }
3152
Argyrios Kyrtzidis84b79642011-12-06 22:05:01 +00003153 if (C.kind == CXCursor_AsmLabelAttr) {
3154 AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
3155 return createCXString(AA->getLabel());
3156 }
3157
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003158 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00003159}
3160
Douglas Gregor358559d2010-10-02 22:49:11 +00003161CXString clang_getCursorDisplayName(CXCursor C) {
3162 if (!clang_isDeclaration(C.kind))
3163 return clang_getCursorSpelling(C);
3164
3165 Decl *D = getCursorDecl(C);
3166 if (!D)
3167 return createCXString("");
3168
Douglas Gregor30c42402011-09-27 22:38:19 +00003169 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
Douglas Gregor358559d2010-10-02 22:49:11 +00003170 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
3171 D = FunTmpl->getTemplatedDecl();
3172
3173 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Dylan Noblesmith36d59272012-02-13 12:32:26 +00003174 SmallString<64> Str;
Douglas Gregor358559d2010-10-02 22:49:11 +00003175 llvm::raw_svector_ostream OS(Str);
Benjamin Kramera59d20b2012-02-07 11:57:57 +00003176 OS << *Function;
Douglas Gregor358559d2010-10-02 22:49:11 +00003177 if (Function->getPrimaryTemplate())
3178 OS << "<>";
3179 OS << "(";
3180 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
3181 if (I)
3182 OS << ", ";
3183 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
3184 }
3185
3186 if (Function->isVariadic()) {
3187 if (Function->getNumParams())
3188 OS << ", ";
3189 OS << "...";
3190 }
3191 OS << ")";
3192 return createCXString(OS.str());
3193 }
3194
3195 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
Dylan Noblesmith36d59272012-02-13 12:32:26 +00003196 SmallString<64> Str;
Douglas Gregor358559d2010-10-02 22:49:11 +00003197 llvm::raw_svector_ostream OS(Str);
Benjamin Kramera59d20b2012-02-07 11:57:57 +00003198 OS << *ClassTemplate;
Douglas Gregor358559d2010-10-02 22:49:11 +00003199 OS << "<";
3200 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
3201 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3202 if (I)
3203 OS << ", ";
3204
3205 NamedDecl *Param = Params->getParam(I);
3206 if (Param->getIdentifier()) {
3207 OS << Param->getIdentifier()->getName();
3208 continue;
3209 }
3210
3211 // There is no parameter name, which makes this tricky. Try to come up
3212 // with something useful that isn't too long.
3213 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3214 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
3215 else if (NonTypeTemplateParmDecl *NTTP
3216 = dyn_cast<NonTypeTemplateParmDecl>(Param))
3217 OS << NTTP->getType().getAsString(Policy);
3218 else
3219 OS << "template<...> class";
3220 }
3221
3222 OS << ">";
3223 return createCXString(OS.str());
3224 }
3225
3226 if (ClassTemplateSpecializationDecl *ClassSpec
3227 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
3228 // If the type was explicitly written, use that.
3229 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
3230 return createCXString(TSInfo->getType().getAsString(Policy));
3231
Dylan Noblesmith36d59272012-02-13 12:32:26 +00003232 SmallString<64> Str;
Douglas Gregor358559d2010-10-02 22:49:11 +00003233 llvm::raw_svector_ostream OS(Str);
Benjamin Kramera59d20b2012-02-07 11:57:57 +00003234 OS << *ClassSpec;
Douglas Gregor358559d2010-10-02 22:49:11 +00003235 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00003236 ClassSpec->getTemplateArgs().data(),
3237 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00003238 Policy);
3239 return createCXString(OS.str());
3240 }
3241
3242 return clang_getCursorSpelling(C);
3243}
3244
Ted Kremeneke68fff62010-02-17 00:41:32 +00003245CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00003246 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00003247 case CXCursor_FunctionDecl:
3248 return createCXString("FunctionDecl");
3249 case CXCursor_TypedefDecl:
3250 return createCXString("TypedefDecl");
3251 case CXCursor_EnumDecl:
3252 return createCXString("EnumDecl");
3253 case CXCursor_EnumConstantDecl:
3254 return createCXString("EnumConstantDecl");
3255 case CXCursor_StructDecl:
3256 return createCXString("StructDecl");
3257 case CXCursor_UnionDecl:
3258 return createCXString("UnionDecl");
3259 case CXCursor_ClassDecl:
3260 return createCXString("ClassDecl");
3261 case CXCursor_FieldDecl:
3262 return createCXString("FieldDecl");
3263 case CXCursor_VarDecl:
3264 return createCXString("VarDecl");
3265 case CXCursor_ParmDecl:
3266 return createCXString("ParmDecl");
3267 case CXCursor_ObjCInterfaceDecl:
3268 return createCXString("ObjCInterfaceDecl");
3269 case CXCursor_ObjCCategoryDecl:
3270 return createCXString("ObjCCategoryDecl");
3271 case CXCursor_ObjCProtocolDecl:
3272 return createCXString("ObjCProtocolDecl");
3273 case CXCursor_ObjCPropertyDecl:
3274 return createCXString("ObjCPropertyDecl");
3275 case CXCursor_ObjCIvarDecl:
3276 return createCXString("ObjCIvarDecl");
3277 case CXCursor_ObjCInstanceMethodDecl:
3278 return createCXString("ObjCInstanceMethodDecl");
3279 case CXCursor_ObjCClassMethodDecl:
3280 return createCXString("ObjCClassMethodDecl");
3281 case CXCursor_ObjCImplementationDecl:
3282 return createCXString("ObjCImplementationDecl");
3283 case CXCursor_ObjCCategoryImplDecl:
3284 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00003285 case CXCursor_CXXMethod:
3286 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003287 case CXCursor_UnexposedDecl:
3288 return createCXString("UnexposedDecl");
3289 case CXCursor_ObjCSuperClassRef:
3290 return createCXString("ObjCSuperClassRef");
3291 case CXCursor_ObjCProtocolRef:
3292 return createCXString("ObjCProtocolRef");
3293 case CXCursor_ObjCClassRef:
3294 return createCXString("ObjCClassRef");
3295 case CXCursor_TypeRef:
3296 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003297 case CXCursor_TemplateRef:
3298 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00003299 case CXCursor_NamespaceRef:
3300 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00003301 case CXCursor_MemberRef:
3302 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00003303 case CXCursor_LabelRef:
3304 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003305 case CXCursor_OverloadedDeclRef:
3306 return createCXString("OverloadedDeclRef");
Douglas Gregor011d8b92012-02-15 00:54:55 +00003307 case CXCursor_VariableRef:
3308 return createCXString("VariableRef");
Douglas Gregor42b29842011-10-05 19:00:14 +00003309 case CXCursor_IntegerLiteral:
3310 return createCXString("IntegerLiteral");
3311 case CXCursor_FloatingLiteral:
3312 return createCXString("FloatingLiteral");
3313 case CXCursor_ImaginaryLiteral:
3314 return createCXString("ImaginaryLiteral");
3315 case CXCursor_StringLiteral:
3316 return createCXString("StringLiteral");
3317 case CXCursor_CharacterLiteral:
3318 return createCXString("CharacterLiteral");
3319 case CXCursor_ParenExpr:
3320 return createCXString("ParenExpr");
3321 case CXCursor_UnaryOperator:
3322 return createCXString("UnaryOperator");
3323 case CXCursor_ArraySubscriptExpr:
3324 return createCXString("ArraySubscriptExpr");
3325 case CXCursor_BinaryOperator:
3326 return createCXString("BinaryOperator");
3327 case CXCursor_CompoundAssignOperator:
3328 return createCXString("CompoundAssignOperator");
3329 case CXCursor_ConditionalOperator:
3330 return createCXString("ConditionalOperator");
3331 case CXCursor_CStyleCastExpr:
3332 return createCXString("CStyleCastExpr");
3333 case CXCursor_CompoundLiteralExpr:
3334 return createCXString("CompoundLiteralExpr");
3335 case CXCursor_InitListExpr:
3336 return createCXString("InitListExpr");
3337 case CXCursor_AddrLabelExpr:
3338 return createCXString("AddrLabelExpr");
3339 case CXCursor_StmtExpr:
3340 return createCXString("StmtExpr");
3341 case CXCursor_GenericSelectionExpr:
3342 return createCXString("GenericSelectionExpr");
3343 case CXCursor_GNUNullExpr:
3344 return createCXString("GNUNullExpr");
3345 case CXCursor_CXXStaticCastExpr:
3346 return createCXString("CXXStaticCastExpr");
3347 case CXCursor_CXXDynamicCastExpr:
3348 return createCXString("CXXDynamicCastExpr");
3349 case CXCursor_CXXReinterpretCastExpr:
3350 return createCXString("CXXReinterpretCastExpr");
3351 case CXCursor_CXXConstCastExpr:
3352 return createCXString("CXXConstCastExpr");
3353 case CXCursor_CXXFunctionalCastExpr:
3354 return createCXString("CXXFunctionalCastExpr");
3355 case CXCursor_CXXTypeidExpr:
3356 return createCXString("CXXTypeidExpr");
3357 case CXCursor_CXXBoolLiteralExpr:
3358 return createCXString("CXXBoolLiteralExpr");
3359 case CXCursor_CXXNullPtrLiteralExpr:
3360 return createCXString("CXXNullPtrLiteralExpr");
3361 case CXCursor_CXXThisExpr:
3362 return createCXString("CXXThisExpr");
3363 case CXCursor_CXXThrowExpr:
3364 return createCXString("CXXThrowExpr");
3365 case CXCursor_CXXNewExpr:
3366 return createCXString("CXXNewExpr");
3367 case CXCursor_CXXDeleteExpr:
3368 return createCXString("CXXDeleteExpr");
3369 case CXCursor_UnaryExpr:
3370 return createCXString("UnaryExpr");
3371 case CXCursor_ObjCStringLiteral:
3372 return createCXString("ObjCStringLiteral");
Ted Kremenekb3f75422012-03-06 20:06:06 +00003373 case CXCursor_ObjCBoolLiteralExpr:
3374 return createCXString("ObjCBoolLiteralExpr");
Douglas Gregor42b29842011-10-05 19:00:14 +00003375 case CXCursor_ObjCEncodeExpr:
3376 return createCXString("ObjCEncodeExpr");
3377 case CXCursor_ObjCSelectorExpr:
3378 return createCXString("ObjCSelectorExpr");
3379 case CXCursor_ObjCProtocolExpr:
3380 return createCXString("ObjCProtocolExpr");
3381 case CXCursor_ObjCBridgedCastExpr:
3382 return createCXString("ObjCBridgedCastExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00003383 case CXCursor_BlockExpr:
3384 return createCXString("BlockExpr");
Douglas Gregor42b29842011-10-05 19:00:14 +00003385 case CXCursor_PackExpansionExpr:
3386 return createCXString("PackExpansionExpr");
3387 case CXCursor_SizeOfPackExpr:
3388 return createCXString("SizeOfPackExpr");
Douglas Gregor011d8b92012-02-15 00:54:55 +00003389 case CXCursor_LambdaExpr:
3390 return createCXString("LambdaExpr");
Douglas Gregor42b29842011-10-05 19:00:14 +00003391 case CXCursor_UnexposedExpr:
3392 return createCXString("UnexposedExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003393 case CXCursor_DeclRefExpr:
3394 return createCXString("DeclRefExpr");
3395 case CXCursor_MemberRefExpr:
3396 return createCXString("MemberRefExpr");
3397 case CXCursor_CallExpr:
3398 return createCXString("CallExpr");
3399 case CXCursor_ObjCMessageExpr:
3400 return createCXString("ObjCMessageExpr");
3401 case CXCursor_UnexposedStmt:
3402 return createCXString("UnexposedStmt");
Douglas Gregor42b29842011-10-05 19:00:14 +00003403 case CXCursor_DeclStmt:
3404 return createCXString("DeclStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00003405 case CXCursor_LabelStmt:
3406 return createCXString("LabelStmt");
Douglas Gregor42b29842011-10-05 19:00:14 +00003407 case CXCursor_CompoundStmt:
3408 return createCXString("CompoundStmt");
3409 case CXCursor_CaseStmt:
3410 return createCXString("CaseStmt");
3411 case CXCursor_DefaultStmt:
3412 return createCXString("DefaultStmt");
3413 case CXCursor_IfStmt:
3414 return createCXString("IfStmt");
3415 case CXCursor_SwitchStmt:
3416 return createCXString("SwitchStmt");
3417 case CXCursor_WhileStmt:
3418 return createCXString("WhileStmt");
3419 case CXCursor_DoStmt:
3420 return createCXString("DoStmt");
3421 case CXCursor_ForStmt:
3422 return createCXString("ForStmt");
3423 case CXCursor_GotoStmt:
3424 return createCXString("GotoStmt");
3425 case CXCursor_IndirectGotoStmt:
3426 return createCXString("IndirectGotoStmt");
3427 case CXCursor_ContinueStmt:
3428 return createCXString("ContinueStmt");
3429 case CXCursor_BreakStmt:
3430 return createCXString("BreakStmt");
3431 case CXCursor_ReturnStmt:
3432 return createCXString("ReturnStmt");
3433 case CXCursor_AsmStmt:
3434 return createCXString("AsmStmt");
3435 case CXCursor_ObjCAtTryStmt:
3436 return createCXString("ObjCAtTryStmt");
3437 case CXCursor_ObjCAtCatchStmt:
3438 return createCXString("ObjCAtCatchStmt");
3439 case CXCursor_ObjCAtFinallyStmt:
3440 return createCXString("ObjCAtFinallyStmt");
3441 case CXCursor_ObjCAtThrowStmt:
3442 return createCXString("ObjCAtThrowStmt");
3443 case CXCursor_ObjCAtSynchronizedStmt:
3444 return createCXString("ObjCAtSynchronizedStmt");
3445 case CXCursor_ObjCAutoreleasePoolStmt:
3446 return createCXString("ObjCAutoreleasePoolStmt");
3447 case CXCursor_ObjCForCollectionStmt:
3448 return createCXString("ObjCForCollectionStmt");
3449 case CXCursor_CXXCatchStmt:
3450 return createCXString("CXXCatchStmt");
3451 case CXCursor_CXXTryStmt:
3452 return createCXString("CXXTryStmt");
3453 case CXCursor_CXXForRangeStmt:
3454 return createCXString("CXXForRangeStmt");
3455 case CXCursor_SEHTryStmt:
3456 return createCXString("SEHTryStmt");
3457 case CXCursor_SEHExceptStmt:
3458 return createCXString("SEHExceptStmt");
3459 case CXCursor_SEHFinallyStmt:
3460 return createCXString("SEHFinallyStmt");
3461 case CXCursor_NullStmt:
3462 return createCXString("NullStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003463 case CXCursor_InvalidFile:
3464 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00003465 case CXCursor_InvalidCode:
3466 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003467 case CXCursor_NoDeclFound:
3468 return createCXString("NoDeclFound");
3469 case CXCursor_NotImplemented:
3470 return createCXString("NotImplemented");
3471 case CXCursor_TranslationUnit:
3472 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00003473 case CXCursor_UnexposedAttr:
3474 return createCXString("UnexposedAttr");
3475 case CXCursor_IBActionAttr:
3476 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003477 case CXCursor_IBOutletAttr:
3478 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003479 case CXCursor_IBOutletCollectionAttr:
3480 return createCXString("attribute(iboutletcollection)");
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00003481 case CXCursor_CXXFinalAttr:
3482 return createCXString("attribute(final)");
3483 case CXCursor_CXXOverrideAttr:
3484 return createCXString("attribute(override)");
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00003485 case CXCursor_AnnotateAttr:
3486 return createCXString("attribute(annotate)");
Argyrios Kyrtzidis84b79642011-12-06 22:05:01 +00003487 case CXCursor_AsmLabelAttr:
3488 return createCXString("asm label");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003489 case CXCursor_PreprocessingDirective:
3490 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003491 case CXCursor_MacroDefinition:
3492 return createCXString("macro definition");
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003493 case CXCursor_MacroExpansion:
3494 return createCXString("macro expansion");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003495 case CXCursor_InclusionDirective:
3496 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003497 case CXCursor_Namespace:
3498 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003499 case CXCursor_LinkageSpec:
3500 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003501 case CXCursor_CXXBaseSpecifier:
3502 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003503 case CXCursor_Constructor:
3504 return createCXString("CXXConstructor");
3505 case CXCursor_Destructor:
3506 return createCXString("CXXDestructor");
3507 case CXCursor_ConversionFunction:
3508 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003509 case CXCursor_TemplateTypeParameter:
3510 return createCXString("TemplateTypeParameter");
3511 case CXCursor_NonTypeTemplateParameter:
3512 return createCXString("NonTypeTemplateParameter");
3513 case CXCursor_TemplateTemplateParameter:
3514 return createCXString("TemplateTemplateParameter");
3515 case CXCursor_FunctionTemplate:
3516 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003517 case CXCursor_ClassTemplate:
3518 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003519 case CXCursor_ClassTemplatePartialSpecialization:
3520 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003521 case CXCursor_NamespaceAlias:
3522 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003523 case CXCursor_UsingDirective:
3524 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003525 case CXCursor_UsingDeclaration:
3526 return createCXString("UsingDeclaration");
Richard Smith162e1c12011-04-15 14:24:37 +00003527 case CXCursor_TypeAliasDecl:
Douglas Gregor352697a2011-06-03 23:08:58 +00003528 return createCXString("TypeAliasDecl");
3529 case CXCursor_ObjCSynthesizeDecl:
3530 return createCXString("ObjCSynthesizeDecl");
3531 case CXCursor_ObjCDynamicDecl:
3532 return createCXString("ObjCDynamicDecl");
Argyrios Kyrtzidis2dfdb942011-09-30 17:58:23 +00003533 case CXCursor_CXXAccessSpecifier:
3534 return createCXString("CXXAccessSpecifier");
Steve Naroff89922f82009-08-31 00:59:03 +00003535 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003536
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003537 llvm_unreachable("Unhandled CXCursorKind");
Steve Naroff600866c2009-08-27 19:51:58 +00003538}
Steve Naroff89922f82009-08-31 00:59:03 +00003539
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003540struct GetCursorData {
3541 SourceLocation TokenBeginLoc;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003542 bool PointsAtMacroArgExpansion;
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003543 CXCursor &BestCursor;
3544
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003545 GetCursorData(SourceManager &SM,
3546 SourceLocation tokenBegin, CXCursor &outputCursor)
3547 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
3548 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
3549 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003550};
3551
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003552static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3553 CXCursor parent,
3554 CXClientData client_data) {
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003555 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
3556 CXCursor *BestCursor = &Data->BestCursor;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003557
3558 // If we point inside a macro argument we should provide info of what the
3559 // token is so use the actual cursor, don't replace it with a macro expansion
3560 // cursor.
3561 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
3562 return CXChildVisit_Recurse;
Argyrios Kyrtzidis65ab9072011-09-26 19:05:37 +00003563
3564 if (clang_isDeclaration(cursor.kind)) {
3565 // Avoid having the implicit methods override the property decls.
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00003566 if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor)))
Argyrios Kyrtzidis65ab9072011-09-26 19:05:37 +00003567 if (MD->isImplicit())
3568 return CXChildVisit_Break;
3569 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003570
3571 if (clang_isExpression(cursor.kind) &&
3572 clang_isDeclaration(BestCursor->kind)) {
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00003573 if (Decl *D = getCursorDecl(*BestCursor)) {
3574 // Avoid having the cursor of an expression replace the declaration cursor
3575 // when the expression source range overlaps the declaration range.
3576 // This can happen for C++ constructor expressions whose range generally
3577 // include the variable declaration, e.g.:
3578 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
3579 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
3580 D->getLocation() == Data->TokenBeginLoc)
3581 return CXChildVisit_Break;
3582 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003583 }
3584
Douglas Gregor93798e22010-11-05 21:11:19 +00003585 // If our current best cursor is the construction of a temporary object,
3586 // don't replace that cursor with a type reference, because we want
3587 // clang_getCursor() to point at the constructor.
3588 if (clang_isExpression(BestCursor->kind) &&
3589 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003590 cursor.kind == CXCursor_TypeRef) {
3591 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
3592 // as having the actual point on the type reference.
3593 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
Douglas Gregor93798e22010-11-05 21:11:19 +00003594 return CXChildVisit_Recurse;
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003595 }
Douglas Gregor93798e22010-11-05 21:11:19 +00003596
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003597 *BestCursor = cursor;
3598 return CXChildVisit_Recurse;
3599}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003600
Douglas Gregorb9790342010-01-22 21:44:22 +00003601CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3602 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003603 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003604
Ted Kremeneka60ed472010-11-16 08:15:36 +00003605 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003606 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3607
Ted Kremeneka297de22010-01-25 22:34:44 +00003608 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003609 CXCursor Result = cxcursor::getCursor(TU, SLoc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003610
Douglas Gregor40749ee2010-11-03 00:35:38 +00003611 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregor40749ee2010-11-03 00:35:38 +00003612 if (Logging) {
3613 CXFile SearchFile;
3614 unsigned SearchLine, SearchColumn;
3615 CXFile ResultFile;
3616 unsigned ResultLine, ResultColumn;
Douglas Gregor66537982010-11-17 17:14:07 +00003617 CXString SearchFileName, ResultFileName, KindSpelling, USR;
3618 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
Douglas Gregor40749ee2010-11-03 00:35:38 +00003619 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3620
Chandler Carruth20174222011-08-31 16:53:37 +00003621 clang_getExpansionLocation(Loc, &SearchFile, &SearchLine, &SearchColumn, 0);
3622 clang_getExpansionLocation(ResultLoc, &ResultFile, &ResultLine,
3623 &ResultColumn, 0);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003624 SearchFileName = clang_getFileName(SearchFile);
3625 ResultFileName = clang_getFileName(ResultFile);
3626 KindSpelling = clang_getCursorKindSpelling(Result.kind);
Douglas Gregor66537982010-11-17 17:14:07 +00003627 USR = clang_getCursorUSR(Result);
3628 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n",
Douglas Gregor40749ee2010-11-03 00:35:38 +00003629 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3630 clang_getCString(KindSpelling),
Douglas Gregor66537982010-11-17 17:14:07 +00003631 clang_getCString(ResultFileName), ResultLine, ResultColumn,
3632 clang_getCString(USR), IsDef);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003633 clang_disposeString(SearchFileName);
3634 clang_disposeString(ResultFileName);
3635 clang_disposeString(KindSpelling);
Douglas Gregor66537982010-11-17 17:14:07 +00003636 clang_disposeString(USR);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003637
3638 CXCursor Definition = clang_getCursorDefinition(Result);
3639 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
3640 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
3641 CXString DefinitionKindSpelling
3642 = clang_getCursorKindSpelling(Definition.kind);
3643 CXFile DefinitionFile;
3644 unsigned DefinitionLine, DefinitionColumn;
Chandler Carruth20174222011-08-31 16:53:37 +00003645 clang_getExpansionLocation(DefinitionLoc, &DefinitionFile,
3646 &DefinitionLine, &DefinitionColumn, 0);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003647 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
3648 fprintf(stderr, " -> %s(%s:%d:%d)\n",
3649 clang_getCString(DefinitionKindSpelling),
3650 clang_getCString(DefinitionFileName),
3651 DefinitionLine, DefinitionColumn);
3652 clang_disposeString(DefinitionFileName);
3653 clang_disposeString(DefinitionKindSpelling);
3654 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003655 }
3656
Ted Kremeneke68fff62010-02-17 00:41:32 +00003657 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003658}
3659
Ted Kremenek73885552009-11-17 19:28:59 +00003660CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003661 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003662}
3663
3664unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003665 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003666}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003667
Douglas Gregor9ce55842010-11-20 00:09:34 +00003668unsigned clang_hashCursor(CXCursor C) {
3669 unsigned Index = 0;
3670 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
3671 Index = 1;
3672
3673 return llvm::DenseMapInfo<std::pair<unsigned, void*> >::getHashValue(
3674 std::make_pair(C.kind, C.data[Index]));
3675}
3676
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003677unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003678 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3679}
3680
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003681unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003682 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3683}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003684
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003685unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003686 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3687}
3688
Douglas Gregor97b98722010-01-19 23:20:36 +00003689unsigned clang_isExpression(enum CXCursorKind K) {
3690 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3691}
3692
3693unsigned clang_isStatement(enum CXCursorKind K) {
3694 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3695}
3696
Douglas Gregor8be80e12011-07-06 03:00:34 +00003697unsigned clang_isAttribute(enum CXCursorKind K) {
3698 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
3699}
3700
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003701unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3702 return K == CXCursor_TranslationUnit;
3703}
3704
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003705unsigned clang_isPreprocessing(enum CXCursorKind K) {
3706 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3707}
3708
Ted Kremenekad6eff62010-03-08 21:17:29 +00003709unsigned clang_isUnexposed(enum CXCursorKind K) {
3710 switch (K) {
3711 case CXCursor_UnexposedDecl:
3712 case CXCursor_UnexposedExpr:
3713 case CXCursor_UnexposedStmt:
3714 case CXCursor_UnexposedAttr:
3715 return true;
3716 default:
3717 return false;
3718 }
3719}
3720
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003721CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003722 return C.kind;
3723}
3724
Douglas Gregor98258af2010-01-18 22:46:11 +00003725CXSourceLocation clang_getCursorLocation(CXCursor C) {
3726 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003727 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003728 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003729 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3730 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003731 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003732 }
3733
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003734 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003735 std::pair<ObjCProtocolDecl *, SourceLocation> P
3736 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003737 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003738 }
3739
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003740 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003741 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3742 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003743 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003744 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003745
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003746 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003747 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003748 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003749 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003750
3751 case CXCursor_TemplateRef: {
3752 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3753 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3754 }
3755
Douglas Gregor69319002010-08-31 23:48:11 +00003756 case CXCursor_NamespaceRef: {
3757 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3758 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3759 }
3760
Douglas Gregora67e03f2010-09-09 21:42:20 +00003761 case CXCursor_MemberRef: {
3762 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3763 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3764 }
3765
Douglas Gregor011d8b92012-02-15 00:54:55 +00003766 case CXCursor_VariableRef: {
3767 std::pair<VarDecl *, SourceLocation> P = getCursorVariableRef(C);
3768 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3769 }
3770
Ted Kremenek3064ef92010-08-27 21:34:58 +00003771 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003772 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3773 if (!BaseSpec)
3774 return clang_getNullLocation();
3775
3776 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3777 return cxloc::translateSourceLocation(getCursorContext(C),
3778 TSInfo->getTypeLoc().getBeginLoc());
3779
3780 return cxloc::translateSourceLocation(getCursorContext(C),
Daniel Dunbar96a00142012-03-09 18:35:03 +00003781 BaseSpec->getLocStart());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003782 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003783
Douglas Gregor36897b02010-09-10 00:22:18 +00003784 case CXCursor_LabelRef: {
3785 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3786 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3787 }
3788
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003789 case CXCursor_OverloadedDeclRef:
3790 return cxloc::translateSourceLocation(getCursorContext(C),
3791 getCursorOverloadedDeclRef(C).second);
3792
Douglas Gregorf46034a2010-01-18 23:41:10 +00003793 default:
3794 // FIXME: Need a way to enumerate all non-reference cases.
3795 llvm_unreachable("Missed a reference kind");
3796 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003797 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003798
3799 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003800 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003801 getLocationFromExpr(getCursorExpr(C)));
3802
Douglas Gregor36897b02010-09-10 00:22:18 +00003803 if (clang_isStatement(C.kind))
3804 return cxloc::translateSourceLocation(getCursorContext(C),
3805 getCursorStmt(C)->getLocStart());
3806
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003807 if (C.kind == CXCursor_PreprocessingDirective) {
3808 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3809 return cxloc::translateSourceLocation(getCursorContext(C), L);
3810 }
Douglas Gregor48072312010-03-18 15:23:44 +00003811
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003812 if (C.kind == CXCursor_MacroExpansion) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003813 SourceLocation L
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003814 = cxcursor::getCursorMacroExpansion(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003815 return cxloc::translateSourceLocation(getCursorContext(C), L);
3816 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003817
3818 if (C.kind == CXCursor_MacroDefinition) {
3819 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3820 return cxloc::translateSourceLocation(getCursorContext(C), L);
3821 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003822
3823 if (C.kind == CXCursor_InclusionDirective) {
3824 SourceLocation L
3825 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3826 return cxloc::translateSourceLocation(getCursorContext(C), L);
3827 }
3828
Ted Kremenek9a700d22010-05-12 06:16:13 +00003829 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003830 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003831
Douglas Gregorf46034a2010-01-18 23:41:10 +00003832 Decl *D = getCursorDecl(C);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00003833 if (!D)
3834 return clang_getNullLocation();
3835
Douglas Gregorf46034a2010-01-18 23:41:10 +00003836 SourceLocation Loc = D->getLocation();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003837 // FIXME: Multiple variables declared in a single declaration
3838 // currently lack the information needed to correctly determine their
3839 // ranges when accounting for the type-specifier. We use context
3840 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3841 // and if so, whether it is the first decl.
3842 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3843 if (!cxcursor::isFirstInDeclGroup(C))
3844 Loc = VD->getLocation();
3845 }
3846
Argyrios Kyrtzidisccc6f362012-03-23 03:33:19 +00003847 // For ObjC methods, give the start location of the method name.
3848 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
3849 Loc = MD->getSelectorStartLoc();
3850
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003851 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003852}
Douglas Gregora7bde202010-01-19 00:34:46 +00003853
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003854} // end extern "C"
3855
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003856CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
3857 assert(TU);
3858
3859 // Guard against an invalid SourceLocation, or we may assert in one
3860 // of the following calls.
3861 if (SLoc.isInvalid())
3862 return clang_getNullCursor();
3863
3864 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
3865
3866 // Translate the given source location to make it point at the beginning of
3867 // the token under the cursor.
3868 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +00003869 CXXUnit->getASTContext().getLangOpts());
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003870
3871 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3872 if (SLoc.isValid()) {
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003873 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003874 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
3875 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00003876 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003877 SourceLocation(SLoc));
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00003878 CursorVis.visitFileRegion();
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003879 }
3880
3881 return Result;
3882}
3883
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003884static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003885 if (clang_isReference(C.kind)) {
3886 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003887 case CXCursor_ObjCSuperClassRef:
3888 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003889
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003890 case CXCursor_ObjCProtocolRef:
3891 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003892
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003893 case CXCursor_ObjCClassRef:
3894 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003895
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003896 case CXCursor_TypeRef:
3897 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003898
3899 case CXCursor_TemplateRef:
3900 return getCursorTemplateRef(C).second;
3901
Douglas Gregor69319002010-08-31 23:48:11 +00003902 case CXCursor_NamespaceRef:
3903 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003904
3905 case CXCursor_MemberRef:
3906 return getCursorMemberRef(C).second;
3907
Ted Kremenek3064ef92010-08-27 21:34:58 +00003908 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003909 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003910
Douglas Gregor36897b02010-09-10 00:22:18 +00003911 case CXCursor_LabelRef:
3912 return getCursorLabelRef(C).second;
3913
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003914 case CXCursor_OverloadedDeclRef:
3915 return getCursorOverloadedDeclRef(C).second;
3916
Douglas Gregor011d8b92012-02-15 00:54:55 +00003917 case CXCursor_VariableRef:
3918 return getCursorVariableRef(C).second;
3919
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003920 default:
3921 // FIXME: Need a way to enumerate all non-reference cases.
3922 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003923 }
3924 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003925
3926 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003927 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003928
3929 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003930 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003931
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00003932 if (clang_isAttribute(C.kind))
3933 return getCursorAttr(C)->getRange();
3934
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003935 if (C.kind == CXCursor_PreprocessingDirective)
3936 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003937
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00003938 if (C.kind == CXCursor_MacroExpansion) {
3939 ASTUnit *TU = getCursorASTUnit(C);
3940 SourceRange Range = cxcursor::getCursorMacroExpansion(C)->getSourceRange();
3941 return TU->mapRangeFromPreamble(Range);
3942 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003943
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00003944 if (C.kind == CXCursor_MacroDefinition) {
3945 ASTUnit *TU = getCursorASTUnit(C);
3946 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
3947 return TU->mapRangeFromPreamble(Range);
3948 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003949
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00003950 if (C.kind == CXCursor_InclusionDirective) {
3951 ASTUnit *TU = getCursorASTUnit(C);
3952 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3953 return TU->mapRangeFromPreamble(Range);
3954 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003955
Argyrios Kyrtzidis0822c5f2012-03-19 23:17:58 +00003956 if (C.kind == CXCursor_TranslationUnit) {
3957 ASTUnit *TU = getCursorASTUnit(C);
3958 FileID MainID = TU->getSourceManager().getMainFileID();
3959 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
3960 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
3961 return SourceRange(Start, End);
3962 }
3963
Ted Kremenek007a7c92010-11-01 23:26:51 +00003964 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3965 Decl *D = cxcursor::getCursorDecl(C);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00003966 if (!D)
3967 return SourceRange();
3968
Ted Kremenek007a7c92010-11-01 23:26:51 +00003969 SourceRange R = D->getSourceRange();
3970 // FIXME: Multiple variables declared in a single declaration
3971 // currently lack the information needed to correctly determine their
3972 // ranges when accounting for the type-specifier. We use context
3973 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3974 // and if so, whether it is the first decl.
3975 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3976 if (!cxcursor::isFirstInDeclGroup(C))
3977 R.setBegin(VD->getLocation());
3978 }
3979 return R;
3980 }
Douglas Gregor66537982010-11-17 17:14:07 +00003981 return SourceRange();
3982}
3983
3984/// \brief Retrieves the "raw" cursor extent, which is then extended to include
3985/// the decl-specifier-seq for declarations.
3986static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
3987 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3988 Decl *D = cxcursor::getCursorDecl(C);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00003989 if (!D)
3990 return SourceRange();
3991
Douglas Gregor66537982010-11-17 17:14:07 +00003992 SourceRange R = D->getSourceRange();
Douglas Gregor66537982010-11-17 17:14:07 +00003993
Douglas Gregor2494dd02011-03-01 01:34:45 +00003994 // Adjust the start of the location for declarations preceded by
3995 // declaration specifiers.
3996 SourceLocation StartLoc;
3997 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
3998 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
Daniel Dunbar96a00142012-03-09 18:35:03 +00003999 StartLoc = TI->getTypeLoc().getLocStart();
Douglas Gregor2494dd02011-03-01 01:34:45 +00004000 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
4001 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
Daniel Dunbar96a00142012-03-09 18:35:03 +00004002 StartLoc = TI->getTypeLoc().getLocStart();
Douglas Gregor2494dd02011-03-01 01:34:45 +00004003 }
4004
4005 if (StartLoc.isValid() && R.getBegin().isValid() &&
4006 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
4007 R.setBegin(StartLoc);
4008
4009 // FIXME: Multiple variables declared in a single declaration
4010 // currently lack the information needed to correctly determine their
4011 // ranges when accounting for the type-specifier. We use context
4012 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
4013 // and if so, whether it is the first decl.
4014 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4015 if (!cxcursor::isFirstInDeclGroup(C))
4016 R.setBegin(VD->getLocation());
Douglas Gregor66537982010-11-17 17:14:07 +00004017 }
4018
4019 return R;
4020 }
4021
4022 return getRawCursorExtent(C);
4023}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004024
4025extern "C" {
4026
4027CXSourceRange clang_getCursorExtent(CXCursor C) {
4028 SourceRange R = getRawCursorExtent(C);
4029 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00004030 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004031
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004032 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00004033}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004034
4035CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00004036 if (clang_isInvalid(C.kind))
4037 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004038
Ted Kremeneka60ed472010-11-16 08:15:36 +00004039 CXTranslationUnit tu = getCursorTU(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004040 if (clang_isDeclaration(C.kind)) {
4041 Decl *D = getCursorDecl(C);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00004042 if (!D)
4043 return clang_getNullCursor();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004044 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004045 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Chris Lattner5f9e2722011-07-23 10:55:15 +00004046 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00004047 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
4048 return MakeCXCursor(Property, tu);
4049
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004050 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004051 }
4052
Douglas Gregor97b98722010-01-19 23:20:36 +00004053 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004054 Expr *E = getCursorExpr(C);
4055 Decl *D = getDeclFromExpr(E);
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00004056 if (D) {
4057 CXCursor declCursor = MakeCXCursor(D, tu);
4058 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
4059 declCursor);
4060 return declCursor;
4061 }
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004062
4063 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004064 return MakeCursorOverloadedDeclRef(Ovl, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004065
Douglas Gregor97b98722010-01-19 23:20:36 +00004066 return clang_getNullCursor();
4067 }
4068
Douglas Gregor36897b02010-09-10 00:22:18 +00004069 if (clang_isStatement(C.kind)) {
4070 Stmt *S = getCursorStmt(C);
4071 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Ted Kremenek37c2e962011-03-15 23:47:49 +00004072 if (LabelDecl *label = Goto->getLabel())
4073 if (LabelStmt *labelS = label->getStmt())
4074 return MakeCXCursor(labelS, getCursorDecl(C), tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00004075
4076 return clang_getNullCursor();
4077 }
4078
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004079 if (C.kind == CXCursor_MacroExpansion) {
Chandler Carruth9e5bb852011-07-14 08:20:46 +00004080 if (MacroDefinition *Def = getCursorMacroExpansion(C)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004081 return MakeMacroDefinitionCursor(Def, tu);
Douglas Gregorbf7efa22010-03-18 18:23:03 +00004082 }
4083
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004084 if (!clang_isReference(C.kind))
4085 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004086
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004087 switch (C.kind) {
4088 case CXCursor_ObjCSuperClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004089 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004090
4091 case CXCursor_ObjCProtocolRef: {
Argyrios Kyrtzidis98c16b82012-01-24 19:40:15 +00004092 ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
4093 if (ObjCProtocolDecl *Def = Prot->getDefinition())
4094 return MakeCXCursor(Def, tu);
4095
Argyrios Kyrtzidisc15707d2012-01-24 21:39:26 +00004096 return MakeCXCursor(Prot, tu);
Argyrios Kyrtzidis98c16b82012-01-24 19:40:15 +00004097 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004098
Douglas Gregor7723fec2011-12-15 20:29:51 +00004099 case CXCursor_ObjCClassRef: {
4100 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
4101 if (ObjCInterfaceDecl *Def = Class->getDefinition())
4102 return MakeCXCursor(Def, tu);
4103
Argyrios Kyrtzidisc15707d2012-01-24 21:39:26 +00004104 return MakeCXCursor(Class, tu);
Douglas Gregor7723fec2011-12-15 20:29:51 +00004105 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00004106
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004107 case CXCursor_TypeRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004108 return MakeCXCursor(getCursorTypeRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00004109
4110 case CXCursor_TemplateRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004111 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00004112
Douglas Gregor69319002010-08-31 23:48:11 +00004113 case CXCursor_NamespaceRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004114 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
Douglas Gregor69319002010-08-31 23:48:11 +00004115
Douglas Gregora67e03f2010-09-09 21:42:20 +00004116 case CXCursor_MemberRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004117 return MakeCXCursor(getCursorMemberRef(C).first, tu );
Douglas Gregora67e03f2010-09-09 21:42:20 +00004118
Ted Kremenek3064ef92010-08-27 21:34:58 +00004119 case CXCursor_CXXBaseSpecifier: {
4120 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
4121 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004122 tu ));
Ted Kremenek3064ef92010-08-27 21:34:58 +00004123 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004124
Douglas Gregor36897b02010-09-10 00:22:18 +00004125 case CXCursor_LabelRef:
4126 // FIXME: We end up faking the "parent" declaration here because we
4127 // don't want to make CXCursor larger.
4128 return MakeCXCursor(getCursorLabelRef(C).first,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004129 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
4130 .getTranslationUnitDecl(),
4131 tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00004132
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004133 case CXCursor_OverloadedDeclRef:
4134 return C;
Douglas Gregor011d8b92012-02-15 00:54:55 +00004135
4136 case CXCursor_VariableRef:
4137 return MakeCXCursor(getCursorVariableRef(C).first, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004138
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004139 default:
4140 // We would prefer to enumerate all non-reference cursor kinds here.
4141 llvm_unreachable("Unhandled reference cursor kind");
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004142 }
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004143}
4144
Douglas Gregorb6998662010-01-19 19:34:47 +00004145CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00004146 if (clang_isInvalid(C.kind))
4147 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004148
Ted Kremeneka60ed472010-11-16 08:15:36 +00004149 CXTranslationUnit TU = getCursorTU(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004150
Douglas Gregorb6998662010-01-19 19:34:47 +00004151 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00004152 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00004153 C = clang_getCursorReferenced(C);
4154 WasReference = true;
4155 }
4156
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004157 if (C.kind == CXCursor_MacroExpansion)
Douglas Gregorbf7efa22010-03-18 18:23:03 +00004158 return clang_getCursorReferenced(C);
4159
Douglas Gregorb6998662010-01-19 19:34:47 +00004160 if (!clang_isDeclaration(C.kind))
4161 return clang_getNullCursor();
4162
4163 Decl *D = getCursorDecl(C);
4164 if (!D)
4165 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004166
Douglas Gregorb6998662010-01-19 19:34:47 +00004167 switch (D->getKind()) {
4168 // Declaration kinds that don't really separate the notions of
4169 // declaration and definition.
4170 case Decl::Namespace:
4171 case Decl::Typedef:
Richard Smith162e1c12011-04-15 14:24:37 +00004172 case Decl::TypeAlias:
Richard Smith3e4c6c42011-05-05 21:57:07 +00004173 case Decl::TypeAliasTemplate:
Douglas Gregorb6998662010-01-19 19:34:47 +00004174 case Decl::TemplateTypeParm:
4175 case Decl::EnumConstant:
4176 case Decl::Field:
Benjamin Kramerd9811462010-11-21 14:11:41 +00004177 case Decl::IndirectField:
Douglas Gregorb6998662010-01-19 19:34:47 +00004178 case Decl::ObjCIvar:
4179 case Decl::ObjCAtDefsField:
4180 case Decl::ImplicitParam:
4181 case Decl::ParmVar:
4182 case Decl::NonTypeTemplateParm:
4183 case Decl::TemplateTemplateParm:
4184 case Decl::ObjCCategoryImpl:
4185 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00004186 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00004187 case Decl::LinkageSpec:
4188 case Decl::ObjCPropertyImpl:
4189 case Decl::FileScopeAsm:
4190 case Decl::StaticAssert:
4191 case Decl::Block:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00004192 case Decl::Label: // FIXME: Is this right??
Francois Pichetaf0f4d02011-08-14 03:52:19 +00004193 case Decl::ClassScopeFunctionSpecialization:
Douglas Gregor15de72c2011-12-02 23:23:56 +00004194 case Decl::Import:
Douglas Gregorb6998662010-01-19 19:34:47 +00004195 return C;
4196
4197 // Declaration kinds that don't make any sense here, but are
4198 // nonetheless harmless.
4199 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00004200 break;
4201
4202 // Declaration kinds for which the definition is not resolvable.
4203 case Decl::UnresolvedUsingTypename:
4204 case Decl::UnresolvedUsingValue:
4205 break;
4206
4207 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00004208 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004209 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004210
4211 case Decl::NamespaceAlias:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004212 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004213
4214 case Decl::Enum:
4215 case Decl::Record:
4216 case Decl::CXXRecord:
4217 case Decl::ClassTemplateSpecialization:
4218 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00004219 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004220 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004221 return clang_getNullCursor();
4222
4223 case Decl::Function:
4224 case Decl::CXXMethod:
4225 case Decl::CXXConstructor:
4226 case Decl::CXXDestructor:
4227 case Decl::CXXConversion: {
4228 const FunctionDecl *Def = 0;
4229 if (cast<FunctionDecl>(D)->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004230 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004231 return clang_getNullCursor();
4232 }
4233
4234 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00004235 // Ask the variable if it has a definition.
4236 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004237 return MakeCXCursor(Def, TU);
Sebastian Redl31310a22010-02-01 20:16:42 +00004238 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00004239 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004240
Douglas Gregorb6998662010-01-19 19:34:47 +00004241 case Decl::FunctionTemplate: {
4242 const FunctionDecl *Def = 0;
4243 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004244 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004245 return clang_getNullCursor();
4246 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004247
Douglas Gregorb6998662010-01-19 19:34:47 +00004248 case Decl::ClassTemplate: {
4249 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00004250 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00004251 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004252 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004253 return clang_getNullCursor();
4254 }
4255
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004256 case Decl::Using:
4257 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004258 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004259
4260 case Decl::UsingShadow:
4261 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004262 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004263 TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004264
4265 case Decl::ObjCMethod: {
4266 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
4267 if (Method->isThisDeclarationADefinition())
4268 return C;
4269
4270 // Dig out the method definition in the associated
4271 // @implementation, if we have it.
4272 // FIXME: The ASTs should make finding the definition easier.
4273 if (ObjCInterfaceDecl *Class
4274 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
4275 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
4276 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
4277 Method->isInstanceMethod()))
4278 if (Def->isThisDeclarationADefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004279 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004280
4281 return clang_getNullCursor();
4282 }
4283
4284 case Decl::ObjCCategory:
4285 if (ObjCCategoryImplDecl *Impl
4286 = cast<ObjCCategoryDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004287 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004288 return clang_getNullCursor();
4289
4290 case Decl::ObjCProtocol:
Douglas Gregor5e2a1ff2012-01-01 19:29:29 +00004291 if (ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
4292 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004293 return clang_getNullCursor();
4294
Douglas Gregor375bb142011-12-27 22:43:10 +00004295 case Decl::ObjCInterface: {
Douglas Gregorb6998662010-01-19 19:34:47 +00004296 // There are two notions of a "definition" for an Objective-C
4297 // class: the interface and its implementation. When we resolved a
4298 // reference to an Objective-C class, produce the @interface as
4299 // the definition; when we were provided with the interface,
4300 // produce the @implementation as the definition.
Douglas Gregor375bb142011-12-27 22:43:10 +00004301 ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
Douglas Gregorb6998662010-01-19 19:34:47 +00004302 if (WasReference) {
Douglas Gregor375bb142011-12-27 22:43:10 +00004303 if (ObjCInterfaceDecl *Def = IFace->getDefinition())
Douglas Gregor7723fec2011-12-15 20:29:51 +00004304 return MakeCXCursor(Def, TU);
Douglas Gregor375bb142011-12-27 22:43:10 +00004305 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004306 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004307 return clang_getNullCursor();
Douglas Gregor375bb142011-12-27 22:43:10 +00004308 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004309
Douglas Gregorb6998662010-01-19 19:34:47 +00004310 case Decl::ObjCProperty:
4311 // FIXME: We don't really know where to find the
4312 // ObjCPropertyImplDecls that implement this property.
4313 return clang_getNullCursor();
4314
4315 case Decl::ObjCCompatibleAlias:
4316 if (ObjCInterfaceDecl *Class
4317 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
Douglas Gregor7723fec2011-12-15 20:29:51 +00004318 if (ObjCInterfaceDecl *Def = Class->getDefinition())
4319 return MakeCXCursor(Def, TU);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004320
Douglas Gregorb6998662010-01-19 19:34:47 +00004321 return clang_getNullCursor();
4322
Douglas Gregorb6998662010-01-19 19:34:47 +00004323 case Decl::Friend:
4324 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004325 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004326 return clang_getNullCursor();
4327
4328 case Decl::FriendTemplate:
4329 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004330 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004331 return clang_getNullCursor();
4332 }
4333
4334 return clang_getNullCursor();
4335}
4336
4337unsigned clang_isCursorDefinition(CXCursor C) {
4338 if (!clang_isDeclaration(C.kind))
4339 return 0;
4340
4341 return clang_getCursorDefinition(C) == C;
4342}
4343
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004344CXCursor clang_getCanonicalCursor(CXCursor C) {
4345 if (!clang_isDeclaration(C.kind))
4346 return C;
4347
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004348 if (Decl *D = getCursorDecl(C)) {
Argyrios Kyrtzidisdebb00f2011-07-15 22:37:58 +00004349 if (ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
4350 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
4351 return MakeCXCursor(CatD, getCursorTU(C));
4352
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004353 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
4354 if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
4355 return MakeCXCursor(IFD, getCursorTU(C));
4356
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004357 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004358 }
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004359
4360 return C;
4361}
4362
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004363unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004364 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004365 return 0;
4366
4367 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
4368 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
4369 return E->getNumDecls();
4370
4371 if (OverloadedTemplateStorage *S
4372 = Storage.dyn_cast<OverloadedTemplateStorage*>())
4373 return S->size();
4374
4375 Decl *D = Storage.get<Decl*>();
4376 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00004377 return Using->shadow_size();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004378
4379 return 0;
4380}
4381
4382CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004383 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004384 return clang_getNullCursor();
4385
4386 if (index >= clang_getNumOverloadedDecls(cursor))
4387 return clang_getNullCursor();
4388
Ted Kremeneka60ed472010-11-16 08:15:36 +00004389 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004390 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
4391 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004392 return MakeCXCursor(E->decls_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004393
4394 if (OverloadedTemplateStorage *S
4395 = Storage.dyn_cast<OverloadedTemplateStorage*>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004396 return MakeCXCursor(S->begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004397
4398 Decl *D = Storage.get<Decl*>();
4399 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
4400 // FIXME: This is, unfortunately, linear time.
4401 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
4402 std::advance(Pos, index);
Ted Kremeneka60ed472010-11-16 08:15:36 +00004403 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004404 }
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004405
4406 return clang_getNullCursor();
4407}
4408
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00004409void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00004410 const char **startBuf,
4411 const char **endBuf,
4412 unsigned *startLine,
4413 unsigned *startColumn,
4414 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00004415 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00004416 assert(getCursorDecl(C) && "CXCursor has null decl");
4417 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00004418 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
4419 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004420
Steve Naroff4ade6d62009-09-23 17:52:52 +00004421 SourceManager &SM = FD->getASTContext().getSourceManager();
4422 *startBuf = SM.getCharacterData(Body->getLBracLoc());
4423 *endBuf = SM.getCharacterData(Body->getRBracLoc());
4424 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
4425 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
4426 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
4427 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
4428}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004429
Douglas Gregor430d7a12011-07-25 17:48:11 +00004430
4431CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
4432 unsigned PieceIndex) {
4433 RefNamePieces Pieces;
4434
4435 switch (C.kind) {
4436 case CXCursor_MemberRefExpr:
4437 if (MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
4438 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
4439 E->getQualifierLoc().getSourceRange());
4440 break;
4441
4442 case CXCursor_DeclRefExpr:
4443 if (DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C)))
4444 Pieces = buildPieces(NameFlags, false, E->getNameInfo(),
4445 E->getQualifierLoc().getSourceRange(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00004446 E->getOptionalExplicitTemplateArgs());
Douglas Gregor430d7a12011-07-25 17:48:11 +00004447 break;
4448
4449 case CXCursor_CallExpr:
4450 if (CXXOperatorCallExpr *OCE =
4451 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
4452 Expr *Callee = OCE->getCallee();
4453 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
4454 Callee = ICE->getSubExpr();
4455
4456 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
4457 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
4458 DRE->getQualifierLoc().getSourceRange());
4459 }
4460 break;
4461
4462 default:
4463 break;
4464 }
4465
4466 if (Pieces.empty()) {
4467 if (PieceIndex == 0)
4468 return clang_getCursorExtent(C);
4469 } else if (PieceIndex < Pieces.size()) {
4470 SourceRange R = Pieces[PieceIndex];
4471 if (R.isValid())
4472 return cxloc::translateSourceRange(getCursorContext(C), R);
4473 }
4474
4475 return clang_getNullRange();
4476}
4477
Douglas Gregor0a812cf2010-02-18 23:07:20 +00004478void clang_enableStackTraces(void) {
4479 llvm::sys::PrintStackTraceOnErrorSignal();
4480}
4481
Daniel Dunbar995aaf92010-11-04 01:26:29 +00004482void clang_executeOnThread(void (*fn)(void*), void *user_data,
4483 unsigned stack_size) {
4484 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
4485}
4486
Ted Kremenekfb480492010-01-13 21:46:36 +00004487} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00004488
Ted Kremenekfb480492010-01-13 21:46:36 +00004489//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004490// Token-based Operations.
4491//===----------------------------------------------------------------------===//
4492
4493/* CXToken layout:
4494 * int_data[0]: a CXTokenKind
4495 * int_data[1]: starting token location
4496 * int_data[2]: token length
4497 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004498 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004499 * otherwise unused.
4500 */
4501extern "C" {
4502
4503CXTokenKind clang_getTokenKind(CXToken CXTok) {
4504 return static_cast<CXTokenKind>(CXTok.int_data[0]);
4505}
4506
4507CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
4508 switch (clang_getTokenKind(CXTok)) {
4509 case CXToken_Identifier:
4510 case CXToken_Keyword:
4511 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004512 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
4513 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004514
4515 case CXToken_Literal: {
4516 // We have stashed the starting pointer in the ptr_data field. Use it.
4517 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Chris Lattner5f9e2722011-07-23 10:55:15 +00004518 return createCXString(StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004519 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004520
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004521 case CXToken_Punctuation:
4522 case CXToken_Comment:
4523 break;
4524 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004525
4526 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004527 // deconstructing the source location.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004528 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004529 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004530 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004531
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004532 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
4533 std::pair<FileID, unsigned> LocInfo
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004534 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00004535 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004536 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004537 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
4538 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00004539 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004540
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004541 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004542}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004543
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004544CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004545 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004546 if (!CXXUnit)
4547 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004548
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004549 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
4550 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4551}
4552
4553CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004554 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor5352ac02010-01-28 00:27:43 +00004555 if (!CXXUnit)
4556 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004557
4558 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004559 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4560}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004561
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004562static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
4563 SmallVectorImpl<CXToken> &CXTokens) {
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004564 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4565 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004566 = SourceMgr.getDecomposedLoc(Range.getBegin());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004567 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004568 = SourceMgr.getDecomposedLoc(Range.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004569
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004570 // Cannot tokenize across files.
4571 if (BeginLocInfo.first != EndLocInfo.first)
4572 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004573
4574 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004575 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004576 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004577 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00004578 if (Invalid)
4579 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00004580
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004581 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
David Blaikie4e4d0842012-03-11 07:00:24 +00004582 CXXUnit->getASTContext().getLangOpts(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004583 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004584 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004585
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004586 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004587 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004588 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00004589 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004590 do {
4591 // Lex the next token
4592 Lex.LexFromRawLexer(Tok);
4593 if (Tok.is(tok::eof))
4594 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004595
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004596 // Initialize the CXToken.
4597 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004598
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004599 // - Common fields
4600 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
4601 CXTok.int_data[2] = Tok.getLength();
4602 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004603
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004604 // - Kind-specific fields
4605 if (Tok.isLiteral()) {
4606 CXTok.int_data[0] = CXToken_Literal;
4607 CXTok.ptr_data = (void *)Tok.getLiteralData();
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004608 } else if (Tok.is(tok::raw_identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00004609 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004610 IdentifierInfo *II
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004611 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004612
David Chisnall096428b2010-10-13 21:44:48 +00004613 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004614 CXTok.int_data[0] = CXToken_Keyword;
4615 }
4616 else {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004617 CXTok.int_data[0] = Tok.is(tok::identifier)
4618 ? CXToken_Identifier
4619 : CXToken_Keyword;
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004620 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004621 CXTok.ptr_data = II;
4622 } else if (Tok.is(tok::comment)) {
4623 CXTok.int_data[0] = CXToken_Comment;
4624 CXTok.ptr_data = 0;
4625 } else {
4626 CXTok.int_data[0] = CXToken_Punctuation;
4627 CXTok.ptr_data = 0;
4628 }
4629 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00004630 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004631 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004632}
4633
4634void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
4635 CXToken **Tokens, unsigned *NumTokens) {
4636 if (Tokens)
4637 *Tokens = 0;
4638 if (NumTokens)
4639 *NumTokens = 0;
4640
4641 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4642 if (!CXXUnit || !Tokens || !NumTokens)
4643 return;
4644
4645 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4646
4647 SourceRange R = cxloc::translateCXSourceRange(Range);
4648 if (R.isInvalid())
4649 return;
4650
4651 SmallVector<CXToken, 32> CXTokens;
4652 getTokens(CXXUnit, R, CXTokens);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004653
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004654 if (CXTokens.empty())
4655 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004656
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004657 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
4658 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
4659 *NumTokens = CXTokens.size();
4660}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004661
Ted Kremenek6db61092010-05-05 00:55:15 +00004662void clang_disposeTokens(CXTranslationUnit TU,
4663 CXToken *Tokens, unsigned NumTokens) {
4664 free(Tokens);
4665}
4666
4667} // end: extern "C"
4668
4669//===----------------------------------------------------------------------===//
4670// Token annotation APIs.
4671//===----------------------------------------------------------------------===//
4672
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004673typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004674static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4675 CXCursor parent,
4676 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00004677namespace {
4678class AnnotateTokensWorker {
4679 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004680 CXToken *Tokens;
4681 CXCursor *Cursors;
4682 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004683 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00004684 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004685 CursorVisitor AnnotateVis;
4686 SourceManager &SrcMgr;
Douglas Gregorf5251602011-03-08 17:10:18 +00004687 bool HasContextSensitiveKeywords;
4688
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004689 bool MoreTokens() const { return TokIdx < NumTokens; }
4690 unsigned NextToken() const { return TokIdx; }
4691 void AdvanceToken() { ++TokIdx; }
4692 SourceLocation GetTokenLoc(unsigned tokI) {
4693 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4694 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004695 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004696 return Tokens[tokI].int_data[3] != 0;
4697 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004698 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004699 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[3]);
4700 }
4701
4702 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004703 void annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
4704 SourceRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004705
Ted Kremenek6db61092010-05-05 00:55:15 +00004706public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00004707 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004708 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004709 CXTranslationUnit tu, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00004710 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00004711 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004712 AnnotateVis(tu,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00004713 AnnotateTokensVisitor, this,
4714 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00004715 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00004716 RegionOfInterest),
Douglas Gregorf5251602011-03-08 17:10:18 +00004717 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()),
4718 HasContextSensitiveKeywords(false) { }
Ted Kremenek11949cb2010-05-05 00:55:17 +00004719
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004720 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00004721 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004722 void AnnotateTokens();
Douglas Gregorf5251602011-03-08 17:10:18 +00004723
4724 /// \brief Determine whether the annotator saw any cursors that have
4725 /// context-sensitive keywords.
4726 bool hasContextSensitiveKeywords() const {
4727 return HasContextSensitiveKeywords;
4728 }
Ted Kremenek6db61092010-05-05 00:55:15 +00004729};
4730}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004731
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004732void AnnotateTokensWorker::AnnotateTokens() {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004733 // Walk the AST within the region of interest, annotating tokens
4734 // along the way.
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004735 AnnotateVis.visitFileRegion();
Ted Kremenek11949cb2010-05-05 00:55:17 +00004736
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004737 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4738 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004739 if (Pos != Annotated.end() &&
4740 (clang_isInvalid(Cursors[I].kind) ||
4741 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004742 Cursors[I] = Pos->second;
4743 }
4744
4745 // Finish up annotating any tokens left.
4746 if (!MoreTokens())
4747 return;
4748
4749 const CXCursor &C = clang_getNullCursor();
4750 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004751 if (I < PreprocessingTokIdx && clang_isPreprocessing(Cursors[I].kind))
4752 continue;
4753
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004754 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4755 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004756 }
4757}
4758
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004759/// \brief It annotates and advances tokens with a cursor until the comparison
4760//// between the cursor location and the source range is the same as
4761/// \arg compResult.
4762///
4763/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
4764/// Pass RangeOverlap to annotate tokens inside a range.
4765void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
4766 RangeComparisonResult compResult,
4767 SourceRange range) {
4768 while (MoreTokens()) {
4769 const unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004770 if (isFunctionMacroToken(I))
4771 return annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004772
4773 SourceLocation TokLoc = GetTokenLoc(I);
4774 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4775 Cursors[I] = updateC;
4776 AdvanceToken();
4777 continue;
4778 }
4779 break;
4780 }
4781}
4782
4783/// \brief Special annotation handling for macro argument tokens.
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004784void AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
4785 CXCursor updateC,
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004786 RangeComparisonResult compResult,
4787 SourceRange range) {
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004788 assert(MoreTokens());
4789 assert(isFunctionMacroToken(NextToken()) &&
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004790 "Should be called only for macro arg tokens");
4791
4792 // This works differently than annotateAndAdvanceTokens; because expanded
4793 // macro arguments can have arbitrary translation-unit source order, we do not
4794 // advance the token index one by one until a token fails the range test.
4795 // We only advance once past all of the macro arg tokens if all of them
4796 // pass the range test. If one of them fails we keep the token index pointing
4797 // at the start of the macro arg tokens so that the failing token will be
4798 // annotated by a subsequent annotation try.
4799
4800 bool atLeastOneCompFail = false;
4801
4802 unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004803 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
4804 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004805 if (TokLoc.isFileID())
4806 continue; // not macro arg token, it's parens or comma.
4807 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4808 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
4809 Cursors[I] = updateC;
4810 } else
4811 atLeastOneCompFail = true;
4812 }
4813
4814 if (!atLeastOneCompFail)
4815 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
4816}
4817
Ted Kremenek6db61092010-05-05 00:55:15 +00004818enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004819AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004820 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004821 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004822 if (cursorRange.isInvalid())
4823 return CXChildVisit_Recurse;
Douglas Gregorf5251602011-03-08 17:10:18 +00004824
4825 if (!HasContextSensitiveKeywords) {
4826 // Objective-C properties can have context-sensitive keywords.
4827 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
4828 if (ObjCPropertyDecl *Property
4829 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
4830 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
4831 }
4832 // Objective-C methods can have context-sensitive keywords.
4833 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
4834 cursor.kind == CXCursor_ObjCClassMethodDecl) {
4835 if (ObjCMethodDecl *Method
4836 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
4837 if (Method->getObjCDeclQualifier())
4838 HasContextSensitiveKeywords = true;
4839 else {
4840 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
4841 PEnd = Method->param_end();
4842 P != PEnd; ++P) {
4843 if ((*P)->getObjCDeclQualifier()) {
4844 HasContextSensitiveKeywords = true;
4845 break;
4846 }
4847 }
4848 }
4849 }
4850 }
4851 // C++ methods can have context-sensitive keywords.
4852 else if (cursor.kind == CXCursor_CXXMethod) {
4853 if (CXXMethodDecl *Method
4854 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
4855 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
4856 HasContextSensitiveKeywords = true;
4857 }
4858 }
4859 // C++ classes can have context-sensitive keywords.
4860 else if (cursor.kind == CXCursor_StructDecl ||
4861 cursor.kind == CXCursor_ClassDecl ||
4862 cursor.kind == CXCursor_ClassTemplate ||
4863 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
4864 if (Decl *D = getCursorDecl(cursor))
4865 if (D->hasAttr<FinalAttr>())
4866 HasContextSensitiveKeywords = true;
4867 }
4868 }
4869
Douglas Gregor4419b672010-10-21 06:10:04 +00004870 if (clang_isPreprocessing(cursor.kind)) {
Chandler Carruthcea731a2011-07-14 16:07:57 +00004871 // For macro expansions, just note where the beginning of the macro
4872 // expansion occurs.
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004873 if (cursor.kind == CXCursor_MacroExpansion) {
Douglas Gregor4419b672010-10-21 06:10:04 +00004874 Annotated[Loc.int_data] = cursor;
4875 return CXChildVisit_Recurse;
4876 }
4877
Douglas Gregor4419b672010-10-21 06:10:04 +00004878 // Items in the preprocessing record are kept separate from items in
4879 // declarations, so we keep a separate token index.
4880 unsigned SavedTokIdx = TokIdx;
4881 TokIdx = PreprocessingTokIdx;
4882
4883 // Skip tokens up until we catch up to the beginning of the preprocessing
4884 // entry.
4885 while (MoreTokens()) {
4886 const unsigned I = NextToken();
4887 SourceLocation TokLoc = GetTokenLoc(I);
4888 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4889 case RangeBefore:
4890 AdvanceToken();
4891 continue;
4892 case RangeAfter:
4893 case RangeOverlap:
4894 break;
4895 }
4896 break;
4897 }
4898
4899 // Look at all of the tokens within this range.
4900 while (MoreTokens()) {
4901 const unsigned I = NextToken();
4902 SourceLocation TokLoc = GetTokenLoc(I);
4903 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4904 case RangeBefore:
David Blaikieb219cfc2011-09-23 05:06:16 +00004905 llvm_unreachable("Infeasible");
Douglas Gregor4419b672010-10-21 06:10:04 +00004906 case RangeAfter:
4907 break;
4908 case RangeOverlap:
4909 Cursors[I] = cursor;
4910 AdvanceToken();
4911 continue;
4912 }
4913 break;
4914 }
4915
4916 // Save the preprocessing token index; restore the non-preprocessing
4917 // token index.
4918 PreprocessingTokIdx = TokIdx;
4919 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004920 return CXChildVisit_Recurse;
4921 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004922
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004923 if (cursorRange.isInvalid())
4924 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004925
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004926 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4927
Ted Kremeneka333c662010-05-12 05:29:33 +00004928 // Adjust the annotated range based specific declarations.
4929 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4930 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004931 Decl *D = cxcursor::getCursorDecl(cursor);
Douglas Gregor2494dd02011-03-01 01:34:45 +00004932
4933 SourceLocation StartLoc;
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00004934 if (const DeclaratorDecl *DD = dyn_cast_or_null<DeclaratorDecl>(D)) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00004935 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
Daniel Dunbar96a00142012-03-09 18:35:03 +00004936 StartLoc = TI->getTypeLoc().getLocStart();
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00004937 } else if (TypedefDecl *Typedef = dyn_cast_or_null<TypedefDecl>(D)) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00004938 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
Daniel Dunbar96a00142012-03-09 18:35:03 +00004939 StartLoc = TI->getTypeLoc().getLocStart();
Ted Kremeneka333c662010-05-12 05:29:33 +00004940 }
Douglas Gregor2494dd02011-03-01 01:34:45 +00004941
4942 if (StartLoc.isValid() && L.isValid() &&
4943 SrcMgr.isBeforeInTranslationUnit(StartLoc, L))
4944 cursorRange.setBegin(StartLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004945 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004946
Ted Kremenek3f404602010-08-14 01:14:06 +00004947 // If the location of the cursor occurs within a macro instantiation, record
4948 // the spelling location of the cursor in our annotation map. We can then
4949 // paper over the token labelings during a post-processing step to try and
4950 // get cursor mappings for tokens that are the *arguments* of a macro
4951 // instantiation.
4952 if (L.isMacroID()) {
4953 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4954 // Only invalidate the old annotation if it isn't part of a preprocessing
4955 // directive. Here we assume that the default construction of CXCursor
4956 // results in CXCursor.kind being an initialized value (i.e., 0). If
4957 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004958
Ted Kremenek3f404602010-08-14 01:14:06 +00004959 CXCursor &oldC = Annotated[rawEncoding];
4960 if (!clang_isPreprocessing(oldC.kind))
4961 oldC = cursor;
4962 }
4963
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004964 const enum CXCursorKind K = clang_getCursorKind(parent);
4965 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004966 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4967 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004968
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004969 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004970
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00004971 // Avoid having the cursor of an expression "overwrite" the annotation of the
4972 // variable declaration that it belongs to.
4973 // This can happen for C++ constructor expressions whose range generally
4974 // include the variable declaration, e.g.:
4975 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
4976 if (clang_isExpression(cursorK)) {
4977 Expr *E = getCursorExpr(cursor);
Argyrios Kyrtzidis8ccac3d2011-06-29 22:20:07 +00004978 if (Decl *D = getCursorParentDecl(cursor)) {
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00004979 const unsigned I = NextToken();
4980 if (E->getLocStart().isValid() && D->getLocation().isValid() &&
4981 E->getLocStart() == D->getLocation() &&
4982 E->getLocStart() == GetTokenLoc(I)) {
4983 Cursors[I] = updateC;
4984 AdvanceToken();
4985 }
4986 }
4987 }
4988
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004989 // Visit children to get their cursor information.
4990 const unsigned BeforeChildren = NextToken();
4991 VisitChildren(cursor);
4992 const unsigned AfterChildren = NextToken();
4993
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004994 // Scan the tokens that are at the end of the cursor, but are not captured
4995 // but the child cursors.
4996 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
Ted Kremenek6db61092010-05-05 00:55:15 +00004997
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004998 // Scan the tokens that are at the beginning of the cursor, but are not
4999 // capture by the child cursors.
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005000 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
5001 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
5002 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00005003
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005004 Cursors[I] = cursor;
5005 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005006
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005007 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005008}
5009
Ted Kremenek6db61092010-05-05 00:55:15 +00005010static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
5011 CXCursor parent,
5012 CXClientData client_data) {
5013 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
5014}
5015
Ted Kremenek6628a612011-03-18 22:51:30 +00005016namespace {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005017
5018/// \brief Uses the macro expansions in the preprocessing record to find
5019/// and mark tokens that are macro arguments. This info is used by the
5020/// AnnotateTokensWorker.
5021class MarkMacroArgTokensVisitor {
5022 SourceManager &SM;
5023 CXToken *Tokens;
5024 unsigned NumTokens;
5025 unsigned CurIdx;
5026
5027public:
5028 MarkMacroArgTokensVisitor(SourceManager &SM,
5029 CXToken *tokens, unsigned numTokens)
5030 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
5031
5032 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
5033 if (cursor.kind != CXCursor_MacroExpansion)
5034 return CXChildVisit_Continue;
5035
5036 SourceRange macroRange = getCursorMacroExpansion(cursor)->getSourceRange();
5037 if (macroRange.getBegin() == macroRange.getEnd())
5038 return CXChildVisit_Continue; // it's not a function macro.
5039
5040 for (; CurIdx < NumTokens; ++CurIdx) {
5041 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
5042 macroRange.getBegin()))
5043 break;
5044 }
5045
5046 if (CurIdx == NumTokens)
5047 return CXChildVisit_Break;
5048
5049 for (; CurIdx < NumTokens; ++CurIdx) {
5050 SourceLocation tokLoc = getTokenLoc(CurIdx);
5051 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
5052 break;
5053
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00005054 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005055 }
5056
5057 if (CurIdx == NumTokens)
5058 return CXChildVisit_Break;
5059
5060 return CXChildVisit_Continue;
5061 }
5062
5063private:
5064 SourceLocation getTokenLoc(unsigned tokI) {
5065 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
5066 }
5067
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00005068 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005069 // The third field is reserved and currently not used. Use it here
5070 // to mark macro arg expanded tokens with their expanded locations.
5071 Tokens[tokI].int_data[3] = loc.getRawEncoding();
5072 }
5073};
5074
5075} // end anonymous namespace
5076
5077static CXChildVisitResult
5078MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
5079 CXClientData client_data) {
5080 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
5081 parent);
5082}
5083
5084namespace {
Ted Kremenek6628a612011-03-18 22:51:30 +00005085 struct clang_annotateTokens_Data {
5086 CXTranslationUnit TU;
5087 ASTUnit *CXXUnit;
5088 CXToken *Tokens;
5089 unsigned NumTokens;
5090 CXCursor *Cursors;
5091 };
5092}
5093
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005094static void annotatePreprocessorTokens(CXTranslationUnit TU,
5095 SourceRange RegionOfInterest,
5096 AnnotateTokensData &Annotated) {
5097 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
5098
5099 SourceManager &SourceMgr = CXXUnit->getSourceManager();
5100 std::pair<FileID, unsigned> BeginLocInfo
5101 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
5102 std::pair<FileID, unsigned> EndLocInfo
5103 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
5104
5105 if (BeginLocInfo.first != EndLocInfo.first)
5106 return;
5107
5108 StringRef Buffer;
5109 bool Invalid = false;
5110 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
5111 if (Buffer.empty() || Invalid)
5112 return;
5113
5114 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
David Blaikie4e4d0842012-03-11 07:00:24 +00005115 CXXUnit->getASTContext().getLangOpts(),
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005116 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
5117 Buffer.end());
5118 Lex.SetCommentRetentionState(true);
5119
5120 // Lex tokens in raw mode until we hit the end of the range, to avoid
5121 // entering #includes or expanding macros.
5122 while (true) {
5123 Token Tok;
5124 Lex.LexFromRawLexer(Tok);
5125
5126 reprocess:
5127 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
5128 // We have found a preprocessing directive. Gobble it up so that we
5129 // don't see it while preprocessing these tokens later, but keep track
5130 // of all of the token locations inside this preprocessing directive so
5131 // that we can annotate them appropriately.
5132 //
5133 // FIXME: Some simple tests here could identify macro definitions and
5134 // #undefs, to provide specific cursor kinds for those.
5135 SmallVector<SourceLocation, 32> Locations;
5136 do {
5137 Locations.push_back(Tok.getLocation());
5138 Lex.LexFromRawLexer(Tok);
5139 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
5140
5141 using namespace cxcursor;
5142 CXCursor Cursor
5143 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
5144 Locations.back()),
5145 TU);
5146 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
5147 Annotated[Locations[I].getRawEncoding()] = Cursor;
5148 }
5149
5150 if (Tok.isAtStartOfLine())
5151 goto reprocess;
5152
5153 continue;
5154 }
5155
5156 if (Tok.is(tok::eof))
5157 break;
5158 }
5159}
5160
Ted Kremenekab979612010-11-11 08:05:23 +00005161// This gets run a separate thread to avoid stack blowout.
Ted Kremenek6628a612011-03-18 22:51:30 +00005162static void clang_annotateTokensImpl(void *UserData) {
5163 CXTranslationUnit TU = ((clang_annotateTokens_Data*)UserData)->TU;
5164 ASTUnit *CXXUnit = ((clang_annotateTokens_Data*)UserData)->CXXUnit;
5165 CXToken *Tokens = ((clang_annotateTokens_Data*)UserData)->Tokens;
5166 const unsigned NumTokens = ((clang_annotateTokens_Data*)UserData)->NumTokens;
5167 CXCursor *Cursors = ((clang_annotateTokens_Data*)UserData)->Cursors;
5168
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00005169 CIndexer *CXXIdx = (CIndexer*)TU->CIdx;
5170 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
Argyrios Kyrtzidis81b5ac32012-03-28 02:49:54 +00005171 setThreadBackgroundPriority();
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00005172
Ted Kremenek6628a612011-03-18 22:51:30 +00005173 // Determine the region of interest, which contains all of the tokens.
5174 SourceRange RegionOfInterest;
5175 RegionOfInterest.setBegin(
5176 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
5177 RegionOfInterest.setEnd(
5178 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
5179 Tokens[NumTokens-1])));
5180
5181 // A mapping from the source locations found when re-lexing or traversing the
5182 // region of interest to the corresponding cursors.
5183 AnnotateTokensData Annotated;
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005184
Ted Kremenek6628a612011-03-18 22:51:30 +00005185 // Relex the tokens within the source range to look for preprocessing
5186 // directives.
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005187 annotatePreprocessorTokens(TU, RegionOfInterest, Annotated);
Ted Kremenek6628a612011-03-18 22:51:30 +00005188
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005189 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
5190 // Search and mark tokens that are macro argument expansions.
5191 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
5192 Tokens, NumTokens);
5193 CursorVisitor MacroArgMarker(TU,
5194 MarkMacroArgTokensVisitorDelegate, &Visitor,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00005195 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00005196 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00005197 RegionOfInterest);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005198 MacroArgMarker.visitPreprocessedEntitiesInRegion();
5199 }
5200
Ted Kremenek6628a612011-03-18 22:51:30 +00005201 // Annotate all of the source locations in the region of interest that map to
5202 // a specific cursor.
5203 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
5204 TU, RegionOfInterest);
5205
5206 // FIXME: We use a ridiculous stack size here because the data-recursion
5207 // algorithm uses a large stack frame than the non-data recursive version,
5208 // and AnnotationTokensWorker currently transforms the data-recursion
5209 // algorithm back into a traditional recursion by explicitly calling
5210 // VisitChildren(). We will need to remove this explicit recursive call.
5211 W.AnnotateTokens();
5212
5213 // If we ran into any entities that involve context-sensitive keywords,
5214 // take another pass through the tokens to mark them as such.
5215 if (W.hasContextSensitiveKeywords()) {
5216 for (unsigned I = 0; I != NumTokens; ++I) {
5217 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
5218 continue;
5219
5220 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
5221 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5222 if (ObjCPropertyDecl *Property
5223 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
5224 if (Property->getPropertyAttributesAsWritten() != 0 &&
5225 llvm::StringSwitch<bool>(II->getName())
5226 .Case("readonly", true)
5227 .Case("assign", true)
John McCallf85e1932011-06-15 23:02:42 +00005228 .Case("unsafe_unretained", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00005229 .Case("readwrite", true)
5230 .Case("retain", true)
5231 .Case("copy", true)
5232 .Case("nonatomic", true)
5233 .Case("atomic", true)
5234 .Case("getter", true)
5235 .Case("setter", true)
John McCallf85e1932011-06-15 23:02:42 +00005236 .Case("strong", true)
5237 .Case("weak", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00005238 .Default(false))
5239 Tokens[I].int_data[0] = CXToken_Keyword;
5240 }
5241 continue;
5242 }
5243
5244 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
5245 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
5246 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5247 if (llvm::StringSwitch<bool>(II->getName())
5248 .Case("in", true)
5249 .Case("out", true)
5250 .Case("inout", true)
5251 .Case("oneway", true)
5252 .Case("bycopy", true)
5253 .Case("byref", true)
5254 .Default(false))
5255 Tokens[I].int_data[0] = CXToken_Keyword;
5256 continue;
5257 }
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00005258
5259 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
5260 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
5261 Tokens[I].int_data[0] = CXToken_Keyword;
Ted Kremenek6628a612011-03-18 22:51:30 +00005262 continue;
5263 }
5264 }
5265 }
Ted Kremenekab979612010-11-11 08:05:23 +00005266}
5267
Ted Kremenek6db61092010-05-05 00:55:15 +00005268extern "C" {
5269
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005270void clang_annotateTokens(CXTranslationUnit TU,
5271 CXToken *Tokens, unsigned NumTokens,
5272 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005273
5274 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005275 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005276
Douglas Gregor4419b672010-10-21 06:10:04 +00005277 // Any token we don't specifically annotate will have a NULL cursor.
5278 CXCursor C = clang_getNullCursor();
5279 for (unsigned I = 0; I != NumTokens; ++I)
5280 Cursors[I] = C;
5281
Ted Kremeneka60ed472010-11-16 08:15:36 +00005282 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor4419b672010-10-21 06:10:04 +00005283 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005284 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005285
Douglas Gregorbdf60622010-03-05 21:16:25 +00005286 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenek6628a612011-03-18 22:51:30 +00005287
5288 clang_annotateTokens_Data data = { TU, CXXUnit, Tokens, NumTokens, Cursors };
Ted Kremenekab979612010-11-11 08:05:23 +00005289 llvm::CrashRecoveryContext CRC;
Ted Kremenek6628a612011-03-18 22:51:30 +00005290 if (!RunSafely(CRC, clang_annotateTokensImpl, &data,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005291 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00005292 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
5293 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005294}
Ted Kremenek6628a612011-03-18 22:51:30 +00005295
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005296} // end: extern "C"
5297
5298//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00005299// Operations for querying linkage of a cursor.
5300//===----------------------------------------------------------------------===//
5301
5302extern "C" {
5303CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00005304 if (!clang_isDeclaration(cursor.kind))
5305 return CXLinkage_Invalid;
5306
Ted Kremenek16b42592010-03-03 06:36:57 +00005307 Decl *D = cxcursor::getCursorDecl(cursor);
5308 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
5309 switch (ND->getLinkage()) {
5310 case NoLinkage: return CXLinkage_NoLinkage;
5311 case InternalLinkage: return CXLinkage_Internal;
5312 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
5313 case ExternalLinkage: return CXLinkage_External;
5314 };
5315
5316 return CXLinkage_Invalid;
5317}
5318} // end: extern "C"
5319
5320//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005321// Operations for querying language of a cursor.
5322//===----------------------------------------------------------------------===//
5323
5324static CXLanguageKind getDeclLanguage(const Decl *D) {
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00005325 if (!D)
5326 return CXLanguage_C;
5327
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005328 switch (D->getKind()) {
5329 default:
5330 break;
5331 case Decl::ImplicitParam:
5332 case Decl::ObjCAtDefsField:
5333 case Decl::ObjCCategory:
5334 case Decl::ObjCCategoryImpl:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005335 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005336 case Decl::ObjCImplementation:
5337 case Decl::ObjCInterface:
5338 case Decl::ObjCIvar:
5339 case Decl::ObjCMethod:
5340 case Decl::ObjCProperty:
5341 case Decl::ObjCPropertyImpl:
5342 case Decl::ObjCProtocol:
5343 return CXLanguage_ObjC;
5344 case Decl::CXXConstructor:
5345 case Decl::CXXConversion:
5346 case Decl::CXXDestructor:
5347 case Decl::CXXMethod:
5348 case Decl::CXXRecord:
5349 case Decl::ClassTemplate:
5350 case Decl::ClassTemplatePartialSpecialization:
5351 case Decl::ClassTemplateSpecialization:
5352 case Decl::Friend:
5353 case Decl::FriendTemplate:
5354 case Decl::FunctionTemplate:
5355 case Decl::LinkageSpec:
5356 case Decl::Namespace:
5357 case Decl::NamespaceAlias:
5358 case Decl::NonTypeTemplateParm:
5359 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005360 case Decl::TemplateTemplateParm:
5361 case Decl::TemplateTypeParm:
5362 case Decl::UnresolvedUsingTypename:
5363 case Decl::UnresolvedUsingValue:
5364 case Decl::Using:
5365 case Decl::UsingDirective:
5366 case Decl::UsingShadow:
5367 return CXLanguage_CPlusPlus;
5368 }
5369
5370 return CXLanguage_C;
5371}
5372
5373extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00005374
5375enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
5376 if (clang_isDeclaration(cursor.kind))
5377 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005378 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Douglas Gregor58ddb602010-08-23 23:00:57 +00005379 return CXAvailability_Available;
5380
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005381 switch (D->getAvailability()) {
5382 case AR_Available:
5383 case AR_NotYetIntroduced:
5384 return CXAvailability_Available;
5385
5386 case AR_Deprecated:
Douglas Gregor58ddb602010-08-23 23:00:57 +00005387 return CXAvailability_Deprecated;
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005388
5389 case AR_Unavailable:
5390 return CXAvailability_NotAvailable;
5391 }
Douglas Gregor58ddb602010-08-23 23:00:57 +00005392 }
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005393
Douglas Gregor58ddb602010-08-23 23:00:57 +00005394 return CXAvailability_Available;
5395}
5396
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005397CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
5398 if (clang_isDeclaration(cursor.kind))
5399 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
5400
5401 return CXLanguage_Invalid;
5402}
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005403
5404 /// \brief If the given cursor is the "templated" declaration
5405 /// descibing a class or function template, return the class or
5406 /// function template.
5407static Decl *maybeGetTemplateCursor(Decl *D) {
5408 if (!D)
5409 return 0;
5410
5411 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
5412 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
5413 return FunTmpl;
5414
5415 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
5416 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
5417 return ClassTmpl;
5418
5419 return D;
5420}
5421
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005422CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
5423 if (clang_isDeclaration(cursor.kind)) {
5424 if (Decl *D = getCursorDecl(cursor)) {
5425 DeclContext *DC = D->getDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005426 if (!DC)
5427 return clang_getNullCursor();
5428
5429 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5430 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005431 }
5432 }
5433
5434 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
5435 if (Decl *D = getCursorDecl(cursor))
Ted Kremeneka60ed472010-11-16 08:15:36 +00005436 return MakeCXCursor(D, getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005437 }
5438
5439 return clang_getNullCursor();
5440}
5441
5442CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
5443 if (clang_isDeclaration(cursor.kind)) {
5444 if (Decl *D = getCursorDecl(cursor)) {
5445 DeclContext *DC = D->getLexicalDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005446 if (!DC)
5447 return clang_getNullCursor();
5448
5449 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5450 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005451 }
5452 }
5453
5454 // FIXME: Note that we can't easily compute the lexical context of a
5455 // statement or expression, so we return nothing.
5456 return clang_getNullCursor();
5457}
5458
Douglas Gregor9f592342010-10-01 20:25:15 +00005459void clang_getOverriddenCursors(CXCursor cursor,
5460 CXCursor **overridden,
5461 unsigned *num_overridden) {
5462 if (overridden)
5463 *overridden = 0;
5464 if (num_overridden)
5465 *num_overridden = 0;
5466 if (!overridden || !num_overridden)
5467 return;
5468
Argyrios Kyrtzidisb11be042011-10-06 07:00:46 +00005469 SmallVector<CXCursor, 8> Overridden;
5470 cxcursor::getOverriddenCursors(cursor, Overridden);
Douglas Gregor9f592342010-10-01 20:25:15 +00005471
Ted Kremenek24077122011-11-14 23:51:37 +00005472 // Don't allocate memory if we have no overriden cursors.
5473 if (Overridden.size() == 0)
5474 return;
5475
Argyrios Kyrtzidisb11be042011-10-06 07:00:46 +00005476 *num_overridden = Overridden.size();
5477 *overridden = new CXCursor [Overridden.size()];
5478 std::copy(Overridden.begin(), Overridden.end(), *overridden);
Douglas Gregor9f592342010-10-01 20:25:15 +00005479}
5480
5481void clang_disposeOverriddenCursors(CXCursor *overridden) {
5482 delete [] overridden;
5483}
5484
Douglas Gregorecdcb882010-10-20 22:00:55 +00005485CXFile clang_getIncludedFile(CXCursor cursor) {
5486 if (cursor.kind != CXCursor_InclusionDirective)
5487 return 0;
5488
5489 InclusionDirective *ID = getCursorInclusionDirective(cursor);
5490 return (void *)ID->getFile();
5491}
5492
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005493} // end: extern "C"
5494
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005495
5496//===----------------------------------------------------------------------===//
5497// C++ AST instrospection.
5498//===----------------------------------------------------------------------===//
5499
5500extern "C" {
5501unsigned clang_CXXMethod_isStatic(CXCursor C) {
5502 if (!clang_isDeclaration(C.kind))
5503 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00005504
5505 CXXMethodDecl *Method = 0;
5506 Decl *D = cxcursor::getCursorDecl(C);
5507 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5508 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5509 else
5510 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5511 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00005512}
Ted Kremenekb12903e2010-05-18 22:32:15 +00005513
Douglas Gregor211924b2011-05-12 15:17:24 +00005514unsigned clang_CXXMethod_isVirtual(CXCursor C) {
5515 if (!clang_isDeclaration(C.kind))
5516 return 0;
5517
5518 CXXMethodDecl *Method = 0;
5519 Decl *D = cxcursor::getCursorDecl(C);
5520 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5521 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5522 else
5523 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5524 return (Method && Method->isVirtual()) ? 1 : 0;
5525}
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005526} // end: extern "C"
5527
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005528//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00005529// Attribute introspection.
5530//===----------------------------------------------------------------------===//
5531
5532extern "C" {
5533CXType clang_getIBOutletCollectionType(CXCursor C) {
5534 if (C.kind != CXCursor_IBOutletCollectionAttr)
Ted Kremeneka60ed472010-11-16 08:15:36 +00005535 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005536
5537 IBOutletCollectionAttr *A =
5538 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
5539
Argyrios Kyrtzidis18aa2ff2011-09-13 18:49:52 +00005540 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005541}
5542} // end: extern "C"
5543
5544//===----------------------------------------------------------------------===//
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005545// Inspecting memory usage.
5546//===----------------------------------------------------------------------===//
5547
Ted Kremenekf7870022011-04-20 16:41:07 +00005548typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005549
Ted Kremenekf7870022011-04-20 16:41:07 +00005550static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
5551 enum CXTUResourceUsageKind k,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005552 unsigned long amount) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005553 CXTUResourceUsageEntry entry = { k, amount };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005554 entries.push_back(entry);
5555}
5556
5557extern "C" {
5558
Ted Kremenekf7870022011-04-20 16:41:07 +00005559const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005560 const char *str = "";
5561 switch (kind) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005562 case CXTUResourceUsage_AST:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005563 str = "ASTContext: expressions, declarations, and types";
5564 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005565 case CXTUResourceUsage_Identifiers:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005566 str = "ASTContext: identifiers";
5567 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005568 case CXTUResourceUsage_Selectors:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005569 str = "ASTContext: selectors";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005570 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005571 case CXTUResourceUsage_GlobalCompletionResults:
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005572 str = "Code completion: cached global results";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005573 break;
Ted Kremenek457aaf02011-04-28 04:10:31 +00005574 case CXTUResourceUsage_SourceManagerContentCache:
5575 str = "SourceManager: content cache allocator";
5576 break;
Ted Kremenekba29bd22011-04-28 04:53:38 +00005577 case CXTUResourceUsage_AST_SideTables:
5578 str = "ASTContext: side tables";
5579 break;
Ted Kremenekf61b8312011-04-28 20:36:42 +00005580 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
5581 str = "SourceManager: malloc'ed memory buffers";
5582 break;
5583 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
5584 str = "SourceManager: mmap'ed memory buffers";
5585 break;
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005586 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
5587 str = "ExternalASTSource: malloc'ed memory buffers";
5588 break;
5589 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
5590 str = "ExternalASTSource: mmap'ed memory buffers";
5591 break;
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005592 case CXTUResourceUsage_Preprocessor:
5593 str = "Preprocessor: malloc'ed memory";
5594 break;
5595 case CXTUResourceUsage_PreprocessingRecord:
5596 str = "Preprocessor: PreprocessingRecord";
5597 break;
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005598 case CXTUResourceUsage_SourceManager_DataStructures:
5599 str = "SourceManager: data structures and tables";
5600 break;
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005601 case CXTUResourceUsage_Preprocessor_HeaderSearch:
5602 str = "Preprocessor: header search tables";
5603 break;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005604 }
5605 return str;
5606}
5607
Ted Kremenekf7870022011-04-20 16:41:07 +00005608CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005609 if (!TU) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005610 CXTUResourceUsage usage = { (void*) 0, 0, 0 };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005611 return usage;
5612 }
5613
5614 ASTUnit *astUnit = static_cast<ASTUnit*>(TU->TUData);
Dylan Noblesmith1e4c01b2012-02-13 12:32:21 +00005615 OwningPtr<MemUsageEntries> entries(new MemUsageEntries());
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005616 ASTContext &astContext = astUnit->getASTContext();
5617
5618 // How much memory is used by AST nodes and types?
Ted Kremenekf7870022011-04-20 16:41:07 +00005619 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005620 (unsigned long) astContext.getASTAllocatedMemory());
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005621
5622 // How much memory is used by identifiers?
Ted Kremenekf7870022011-04-20 16:41:07 +00005623 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005624 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
5625
5626 // How much memory is used for selectors?
Ted Kremenekf7870022011-04-20 16:41:07 +00005627 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005628 (unsigned long) astContext.Selectors.getTotalMemory());
5629
Ted Kremenekba29bd22011-04-28 04:53:38 +00005630 // How much memory is used by ASTContext's side tables?
5631 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
5632 (unsigned long) astContext.getSideTableAllocatedMemory());
5633
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005634 // How much memory is used for caching global code completion results?
5635 unsigned long completionBytes = 0;
5636 if (GlobalCodeCompletionAllocator *completionAllocator =
5637 astUnit->getCachedCompletionAllocator().getPtr()) {
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005638 completionBytes = completionAllocator->getTotalMemory();
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005639 }
Ted Kremenek457aaf02011-04-28 04:10:31 +00005640 createCXTUResourceUsageEntry(*entries,
5641 CXTUResourceUsage_GlobalCompletionResults,
5642 completionBytes);
5643
5644 // How much memory is being used by SourceManager's content cache?
5645 createCXTUResourceUsageEntry(*entries,
5646 CXTUResourceUsage_SourceManagerContentCache,
5647 (unsigned long) astContext.getSourceManager().getContentCacheSize());
Ted Kremenekf61b8312011-04-28 20:36:42 +00005648
5649 // How much memory is being used by the MemoryBuffer's in SourceManager?
5650 const SourceManager::MemoryBufferSizes &srcBufs =
5651 astUnit->getSourceManager().getMemoryBufferSizes();
5652
5653 createCXTUResourceUsageEntry(*entries,
5654 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
5655 (unsigned long) srcBufs.malloc_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005656 createCXTUResourceUsageEntry(*entries,
Ted Kremenekf61b8312011-04-28 20:36:42 +00005657 CXTUResourceUsage_SourceManager_Membuffer_MMap,
5658 (unsigned long) srcBufs.mmap_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005659 createCXTUResourceUsageEntry(*entries,
5660 CXTUResourceUsage_SourceManager_DataStructures,
5661 (unsigned long) astContext.getSourceManager()
5662 .getDataStructureSizes());
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005663
5664 // How much memory is being used by the ExternalASTSource?
5665 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
5666 const ExternalASTSource::MemoryBufferSizes &sizes =
5667 esrc->getMemoryBufferSizes();
5668
5669 createCXTUResourceUsageEntry(*entries,
5670 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
5671 (unsigned long) sizes.malloc_bytes);
5672 createCXTUResourceUsageEntry(*entries,
5673 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
5674 (unsigned long) sizes.mmap_bytes);
5675 }
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005676
5677 // How much memory is being used by the Preprocessor?
5678 Preprocessor &pp = astUnit->getPreprocessor();
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005679 createCXTUResourceUsageEntry(*entries,
5680 CXTUResourceUsage_Preprocessor,
Argyrios Kyrtzidisc5c5e922011-06-29 22:20:04 +00005681 pp.getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005682
5683 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
5684 createCXTUResourceUsageEntry(*entries,
5685 CXTUResourceUsage_PreprocessingRecord,
5686 pRec->getTotalMemory());
5687 }
5688
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005689 createCXTUResourceUsageEntry(*entries,
5690 CXTUResourceUsage_Preprocessor_HeaderSearch,
5691 pp.getHeaderSearchInfo().getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005692
Ted Kremenekf7870022011-04-20 16:41:07 +00005693 CXTUResourceUsage usage = { (void*) entries.get(),
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005694 (unsigned) entries->size(),
5695 entries->size() ? &(*entries)[0] : 0 };
5696 entries.take();
5697 return usage;
5698}
5699
Ted Kremenekf7870022011-04-20 16:41:07 +00005700void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005701 if (usage.data)
5702 delete (MemUsageEntries*) usage.data;
5703}
5704
5705} // end extern "C"
5706
Douglas Gregor6df78732011-05-05 20:27:22 +00005707void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
5708 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
5709 for (unsigned I = 0; I != Usage.numEntries; ++I)
5710 fprintf(stderr, " %s: %lu\n",
5711 clang_getTUResourceUsageName(Usage.entries[I].kind),
5712 Usage.entries[I].amount);
5713
5714 clang_disposeCXTUResourceUsage(Usage);
5715}
5716
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005717//===----------------------------------------------------------------------===//
Ted Kremenek04bb7162010-01-22 22:44:15 +00005718// Misc. utility functions.
5719//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00005720
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00005721/// Default to using an 8 MB stack size on "safety" threads.
5722static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005723
5724namespace clang {
5725
5726bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005727 void (*Fn)(void*), void *UserData,
5728 unsigned Size) {
5729 if (!Size)
5730 Size = GetSafetyThreadStackSize();
5731 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005732 return CRC.RunSafelyOnThread(Fn, UserData, Size);
5733 return CRC.RunSafely(Fn, UserData);
5734}
5735
5736unsigned GetSafetyThreadStackSize() {
5737 return SafetyStackThreadSize;
5738}
5739
5740void SetSafetyThreadStackSize(unsigned Value) {
5741 SafetyStackThreadSize = Value;
5742}
5743
Argyrios Kyrtzidis8e7c48a2012-03-28 02:49:50 +00005744}
5745
Argyrios Kyrtzidis81b5ac32012-03-28 02:49:54 +00005746void clang::setThreadBackgroundPriority() {
Argyrios Kyrtzidisfdc17952012-03-28 02:18:05 +00005747 // FIXME: Move to llvm/Support and make it cross-platform.
5748#ifdef __APPLE__
5749 setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG);
5750#endif
5751}
5752
Ted Kremenek04bb7162010-01-22 22:44:15 +00005753extern "C" {
5754
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00005755CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00005756 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00005757}
5758
5759} // end: extern "C"
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005760