blob: b3a29ef105289844ffdb5c1a59ce479f524ae35f [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 Kyrtzidis9049cf62011-10-12 07:07:33 +000055CXTranslationUnit cxtu::MakeCXTranslationUnit(ASTUnit *TU) {
Ted Kremeneka60ed472010-11-16 08:15:36 +000056 if (!TU)
57 return 0;
58 CXTranslationUnit D = new CXTranslationUnitImpl();
59 D->TUData = TU;
60 D->StringPool = createCXStringPool();
Ted Kremenek15322172011-11-10 08:43:12 +000061 D->Diagnostics = 0;
Ted Kremeneka60ed472010-11-16 08:15:36 +000062 return D;
63}
64
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +000065cxtu::CXTUOwner::~CXTUOwner() {
66 if (TU)
67 clang_disposeTranslationUnit(TU);
68}
69
Ted Kremenekf0e23e82010-02-17 00:41:40 +000070/// \brief Compare two source ranges to determine their relative position in
Douglas Gregor33e9abd2010-01-22 19:49:59 +000071/// the translation unit.
Ted Kremenekf0e23e82010-02-17 00:41:40 +000072static RangeComparisonResult RangeCompare(SourceManager &SM,
73 SourceRange R1,
Douglas Gregor33e9abd2010-01-22 19:49:59 +000074 SourceRange R2) {
75 assert(R1.isValid() && "First range is invalid?");
76 assert(R2.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000077 if (R1.getEnd() != R2.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000078 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000079 return RangeBefore;
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000080 if (R2.getEnd() != R1.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000081 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000082 return RangeAfter;
83 return RangeOverlap;
84}
85
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000086/// \brief Determine if a source location falls within, before, or after a
87/// a given source range.
88static RangeComparisonResult LocationCompare(SourceManager &SM,
89 SourceLocation L, SourceRange R) {
90 assert(R.isValid() && "First range is invalid?");
91 assert(L.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000092 if (L == R.getBegin() || L == R.getEnd())
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000093 return RangeOverlap;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000094 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
95 return RangeBefore;
96 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
97 return RangeAfter;
98 return RangeOverlap;
99}
100
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000101/// \brief Translate a Clang source range into a CIndex source range.
102///
103/// Clang internally represents ranges where the end location points to the
104/// start of the token at the end. However, for external clients it is more
105/// useful to have a CXSourceRange be a proper half-open interval. This routine
106/// does the appropriate translation.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000107CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000108 const LangOptions &LangOpts,
Chris Lattner0a76aae2010-06-18 22:45:06 +0000109 const CharSourceRange &R) {
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000110 // We want the last character in this location, so we will adjust the
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000111 // location accordingly.
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000112 SourceLocation EndLoc = R.getEnd();
Douglas Gregora9b06d42010-11-09 06:24:54 +0000113 if (EndLoc.isValid() && EndLoc.isMacroID())
Chandler Carruthedc3dcc2011-07-25 16:56:02 +0000114 EndLoc = SM.getExpansionRange(EndLoc).second;
Chris Lattner0a76aae2010-06-18 22:45:06 +0000115 if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) {
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000116 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000117 EndLoc = EndLoc.getLocWithOffset(Length);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000118 }
119
120 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
121 R.getBegin().getRawEncoding(),
122 EndLoc.getRawEncoding() };
123 return Result;
124}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000125
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000126//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000127// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000128//===----------------------------------------------------------------------===//
129
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000130static SourceRange getRawCursorExtent(CXCursor C);
Douglas Gregor66537982010-11-17 17:14:07 +0000131static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
132
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000133
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000134RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000135 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000136}
137
Douglas Gregorb1373d02010-01-20 20:59:29 +0000138/// \brief Visit the given cursor and, if requested by the visitor,
139/// its children.
140///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000141/// \param Cursor the cursor to visit.
142///
143/// \param CheckRegionOfInterest if true, then the caller already checked that
144/// this cursor is within the region of interest.
145///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000146/// \returns true if the visitation should be aborted, false if it
147/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000148bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000149 if (clang_isInvalid(Cursor.kind))
150 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000151
Douglas Gregorb1373d02010-01-20 20:59:29 +0000152 if (clang_isDeclaration(Cursor.kind)) {
153 Decl *D = getCursorDecl(Cursor);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +0000154 if (!D) {
155 assert(0 && "Invalid declaration cursor");
156 return true; // abort.
157 }
158
Argyrios Kyrtzidis65ab9072011-09-26 19:05:37 +0000159 // Ignore implicit declarations, unless it's an objc method because
160 // currently we should report implicit methods for properties when indexing.
161 if (D->isImplicit() && !isa<ObjCMethodDecl>(D))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000162 return false;
163 }
164
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000165 // If we have a range of interest, and this cursor doesn't intersect with it,
166 // we're done.
167 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000168 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000169 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000170 return false;
171 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000172
Douglas Gregorb1373d02010-01-20 20:59:29 +0000173 switch (Visitor(Cursor, Parent, ClientData)) {
174 case CXChildVisit_Break:
175 return true;
176
177 case CXChildVisit_Continue:
178 return false;
179
180 case CXChildVisit_Recurse:
181 return VisitChildren(Cursor);
182 }
183
David Blaikie7530c032012-01-17 06:56:22 +0000184 llvm_unreachable("Invalid CXChildVisitResult!");
Douglas Gregorb1373d02010-01-20 20:59:29 +0000185}
186
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000187static bool visitPreprocessedEntitiesInRange(SourceRange R,
188 PreprocessingRecord &PPRec,
189 CursorVisitor &Visitor) {
190 SourceManager &SM = Visitor.getASTUnit()->getSourceManager();
191 FileID FID;
192
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +0000193 if (!Visitor.shouldVisitIncludedEntities()) {
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000194 // If the begin/end of the range lie in the same FileID, do the optimization
195 // where we skip preprocessed entities that do not come from the same FileID.
Argyrios Kyrtzidisacca4112011-12-21 16:56:38 +0000196 FID = SM.getFileID(SM.getFileLoc(R.getBegin()));
197 if (FID != SM.getFileID(SM.getFileLoc(R.getEnd())))
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000198 FID = FileID();
199 }
200
201 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
202 Entities = PPRec.getPreprocessedEntitiesInRange(R);
203 return Visitor.visitPreprocessedEntities(Entities.first, Entities.second,
204 PPRec, FID);
205}
206
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000207void CursorVisitor::visitFileRegion() {
208 if (RegionOfInterest.isInvalid())
209 return;
210
211 ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData);
212 SourceManager &SM = Unit->getSourceManager();
213
214 std::pair<FileID, unsigned>
215 Begin = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getBegin())),
216 End = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getEnd()));
217
218 if (End.first != Begin.first) {
219 // If the end does not reside in the same file, try to recover by
220 // picking the end of the file of begin location.
221 End.first = Begin.first;
222 End.second = SM.getFileIDSize(Begin.first);
223 }
224
225 assert(Begin.first == End.first);
226 if (Begin.second > End.second)
227 return;
228
229 FileID File = Begin.first;
230 unsigned Offset = Begin.second;
231 unsigned Length = End.second - Begin.second;
232
Argyrios Kyrtzidisb49e7282011-11-29 03:14:11 +0000233 if (!VisitDeclsOnly && !VisitPreprocessorLast)
234 if (visitPreprocessedEntitiesInRegion())
235 return; // visitation break.
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000236
237 visitDeclsFromFileRegion(File, Offset, Length);
238
Argyrios Kyrtzidisb49e7282011-11-29 03:14:11 +0000239 if (!VisitDeclsOnly && VisitPreprocessorLast)
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000240 visitPreprocessedEntitiesInRegion();
241}
242
Argyrios Kyrtzidise2079cf2011-11-16 08:58:54 +0000243static bool isInLexicalContext(Decl *D, DeclContext *DC) {
244 if (!DC)
245 return false;
246
247 for (DeclContext *DeclDC = D->getLexicalDeclContext();
248 DeclDC; DeclDC = DeclDC->getLexicalParent()) {
249 if (DeclDC == DC)
250 return true;
251 }
252 return false;
253}
254
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000255void CursorVisitor::visitDeclsFromFileRegion(FileID File,
256 unsigned Offset, unsigned Length) {
257 ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData);
258 SourceManager &SM = Unit->getSourceManager();
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000259 SourceRange Range = RegionOfInterest;
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000260
261 SmallVector<Decl *, 16> Decls;
262 Unit->findFileRegionDecls(File, Offset, Length, Decls);
263
264 // If we didn't find any file level decls for the file, try looking at the
265 // file that it was included from.
Argyrios Kyrtzidisc14a03d2011-11-23 20:27:36 +0000266 while (Decls.empty() || Decls.front()->isTopLevelDeclInObjCContainer()) {
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000267 bool Invalid = false;
268 const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid);
269 if (Invalid)
270 return;
271
272 SourceLocation Outer;
273 if (SLEntry.isFile())
274 Outer = SLEntry.getFile().getIncludeLoc();
275 else
276 Outer = SLEntry.getExpansion().getExpansionLocStart();
277 if (Outer.isInvalid())
278 return;
279
280 llvm::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer);
281 Length = 0;
282 Unit->findFileRegionDecls(File, Offset, Length, Decls);
283 }
284
285 assert(!Decls.empty());
286
287 bool VisitedAtLeastOnce = false;
Argyrios Kyrtzidise2079cf2011-11-16 08:58:54 +0000288 DeclContext *CurDC = 0;
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000289 SmallVector<Decl *, 16>::iterator DIt = Decls.begin();
290 for (SmallVector<Decl *, 16>::iterator DE = Decls.end(); DIt != DE; ++DIt) {
291 Decl *D = *DIt;
Argyrios Kyrtzidised8bef42011-11-28 22:38:07 +0000292 if (D->getSourceRange().isInvalid())
293 continue;
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000294
Argyrios Kyrtzidise2079cf2011-11-16 08:58:54 +0000295 if (isInLexicalContext(D, CurDC))
296 continue;
297
298 CurDC = dyn_cast<DeclContext>(D);
299
Argyrios Kyrtzidise2079cf2011-11-16 08:58:54 +0000300 if (TagDecl *TD = dyn_cast<TagDecl>(D))
301 if (!TD->isFreeStanding())
302 continue;
303
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000304 RangeComparisonResult CompRes = RangeCompare(SM, D->getSourceRange(),Range);
305 if (CompRes == RangeBefore)
306 continue;
307 if (CompRes == RangeAfter)
308 break;
309
310 assert(CompRes == RangeOverlap);
311 VisitedAtLeastOnce = true;
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +0000312
313 if (isa<ObjCContainerDecl>(D)) {
314 FileDI_current = &DIt;
315 FileDE_current = DE;
316 } else {
317 FileDI_current = 0;
318 }
319
Argyrios Kyrtzidisba986172011-11-03 19:02:28 +0000320 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000321 break;
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000322 }
323
324 if (VisitedAtLeastOnce)
325 return;
326
327 // No Decls overlapped with the range. Move up the lexical context until there
328 // is a context that contains the range or we reach the translation unit
329 // level.
330 DeclContext *DC = DIt == Decls.begin() ? (*DIt)->getLexicalDeclContext()
331 : (*(DIt-1))->getLexicalDeclContext();
332
333 while (DC && !DC->isTranslationUnit()) {
334 Decl *D = cast<Decl>(DC);
335 SourceRange CurDeclRange = D->getSourceRange();
336 if (CurDeclRange.isInvalid())
337 break;
338
339 if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) {
Argyrios Kyrtzidisba986172011-11-03 19:02:28 +0000340 Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true);
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000341 break;
342 }
343
344 DC = D->getLexicalDeclContext();
345 }
346}
347
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000348bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
Argyrios Kyrtzidisb49e7282011-11-29 03:14:11 +0000349 if (!AU->getPreprocessor().getPreprocessingRecord())
350 return false;
351
Douglas Gregor788f5a12010-03-20 00:41:21 +0000352 PreprocessingRecord &PPRec
Ted Kremeneka60ed472010-11-16 08:15:36 +0000353 = *AU->getPreprocessor().getPreprocessingRecord();
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000354 SourceManager &SM = AU->getSourceManager();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000355
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000356 if (RegionOfInterest.isValid()) {
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +0000357 SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000358 SourceLocation B = MappedRange.getBegin();
359 SourceLocation E = MappedRange.getEnd();
360
361 if (AU->isInPreambleFileID(B)) {
362 if (SM.isLoadedSourceLocation(E))
363 return visitPreprocessedEntitiesInRange(SourceRange(B, E),
364 PPRec, *this);
365
366 // Beginning of range lies in the preamble but it also extends beyond
367 // it into the main file. Split the range into 2 parts, one covering
368 // the preamble and another covering the main file. This allows subsequent
369 // calls to visitPreprocessedEntitiesInRange to accept a source range that
370 // lies in the same FileID, allowing it to skip preprocessed entities that
371 // do not come from the same FileID.
372 bool breaked =
373 visitPreprocessedEntitiesInRange(
374 SourceRange(B, AU->getEndOfPreambleFileID()),
375 PPRec, *this);
376 if (breaked) return true;
377 return visitPreprocessedEntitiesInRange(
378 SourceRange(AU->getStartOfMainFileID(), E),
379 PPRec, *this);
380 }
381
382 return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this);
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000383 }
384
Douglas Gregor788f5a12010-03-20 00:41:21 +0000385 bool OnlyLocalDecls
Douglas Gregor32038bb2010-12-21 19:07:48 +0000386 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
387
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000388 if (OnlyLocalDecls)
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000389 return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(),
390 PPRec);
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000391
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000392 return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec);
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000393}
394
395template<typename InputIterator>
396bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000397 InputIterator Last,
398 PreprocessingRecord &PPRec,
399 FileID FID) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000400 for (; First != Last; ++First) {
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000401 if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID))
402 continue;
403
404 PreprocessedEntity *PPE = *First;
405 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000406 if (Visit(MakeMacroExpansionCursor(ME, TU)))
407 return true;
408
409 continue;
410 }
411
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000412 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(PPE)) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000413 if (Visit(MakeMacroDefinitionCursor(MD, TU)))
414 return true;
415
416 continue;
417 }
418
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000419 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000420 if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
421 return true;
422
423 continue;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000424 }
425 }
426
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000427 return false;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000428}
429
Douglas Gregorb1373d02010-01-20 20:59:29 +0000430/// \brief Visit the children of the given cursor.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000431///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000432/// \returns true if the visitation should be aborted, false if it
433/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000434bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregorc314aa42011-03-02 19:17:03 +0000435 if (clang_isReference(Cursor.kind) &&
436 Cursor.kind != CXCursor_CXXBaseSpecifier) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000437 // By definition, references have no children.
438 return false;
439 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000440
441 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000442 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000443 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000444
Douglas Gregorb1373d02010-01-20 20:59:29 +0000445 if (clang_isDeclaration(Cursor.kind)) {
446 Decl *D = getCursorDecl(Cursor);
Douglas Gregor06d9b1a2011-04-14 21:41:34 +0000447 if (!D)
448 return false;
449
Ted Kremenek539311e2010-02-18 18:47:01 +0000450 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000451 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000452
Douglas Gregor06d9b1a2011-04-14 21:41:34 +0000453 if (clang_isStatement(Cursor.kind)) {
454 if (Stmt *S = getCursorStmt(Cursor))
455 return Visit(S);
456
457 return false;
458 }
459
460 if (clang_isExpression(Cursor.kind)) {
461 if (Expr *E = getCursorExpr(Cursor))
462 return Visit(E);
463
464 return false;
465 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000466
Douglas Gregorb1373d02010-01-20 20:59:29 +0000467 if (clang_isTranslationUnit(Cursor.kind)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000468 CXTranslationUnit tu = getCursorTU(Cursor);
469 ASTUnit *CXXUnit = static_cast<ASTUnit*>(tu->TUData);
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000470
471 int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
472 for (unsigned I = 0; I != 2; ++I) {
473 if (VisitOrder[I]) {
474 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
475 RegionOfInterest.isInvalid()) {
476 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
477 TLEnd = CXXUnit->top_level_end();
478 TL != TLEnd; ++TL) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000479 if (Visit(MakeCXCursor(*TL, tu, RegionOfInterest), true))
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000480 return true;
481 }
482 } else if (VisitDeclContext(
483 CXXUnit->getASTContext().getTranslationUnitDecl()))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000484 return true;
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000485 continue;
Douglas Gregor7b691f332010-01-20 21:13:59 +0000486 }
Bob Wilson3178cb62010-03-19 03:57:57 +0000487
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000488 // Walk the preprocessing record.
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000489 if (CXXUnit->getPreprocessor().getPreprocessingRecord())
490 visitPreprocessedEntitiesInRegion();
Douglas Gregor0396f462010-03-19 05:22:59 +0000491 }
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000492
Douglas Gregor7b691f332010-01-20 21:13:59 +0000493 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000494 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000495
Douglas Gregorc314aa42011-03-02 19:17:03 +0000496 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
497 if (CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
498 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
499 return Visit(BaseTSInfo->getTypeLoc());
500 }
501 }
502 }
Argyrios Kyrtzidis221d5a52011-09-13 18:49:56 +0000503
504 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
505 IBOutletCollectionAttr *A =
506 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
507 if (const ObjCInterfaceType *InterT = A->getInterface()->getAs<ObjCInterfaceType>())
508 return Visit(cxcursor::MakeCursorObjCClassRef(InterT->getInterface(),
509 A->getInterfaceLoc(), TU));
510 }
511
Douglas Gregorb1373d02010-01-20 20:59:29 +0000512 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000513 return false;
514}
515
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000516bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
Douglas Gregor13c8ccb2011-04-22 23:49:24 +0000517 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
518 if (Visit(TSInfo->getTypeLoc()))
519 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000520
Ted Kremenek664cffd2010-07-22 11:30:19 +0000521 if (Stmt *Body = B->getBody())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000522 return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest));
Ted Kremenek664cffd2010-07-22 11:30:19 +0000523
524 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000525}
526
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000527llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
528 if (RegionOfInterest.isValid()) {
Douglas Gregor66537982010-11-17 17:14:07 +0000529 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000530 if (Range.isInvalid())
531 return llvm::Optional<bool>();
Douglas Gregor66537982010-11-17 17:14:07 +0000532
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000533 switch (CompareRegionOfInterest(Range)) {
534 case RangeBefore:
535 // This declaration comes before the region of interest; skip it.
536 return llvm::Optional<bool>();
537
538 case RangeAfter:
539 // This declaration comes after the region of interest; we're done.
540 return false;
541
542 case RangeOverlap:
543 // This declaration overlaps the region of interest; visit it.
544 break;
545 }
546 }
547 return true;
548}
549
550bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
551 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
552
553 // FIXME: Eventually remove. This part of a hack to support proper
554 // iteration over all Decls contained lexically within an ObjC container.
555 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
556 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
557
558 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000559 Decl *D = *I;
560 if (D->getLexicalDeclContext() != DC)
561 continue;
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000562 CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
Argyrios Kyrtzidis1836db02012-02-04 01:04:58 +0000563
564 // FIXME: ObjCClassRef/ObjCProtocolRef for forward class/protocol
565 // declarations is a mismatch with the compiler semantics.
566 if (Cursor.kind == CXCursor_ObjCInterfaceDecl) {
567 ObjCInterfaceDecl *ID = cast<ObjCInterfaceDecl>(D);
568 if (!ID->isThisDeclarationADefinition())
569 Cursor = MakeCursorObjCClassRef(ID, ID->getLocation(), TU);
570
571 } else if (Cursor.kind == CXCursor_ObjCProtocolDecl) {
572 ObjCProtocolDecl *PD = cast<ObjCProtocolDecl>(D);
573 if (!PD->isThisDeclarationADefinition())
574 Cursor = MakeCursorObjCProtocolRef(PD, PD->getLocation(), TU);
575 }
576
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000577 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
578 if (!V.hasValue())
579 continue;
580 if (!V.getValue())
581 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000582 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000583 return true;
584 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000585 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000586}
587
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000588bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
589 llvm_unreachable("Translation units are visited directly by Visit()");
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000590}
591
Richard Smith162e1c12011-04-15 14:24:37 +0000592bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
593 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
594 return Visit(TSInfo->getTypeLoc());
595
596 return false;
597}
598
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000599bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
600 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
601 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000602
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000603 return false;
604}
605
606bool CursorVisitor::VisitTagDecl(TagDecl *D) {
607 return VisitDeclContext(D);
608}
609
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000610bool CursorVisitor::VisitClassTemplateSpecializationDecl(
611 ClassTemplateSpecializationDecl *D) {
612 bool ShouldVisitBody = false;
613 switch (D->getSpecializationKind()) {
614 case TSK_Undeclared:
615 case TSK_ImplicitInstantiation:
616 // Nothing to visit
617 return false;
618
619 case TSK_ExplicitInstantiationDeclaration:
620 case TSK_ExplicitInstantiationDefinition:
621 break;
622
623 case TSK_ExplicitSpecialization:
624 ShouldVisitBody = true;
625 break;
626 }
627
628 // Visit the template arguments used in the specialization.
629 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
630 TypeLoc TL = SpecType->getTypeLoc();
631 if (TemplateSpecializationTypeLoc *TSTLoc
632 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
633 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
634 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
635 return true;
636 }
637 }
638
639 if (ShouldVisitBody && VisitCXXRecordDecl(D))
640 return true;
641
642 return false;
643}
644
Douglas Gregor74dbe642010-08-31 19:31:58 +0000645bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
646 ClassTemplatePartialSpecializationDecl *D) {
647 // FIXME: Visit the "outer" template parameter lists on the TagDecl
648 // before visiting these template parameters.
649 if (VisitTemplateParameters(D->getTemplateParameters()))
650 return true;
651
652 // Visit the partial specialization arguments.
653 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
654 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
655 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
656 return true;
657
658 return VisitCXXRecordDecl(D);
659}
660
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000661bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000662 // Visit the default argument.
663 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
664 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
665 if (Visit(DefArg->getTypeLoc()))
666 return true;
667
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000668 return false;
669}
670
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000671bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
672 if (Expr *Init = D->getInitExpr())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000673 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000674 return false;
675}
676
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000677bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
678 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
679 if (Visit(TSInfo->getTypeLoc()))
680 return true;
681
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000682 // Visit the nested-name-specifier, if present.
683 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
684 if (VisitNestedNameSpecifierLoc(QualifierLoc))
685 return true;
686
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000687 return false;
688}
689
Douglas Gregora67e03f2010-09-09 21:42:20 +0000690/// \brief Compare two base or member initializers based on their source order.
Sean Huntcbb67482011-01-08 20:30:50 +0000691static int CompareCXXCtorInitializers(const void* Xp, const void *Yp) {
692 CXXCtorInitializer const * const *X
693 = static_cast<CXXCtorInitializer const * const *>(Xp);
694 CXXCtorInitializer const * const *Y
695 = static_cast<CXXCtorInitializer const * const *>(Yp);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000696
697 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
698 return -1;
699 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
700 return 1;
701 else
702 return 0;
703}
704
Douglas Gregorb1373d02010-01-20 20:59:29 +0000705bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000706 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
707 // Visit the function declaration's syntactic components in the order
708 // written. This requires a bit of work.
Abramo Bagnara723df242010-12-14 22:11:44 +0000709 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
Douglas Gregor01829d32010-08-31 14:41:23 +0000710 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
711
712 // If we have a function declared directly (without the use of a typedef),
713 // visit just the return type. Otherwise, just visit the function's type
714 // now.
715 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
716 (!FTL && Visit(TL)))
717 return true;
718
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000719 // Visit the nested-name-specifier, if present.
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000720 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
721 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000722 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000723
724 // Visit the declaration name.
725 if (VisitDeclarationNameInfo(ND->getNameInfo()))
726 return true;
727
728 // FIXME: Visit explicitly-specified template arguments!
729
730 // Visit the function parameters, if we have a function type.
731 if (FTL && VisitFunctionTypeLoc(*FTL, true))
732 return true;
733
734 // FIXME: Attributes?
735 }
736
Sean Hunt10620eb2011-05-06 20:44:56 +0000737 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
Douglas Gregora67e03f2010-09-09 21:42:20 +0000738 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
739 // Find the initializers that were written in the source.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000740 SmallVector<CXXCtorInitializer *, 4> WrittenInits;
Douglas Gregora67e03f2010-09-09 21:42:20 +0000741 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
742 IEnd = Constructor->init_end();
743 I != IEnd; ++I) {
744 if (!(*I)->isWritten())
745 continue;
746
747 WrittenInits.push_back(*I);
748 }
749
750 // Sort the initializers in source order
751 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
Sean Huntcbb67482011-01-08 20:30:50 +0000752 &CompareCXXCtorInitializers);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000753
754 // Visit the initializers in source order
755 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
Sean Huntcbb67482011-01-08 20:30:50 +0000756 CXXCtorInitializer *Init = WrittenInits[I];
Francois Pichet00eb3f92010-12-04 09:14:42 +0000757 if (Init->isAnyMemberInitializer()) {
758 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
Douglas Gregora67e03f2010-09-09 21:42:20 +0000759 Init->getMemberLocation(), TU)))
760 return true;
Douglas Gregor76852c22011-11-01 01:16:03 +0000761 } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) {
762 if (Visit(TInfo->getTypeLoc()))
Douglas Gregora67e03f2010-09-09 21:42:20 +0000763 return true;
764 }
765
766 // Visit the initializer value.
767 if (Expr *Initializer = Init->getInit())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000768 if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
Douglas Gregora67e03f2010-09-09 21:42:20 +0000769 return true;
770 }
771 }
772
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000773 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
Douglas Gregora67e03f2010-09-09 21:42:20 +0000774 return true;
775 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000776
Douglas Gregorb1373d02010-01-20 20:59:29 +0000777 return false;
778}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000779
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000780bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
781 if (VisitDeclaratorDecl(D))
782 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000783
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000784 if (Expr *BitWidth = D->getBitWidth())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000785 return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000786
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000787 return false;
788}
789
790bool CursorVisitor::VisitVarDecl(VarDecl *D) {
791 if (VisitDeclaratorDecl(D))
792 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000793
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000794 if (Expr *Init = D->getInit())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000795 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000796
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000797 return false;
798}
799
Douglas Gregor84b51d72010-09-01 20:16:53 +0000800bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
801 if (VisitDeclaratorDecl(D))
802 return true;
803
804 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
805 if (Expr *DefArg = D->getDefaultArgument())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000806 return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
Douglas Gregor84b51d72010-09-01 20:16:53 +0000807
808 return false;
809}
810
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000811bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
812 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
813 // before visiting these template parameters.
814 if (VisitTemplateParameters(D->getTemplateParameters()))
815 return true;
816
817 return VisitFunctionDecl(D->getTemplatedDecl());
818}
819
Douglas Gregor39d6f072010-08-31 19:02:00 +0000820bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
821 // FIXME: Visit the "outer" template parameter lists on the TagDecl
822 // before visiting these template parameters.
823 if (VisitTemplateParameters(D->getTemplateParameters()))
824 return true;
825
826 return VisitCXXRecordDecl(D->getTemplatedDecl());
827}
828
Douglas Gregor84b51d72010-09-01 20:16:53 +0000829bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
830 if (VisitTemplateParameters(D->getTemplateParameters()))
831 return true;
832
833 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
834 VisitTemplateArgumentLoc(D->getDefaultArgument()))
835 return true;
836
837 return false;
838}
839
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000840bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000841 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
842 if (Visit(TSInfo->getTypeLoc()))
843 return true;
844
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000845 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000846 PEnd = ND->param_end();
847 P != PEnd; ++P) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000848 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000849 return true;
850 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000851
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000852 if (ND->isThisDeclarationADefinition() &&
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000853 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000854 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000855
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000856 return false;
857}
858
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +0000859template <typename DeclIt>
860static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current,
861 SourceManager &SM, SourceLocation EndLoc,
862 SmallVectorImpl<Decl *> &Decls) {
863 DeclIt next = *DI_current;
864 while (++next != DE_current) {
865 Decl *D_next = *next;
866 if (!D_next)
867 break;
868 SourceLocation L = D_next->getLocStart();
869 if (!L.isValid())
870 break;
871 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
872 *DI_current = next;
873 Decls.push_back(D_next);
874 continue;
875 }
876 break;
877 }
878}
879
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000880namespace {
881 struct ContainerDeclsSort {
882 SourceManager &SM;
883 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
884 bool operator()(Decl *A, Decl *B) {
885 SourceLocation L_A = A->getLocStart();
886 SourceLocation L_B = B->getLocStart();
887 assert(L_A.isValid() && L_B.isValid());
888 return SM.isBeforeInTranslationUnit(L_A, L_B);
889 }
890 };
891}
892
Douglas Gregora59e3902010-01-21 23:27:09 +0000893bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000894 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
895 // an @implementation can lexically contain Decls that are not properly
896 // nested in the AST. When we identify such cases, we need to retrofit
897 // this nesting here.
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +0000898 if (!DI_current && !FileDI_current)
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000899 return VisitDeclContext(D);
900
901 // Scan the Decls that immediately come after the container
902 // in the current DeclContext. If any fall within the
903 // container's lexical region, stash them into a vector
904 // for later processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000905 SmallVector<Decl *, 24> DeclsInContainer;
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000906 SourceLocation EndLoc = D->getSourceRange().getEnd();
Ted Kremeneka60ed472010-11-16 08:15:36 +0000907 SourceManager &SM = AU->getSourceManager();
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000908 if (EndLoc.isValid()) {
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +0000909 if (DI_current) {
910 addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc,
911 DeclsInContainer);
912 } else {
913 addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc,
914 DeclsInContainer);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000915 }
916 }
917
918 // The common case.
919 if (DeclsInContainer.empty())
920 return VisitDeclContext(D);
921
922 // Get all the Decls in the DeclContext, and sort them with the
923 // additional ones we've collected. Then visit them.
924 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
925 I!=E; ++I) {
926 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000927 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
928 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000929 continue;
930 DeclsInContainer.push_back(subDecl);
931 }
932
933 // Now sort the Decls so that they appear in lexical order.
934 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
935 ContainerDeclsSort(SM));
936
937 // Now visit the decls.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000938 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000939 E = DeclsInContainer.end(); I != E; ++I) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000940 CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000941 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
942 if (!V.hasValue())
943 continue;
944 if (!V.getValue())
945 return false;
946 if (Visit(Cursor, true))
947 return true;
948 }
949 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000950}
951
Douglas Gregorb1373d02010-01-20 20:59:29 +0000952bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000953 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
954 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000955 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000956
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000957 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
958 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
959 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000960 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000961 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000962
Douglas Gregora59e3902010-01-21 23:27:09 +0000963 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000964}
965
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000966bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000967 if (!PID->isThisDeclarationADefinition())
968 return Visit(MakeCursorObjCProtocolRef(PID, PID->getLocation(), TU));
969
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000970 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
971 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
972 E = PID->protocol_end(); I != E; ++I, ++PL)
973 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
974 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000975
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000976 return VisitObjCContainerDecl(PID);
977}
978
Ted Kremenek23173d72010-05-18 21:09:07 +0000979bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000980 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000981 return true;
982
Ted Kremenek23173d72010-05-18 21:09:07 +0000983 // FIXME: This implements a workaround with @property declarations also being
984 // installed in the DeclContext for the @interface. Eventually this code
985 // should be removed.
986 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
987 if (!CDecl || !CDecl->IsClassExtension())
988 return false;
989
990 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
991 if (!ID)
992 return false;
993
994 IdentifierInfo *PropertyId = PD->getIdentifier();
995 ObjCPropertyDecl *prevDecl =
996 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
997
998 if (!prevDecl)
999 return false;
1000
1001 // Visit synthesized methods since they will be skipped when visiting
1002 // the @interface.
1003 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +00001004 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001005 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
Ted Kremenek23173d72010-05-18 21:09:07 +00001006 return true;
1007
1008 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +00001009 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001010 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
Ted Kremenek23173d72010-05-18 21:09:07 +00001011 return true;
1012
1013 return false;
1014}
1015
Douglas Gregorb1373d02010-01-20 20:59:29 +00001016bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Douglas Gregor375bb142011-12-27 22:43:10 +00001017 if (!D->isThisDeclarationADefinition()) {
1018 // Forward declaration is treated like a reference.
1019 return Visit(MakeCursorObjCClassRef(D, D->getLocation(), TU));
1020 }
1021
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001022 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +00001023 if (D->getSuperClass() &&
1024 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001025 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001026 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001027 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001028
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001029 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1030 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1031 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001032 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001033 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001034
Douglas Gregora59e3902010-01-21 23:27:09 +00001035 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001036}
1037
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001038bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1039 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001040}
1041
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001042bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +00001043 // 'ID' could be null when dealing with invalid code.
1044 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1045 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1046 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001047
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001048 return VisitObjCImplDecl(D);
1049}
1050
1051bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1052#if 0
1053 // Issue callbacks for super class.
1054 // FIXME: No source location information!
1055 if (D->getSuperClass() &&
1056 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001057 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001058 TU)))
1059 return true;
1060#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001061
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001062 return VisitObjCImplDecl(D);
1063}
1064
Douglas Gregora4ffd852010-11-17 01:03:52 +00001065bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1066 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1067 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1068
1069 return false;
1070}
1071
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001072bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1073 return VisitDeclContext(D);
1074}
1075
Douglas Gregor69319002010-08-31 23:48:11 +00001076bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001077 // Visit nested-name-specifier.
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00001078 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1079 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001080 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001081
1082 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1083 D->getTargetNameLoc(), TU));
1084}
1085
Douglas Gregor7e242562010-09-01 19:52:22 +00001086bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001087 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001088 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1089 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001090 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001091 }
Douglas Gregor7e242562010-09-01 19:52:22 +00001092
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001093 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1094 return true;
1095
Douglas Gregor7e242562010-09-01 19:52:22 +00001096 return VisitDeclarationNameInfo(D->getNameInfo());
1097}
1098
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001099bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001100 // Visit nested-name-specifier.
Douglas Gregordb992412011-02-25 16:33:46 +00001101 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1102 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001103 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001104
1105 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1106 D->getIdentLocation(), TU));
1107}
1108
Douglas Gregor7e242562010-09-01 19:52:22 +00001109bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001110 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001111 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1112 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001113 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001114 }
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001115
Douglas Gregor7e242562010-09-01 19:52:22 +00001116 return VisitDeclarationNameInfo(D->getNameInfo());
1117}
1118
1119bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1120 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001121 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001122 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1123 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001124 return true;
1125
Douglas Gregor7e242562010-09-01 19:52:22 +00001126 return false;
1127}
1128
Douglas Gregor01829d32010-08-31 14:41:23 +00001129bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1130 switch (Name.getName().getNameKind()) {
1131 case clang::DeclarationName::Identifier:
1132 case clang::DeclarationName::CXXLiteralOperatorName:
1133 case clang::DeclarationName::CXXOperatorName:
1134 case clang::DeclarationName::CXXUsingDirective:
1135 return false;
1136
1137 case clang::DeclarationName::CXXConstructorName:
1138 case clang::DeclarationName::CXXDestructorName:
1139 case clang::DeclarationName::CXXConversionFunctionName:
1140 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1141 return Visit(TSInfo->getTypeLoc());
1142 return false;
1143
1144 case clang::DeclarationName::ObjCZeroArgSelector:
1145 case clang::DeclarationName::ObjCOneArgSelector:
1146 case clang::DeclarationName::ObjCMultiArgSelector:
1147 // FIXME: Per-identifier location info?
1148 return false;
1149 }
David Blaikie7530c032012-01-17 06:56:22 +00001150
1151 llvm_unreachable("Invalid DeclarationName::Kind!");
Douglas Gregor01829d32010-08-31 14:41:23 +00001152}
1153
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001154bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1155 SourceRange Range) {
1156 // FIXME: This whole routine is a hack to work around the lack of proper
1157 // source information in nested-name-specifiers (PR5791). Since we do have
1158 // a beginning source location, we can visit the first component of the
1159 // nested-name-specifier, if it's a single-token component.
1160 if (!NNS)
1161 return false;
1162
1163 // Get the first component in the nested-name-specifier.
1164 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1165 NNS = Prefix;
1166
1167 switch (NNS->getKind()) {
1168 case NestedNameSpecifier::Namespace:
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001169 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1170 TU));
1171
Douglas Gregor14aba762011-02-24 02:36:08 +00001172 case NestedNameSpecifier::NamespaceAlias:
1173 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1174 Range.getBegin(), TU));
1175
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001176 case NestedNameSpecifier::TypeSpec: {
1177 // If the type has a form where we know that the beginning of the source
1178 // range matches up with a reference cursor. Visit the appropriate reference
1179 // cursor.
John McCallf4c73712011-01-19 06:33:43 +00001180 const Type *T = NNS->getAsType();
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001181 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1182 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1183 if (const TagType *Tag = dyn_cast<TagType>(T))
1184 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1185 if (const TemplateSpecializationType *TST
1186 = dyn_cast<TemplateSpecializationType>(T))
1187 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1188 break;
1189 }
1190
1191 case NestedNameSpecifier::TypeSpecWithTemplate:
1192 case NestedNameSpecifier::Global:
1193 case NestedNameSpecifier::Identifier:
1194 break;
1195 }
1196
1197 return false;
1198}
1199
Douglas Gregordc355712011-02-25 00:36:19 +00001200bool
1201CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001202 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
Douglas Gregordc355712011-02-25 00:36:19 +00001203 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1204 Qualifiers.push_back(Qualifier);
1205
1206 while (!Qualifiers.empty()) {
1207 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1208 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1209 switch (NNS->getKind()) {
1210 case NestedNameSpecifier::Namespace:
1211 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001212 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001213 TU)))
1214 return true;
1215
1216 break;
1217
1218 case NestedNameSpecifier::NamespaceAlias:
1219 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001220 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001221 TU)))
1222 return true;
1223
1224 break;
1225
1226 case NestedNameSpecifier::TypeSpec:
1227 case NestedNameSpecifier::TypeSpecWithTemplate:
1228 if (Visit(Q.getTypeLoc()))
1229 return true;
1230
1231 break;
1232
1233 case NestedNameSpecifier::Global:
1234 case NestedNameSpecifier::Identifier:
1235 break;
1236 }
1237 }
1238
1239 return false;
1240}
1241
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001242bool CursorVisitor::VisitTemplateParameters(
1243 const TemplateParameterList *Params) {
1244 if (!Params)
1245 return false;
1246
1247 for (TemplateParameterList::const_iterator P = Params->begin(),
1248 PEnd = Params->end();
1249 P != PEnd; ++P) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001250 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001251 return true;
1252 }
1253
1254 return false;
1255}
1256
Douglas Gregor0b36e612010-08-31 20:37:03 +00001257bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1258 switch (Name.getKind()) {
1259 case TemplateName::Template:
1260 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1261
1262 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001263 // Visit the overloaded template set.
1264 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1265 return true;
1266
Douglas Gregor0b36e612010-08-31 20:37:03 +00001267 return false;
1268
1269 case TemplateName::DependentTemplate:
1270 // FIXME: Visit nested-name-specifier.
1271 return false;
1272
1273 case TemplateName::QualifiedTemplate:
1274 // FIXME: Visit nested-name-specifier.
1275 return Visit(MakeCursorTemplateRef(
1276 Name.getAsQualifiedTemplateName()->getDecl(),
1277 Loc, TU));
John McCall14606042011-06-30 08:33:18 +00001278
1279 case TemplateName::SubstTemplateTemplateParm:
1280 return Visit(MakeCursorTemplateRef(
1281 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1282 Loc, TU));
Douglas Gregor1aee05d2011-01-15 06:45:20 +00001283
1284 case TemplateName::SubstTemplateTemplateParmPack:
1285 return Visit(MakeCursorTemplateRef(
1286 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1287 Loc, TU));
Douglas Gregor0b36e612010-08-31 20:37:03 +00001288 }
David Blaikie7530c032012-01-17 06:56:22 +00001289
1290 llvm_unreachable("Invalid TemplateName::Kind!");
Douglas Gregor0b36e612010-08-31 20:37:03 +00001291}
1292
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001293bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1294 switch (TAL.getArgument().getKind()) {
1295 case TemplateArgument::Null:
1296 case TemplateArgument::Integral:
Douglas Gregor87dd6972010-12-20 16:52:59 +00001297 case TemplateArgument::Pack:
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001298 return false;
1299
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001300 case TemplateArgument::Type:
1301 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1302 return Visit(TSInfo->getTypeLoc());
1303 return false;
1304
1305 case TemplateArgument::Declaration:
1306 if (Expr *E = TAL.getSourceDeclExpression())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001307 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001308 return false;
1309
1310 case TemplateArgument::Expression:
1311 if (Expr *E = TAL.getSourceExpression())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001312 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001313 return false;
1314
1315 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001316 case TemplateArgument::TemplateExpansion:
Douglas Gregorb6744ef2011-03-02 17:09:35 +00001317 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1318 return true;
1319
Douglas Gregora7fc9012011-01-05 18:58:31 +00001320 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
Douglas Gregor0b36e612010-08-31 20:37:03 +00001321 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001322 }
David Blaikie7530c032012-01-17 06:56:22 +00001323
1324 llvm_unreachable("Invalid TemplateArgument::Kind!");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001325}
1326
Ted Kremeneka0536d82010-05-07 01:04:29 +00001327bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1328 return VisitDeclContext(D);
1329}
1330
Douglas Gregor01829d32010-08-31 14:41:23 +00001331bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1332 return Visit(TL.getUnqualifiedLoc());
1333}
1334
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001335bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00001336 ASTContext &Context = AU->getASTContext();
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001337
1338 // Some builtin types (such as Objective-C's "id", "sel", and
1339 // "Class") have associated declarations. Create cursors for those.
1340 QualType VisitType;
John McCalle0a22d02011-10-18 21:02:43 +00001341 switch (TL.getTypePtr()->getKind()) {
John McCall2dde35b2011-10-18 22:28:37 +00001342
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001343 case BuiltinType::Void:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001344 case BuiltinType::NullPtr:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001345 case BuiltinType::Dependent:
John McCall2dde35b2011-10-18 22:28:37 +00001346#define BUILTIN_TYPE(Id, SingletonId)
1347#define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1348#define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1349#define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
1350#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
1351#include "clang/AST/BuiltinTypes.def"
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001352 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001353
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001354 case BuiltinType::ObjCId:
1355 VisitType = Context.getObjCIdType();
1356 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001357
1358 case BuiltinType::ObjCClass:
1359 VisitType = Context.getObjCClassType();
1360 break;
1361
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001362 case BuiltinType::ObjCSel:
1363 VisitType = Context.getObjCSelType();
1364 break;
1365 }
1366
1367 if (!VisitType.isNull()) {
1368 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001369 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001370 TU));
1371 }
1372
1373 return false;
1374}
1375
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001376bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
Richard Smith162e1c12011-04-15 14:24:37 +00001377 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001378}
1379
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001380bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1381 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1382}
1383
1384bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
Argyrios Kyrtzidis6f155de2011-08-25 22:24:47 +00001385 if (TL.isDefinition())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001386 return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
Argyrios Kyrtzidis6f155de2011-08-25 22:24:47 +00001387
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001388 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1389}
1390
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001391bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Chandler Carruth960d13d2011-05-01 09:53:37 +00001392 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001393}
1394
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001395bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1396 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1397 return true;
1398
John McCallc12c5bb2010-05-15 11:32:37 +00001399 return false;
1400}
1401
1402bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1403 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1404 return true;
1405
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001406 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1407 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1408 TU)))
1409 return true;
1410 }
1411
1412 return false;
1413}
1414
1415bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001416 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001417}
1418
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001419bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1420 return Visit(TL.getInnerLoc());
1421}
1422
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001423bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1424 return Visit(TL.getPointeeLoc());
1425}
1426
1427bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1428 return Visit(TL.getPointeeLoc());
1429}
1430
1431bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1432 return Visit(TL.getPointeeLoc());
1433}
1434
1435bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001436 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001437}
1438
1439bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001440 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001441}
1442
Argyrios Kyrtzidis3422fbc2011-08-15 18:44:43 +00001443bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1444 return Visit(TL.getModifiedLoc());
1445}
1446
Douglas Gregor01829d32010-08-31 14:41:23 +00001447bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1448 bool SkipResultType) {
1449 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001450 return true;
1451
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001452 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001453 if (Decl *D = TL.getArg(I))
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001454 if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001455 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001456
1457 return false;
1458}
1459
1460bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1461 if (Visit(TL.getElementLoc()))
1462 return true;
1463
1464 if (Expr *Size = TL.getSizeExpr())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001465 return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001466
1467 return false;
1468}
1469
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001470bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1471 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001472 // Visit the template name.
1473 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1474 TL.getTemplateNameLoc()))
1475 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001476
1477 // Visit the template arguments.
1478 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1479 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1480 return true;
1481
1482 return false;
1483}
1484
Douglas Gregor2332c112010-01-21 20:48:56 +00001485bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1486 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1487}
1488
1489bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1490 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1491 return Visit(TSInfo->getTypeLoc());
1492
1493 return false;
1494}
1495
Sean Huntca63c202011-05-24 22:41:36 +00001496bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1497 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1498 return Visit(TSInfo->getTypeLoc());
1499
1500 return false;
1501}
1502
Douglas Gregor2494dd02011-03-01 01:34:45 +00001503bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
1504 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1505 return true;
1506
1507 return false;
1508}
1509
Douglas Gregor94fdffa2011-03-01 20:11:18 +00001510bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1511 DependentTemplateSpecializationTypeLoc TL) {
1512 // Visit the nested-name-specifier, if there is one.
1513 if (TL.getQualifierLoc() &&
1514 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1515 return true;
1516
1517 // Visit the template arguments.
1518 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1519 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1520 return true;
1521
1522 return false;
1523}
1524
Douglas Gregor9e876872011-03-01 18:12:44 +00001525bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1526 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1527 return true;
1528
1529 return Visit(TL.getNamedTypeLoc());
1530}
1531
Douglas Gregor7536dd52010-12-20 02:24:11 +00001532bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1533 return Visit(TL.getPatternLoc());
1534}
1535
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +00001536bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1537 if (Expr *E = TL.getUnderlyingExpr())
1538 return Visit(MakeCXCursor(E, StmtParent, TU));
1539
1540 return false;
1541}
1542
1543bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1544 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1545}
1546
Eli Friedmanb001de72011-10-06 23:00:33 +00001547bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1548 return Visit(TL.getValueLoc());
1549}
1550
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +00001551#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1552bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1553 return Visit##PARENT##Loc(TL); \
1554}
1555
1556DEFAULT_TYPELOC_IMPL(Complex, Type)
1557DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1558DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1559DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1560DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
1561DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1562DEFAULT_TYPELOC_IMPL(Vector, Type)
1563DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1564DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1565DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1566DEFAULT_TYPELOC_IMPL(Record, TagType)
1567DEFAULT_TYPELOC_IMPL(Enum, TagType)
1568DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1569DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1570DEFAULT_TYPELOC_IMPL(Auto, Type)
1571
Ted Kremenek3064ef92010-08-27 21:34:58 +00001572bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001573 // Visit the nested-name-specifier, if present.
1574 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1575 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1576 return true;
1577
John McCall5e1cdac2011-10-07 06:10:15 +00001578 if (D->isCompleteDefinition()) {
Ted Kremenek3064ef92010-08-27 21:34:58 +00001579 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1580 E = D->bases_end(); I != E; ++I) {
1581 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1582 return true;
1583 }
1584 }
1585
1586 return VisitTagDecl(D);
1587}
1588
Ted Kremenek09dfa372010-02-18 05:46:33 +00001589bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001590 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1591 i != e; ++i)
1592 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001593 return true;
1594
1595 return false;
1596}
1597
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001598//===----------------------------------------------------------------------===//
1599// Data-recursive visitor methods.
1600//===----------------------------------------------------------------------===//
1601
Ted Kremenek28a71942010-11-13 00:36:47 +00001602namespace {
Ted Kremenek035dc412010-11-13 00:36:50 +00001603#define DEF_JOB(NAME, DATA, KIND)\
1604class NAME : public VisitorJob {\
1605public:\
1606 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1607 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Ted Kremenekf64d8032010-11-18 00:02:32 +00001608 DATA *get() const { return static_cast<DATA*>(data[0]); }\
Ted Kremenek035dc412010-11-13 00:36:50 +00001609};
1610
1611DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1612DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001613DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001614DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001615DEF_JOB(ExplicitTemplateArgsVisit, ASTTemplateArgumentListInfo,
Ted Kremenek60608ec2010-11-17 00:50:47 +00001616 ExplicitTemplateArgsVisitKind)
Douglas Gregor94d96292011-01-19 20:34:17 +00001617DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
Douglas Gregor011d8b92012-02-15 00:54:55 +00001618DEF_JOB(LambdaExprParts, LambdaExpr, LambdaExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001619#undef DEF_JOB
1620
1621class DeclVisit : public VisitorJob {
1622public:
1623 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1624 VisitorJob(parent, VisitorJob::DeclVisitKind,
1625 d, isFirst ? (void*) 1 : (void*) 0) {}
1626 static bool classof(const VisitorJob *VJ) {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001627 return VJ->getKind() == DeclVisitKind;
Ted Kremenek035dc412010-11-13 00:36:50 +00001628 }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001629 Decl *get() const { return static_cast<Decl*>(data[0]); }
1630 bool isFirst() const { return data[1] ? true : false; }
Ted Kremenek035dc412010-11-13 00:36:50 +00001631};
Ted Kremenek035dc412010-11-13 00:36:50 +00001632class TypeLocVisit : public VisitorJob {
1633public:
1634 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1635 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1636 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1637
1638 static bool classof(const VisitorJob *VJ) {
1639 return VJ->getKind() == TypeLocVisitKind;
1640 }
1641
Ted Kremenek82f3c502010-11-15 22:23:26 +00001642 TypeLoc get() const {
Ted Kremenekf64d8032010-11-18 00:02:32 +00001643 QualType T = QualType::getFromOpaquePtr(data[0]);
1644 return TypeLoc(T, data[1]);
Ted Kremenek035dc412010-11-13 00:36:50 +00001645 }
1646};
1647
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001648class LabelRefVisit : public VisitorJob {
1649public:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001650 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1651 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001652 labelLoc.getPtrEncoding()) {}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001653
1654 static bool classof(const VisitorJob *VJ) {
1655 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1656 }
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001657 LabelDecl *get() const { return static_cast<LabelDecl*>(data[0]); }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001658 SourceLocation getLoc() const {
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001659 return SourceLocation::getFromPtrEncoding(data[1]); }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001660};
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001661
1662class NestedNameSpecifierLocVisit : public VisitorJob {
1663public:
1664 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1665 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1666 Qualifier.getNestedNameSpecifier(),
1667 Qualifier.getOpaqueData()) { }
1668
1669 static bool classof(const VisitorJob *VJ) {
1670 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1671 }
1672
1673 NestedNameSpecifierLoc get() const {
1674 return NestedNameSpecifierLoc(static_cast<NestedNameSpecifier*>(data[0]),
1675 data[1]);
1676 }
1677};
1678
Ted Kremenekf64d8032010-11-18 00:02:32 +00001679class DeclarationNameInfoVisit : public VisitorJob {
1680public:
1681 DeclarationNameInfoVisit(Stmt *S, CXCursor parent)
1682 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
1683 static bool classof(const VisitorJob *VJ) {
1684 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1685 }
1686 DeclarationNameInfo get() const {
1687 Stmt *S = static_cast<Stmt*>(data[0]);
1688 switch (S->getStmtClass()) {
1689 default:
1690 llvm_unreachable("Unhandled Stmt");
Douglas Gregorba0513d2011-10-25 01:33:02 +00001691 case clang::Stmt::MSDependentExistsStmtClass:
1692 return cast<MSDependentExistsStmt>(S)->getNameInfo();
Ted Kremenekf64d8032010-11-18 00:02:32 +00001693 case Stmt::CXXDependentScopeMemberExprClass:
1694 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1695 case Stmt::DependentScopeDeclRefExprClass:
1696 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
1697 }
1698 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001699};
Ted Kremenekcdba6592010-11-18 00:42:18 +00001700class MemberRefVisit : public VisitorJob {
1701public:
1702 MemberRefVisit(FieldDecl *D, SourceLocation L, CXCursor parent)
1703 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001704 L.getPtrEncoding()) {}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001705 static bool classof(const VisitorJob *VJ) {
1706 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1707 }
1708 FieldDecl *get() const {
1709 return static_cast<FieldDecl*>(data[0]);
1710 }
1711 SourceLocation getLoc() const {
1712 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1713 }
1714};
Ted Kremenek28a71942010-11-13 00:36:47 +00001715class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1716 VisitorWorkList &WL;
1717 CXCursor Parent;
1718public:
1719 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1720 : WL(wl), Parent(parent) {}
1721
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001722 void VisitAddrLabelExpr(AddrLabelExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001723 void VisitBlockExpr(BlockExpr *B);
Ted Kremenek28a71942010-11-13 00:36:47 +00001724 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek083c7e22010-11-13 05:38:03 +00001725 void VisitCompoundStmt(CompoundStmt *S);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001726 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
Douglas Gregorba0513d2011-10-25 01:33:02 +00001727 void VisitMSDependentExistsStmt(MSDependentExistsStmt *S);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001728 void VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001729 void VisitCXXNewExpr(CXXNewExpr *E);
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001730 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001731 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001732 void VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001733 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001734 void VisitCXXTypeidExpr(CXXTypeidExpr *E);
Ted Kremenek55b933a2010-11-17 00:50:36 +00001735 void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001736 void VisitCXXUuidofExpr(CXXUuidofExpr *E);
Argyrios Kyrtzidisdcbb2fb2011-12-03 03:49:44 +00001737 void VisitCXXCatchStmt(CXXCatchStmt *S);
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001738 void VisitDeclRefExpr(DeclRefExpr *D);
Ted Kremenek035dc412010-11-13 00:36:50 +00001739 void VisitDeclStmt(DeclStmt *S);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001740 void VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001741 void VisitDesignatedInitExpr(DesignatedInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001742 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1743 void VisitForStmt(ForStmt *FS);
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001744 void VisitGotoStmt(GotoStmt *GS);
Ted Kremenek28a71942010-11-13 00:36:47 +00001745 void VisitIfStmt(IfStmt *If);
1746 void VisitInitListExpr(InitListExpr *IE);
1747 void VisitMemberExpr(MemberExpr *M);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001748 void VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001749 void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001750 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1751 void VisitOverloadExpr(OverloadExpr *E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001752 void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001753 void VisitStmt(Stmt *S);
1754 void VisitSwitchStmt(SwitchStmt *S);
1755 void VisitWhileStmt(WhileStmt *W);
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001756 void VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Francois Pichet6ad6f282010-12-07 00:08:36 +00001757 void VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E);
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00001758 void VisitTypeTraitExpr(TypeTraitExpr *E);
John Wiegley21ff2e52011-04-28 00:16:57 +00001759 void VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E);
John Wiegley55262202011-04-25 06:54:41 +00001760 void VisitExpressionTraitExpr(ExpressionTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001761 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001762 void VisitVAArgExpr(VAArgExpr *E);
Douglas Gregor94d96292011-01-19 20:34:17 +00001763 void VisitSizeOfPackExpr(SizeOfPackExpr *E);
John McCall4b9c2d22011-11-06 09:01:30 +00001764 void VisitPseudoObjectExpr(PseudoObjectExpr *E);
1765 void VisitOpaqueValueExpr(OpaqueValueExpr *E);
Douglas Gregor011d8b92012-02-15 00:54:55 +00001766 void VisitLambdaExpr(LambdaExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00001767
Ted Kremenek28a71942010-11-13 00:36:47 +00001768private:
Ted Kremenekf64d8032010-11-18 00:02:32 +00001769 void AddDeclarationNameInfo(Stmt *S);
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001770 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001771 void AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001772 void AddMemberRef(FieldDecl *D, SourceLocation L);
Ted Kremenek28a71942010-11-13 00:36:47 +00001773 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001774 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001775 void AddTypeLoc(TypeSourceInfo *TI);
1776 void EnqueueChildren(Stmt *S);
1777};
1778} // end anonyous namespace
1779
Ted Kremenekf64d8032010-11-18 00:02:32 +00001780void EnqueueVisitor::AddDeclarationNameInfo(Stmt *S) {
1781 // 'S' should always be non-null, since it comes from the
1782 // statement we are visiting.
1783 WL.push_back(DeclarationNameInfoVisit(S, Parent));
1784}
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001785
1786void
1787EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1788 if (Qualifier)
1789 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
1790}
1791
Ted Kremenek28a71942010-11-13 00:36:47 +00001792void EnqueueVisitor::AddStmt(Stmt *S) {
1793 if (S)
1794 WL.push_back(StmtVisit(S, Parent));
1795}
Ted Kremenek035dc412010-11-13 00:36:50 +00001796void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001797 if (D)
Ted Kremenek035dc412010-11-13 00:36:50 +00001798 WL.push_back(DeclVisit(D, Parent, isFirst));
Ted Kremenek28a71942010-11-13 00:36:47 +00001799}
Ted Kremenek60608ec2010-11-17 00:50:47 +00001800void EnqueueVisitor::
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001801 AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001802 if (A)
1803 WL.push_back(ExplicitTemplateArgsVisit(
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001804 const_cast<ASTTemplateArgumentListInfo*>(A), Parent));
Ted Kremenek60608ec2010-11-17 00:50:47 +00001805}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001806void EnqueueVisitor::AddMemberRef(FieldDecl *D, SourceLocation L) {
1807 if (D)
1808 WL.push_back(MemberRefVisit(D, L, Parent));
1809}
Ted Kremenek28a71942010-11-13 00:36:47 +00001810void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1811 if (TI)
1812 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1813 }
1814void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001815 unsigned size = WL.size();
John McCall7502c1d2011-02-13 04:07:26 +00001816 for (Stmt::child_range Child = S->children(); Child; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001817 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001818 }
1819 if (size == WL.size())
1820 return;
1821 // Now reverse the entries we just added. This will match the DFS
1822 // ordering performed by the worklist.
1823 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1824 std::reverse(I, E);
1825}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001826void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1827 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
1828}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001829void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1830 AddDecl(B->getBlockDecl());
1831}
Ted Kremenek28a71942010-11-13 00:36:47 +00001832void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1833 EnqueueChildren(E);
1834 AddTypeLoc(E->getTypeSourceInfo());
1835}
Ted Kremenek083c7e22010-11-13 05:38:03 +00001836void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1837 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1838 E = S->body_rend(); I != E; ++I) {
1839 AddStmt(*I);
1840 }
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001841}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001842void EnqueueVisitor::
Douglas Gregorba0513d2011-10-25 01:33:02 +00001843VisitMSDependentExistsStmt(MSDependentExistsStmt *S) {
1844 AddStmt(S->getSubStmt());
1845 AddDeclarationNameInfo(S);
1846 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
1847 AddNestedNameSpecifierLoc(QualifierLoc);
1848}
1849
1850void EnqueueVisitor::
Ted Kremenekf64d8032010-11-18 00:02:32 +00001851VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
1852 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1853 AddDeclarationNameInfo(E);
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001854 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1855 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001856 if (!E->isImplicitAccess())
1857 AddStmt(E->getBase());
1858}
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001859void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001860 // Enqueue the initializer , if any.
1861 AddStmt(E->getInitializer());
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001862 // Enqueue the array size, if any.
1863 AddStmt(E->getArraySize());
1864 // Enqueue the allocated type.
1865 AddTypeLoc(E->getAllocatedTypeSourceInfo());
1866 // Enqueue the placement arguments.
1867 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1868 AddStmt(E->getPlacementArg(I-1));
1869}
Ted Kremenek28a71942010-11-13 00:36:47 +00001870void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
Ted Kremenek8b8d8c92010-11-13 05:55:56 +00001871 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1872 AddStmt(CE->getArg(I-1));
Ted Kremenek28a71942010-11-13 00:36:47 +00001873 AddStmt(CE->getCallee());
1874 AddStmt(CE->getArg(0));
1875}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001876void EnqueueVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1877 // Visit the name of the type being destroyed.
1878 AddTypeLoc(E->getDestroyedTypeInfo());
1879 // Visit the scope type that looks disturbingly like the nested-name-specifier
1880 // but isn't.
1881 AddTypeLoc(E->getScopeTypeInfo());
1882 // Visit the nested-name-specifier.
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001883 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1884 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001885 // Visit base expression.
1886 AddStmt(E->getBase());
1887}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001888void EnqueueVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1889 AddTypeLoc(E->getTypeSourceInfo());
1890}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001891void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1892 EnqueueChildren(E);
1893 AddTypeLoc(E->getTypeSourceInfo());
1894}
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001895void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1896 EnqueueChildren(E);
1897 if (E->isTypeOperand())
1898 AddTypeLoc(E->getTypeOperandSourceInfo());
1899}
Ted Kremenek55b933a2010-11-17 00:50:36 +00001900
1901void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
1902 *E) {
1903 EnqueueChildren(E);
1904 AddTypeLoc(E->getTypeSourceInfo());
1905}
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001906void EnqueueVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1907 EnqueueChildren(E);
1908 if (E->isTypeOperand())
1909 AddTypeLoc(E->getTypeOperandSourceInfo());
1910}
Argyrios Kyrtzidisdcbb2fb2011-12-03 03:49:44 +00001911
1912void EnqueueVisitor::VisitCXXCatchStmt(CXXCatchStmt *S) {
1913 EnqueueChildren(S);
1914 AddDecl(S->getExceptionDecl());
1915}
1916
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001917void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001918 if (DR->hasExplicitTemplateArgs()) {
1919 AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
1920 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001921 WL.push_back(DeclRefExprParts(DR, Parent));
1922}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001923void EnqueueVisitor::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
1924 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1925 AddDeclarationNameInfo(E);
Douglas Gregor00cf3cc2011-02-25 20:49:16 +00001926 AddNestedNameSpecifierLoc(E->getQualifierLoc());
Ted Kremenekf64d8032010-11-18 00:02:32 +00001927}
Ted Kremenek035dc412010-11-13 00:36:50 +00001928void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1929 unsigned size = WL.size();
1930 bool isFirst = true;
1931 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1932 D != DEnd; ++D) {
1933 AddDecl(*D, isFirst);
1934 isFirst = false;
1935 }
1936 if (size == WL.size())
1937 return;
1938 // Now reverse the entries we just added. This will match the DFS
1939 // ordering performed by the worklist.
1940 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1941 std::reverse(I, E);
1942}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001943void EnqueueVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1944 AddStmt(E->getInit());
1945 typedef DesignatedInitExpr::Designator Designator;
1946 for (DesignatedInitExpr::reverse_designators_iterator
1947 D = E->designators_rbegin(), DEnd = E->designators_rend();
1948 D != DEnd; ++D) {
1949 if (D->isFieldDesignator()) {
1950 if (FieldDecl *Field = D->getField())
1951 AddMemberRef(Field, D->getFieldLoc());
1952 continue;
1953 }
1954 if (D->isArrayDesignator()) {
1955 AddStmt(E->getArrayIndex(*D));
1956 continue;
1957 }
1958 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1959 AddStmt(E->getArrayRangeEnd(*D));
1960 AddStmt(E->getArrayRangeStart(*D));
1961 }
1962}
Ted Kremenek28a71942010-11-13 00:36:47 +00001963void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1964 EnqueueChildren(E);
1965 AddTypeLoc(E->getTypeInfoAsWritten());
1966}
1967void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1968 AddStmt(FS->getBody());
1969 AddStmt(FS->getInc());
1970 AddStmt(FS->getCond());
1971 AddDecl(FS->getConditionVariable());
1972 AddStmt(FS->getInit());
1973}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001974void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) {
1975 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
1976}
Ted Kremenek28a71942010-11-13 00:36:47 +00001977void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
1978 AddStmt(If->getElse());
1979 AddStmt(If->getThen());
1980 AddStmt(If->getCond());
1981 AddDecl(If->getConditionVariable());
1982}
1983void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
1984 // We care about the syntactic form of the initializer list, only.
1985 if (InitListExpr *Syntactic = IE->getSyntacticForm())
1986 IE = Syntactic;
1987 EnqueueChildren(IE);
1988}
1989void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
Douglas Gregor89629a72010-11-17 17:15:08 +00001990 WL.push_back(MemberExprParts(M, Parent));
1991
1992 // If the base of the member access expression is an implicit 'this', don't
1993 // visit it.
1994 // FIXME: If we ever want to show these implicit accesses, this will be
1995 // unfortunate. However, clang_getCursor() relies on this behavior.
Douglas Gregor75e85042011-03-02 21:06:53 +00001996 if (!M->isImplicitAccess())
1997 AddStmt(M->getBase());
Ted Kremenek28a71942010-11-13 00:36:47 +00001998}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001999void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
2000 AddTypeLoc(E->getEncodedTypeSourceInfo());
2001}
Ted Kremenek28a71942010-11-13 00:36:47 +00002002void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
2003 EnqueueChildren(M);
2004 AddTypeLoc(M->getClassReceiverTypeInfo());
2005}
Ted Kremenekcdba6592010-11-18 00:42:18 +00002006void EnqueueVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
2007 // Visit the components of the offsetof expression.
2008 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
2009 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
2010 const OffsetOfNode &Node = E->getComponent(I-1);
2011 switch (Node.getKind()) {
2012 case OffsetOfNode::Array:
2013 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2014 break;
2015 case OffsetOfNode::Field:
Abramo Bagnara06dec892011-03-12 09:45:03 +00002016 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
Ted Kremenekcdba6592010-11-18 00:42:18 +00002017 break;
2018 case OffsetOfNode::Identifier:
2019 case OffsetOfNode::Base:
2020 continue;
2021 }
2022 }
2023 // Visit the type into which we're computing the offset.
2024 AddTypeLoc(E->getTypeSourceInfo());
2025}
Ted Kremenek28a71942010-11-13 00:36:47 +00002026void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00002027 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
Ted Kremenek60458782010-11-12 21:34:16 +00002028 WL.push_back(OverloadExprParts(E, Parent));
2029}
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002030void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
2031 UnaryExprOrTypeTraitExpr *E) {
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00002032 EnqueueChildren(E);
2033 if (E->isArgumentType())
2034 AddTypeLoc(E->getArgumentTypeInfo());
2035}
Ted Kremenek28a71942010-11-13 00:36:47 +00002036void EnqueueVisitor::VisitStmt(Stmt *S) {
2037 EnqueueChildren(S);
2038}
2039void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
2040 AddStmt(S->getBody());
2041 AddStmt(S->getCond());
2042 AddDecl(S->getConditionVariable());
2043}
Ted Kremenekfafa75a2010-11-17 00:50:39 +00002044
Ted Kremenek28a71942010-11-13 00:36:47 +00002045void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
2046 AddStmt(W->getBody());
2047 AddStmt(W->getCond());
2048 AddDecl(W->getConditionVariable());
2049}
John Wiegley21ff2e52011-04-28 00:16:57 +00002050
Ted Kremenek2939b6f2010-11-17 00:50:50 +00002051void EnqueueVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
2052 AddTypeLoc(E->getQueriedTypeSourceInfo());
2053}
Francois Pichet6ad6f282010-12-07 00:08:36 +00002054
2055void EnqueueVisitor::VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
Francois Pichet6ad6f282010-12-07 00:08:36 +00002056 AddTypeLoc(E->getRhsTypeSourceInfo());
Francois Pichet0a03a3f2010-12-08 09:11:05 +00002057 AddTypeLoc(E->getLhsTypeSourceInfo());
Francois Pichet6ad6f282010-12-07 00:08:36 +00002058}
2059
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00002060void EnqueueVisitor::VisitTypeTraitExpr(TypeTraitExpr *E) {
2061 for (unsigned I = E->getNumArgs(); I > 0; --I)
2062 AddTypeLoc(E->getArg(I-1));
2063}
2064
John Wiegley21ff2e52011-04-28 00:16:57 +00002065void EnqueueVisitor::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
2066 AddTypeLoc(E->getQueriedTypeSourceInfo());
2067}
2068
John Wiegley55262202011-04-25 06:54:41 +00002069void EnqueueVisitor::VisitExpressionTraitExpr(ExpressionTraitExpr *E) {
2070 EnqueueChildren(E);
2071}
2072
Ted Kremenek28a71942010-11-13 00:36:47 +00002073void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
2074 VisitOverloadExpr(U);
2075 if (!U->isImplicitAccess())
2076 AddStmt(U->getBase());
2077}
Ted Kremenek9d3bf792010-11-17 00:50:43 +00002078void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) {
2079 AddStmt(E->getSubExpr());
2080 AddTypeLoc(E->getWrittenTypeInfo());
2081}
Douglas Gregor94d96292011-01-19 20:34:17 +00002082void EnqueueVisitor::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
2083 WL.push_back(SizeOfPackExprParts(E, Parent));
2084}
John McCall4b9c2d22011-11-06 09:01:30 +00002085void EnqueueVisitor::VisitOpaqueValueExpr(OpaqueValueExpr *E) {
2086 // If the opaque value has a source expression, just transparently
2087 // visit that. This is useful for (e.g.) pseudo-object expressions.
2088 if (Expr *SourceExpr = E->getSourceExpr())
2089 return Visit(SourceExpr);
John McCall4b9c2d22011-11-06 09:01:30 +00002090}
Douglas Gregor011d8b92012-02-15 00:54:55 +00002091void EnqueueVisitor::VisitLambdaExpr(LambdaExpr *E) {
2092 AddStmt(E->getBody());
2093 WL.push_back(LambdaExprParts(E, Parent));
2094}
John McCall4b9c2d22011-11-06 09:01:30 +00002095void EnqueueVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *E) {
2096 // Treat the expression like its syntactic form.
2097 Visit(E->getSyntacticForm());
2098}
Ted Kremenek60458782010-11-12 21:34:16 +00002099
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002100void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002101 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002102}
2103
2104bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2105 if (RegionOfInterest.isValid()) {
2106 SourceRange Range = getRawCursorExtent(C);
2107 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2108 return false;
2109 }
2110 return true;
2111}
2112
2113bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2114 while (!WL.empty()) {
2115 // Dequeue the worklist item.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002116 VisitorJob LI = WL.back();
2117 WL.pop_back();
2118
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002119 // Set the Parent field, then back to its old value once we're done.
2120 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2121
2122 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00002123 case VisitorJob::DeclVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002124 Decl *D = cast<DeclVisit>(&LI)->get();
Ted Kremenekf1107452010-11-12 18:26:56 +00002125 if (!D)
2126 continue;
2127
2128 // For now, perform default visitation for Decls.
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002129 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2130 cast<DeclVisit>(&LI)->isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00002131 return true;
2132
2133 continue;
2134 }
Ted Kremenek60608ec2010-11-17 00:50:47 +00002135 case VisitorJob::ExplicitTemplateArgsVisitKind: {
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00002136 const ASTTemplateArgumentListInfo *ArgList =
Ted Kremenek60608ec2010-11-17 00:50:47 +00002137 cast<ExplicitTemplateArgsVisit>(&LI)->get();
2138 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2139 *ArgEnd = Arg + ArgList->NumTemplateArgs;
2140 Arg != ArgEnd; ++Arg) {
2141 if (VisitTemplateArgumentLoc(*Arg))
2142 return true;
2143 }
2144 continue;
2145 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002146 case VisitorJob::TypeLocVisitKind: {
2147 // Perform default visitation for TypeLocs.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002148 if (Visit(cast<TypeLocVisit>(&LI)->get()))
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002149 return true;
2150 continue;
2151 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002152 case VisitorJob::LabelRefVisitKind: {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002153 LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Ted Kremeneke7455012011-02-23 04:54:51 +00002154 if (LabelStmt *stmt = LS->getStmt()) {
2155 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2156 TU))) {
2157 return true;
2158 }
2159 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002160 continue;
2161 }
Ted Kremenek47695c82011-08-18 22:25:21 +00002162
Douglas Gregorf3db29f2011-02-25 18:19:59 +00002163 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2164 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2165 if (VisitNestedNameSpecifierLoc(V->get()))
2166 return true;
2167 continue;
2168 }
2169
Ted Kremenekf64d8032010-11-18 00:02:32 +00002170 case VisitorJob::DeclarationNameInfoVisitKind: {
2171 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2172 ->get()))
2173 return true;
2174 continue;
2175 }
Ted Kremenekcdba6592010-11-18 00:42:18 +00002176 case VisitorJob::MemberRefVisitKind: {
2177 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2178 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2179 return true;
2180 continue;
2181 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002182 case VisitorJob::StmtVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002183 Stmt *S = cast<StmtVisit>(&LI)->get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00002184 if (!S)
2185 continue;
2186
Ted Kremenekf1107452010-11-12 18:26:56 +00002187 // Update the current cursor.
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002188 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
Ted Kremenekcdba6592010-11-18 00:42:18 +00002189 if (!IsInRegionOfInterest(Cursor))
2190 continue;
2191 switch (Visitor(Cursor, Parent, ClientData)) {
2192 case CXChildVisit_Break: return true;
2193 case CXChildVisit_Continue: break;
2194 case CXChildVisit_Recurse:
2195 EnqueueWorkList(WL, S);
Ted Kremenek82f3c502010-11-15 22:23:26 +00002196 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002197 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00002198 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002199 }
2200 case VisitorJob::MemberExprPartsKind: {
2201 // Handle the other pieces in the MemberExpr besides the base.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002202 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002203
2204 // Visit the nested-name-specifier
Douglas Gregor40d96a62011-02-28 21:54:11 +00002205 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
2206 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002207 return true;
2208
2209 // Visit the declaration name.
2210 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2211 return true;
2212
2213 // Visit the explicitly-specified template arguments, if any.
2214 if (M->hasExplicitTemplateArgs()) {
2215 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2216 *ArgEnd = Arg + M->getNumTemplateArgs();
2217 Arg != ArgEnd; ++Arg) {
2218 if (VisitTemplateArgumentLoc(*Arg))
2219 return true;
2220 }
2221 }
2222 continue;
2223 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002224 case VisitorJob::DeclRefExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002225 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002226 // Visit nested-name-specifier, if present.
Douglas Gregor40d96a62011-02-28 21:54:11 +00002227 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
2228 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002229 return true;
2230 // Visit declaration name.
2231 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2232 return true;
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002233 continue;
2234 }
Ted Kremenek60458782010-11-12 21:34:16 +00002235 case VisitorJob::OverloadExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002236 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Ted Kremenek60458782010-11-12 21:34:16 +00002237 // Visit the nested-name-specifier.
Douglas Gregor4c9be892011-02-28 20:01:57 +00002238 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
2239 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenek60458782010-11-12 21:34:16 +00002240 return true;
2241 // Visit the declaration name.
2242 if (VisitDeclarationNameInfo(O->getNameInfo()))
2243 return true;
2244 // Visit the overloaded declaration reference.
2245 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2246 return true;
Ted Kremenek60458782010-11-12 21:34:16 +00002247 continue;
2248 }
Douglas Gregor94d96292011-01-19 20:34:17 +00002249 case VisitorJob::SizeOfPackExprPartsKind: {
2250 SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
2251 NamedDecl *Pack = E->getPack();
2252 if (isa<TemplateTypeParmDecl>(Pack)) {
2253 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
2254 E->getPackLoc(), TU)))
2255 return true;
2256
2257 continue;
2258 }
2259
2260 if (isa<TemplateTemplateParmDecl>(Pack)) {
2261 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
2262 E->getPackLoc(), TU)))
2263 return true;
2264
2265 continue;
2266 }
2267
2268 // Non-type template parameter packs and function parameter packs are
2269 // treated like DeclRefExpr cursors.
2270 continue;
2271 }
Douglas Gregor011d8b92012-02-15 00:54:55 +00002272
2273 case VisitorJob::LambdaExprPartsKind: {
2274 // Visit captures.
2275 LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
2276 for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
2277 CEnd = E->explicit_capture_end();
2278 C != CEnd; ++C) {
2279 if (C->capturesThis())
2280 continue;
2281
2282 if (Visit(MakeCursorVariableRef(C->getCapturedVar(),
2283 C->getLocation(),
2284 TU)))
2285 return true;
2286 }
2287
2288 // Visit parameters and return type, if present.
2289 if (E->hasExplicitParameters() || E->hasExplicitResultType()) {
2290 TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
2291 if (E->hasExplicitParameters() && E->hasExplicitResultType()) {
2292 // Visit the whole type.
2293 if (Visit(TL))
2294 return true;
2295 } else if (isa<FunctionProtoTypeLoc>(TL)) {
2296 FunctionProtoTypeLoc Proto = cast<FunctionProtoTypeLoc>(TL);
2297 if (E->hasExplicitParameters()) {
2298 // Visit parameters.
2299 for (unsigned I = 0, N = Proto.getNumArgs(); I != N; ++I)
2300 if (Visit(MakeCXCursor(Proto.getArg(I), TU)))
2301 return true;
2302 } else {
2303 // Visit result type.
2304 if (Visit(Proto.getResultLoc()))
2305 return true;
2306 }
2307 }
2308 }
2309 break;
2310 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002311 }
2312 }
2313 return false;
2314}
2315
Ted Kremenekcdba6592010-11-18 00:42:18 +00002316bool CursorVisitor::Visit(Stmt *S) {
Ted Kremenekd1ded662010-11-15 23:31:32 +00002317 VisitorWorkList *WL = 0;
2318 if (!WorkListFreeList.empty()) {
2319 WL = WorkListFreeList.back();
2320 WL->clear();
2321 WorkListFreeList.pop_back();
2322 }
2323 else {
2324 WL = new VisitorWorkList();
2325 WorkListCache.push_back(WL);
2326 }
2327 EnqueueWorkList(*WL, S);
2328 bool result = RunVisitorWorkList(*WL);
2329 WorkListFreeList.push_back(WL);
2330 return result;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002331}
2332
Francois Pichet48a8d142011-07-25 22:00:44 +00002333namespace {
2334typedef llvm::SmallVector<SourceRange, 4> RefNamePieces;
2335RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
2336 const DeclarationNameInfo &NI,
2337 const SourceRange &QLoc,
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00002338 const ASTTemplateArgumentListInfo *TemplateArgs = 0){
Francois Pichet48a8d142011-07-25 22:00:44 +00002339 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
2340 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
2341 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
2342
2343 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
2344
2345 RefNamePieces Pieces;
2346
2347 if (WantQualifier && QLoc.isValid())
2348 Pieces.push_back(QLoc);
2349
2350 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
2351 Pieces.push_back(NI.getLoc());
2352
2353 if (WantTemplateArgs && TemplateArgs)
2354 Pieces.push_back(SourceRange(TemplateArgs->LAngleLoc,
2355 TemplateArgs->RAngleLoc));
2356
2357 if (Kind == DeclarationName::CXXOperatorName) {
2358 Pieces.push_back(SourceLocation::getFromRawEncoding(
2359 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
2360 Pieces.push_back(SourceLocation::getFromRawEncoding(
2361 NI.getInfo().CXXOperatorName.EndOpNameLoc));
2362 }
2363
2364 if (WantSinglePiece) {
2365 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
2366 Pieces.clear();
2367 Pieces.push_back(R);
2368 }
2369
2370 return Pieces;
2371}
2372}
2373
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002374//===----------------------------------------------------------------------===//
2375// Misc. API hooks.
2376//===----------------------------------------------------------------------===//
2377
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002378static llvm::sys::Mutex EnableMultithreadingMutex;
2379static bool EnabledMultithreading;
2380
Argyrios Kyrtzidisfa39f5b2011-12-15 04:52:41 +00002381static void fatal_error_handler(void *user_data, const std::string& reason) {
Argyrios Kyrtzidisfa39f5b2011-12-15 04:52:41 +00002382 // Write the result out to stderr avoiding errs() because raw_ostreams can
2383 // call report_fatal_error.
Argyrios Kyrtzidisdb7a8002011-12-15 06:51:30 +00002384 fprintf(stderr, "LIBCLANG FATAL ERROR: %s\n", reason.c_str());
Argyrios Kyrtzidisfa39f5b2011-12-15 04:52:41 +00002385 ::abort();
2386}
2387
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002388extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002389CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2390 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002391 // Disable pretty stack trace functionality, which will otherwise be a very
2392 // poor citizen of the world and set up all sorts of signal handlers.
2393 llvm::DisablePrettyStackTrace = true;
2394
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002395 // We use crash recovery to make some of our APIs more reliable, implicitly
2396 // enable it.
2397 llvm::CrashRecoveryContext::Enable();
2398
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002399 // Enable support for multithreading in LLVM.
2400 {
2401 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2402 if (!EnabledMultithreading) {
Argyrios Kyrtzidisfa39f5b2011-12-15 04:52:41 +00002403 llvm::install_fatal_error_handler(fatal_error_handler, 0);
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002404 llvm::llvm_start_multithreaded();
2405 EnabledMultithreading = true;
2406 }
2407 }
2408
Douglas Gregora030b7c2010-01-22 20:35:53 +00002409 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002410 if (excludeDeclarationsFromPCH)
2411 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002412 if (displayDiagnostics)
2413 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002414 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002415}
2416
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002417void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002418 if (CIdx)
2419 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002420}
2421
Ted Kremenekd2427dd2011-03-18 23:05:39 +00002422void clang_toggleCrashRecovery(unsigned isEnabled) {
2423 if (isEnabled)
2424 llvm::CrashRecoveryContext::Enable();
2425 else
2426 llvm::CrashRecoveryContext::Disable();
2427}
2428
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002429CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002430 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002431 if (!CIdx)
2432 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002433
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002434 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002435 FileSystemOptions FileSystemOpts;
2436 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002437
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00002438 IntrusiveRefCntPtr<DiagnosticsEngine> Diags;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002439 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002440 CXXIdx->getOnlyLocalDecls(),
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00002441 0, 0,
2442 /*CaptureDiagnostics=*/true,
2443 /*AllowPCHWithCompilerErrors=*/true);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002444 return MakeCXTranslationUnit(TU);
Steve Naroff600866c2009-08-27 19:51:58 +00002445}
2446
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002447unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002448 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregorb5af8432011-08-25 22:54:01 +00002449 CXTranslationUnit_CacheCompletionResults;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002450}
2451
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002452CXTranslationUnit
2453clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2454 const char *source_filename,
2455 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002456 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002457 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002458 struct CXUnsavedFile *unsaved_files) {
Argyrios Kyrtzidise1d43302012-02-25 02:41:16 +00002459 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
Douglas Gregor5a430212010-07-21 18:52:53 +00002460 return clang_parseTranslationUnit(CIdx, source_filename,
2461 command_line_args, num_command_line_args,
2462 unsaved_files, num_unsaved_files,
Douglas Gregordca8ee82011-05-06 16:33:08 +00002463 Options);
Douglas Gregor5a430212010-07-21 18:52:53 +00002464}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002465
2466struct ParseTranslationUnitInfo {
2467 CXIndex CIdx;
2468 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002469 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002470 int num_command_line_args;
2471 struct CXUnsavedFile *unsaved_files;
2472 unsigned num_unsaved_files;
2473 unsigned options;
2474 CXTranslationUnit result;
2475};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002476static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002477 ParseTranslationUnitInfo *PTUI =
2478 static_cast<ParseTranslationUnitInfo*>(UserData);
2479 CXIndex CIdx = PTUI->CIdx;
2480 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002481 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002482 int num_command_line_args = PTUI->num_command_line_args;
2483 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2484 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2485 unsigned options = PTUI->options;
2486 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002487
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002488 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002489 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002490
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002491 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2492
Douglas Gregor44c181a2010-07-23 00:33:23 +00002493 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregor467dc882011-08-25 22:30:56 +00002494 // FIXME: Add a flag for modules.
2495 TranslationUnitKind TUKind
2496 = (options & CXTranslationUnit_Incomplete)? TU_Prefix : TU_Complete;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002497 bool CacheCodeCompetionResults
2498 = options & CXTranslationUnit_CacheCompletionResults;
2499
Douglas Gregor5352ac02010-01-28 00:27:43 +00002500 // Configure the diagnostics.
2501 DiagnosticOptions DiagOpts;
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00002502 IntrusiveRefCntPtr<DiagnosticsEngine>
Ted Kremenek25a11e12011-03-22 01:15:24 +00002503 Diags(CompilerInstance::createDiagnostics(DiagOpts, num_command_line_args,
2504 command_line_args));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002505
Ted Kremenek25a11e12011-03-22 01:15:24 +00002506 // Recover resources if we crash before exiting this function.
David Blaikied6471f72011-09-25 23:23:43 +00002507 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
2508 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00002509 DiagCleanup(Diags.getPtr());
2510
Dylan Noblesmith1e4c01b2012-02-13 12:32:21 +00002511 OwningPtr<std::vector<ASTUnit::RemappedFile> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00002512 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2513
2514 // Recover resources if we crash before exiting this function.
2515 llvm::CrashRecoveryContextCleanupRegistrar<
2516 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2517
Douglas Gregor4db64a42010-01-23 00:14:00 +00002518 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002519 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002520 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002521 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002522 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2523 Buffer));
Douglas Gregor4db64a42010-01-23 00:14:00 +00002524 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002525
Dylan Noblesmith1e4c01b2012-02-13 12:32:21 +00002526 OwningPtr<std::vector<const char *> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00002527 Args(new std::vector<const char*>());
2528
2529 // Recover resources if we crash before exiting this method.
2530 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
2531 ArgsCleanup(Args.get());
2532
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002533 // Since the Clang C library is primarily used by batch tools dealing with
2534 // (often very broken) source code, where spell-checking can have a
2535 // significant negative impact on performance (particularly when
2536 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002537 // Only do this if we haven't found a spell-checking-related argument.
2538 bool FoundSpellCheckingArgument = false;
2539 for (int I = 0; I != num_command_line_args; ++I) {
2540 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2541 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2542 FoundSpellCheckingArgument = true;
2543 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002544 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002545 }
2546 if (!FoundSpellCheckingArgument)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002547 Args->push_back("-fno-spell-checking");
Douglas Gregorb10daed2010-10-11 16:52:23 +00002548
Ted Kremenek25a11e12011-03-22 01:15:24 +00002549 Args->insert(Args->end(), command_line_args,
2550 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002551
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002552 // The 'source_filename' argument is optional. If the caller does not
2553 // specify it then it is assumed that the source file is specified
2554 // in the actual argument list.
2555 // Put the source file after command_line_args otherwise if '-x' flag is
2556 // present it will be unused.
2557 if (source_filename)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002558 Args->push_back(source_filename);
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002559
Douglas Gregor44c181a2010-07-23 00:33:23 +00002560 // Do we need the detailed preprocessing record?
2561 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Ted Kremenek25a11e12011-03-22 01:15:24 +00002562 Args->push_back("-Xclang");
2563 Args->push_back("-detailed-preprocessing-record");
Douglas Gregor44c181a2010-07-23 00:33:23 +00002564 }
2565
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002566 unsigned NumErrors = Diags->getClient()->getNumErrors();
Dylan Noblesmith1e4c01b2012-02-13 12:32:21 +00002567 OwningPtr<ASTUnit> Unit(
Ted Kremenek4ee99262011-03-22 20:16:19 +00002568 ASTUnit::LoadFromCommandLine(Args->size() ? &(*Args)[0] : 0
2569 /* vector::data() not portable */,
2570 Args->size() ? (&(*Args)[0] + Args->size()) :0,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002571 Diags,
2572 CXXIdx->getClangResourcesPath(),
2573 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002574 /*CaptureDiagnostics=*/true,
Ted Kremenek4ee99262011-03-22 20:16:19 +00002575 RemappedFiles->size() ? &(*RemappedFiles)[0]:0,
Ted Kremenek25a11e12011-03-22 01:15:24 +00002576 RemappedFiles->size(),
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00002577 /*RemappedFilesKeepOriginalName=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002578 PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00002579 TUKind,
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00002580 CacheCodeCompetionResults,
2581 /*AllowPCHWithCompilerErrors=*/true));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002582
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002583 if (NumErrors != Diags->getClient()->getNumErrors()) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002584 // Make sure to check that 'Unit' is non-NULL.
2585 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2586 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2587 DEnd = Unit->stored_diag_end();
2588 D != DEnd; ++D) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002589 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOpts());
Douglas Gregorb10daed2010-10-11 16:52:23 +00002590 CXString Msg = clang_formatDiagnostic(&Diag,
2591 clang_defaultDiagnosticDisplayOptions());
2592 fprintf(stderr, "%s\n", clang_getCString(Msg));
2593 clang_disposeString(Msg);
2594 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002595#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002596 // On Windows, force a flush, since there may be multiple copies of
2597 // stderr and stdout in the file system, all with different buffers
2598 // but writing to the same device.
2599 fflush(stderr);
2600#endif
2601 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002602 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002603
Ted Kremeneka60ed472010-11-16 08:15:36 +00002604 PTUI->result = MakeCXTranslationUnit(Unit.take());
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002605}
2606CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2607 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002608 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002609 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002610 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002611 unsigned num_unsaved_files,
2612 unsigned options) {
2613 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002614 num_command_line_args, unsaved_files,
2615 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002616 llvm::CrashRecoveryContext CRC;
2617
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002618 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002619 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2620 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2621 fprintf(stderr, " 'command_line_args' : [");
2622 for (int i = 0; i != num_command_line_args; ++i) {
2623 if (i)
2624 fprintf(stderr, ", ");
2625 fprintf(stderr, "'%s'", command_line_args[i]);
2626 }
2627 fprintf(stderr, "],\n");
2628 fprintf(stderr, " 'unsaved_files' : [");
2629 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2630 if (i)
2631 fprintf(stderr, ", ");
2632 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2633 unsaved_files[i].Length);
2634 }
2635 fprintf(stderr, "],\n");
2636 fprintf(stderr, " 'options' : %d,\n", options);
2637 fprintf(stderr, "}\n");
2638
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002639 return 0;
Douglas Gregor6df78732011-05-05 20:27:22 +00002640 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
2641 PrintLibclangResourceUsage(PTUI.result);
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002642 }
Douglas Gregor6df78732011-05-05 20:27:22 +00002643
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002644 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002645}
2646
Douglas Gregor19998442010-08-13 15:35:05 +00002647unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2648 return CXSaveTranslationUnit_None;
2649}
Argyrios Kyrtzidis142bcb52012-03-28 02:17:59 +00002650
2651namespace {
2652
2653struct SaveTranslationUnitInfo {
2654 CXTranslationUnit TU;
2655 const char *FileName;
2656 unsigned options;
2657 CXSaveError result;
2658};
2659
2660}
2661
2662static void clang_saveTranslationUnit_Impl(void *UserData) {
2663 SaveTranslationUnitInfo *STUI =
2664 static_cast<SaveTranslationUnitInfo*>(UserData);
2665
2666 STUI->result = static_cast<ASTUnit *>(STUI->TU->TUData)->Save(STUI->FileName);
2667}
2668
Douglas Gregor19998442010-08-13 15:35:05 +00002669int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2670 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002671 if (!TU)
Douglas Gregor39c411f2011-07-06 16:43:36 +00002672 return CXSaveError_InvalidTU;
Argyrios Kyrtzidis142bcb52012-03-28 02:17:59 +00002673
2674 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
2675 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2676
2677 SaveTranslationUnitInfo STUI = { TU, FileName, options, CXSaveError_None };
2678
2679 if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred() ||
2680 getenv("LIBCLANG_NOTHREADS")) {
2681 clang_saveTranslationUnit_Impl(&STUI);
2682
2683 if (getenv("LIBCLANG_RESOURCE_USAGE"))
2684 PrintLibclangResourceUsage(TU);
2685
2686 return STUI.result;
2687 }
2688
2689 // We have an AST that has invalid nodes due to compiler errors.
2690 // Use a crash recovery thread for protection.
2691
2692 llvm::CrashRecoveryContext CRC;
2693
2694 if (!RunSafely(CRC, clang_saveTranslationUnit_Impl, &STUI)) {
2695 fprintf(stderr, "libclang: crash detected during AST saving: {\n");
2696 fprintf(stderr, " 'filename' : '%s'\n", FileName);
2697 fprintf(stderr, " 'options' : %d,\n", options);
2698 fprintf(stderr, "}\n");
2699
2700 return CXSaveError_Unknown;
2701
2702 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
Douglas Gregor6df78732011-05-05 20:27:22 +00002703 PrintLibclangResourceUsage(TU);
Argyrios Kyrtzidis142bcb52012-03-28 02:17:59 +00002704 }
2705
2706 return STUI.result;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002707}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002708
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002709void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002710 if (CTUnit) {
2711 // If the translation unit has been marked as unsafe to free, just discard
2712 // it.
Ted Kremeneka60ed472010-11-16 08:15:36 +00002713 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002714 return;
2715
Ted Kremeneka60ed472010-11-16 08:15:36 +00002716 delete static_cast<ASTUnit *>(CTUnit->TUData);
2717 disposeCXStringPool(CTUnit->StringPool);
Ted Kremenek15322172011-11-10 08:43:12 +00002718 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002719 delete CTUnit;
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002720 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002721}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002722
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002723unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2724 return CXReparse_None;
2725}
2726
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002727struct ReparseTranslationUnitInfo {
2728 CXTranslationUnit TU;
2729 unsigned num_unsaved_files;
2730 struct CXUnsavedFile *unsaved_files;
2731 unsigned options;
2732 int result;
2733};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002734
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002735static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002736 ReparseTranslationUnitInfo *RTUI =
2737 static_cast<ReparseTranslationUnitInfo*>(UserData);
2738 CXTranslationUnit TU = RTUI->TU;
Ted Kremenek15322172011-11-10 08:43:12 +00002739
2740 // Reset the associated diagnostics.
2741 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
2742 TU->Diagnostics = 0;
2743
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002744 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2745 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2746 unsigned options = RTUI->options;
2747 (void) options;
2748 RTUI->result = 1;
2749
Douglas Gregorabc563f2010-07-19 21:46:24 +00002750 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002751 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002752
Ted Kremeneka60ed472010-11-16 08:15:36 +00002753 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor593b0c12010-09-23 18:47:53 +00002754 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002755
Dylan Noblesmith1e4c01b2012-02-13 12:32:21 +00002756 OwningPtr<std::vector<ASTUnit::RemappedFile> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00002757 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2758
2759 // Recover resources if we crash before exiting this function.
2760 llvm::CrashRecoveryContextCleanupRegistrar<
2761 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2762
Douglas Gregorabc563f2010-07-19 21:46:24 +00002763 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002764 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002765 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002766 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002767 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2768 Buffer));
Douglas Gregorabc563f2010-07-19 21:46:24 +00002769 }
2770
Ted Kremenek4ee99262011-03-22 20:16:19 +00002771 if (!CXXUnit->Reparse(RemappedFiles->size() ? &(*RemappedFiles)[0] : 0,
2772 RemappedFiles->size()))
Douglas Gregor593b0c12010-09-23 18:47:53 +00002773 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002774}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002775
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002776int clang_reparseTranslationUnit(CXTranslationUnit TU,
2777 unsigned num_unsaved_files,
2778 struct CXUnsavedFile *unsaved_files,
2779 unsigned options) {
2780 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2781 options, 0 };
Argyrios Kyrtzidis8c4b47e2011-10-28 22:54:33 +00002782
Argyrios Kyrtzidise7de9b42011-10-29 19:32:39 +00002783 if (getenv("LIBCLANG_NOTHREADS")) {
Argyrios Kyrtzidis8c4b47e2011-10-28 22:54:33 +00002784 clang_reparseTranslationUnit_Impl(&RTUI);
2785 return RTUI.result;
2786 }
2787
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002788 llvm::CrashRecoveryContext CRC;
2789
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002790 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002791 fprintf(stderr, "libclang: crash detected during reparsing\n");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002792 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002793 return 1;
Douglas Gregor6df78732011-05-05 20:27:22 +00002794 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
2795 PrintLibclangResourceUsage(TU);
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002796
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002797 return RTUI.result;
2798}
2799
Douglas Gregordf95a132010-08-09 20:45:32 +00002800
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002801CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002802 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002803 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002804
Ted Kremeneka60ed472010-11-16 08:15:36 +00002805 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002806 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002807}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002808
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002809CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002810 CXCursor Result = { CXCursor_TranslationUnit, 0, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002811 return Result;
2812}
2813
Ted Kremenekfb480492010-01-13 21:46:36 +00002814} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002815
Ted Kremenekfb480492010-01-13 21:46:36 +00002816//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002817// CXFile Operations.
2818//===----------------------------------------------------------------------===//
2819
2820extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002821CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002822 if (!SFile)
Ted Kremeneka60ed472010-11-16 08:15:36 +00002823 return createCXString((const char*)NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002824
Steve Naroff88145032009-10-27 14:35:18 +00002825 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002826 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002827}
2828
2829time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002830 if (!SFile)
2831 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002832
Steve Naroff88145032009-10-27 14:35:18 +00002833 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2834 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002835}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002836
Douglas Gregorb9790342010-01-22 21:44:22 +00002837CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2838 if (!tu)
2839 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002840
Ted Kremeneka60ed472010-11-16 08:15:36 +00002841 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002842
Douglas Gregorb9790342010-01-22 21:44:22 +00002843 FileManager &FMgr = CXXUnit->getFileManager();
Chris Lattner39b49bc2010-11-23 08:35:12 +00002844 return const_cast<FileEntry *>(FMgr.getFile(file_name));
Douglas Gregorb9790342010-01-22 21:44:22 +00002845}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002846
Douglas Gregordd3e5542011-05-04 00:14:37 +00002847unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit tu, CXFile file) {
2848 if (!tu || !file)
2849 return 0;
2850
2851 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
2852 FileEntry *FEnt = static_cast<FileEntry *>(file);
2853 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
2854 .isFileMultipleIncludeGuarded(FEnt);
2855}
2856
Ted Kremenekfb480492010-01-13 21:46:36 +00002857} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002858
Ted Kremenekfb480492010-01-13 21:46:36 +00002859//===----------------------------------------------------------------------===//
2860// CXCursor Operations.
2861//===----------------------------------------------------------------------===//
2862
Ted Kremenekfb480492010-01-13 21:46:36 +00002863static Decl *getDeclFromExpr(Stmt *E) {
Argyrios Kyrtzidisc2954612011-09-12 22:17:26 +00002864 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Douglas Gregordb1314e2010-10-01 21:11:22 +00002865 return getDeclFromExpr(CE->getSubExpr());
2866
Ted Kremenekfb480492010-01-13 21:46:36 +00002867 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2868 return RefExpr->getDecl();
2869 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2870 return ME->getMemberDecl();
2871 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2872 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002873 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
John McCall12f78a62010-12-02 01:19:52 +00002874 return PRE->isExplicitProperty() ? PRE->getExplicitProperty() : 0;
John McCall4b9c2d22011-11-06 09:01:30 +00002875 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
2876 return getDeclFromExpr(POE->getSyntacticForm());
2877 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
2878 if (Expr *Src = OVE->getSourceExpr())
2879 return getDeclFromExpr(Src);
Douglas Gregordb1314e2010-10-01 21:11:22 +00002880
Ted Kremenekfb480492010-01-13 21:46:36 +00002881 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2882 return getDeclFromExpr(CE->getCallee());
Chris Lattner5f9e2722011-07-23 10:55:15 +00002883 if (CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Douglas Gregor93798e22010-11-05 21:11:19 +00002884 if (!CE->isElidable())
2885 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002886 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2887 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002888
Douglas Gregordb1314e2010-10-01 21:11:22 +00002889 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2890 return PE->getProtocol();
Douglas Gregorc7793c72011-01-15 01:15:58 +00002891 if (SubstNonTypeTemplateParmPackExpr *NTTP
2892 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
2893 return NTTP->getParameterPack();
Douglas Gregor94d96292011-01-19 20:34:17 +00002894 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2895 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
2896 isa<ParmVarDecl>(SizeOfPack->getPack()))
2897 return SizeOfPack->getPack();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002898
Ted Kremenekfb480492010-01-13 21:46:36 +00002899 return 0;
2900}
2901
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002902static SourceLocation getLocationFromExpr(Expr *E) {
Argyrios Kyrtzidisc2954612011-09-12 22:17:26 +00002903 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
2904 return getLocationFromExpr(CE->getSubExpr());
2905
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002906 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2907 return /*FIXME:*/Msg->getLeftLoc();
2908 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2909 return DRE->getLocation();
2910 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2911 return Member->getMemberLoc();
2912 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2913 return Ivar->getLocation();
Douglas Gregor94d96292011-01-19 20:34:17 +00002914 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2915 return SizeOfPack->getPackLoc();
2916
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002917 return E->getLocStart();
2918}
2919
Ted Kremenekfb480492010-01-13 21:46:36 +00002920extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002921
2922unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002923 CXCursorVisitor visitor,
2924 CXClientData client_data) {
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00002925 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
2926 /*VisitPreprocessorLast=*/false);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002927 return CursorVis.VisitChildren(parent);
2928}
2929
David Chisnall3387c652010-11-03 14:12:26 +00002930#ifndef __has_feature
2931#define __has_feature(x) 0
2932#endif
2933#if __has_feature(blocks)
2934typedef enum CXChildVisitResult
2935 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2936
2937static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2938 CXClientData client_data) {
2939 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2940 return block(cursor, parent);
2941}
2942#else
2943// If we are compiled with a compiler that doesn't have native blocks support,
2944// define and call the block manually, so the
2945typedef struct _CXChildVisitResult
2946{
2947 void *isa;
2948 int flags;
2949 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002950 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2951 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00002952} *CXCursorVisitorBlock;
2953
2954static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2955 CXClientData client_data) {
2956 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2957 return block->invoke(block, cursor, parent);
2958}
2959#endif
2960
2961
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002962unsigned clang_visitChildrenWithBlock(CXCursor parent,
2963 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00002964 return clang_visitChildren(parent, visitWithBlock, block);
2965}
2966
Douglas Gregor78205d42010-01-20 21:45:58 +00002967static CXString getDeclSpelling(Decl *D) {
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00002968 if (!D)
2969 return createCXString("");
2970
2971 NamedDecl *ND = dyn_cast<NamedDecl>(D);
Douglas Gregore3c60a72010-11-17 00:13:31 +00002972 if (!ND) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002973 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00002974 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
2975 return createCXString(Property->getIdentifier()->getName());
2976
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002977 return createCXString("");
Douglas Gregore3c60a72010-11-17 00:13:31 +00002978 }
2979
Douglas Gregor78205d42010-01-20 21:45:58 +00002980 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002981 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002982
Douglas Gregor78205d42010-01-20 21:45:58 +00002983 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2984 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2985 // and returns different names. NamedDecl returns the class name and
2986 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002987 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002988
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002989 if (isa<UsingDirectiveDecl>(D))
2990 return createCXString("");
2991
Dylan Noblesmith36d59272012-02-13 12:32:26 +00002992 SmallString<1024> S;
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002993 llvm::raw_svector_ostream os(S);
2994 ND->printName(os);
2995
2996 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002997}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002998
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002999CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003000 if (clang_isTranslationUnit(C.kind))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003001 return clang_getTranslationUnitSpelling(
3002 static_cast<CXTranslationUnit>(C.data[2]));
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003003
Steve Narofff334b4e2009-09-02 18:26:48 +00003004 if (clang_isReference(C.kind)) {
3005 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00003006 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00003007 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003008 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003009 }
3010 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00003011 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003012 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003013 }
3014 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00003015 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00003016 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003017 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003018 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00003019 case CXCursor_CXXBaseSpecifier: {
3020 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
3021 return createCXString(B->getType().getAsString());
3022 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003023 case CXCursor_TypeRef: {
3024 TypeDecl *Type = getCursorTypeRef(C).first;
3025 assert(Type && "Missing type decl");
3026
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003027 return createCXString(getCursorContext(C).getTypeDeclType(Type).
3028 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003029 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003030 case CXCursor_TemplateRef: {
3031 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00003032 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003033
3034 return createCXString(Template->getNameAsString());
3035 }
Douglas Gregor69319002010-08-31 23:48:11 +00003036
3037 case CXCursor_NamespaceRef: {
3038 NamedDecl *NS = getCursorNamespaceRef(C).first;
3039 assert(NS && "Missing namespace decl");
3040
3041 return createCXString(NS->getNameAsString());
3042 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003043
Douglas Gregora67e03f2010-09-09 21:42:20 +00003044 case CXCursor_MemberRef: {
3045 FieldDecl *Field = getCursorMemberRef(C).first;
3046 assert(Field && "Missing member decl");
3047
3048 return createCXString(Field->getNameAsString());
3049 }
3050
Douglas Gregor36897b02010-09-10 00:22:18 +00003051 case CXCursor_LabelRef: {
3052 LabelStmt *Label = getCursorLabelRef(C).first;
3053 assert(Label && "Missing label");
3054
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003055 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00003056 }
3057
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003058 case CXCursor_OverloadedDeclRef: {
3059 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3060 if (Decl *D = Storage.dyn_cast<Decl *>()) {
3061 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
3062 return createCXString(ND->getNameAsString());
3063 return createCXString("");
3064 }
3065 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3066 return createCXString(E->getName().getAsString());
3067 OverloadedTemplateStorage *Ovl
3068 = Storage.get<OverloadedTemplateStorage*>();
3069 if (Ovl->size() == 0)
3070 return createCXString("");
3071 return createCXString((*Ovl->begin())->getNameAsString());
3072 }
3073
Douglas Gregor011d8b92012-02-15 00:54:55 +00003074 case CXCursor_VariableRef: {
3075 VarDecl *Var = getCursorVariableRef(C).first;
3076 assert(Var && "Missing variable decl");
3077
3078 return createCXString(Var->getNameAsString());
3079 }
3080
Daniel Dunbaracca7252009-11-30 20:42:49 +00003081 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003082 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00003083 }
3084 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003085
3086 if (clang_isExpression(C.kind)) {
3087 Decl *D = getDeclFromExpr(getCursorExpr(C));
3088 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00003089 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003090 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00003091 }
3092
Douglas Gregor36897b02010-09-10 00:22:18 +00003093 if (clang_isStatement(C.kind)) {
3094 Stmt *S = getCursorStmt(C);
3095 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003096 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00003097
3098 return createCXString("");
3099 }
3100
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003101 if (C.kind == CXCursor_MacroExpansion)
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003102 return createCXString(getCursorMacroExpansion(C)->getName()
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003103 ->getNameStart());
3104
Douglas Gregor572feb22010-03-18 18:04:21 +00003105 if (C.kind == CXCursor_MacroDefinition)
3106 return createCXString(getCursorMacroDefinition(C)->getName()
3107 ->getNameStart());
3108
Douglas Gregorecdcb882010-10-20 22:00:55 +00003109 if (C.kind == CXCursor_InclusionDirective)
3110 return createCXString(getCursorInclusionDirective(C)->getFileName());
3111
Douglas Gregor60cbfac2010-01-25 16:56:17 +00003112 if (clang_isDeclaration(C.kind))
3113 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00003114
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00003115 if (C.kind == CXCursor_AnnotateAttr) {
3116 AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
3117 return createCXString(AA->getAnnotation());
3118 }
3119
Argyrios Kyrtzidis84b79642011-12-06 22:05:01 +00003120 if (C.kind == CXCursor_AsmLabelAttr) {
3121 AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
3122 return createCXString(AA->getLabel());
3123 }
3124
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003125 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00003126}
3127
Douglas Gregor358559d2010-10-02 22:49:11 +00003128CXString clang_getCursorDisplayName(CXCursor C) {
3129 if (!clang_isDeclaration(C.kind))
3130 return clang_getCursorSpelling(C);
3131
3132 Decl *D = getCursorDecl(C);
3133 if (!D)
3134 return createCXString("");
3135
Douglas Gregor30c42402011-09-27 22:38:19 +00003136 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
Douglas Gregor358559d2010-10-02 22:49:11 +00003137 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
3138 D = FunTmpl->getTemplatedDecl();
3139
3140 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Dylan Noblesmith36d59272012-02-13 12:32:26 +00003141 SmallString<64> Str;
Douglas Gregor358559d2010-10-02 22:49:11 +00003142 llvm::raw_svector_ostream OS(Str);
Benjamin Kramera59d20b2012-02-07 11:57:57 +00003143 OS << *Function;
Douglas Gregor358559d2010-10-02 22:49:11 +00003144 if (Function->getPrimaryTemplate())
3145 OS << "<>";
3146 OS << "(";
3147 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
3148 if (I)
3149 OS << ", ";
3150 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
3151 }
3152
3153 if (Function->isVariadic()) {
3154 if (Function->getNumParams())
3155 OS << ", ";
3156 OS << "...";
3157 }
3158 OS << ")";
3159 return createCXString(OS.str());
3160 }
3161
3162 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
Dylan Noblesmith36d59272012-02-13 12:32:26 +00003163 SmallString<64> Str;
Douglas Gregor358559d2010-10-02 22:49:11 +00003164 llvm::raw_svector_ostream OS(Str);
Benjamin Kramera59d20b2012-02-07 11:57:57 +00003165 OS << *ClassTemplate;
Douglas Gregor358559d2010-10-02 22:49:11 +00003166 OS << "<";
3167 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
3168 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3169 if (I)
3170 OS << ", ";
3171
3172 NamedDecl *Param = Params->getParam(I);
3173 if (Param->getIdentifier()) {
3174 OS << Param->getIdentifier()->getName();
3175 continue;
3176 }
3177
3178 // There is no parameter name, which makes this tricky. Try to come up
3179 // with something useful that isn't too long.
3180 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3181 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
3182 else if (NonTypeTemplateParmDecl *NTTP
3183 = dyn_cast<NonTypeTemplateParmDecl>(Param))
3184 OS << NTTP->getType().getAsString(Policy);
3185 else
3186 OS << "template<...> class";
3187 }
3188
3189 OS << ">";
3190 return createCXString(OS.str());
3191 }
3192
3193 if (ClassTemplateSpecializationDecl *ClassSpec
3194 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
3195 // If the type was explicitly written, use that.
3196 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
3197 return createCXString(TSInfo->getType().getAsString(Policy));
3198
Dylan Noblesmith36d59272012-02-13 12:32:26 +00003199 SmallString<64> Str;
Douglas Gregor358559d2010-10-02 22:49:11 +00003200 llvm::raw_svector_ostream OS(Str);
Benjamin Kramera59d20b2012-02-07 11:57:57 +00003201 OS << *ClassSpec;
Douglas Gregor358559d2010-10-02 22:49:11 +00003202 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00003203 ClassSpec->getTemplateArgs().data(),
3204 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00003205 Policy);
3206 return createCXString(OS.str());
3207 }
3208
3209 return clang_getCursorSpelling(C);
3210}
3211
Ted Kremeneke68fff62010-02-17 00:41:32 +00003212CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00003213 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00003214 case CXCursor_FunctionDecl:
3215 return createCXString("FunctionDecl");
3216 case CXCursor_TypedefDecl:
3217 return createCXString("TypedefDecl");
3218 case CXCursor_EnumDecl:
3219 return createCXString("EnumDecl");
3220 case CXCursor_EnumConstantDecl:
3221 return createCXString("EnumConstantDecl");
3222 case CXCursor_StructDecl:
3223 return createCXString("StructDecl");
3224 case CXCursor_UnionDecl:
3225 return createCXString("UnionDecl");
3226 case CXCursor_ClassDecl:
3227 return createCXString("ClassDecl");
3228 case CXCursor_FieldDecl:
3229 return createCXString("FieldDecl");
3230 case CXCursor_VarDecl:
3231 return createCXString("VarDecl");
3232 case CXCursor_ParmDecl:
3233 return createCXString("ParmDecl");
3234 case CXCursor_ObjCInterfaceDecl:
3235 return createCXString("ObjCInterfaceDecl");
3236 case CXCursor_ObjCCategoryDecl:
3237 return createCXString("ObjCCategoryDecl");
3238 case CXCursor_ObjCProtocolDecl:
3239 return createCXString("ObjCProtocolDecl");
3240 case CXCursor_ObjCPropertyDecl:
3241 return createCXString("ObjCPropertyDecl");
3242 case CXCursor_ObjCIvarDecl:
3243 return createCXString("ObjCIvarDecl");
3244 case CXCursor_ObjCInstanceMethodDecl:
3245 return createCXString("ObjCInstanceMethodDecl");
3246 case CXCursor_ObjCClassMethodDecl:
3247 return createCXString("ObjCClassMethodDecl");
3248 case CXCursor_ObjCImplementationDecl:
3249 return createCXString("ObjCImplementationDecl");
3250 case CXCursor_ObjCCategoryImplDecl:
3251 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00003252 case CXCursor_CXXMethod:
3253 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003254 case CXCursor_UnexposedDecl:
3255 return createCXString("UnexposedDecl");
3256 case CXCursor_ObjCSuperClassRef:
3257 return createCXString("ObjCSuperClassRef");
3258 case CXCursor_ObjCProtocolRef:
3259 return createCXString("ObjCProtocolRef");
3260 case CXCursor_ObjCClassRef:
3261 return createCXString("ObjCClassRef");
3262 case CXCursor_TypeRef:
3263 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003264 case CXCursor_TemplateRef:
3265 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00003266 case CXCursor_NamespaceRef:
3267 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00003268 case CXCursor_MemberRef:
3269 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00003270 case CXCursor_LabelRef:
3271 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003272 case CXCursor_OverloadedDeclRef:
3273 return createCXString("OverloadedDeclRef");
Douglas Gregor011d8b92012-02-15 00:54:55 +00003274 case CXCursor_VariableRef:
3275 return createCXString("VariableRef");
Douglas Gregor42b29842011-10-05 19:00:14 +00003276 case CXCursor_IntegerLiteral:
3277 return createCXString("IntegerLiteral");
3278 case CXCursor_FloatingLiteral:
3279 return createCXString("FloatingLiteral");
3280 case CXCursor_ImaginaryLiteral:
3281 return createCXString("ImaginaryLiteral");
3282 case CXCursor_StringLiteral:
3283 return createCXString("StringLiteral");
3284 case CXCursor_CharacterLiteral:
3285 return createCXString("CharacterLiteral");
3286 case CXCursor_ParenExpr:
3287 return createCXString("ParenExpr");
3288 case CXCursor_UnaryOperator:
3289 return createCXString("UnaryOperator");
3290 case CXCursor_ArraySubscriptExpr:
3291 return createCXString("ArraySubscriptExpr");
3292 case CXCursor_BinaryOperator:
3293 return createCXString("BinaryOperator");
3294 case CXCursor_CompoundAssignOperator:
3295 return createCXString("CompoundAssignOperator");
3296 case CXCursor_ConditionalOperator:
3297 return createCXString("ConditionalOperator");
3298 case CXCursor_CStyleCastExpr:
3299 return createCXString("CStyleCastExpr");
3300 case CXCursor_CompoundLiteralExpr:
3301 return createCXString("CompoundLiteralExpr");
3302 case CXCursor_InitListExpr:
3303 return createCXString("InitListExpr");
3304 case CXCursor_AddrLabelExpr:
3305 return createCXString("AddrLabelExpr");
3306 case CXCursor_StmtExpr:
3307 return createCXString("StmtExpr");
3308 case CXCursor_GenericSelectionExpr:
3309 return createCXString("GenericSelectionExpr");
3310 case CXCursor_GNUNullExpr:
3311 return createCXString("GNUNullExpr");
3312 case CXCursor_CXXStaticCastExpr:
3313 return createCXString("CXXStaticCastExpr");
3314 case CXCursor_CXXDynamicCastExpr:
3315 return createCXString("CXXDynamicCastExpr");
3316 case CXCursor_CXXReinterpretCastExpr:
3317 return createCXString("CXXReinterpretCastExpr");
3318 case CXCursor_CXXConstCastExpr:
3319 return createCXString("CXXConstCastExpr");
3320 case CXCursor_CXXFunctionalCastExpr:
3321 return createCXString("CXXFunctionalCastExpr");
3322 case CXCursor_CXXTypeidExpr:
3323 return createCXString("CXXTypeidExpr");
3324 case CXCursor_CXXBoolLiteralExpr:
3325 return createCXString("CXXBoolLiteralExpr");
3326 case CXCursor_CXXNullPtrLiteralExpr:
3327 return createCXString("CXXNullPtrLiteralExpr");
3328 case CXCursor_CXXThisExpr:
3329 return createCXString("CXXThisExpr");
3330 case CXCursor_CXXThrowExpr:
3331 return createCXString("CXXThrowExpr");
3332 case CXCursor_CXXNewExpr:
3333 return createCXString("CXXNewExpr");
3334 case CXCursor_CXXDeleteExpr:
3335 return createCXString("CXXDeleteExpr");
3336 case CXCursor_UnaryExpr:
3337 return createCXString("UnaryExpr");
3338 case CXCursor_ObjCStringLiteral:
3339 return createCXString("ObjCStringLiteral");
Ted Kremenekb3f75422012-03-06 20:06:06 +00003340 case CXCursor_ObjCBoolLiteralExpr:
3341 return createCXString("ObjCBoolLiteralExpr");
Douglas Gregor42b29842011-10-05 19:00:14 +00003342 case CXCursor_ObjCEncodeExpr:
3343 return createCXString("ObjCEncodeExpr");
3344 case CXCursor_ObjCSelectorExpr:
3345 return createCXString("ObjCSelectorExpr");
3346 case CXCursor_ObjCProtocolExpr:
3347 return createCXString("ObjCProtocolExpr");
3348 case CXCursor_ObjCBridgedCastExpr:
3349 return createCXString("ObjCBridgedCastExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00003350 case CXCursor_BlockExpr:
3351 return createCXString("BlockExpr");
Douglas Gregor42b29842011-10-05 19:00:14 +00003352 case CXCursor_PackExpansionExpr:
3353 return createCXString("PackExpansionExpr");
3354 case CXCursor_SizeOfPackExpr:
3355 return createCXString("SizeOfPackExpr");
Douglas Gregor011d8b92012-02-15 00:54:55 +00003356 case CXCursor_LambdaExpr:
3357 return createCXString("LambdaExpr");
Douglas Gregor42b29842011-10-05 19:00:14 +00003358 case CXCursor_UnexposedExpr:
3359 return createCXString("UnexposedExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003360 case CXCursor_DeclRefExpr:
3361 return createCXString("DeclRefExpr");
3362 case CXCursor_MemberRefExpr:
3363 return createCXString("MemberRefExpr");
3364 case CXCursor_CallExpr:
3365 return createCXString("CallExpr");
3366 case CXCursor_ObjCMessageExpr:
3367 return createCXString("ObjCMessageExpr");
3368 case CXCursor_UnexposedStmt:
3369 return createCXString("UnexposedStmt");
Douglas Gregor42b29842011-10-05 19:00:14 +00003370 case CXCursor_DeclStmt:
3371 return createCXString("DeclStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00003372 case CXCursor_LabelStmt:
3373 return createCXString("LabelStmt");
Douglas Gregor42b29842011-10-05 19:00:14 +00003374 case CXCursor_CompoundStmt:
3375 return createCXString("CompoundStmt");
3376 case CXCursor_CaseStmt:
3377 return createCXString("CaseStmt");
3378 case CXCursor_DefaultStmt:
3379 return createCXString("DefaultStmt");
3380 case CXCursor_IfStmt:
3381 return createCXString("IfStmt");
3382 case CXCursor_SwitchStmt:
3383 return createCXString("SwitchStmt");
3384 case CXCursor_WhileStmt:
3385 return createCXString("WhileStmt");
3386 case CXCursor_DoStmt:
3387 return createCXString("DoStmt");
3388 case CXCursor_ForStmt:
3389 return createCXString("ForStmt");
3390 case CXCursor_GotoStmt:
3391 return createCXString("GotoStmt");
3392 case CXCursor_IndirectGotoStmt:
3393 return createCXString("IndirectGotoStmt");
3394 case CXCursor_ContinueStmt:
3395 return createCXString("ContinueStmt");
3396 case CXCursor_BreakStmt:
3397 return createCXString("BreakStmt");
3398 case CXCursor_ReturnStmt:
3399 return createCXString("ReturnStmt");
3400 case CXCursor_AsmStmt:
3401 return createCXString("AsmStmt");
3402 case CXCursor_ObjCAtTryStmt:
3403 return createCXString("ObjCAtTryStmt");
3404 case CXCursor_ObjCAtCatchStmt:
3405 return createCXString("ObjCAtCatchStmt");
3406 case CXCursor_ObjCAtFinallyStmt:
3407 return createCXString("ObjCAtFinallyStmt");
3408 case CXCursor_ObjCAtThrowStmt:
3409 return createCXString("ObjCAtThrowStmt");
3410 case CXCursor_ObjCAtSynchronizedStmt:
3411 return createCXString("ObjCAtSynchronizedStmt");
3412 case CXCursor_ObjCAutoreleasePoolStmt:
3413 return createCXString("ObjCAutoreleasePoolStmt");
3414 case CXCursor_ObjCForCollectionStmt:
3415 return createCXString("ObjCForCollectionStmt");
3416 case CXCursor_CXXCatchStmt:
3417 return createCXString("CXXCatchStmt");
3418 case CXCursor_CXXTryStmt:
3419 return createCXString("CXXTryStmt");
3420 case CXCursor_CXXForRangeStmt:
3421 return createCXString("CXXForRangeStmt");
3422 case CXCursor_SEHTryStmt:
3423 return createCXString("SEHTryStmt");
3424 case CXCursor_SEHExceptStmt:
3425 return createCXString("SEHExceptStmt");
3426 case CXCursor_SEHFinallyStmt:
3427 return createCXString("SEHFinallyStmt");
3428 case CXCursor_NullStmt:
3429 return createCXString("NullStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003430 case CXCursor_InvalidFile:
3431 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00003432 case CXCursor_InvalidCode:
3433 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003434 case CXCursor_NoDeclFound:
3435 return createCXString("NoDeclFound");
3436 case CXCursor_NotImplemented:
3437 return createCXString("NotImplemented");
3438 case CXCursor_TranslationUnit:
3439 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00003440 case CXCursor_UnexposedAttr:
3441 return createCXString("UnexposedAttr");
3442 case CXCursor_IBActionAttr:
3443 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003444 case CXCursor_IBOutletAttr:
3445 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003446 case CXCursor_IBOutletCollectionAttr:
3447 return createCXString("attribute(iboutletcollection)");
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00003448 case CXCursor_CXXFinalAttr:
3449 return createCXString("attribute(final)");
3450 case CXCursor_CXXOverrideAttr:
3451 return createCXString("attribute(override)");
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00003452 case CXCursor_AnnotateAttr:
3453 return createCXString("attribute(annotate)");
Argyrios Kyrtzidis84b79642011-12-06 22:05:01 +00003454 case CXCursor_AsmLabelAttr:
3455 return createCXString("asm label");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003456 case CXCursor_PreprocessingDirective:
3457 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003458 case CXCursor_MacroDefinition:
3459 return createCXString("macro definition");
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003460 case CXCursor_MacroExpansion:
3461 return createCXString("macro expansion");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003462 case CXCursor_InclusionDirective:
3463 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003464 case CXCursor_Namespace:
3465 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003466 case CXCursor_LinkageSpec:
3467 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003468 case CXCursor_CXXBaseSpecifier:
3469 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003470 case CXCursor_Constructor:
3471 return createCXString("CXXConstructor");
3472 case CXCursor_Destructor:
3473 return createCXString("CXXDestructor");
3474 case CXCursor_ConversionFunction:
3475 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003476 case CXCursor_TemplateTypeParameter:
3477 return createCXString("TemplateTypeParameter");
3478 case CXCursor_NonTypeTemplateParameter:
3479 return createCXString("NonTypeTemplateParameter");
3480 case CXCursor_TemplateTemplateParameter:
3481 return createCXString("TemplateTemplateParameter");
3482 case CXCursor_FunctionTemplate:
3483 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003484 case CXCursor_ClassTemplate:
3485 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003486 case CXCursor_ClassTemplatePartialSpecialization:
3487 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003488 case CXCursor_NamespaceAlias:
3489 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003490 case CXCursor_UsingDirective:
3491 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003492 case CXCursor_UsingDeclaration:
3493 return createCXString("UsingDeclaration");
Richard Smith162e1c12011-04-15 14:24:37 +00003494 case CXCursor_TypeAliasDecl:
Douglas Gregor352697a2011-06-03 23:08:58 +00003495 return createCXString("TypeAliasDecl");
3496 case CXCursor_ObjCSynthesizeDecl:
3497 return createCXString("ObjCSynthesizeDecl");
3498 case CXCursor_ObjCDynamicDecl:
3499 return createCXString("ObjCDynamicDecl");
Argyrios Kyrtzidis2dfdb942011-09-30 17:58:23 +00003500 case CXCursor_CXXAccessSpecifier:
3501 return createCXString("CXXAccessSpecifier");
Steve Naroff89922f82009-08-31 00:59:03 +00003502 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003503
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003504 llvm_unreachable("Unhandled CXCursorKind");
Steve Naroff600866c2009-08-27 19:51:58 +00003505}
Steve Naroff89922f82009-08-31 00:59:03 +00003506
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003507struct GetCursorData {
3508 SourceLocation TokenBeginLoc;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003509 bool PointsAtMacroArgExpansion;
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003510 CXCursor &BestCursor;
3511
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003512 GetCursorData(SourceManager &SM,
3513 SourceLocation tokenBegin, CXCursor &outputCursor)
3514 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
3515 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
3516 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003517};
3518
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003519static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3520 CXCursor parent,
3521 CXClientData client_data) {
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003522 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
3523 CXCursor *BestCursor = &Data->BestCursor;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003524
3525 // If we point inside a macro argument we should provide info of what the
3526 // token is so use the actual cursor, don't replace it with a macro expansion
3527 // cursor.
3528 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
3529 return CXChildVisit_Recurse;
Argyrios Kyrtzidis65ab9072011-09-26 19:05:37 +00003530
3531 if (clang_isDeclaration(cursor.kind)) {
3532 // Avoid having the implicit methods override the property decls.
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00003533 if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor)))
Argyrios Kyrtzidis65ab9072011-09-26 19:05:37 +00003534 if (MD->isImplicit())
3535 return CXChildVisit_Break;
3536 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003537
3538 if (clang_isExpression(cursor.kind) &&
3539 clang_isDeclaration(BestCursor->kind)) {
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00003540 if (Decl *D = getCursorDecl(*BestCursor)) {
3541 // Avoid having the cursor of an expression replace the declaration cursor
3542 // when the expression source range overlaps the declaration range.
3543 // This can happen for C++ constructor expressions whose range generally
3544 // include the variable declaration, e.g.:
3545 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
3546 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
3547 D->getLocation() == Data->TokenBeginLoc)
3548 return CXChildVisit_Break;
3549 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003550 }
3551
Douglas Gregor93798e22010-11-05 21:11:19 +00003552 // If our current best cursor is the construction of a temporary object,
3553 // don't replace that cursor with a type reference, because we want
3554 // clang_getCursor() to point at the constructor.
3555 if (clang_isExpression(BestCursor->kind) &&
3556 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003557 cursor.kind == CXCursor_TypeRef) {
3558 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
3559 // as having the actual point on the type reference.
3560 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
Douglas Gregor93798e22010-11-05 21:11:19 +00003561 return CXChildVisit_Recurse;
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003562 }
Douglas Gregor93798e22010-11-05 21:11:19 +00003563
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003564 *BestCursor = cursor;
3565 return CXChildVisit_Recurse;
3566}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003567
Douglas Gregorb9790342010-01-22 21:44:22 +00003568CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3569 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003570 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003571
Ted Kremeneka60ed472010-11-16 08:15:36 +00003572 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003573 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3574
Ted Kremeneka297de22010-01-25 22:34:44 +00003575 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003576 CXCursor Result = cxcursor::getCursor(TU, SLoc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003577
Douglas Gregor40749ee2010-11-03 00:35:38 +00003578 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregor40749ee2010-11-03 00:35:38 +00003579 if (Logging) {
3580 CXFile SearchFile;
3581 unsigned SearchLine, SearchColumn;
3582 CXFile ResultFile;
3583 unsigned ResultLine, ResultColumn;
Douglas Gregor66537982010-11-17 17:14:07 +00003584 CXString SearchFileName, ResultFileName, KindSpelling, USR;
3585 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
Douglas Gregor40749ee2010-11-03 00:35:38 +00003586 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3587
Chandler Carruth20174222011-08-31 16:53:37 +00003588 clang_getExpansionLocation(Loc, &SearchFile, &SearchLine, &SearchColumn, 0);
3589 clang_getExpansionLocation(ResultLoc, &ResultFile, &ResultLine,
3590 &ResultColumn, 0);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003591 SearchFileName = clang_getFileName(SearchFile);
3592 ResultFileName = clang_getFileName(ResultFile);
3593 KindSpelling = clang_getCursorKindSpelling(Result.kind);
Douglas Gregor66537982010-11-17 17:14:07 +00003594 USR = clang_getCursorUSR(Result);
3595 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n",
Douglas Gregor40749ee2010-11-03 00:35:38 +00003596 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3597 clang_getCString(KindSpelling),
Douglas Gregor66537982010-11-17 17:14:07 +00003598 clang_getCString(ResultFileName), ResultLine, ResultColumn,
3599 clang_getCString(USR), IsDef);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003600 clang_disposeString(SearchFileName);
3601 clang_disposeString(ResultFileName);
3602 clang_disposeString(KindSpelling);
Douglas Gregor66537982010-11-17 17:14:07 +00003603 clang_disposeString(USR);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003604
3605 CXCursor Definition = clang_getCursorDefinition(Result);
3606 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
3607 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
3608 CXString DefinitionKindSpelling
3609 = clang_getCursorKindSpelling(Definition.kind);
3610 CXFile DefinitionFile;
3611 unsigned DefinitionLine, DefinitionColumn;
Chandler Carruth20174222011-08-31 16:53:37 +00003612 clang_getExpansionLocation(DefinitionLoc, &DefinitionFile,
3613 &DefinitionLine, &DefinitionColumn, 0);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003614 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
3615 fprintf(stderr, " -> %s(%s:%d:%d)\n",
3616 clang_getCString(DefinitionKindSpelling),
3617 clang_getCString(DefinitionFileName),
3618 DefinitionLine, DefinitionColumn);
3619 clang_disposeString(DefinitionFileName);
3620 clang_disposeString(DefinitionKindSpelling);
3621 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003622 }
3623
Ted Kremeneke68fff62010-02-17 00:41:32 +00003624 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003625}
3626
Ted Kremenek73885552009-11-17 19:28:59 +00003627CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003628 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003629}
3630
3631unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003632 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003633}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003634
Douglas Gregor9ce55842010-11-20 00:09:34 +00003635unsigned clang_hashCursor(CXCursor C) {
3636 unsigned Index = 0;
3637 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
3638 Index = 1;
3639
3640 return llvm::DenseMapInfo<std::pair<unsigned, void*> >::getHashValue(
3641 std::make_pair(C.kind, C.data[Index]));
3642}
3643
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003644unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003645 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3646}
3647
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003648unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003649 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3650}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003651
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003652unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003653 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3654}
3655
Douglas Gregor97b98722010-01-19 23:20:36 +00003656unsigned clang_isExpression(enum CXCursorKind K) {
3657 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3658}
3659
3660unsigned clang_isStatement(enum CXCursorKind K) {
3661 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3662}
3663
Douglas Gregor8be80e12011-07-06 03:00:34 +00003664unsigned clang_isAttribute(enum CXCursorKind K) {
3665 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
3666}
3667
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003668unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3669 return K == CXCursor_TranslationUnit;
3670}
3671
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003672unsigned clang_isPreprocessing(enum CXCursorKind K) {
3673 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3674}
3675
Ted Kremenekad6eff62010-03-08 21:17:29 +00003676unsigned clang_isUnexposed(enum CXCursorKind K) {
3677 switch (K) {
3678 case CXCursor_UnexposedDecl:
3679 case CXCursor_UnexposedExpr:
3680 case CXCursor_UnexposedStmt:
3681 case CXCursor_UnexposedAttr:
3682 return true;
3683 default:
3684 return false;
3685 }
3686}
3687
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003688CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003689 return C.kind;
3690}
3691
Douglas Gregor98258af2010-01-18 22:46:11 +00003692CXSourceLocation clang_getCursorLocation(CXCursor C) {
3693 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003694 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003695 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003696 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3697 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003698 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003699 }
3700
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003701 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003702 std::pair<ObjCProtocolDecl *, SourceLocation> P
3703 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003704 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003705 }
3706
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003707 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003708 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3709 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003710 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003711 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003712
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003713 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003714 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003715 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003716 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003717
3718 case CXCursor_TemplateRef: {
3719 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3720 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3721 }
3722
Douglas Gregor69319002010-08-31 23:48:11 +00003723 case CXCursor_NamespaceRef: {
3724 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3725 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3726 }
3727
Douglas Gregora67e03f2010-09-09 21:42:20 +00003728 case CXCursor_MemberRef: {
3729 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3730 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3731 }
3732
Douglas Gregor011d8b92012-02-15 00:54:55 +00003733 case CXCursor_VariableRef: {
3734 std::pair<VarDecl *, SourceLocation> P = getCursorVariableRef(C);
3735 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3736 }
3737
Ted Kremenek3064ef92010-08-27 21:34:58 +00003738 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003739 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3740 if (!BaseSpec)
3741 return clang_getNullLocation();
3742
3743 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3744 return cxloc::translateSourceLocation(getCursorContext(C),
3745 TSInfo->getTypeLoc().getBeginLoc());
3746
3747 return cxloc::translateSourceLocation(getCursorContext(C),
Daniel Dunbar96a00142012-03-09 18:35:03 +00003748 BaseSpec->getLocStart());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003749 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003750
Douglas Gregor36897b02010-09-10 00:22:18 +00003751 case CXCursor_LabelRef: {
3752 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3753 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3754 }
3755
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003756 case CXCursor_OverloadedDeclRef:
3757 return cxloc::translateSourceLocation(getCursorContext(C),
3758 getCursorOverloadedDeclRef(C).second);
3759
Douglas Gregorf46034a2010-01-18 23:41:10 +00003760 default:
3761 // FIXME: Need a way to enumerate all non-reference cases.
3762 llvm_unreachable("Missed a reference kind");
3763 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003764 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003765
3766 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003767 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003768 getLocationFromExpr(getCursorExpr(C)));
3769
Douglas Gregor36897b02010-09-10 00:22:18 +00003770 if (clang_isStatement(C.kind))
3771 return cxloc::translateSourceLocation(getCursorContext(C),
3772 getCursorStmt(C)->getLocStart());
3773
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003774 if (C.kind == CXCursor_PreprocessingDirective) {
3775 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3776 return cxloc::translateSourceLocation(getCursorContext(C), L);
3777 }
Douglas Gregor48072312010-03-18 15:23:44 +00003778
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003779 if (C.kind == CXCursor_MacroExpansion) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003780 SourceLocation L
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003781 = cxcursor::getCursorMacroExpansion(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003782 return cxloc::translateSourceLocation(getCursorContext(C), L);
3783 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003784
3785 if (C.kind == CXCursor_MacroDefinition) {
3786 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3787 return cxloc::translateSourceLocation(getCursorContext(C), L);
3788 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003789
3790 if (C.kind == CXCursor_InclusionDirective) {
3791 SourceLocation L
3792 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3793 return cxloc::translateSourceLocation(getCursorContext(C), L);
3794 }
3795
Ted Kremenek9a700d22010-05-12 06:16:13 +00003796 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003797 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003798
Douglas Gregorf46034a2010-01-18 23:41:10 +00003799 Decl *D = getCursorDecl(C);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00003800 if (!D)
3801 return clang_getNullLocation();
3802
Douglas Gregorf46034a2010-01-18 23:41:10 +00003803 SourceLocation Loc = D->getLocation();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003804 // FIXME: Multiple variables declared in a single declaration
3805 // currently lack the information needed to correctly determine their
3806 // ranges when accounting for the type-specifier. We use context
3807 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3808 // and if so, whether it is the first decl.
3809 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3810 if (!cxcursor::isFirstInDeclGroup(C))
3811 Loc = VD->getLocation();
3812 }
3813
Argyrios Kyrtzidisccc6f362012-03-23 03:33:19 +00003814 // For ObjC methods, give the start location of the method name.
3815 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
3816 Loc = MD->getSelectorStartLoc();
3817
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003818 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003819}
Douglas Gregora7bde202010-01-19 00:34:46 +00003820
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003821} // end extern "C"
3822
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003823CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
3824 assert(TU);
3825
3826 // Guard against an invalid SourceLocation, or we may assert in one
3827 // of the following calls.
3828 if (SLoc.isInvalid())
3829 return clang_getNullCursor();
3830
3831 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
3832
3833 // Translate the given source location to make it point at the beginning of
3834 // the token under the cursor.
3835 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +00003836 CXXUnit->getASTContext().getLangOpts());
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003837
3838 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3839 if (SLoc.isValid()) {
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003840 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003841 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
3842 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00003843 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003844 SourceLocation(SLoc));
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00003845 CursorVis.visitFileRegion();
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003846 }
3847
3848 return Result;
3849}
3850
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003851static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003852 if (clang_isReference(C.kind)) {
3853 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003854 case CXCursor_ObjCSuperClassRef:
3855 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003856
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003857 case CXCursor_ObjCProtocolRef:
3858 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003859
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003860 case CXCursor_ObjCClassRef:
3861 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003862
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003863 case CXCursor_TypeRef:
3864 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003865
3866 case CXCursor_TemplateRef:
3867 return getCursorTemplateRef(C).second;
3868
Douglas Gregor69319002010-08-31 23:48:11 +00003869 case CXCursor_NamespaceRef:
3870 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003871
3872 case CXCursor_MemberRef:
3873 return getCursorMemberRef(C).second;
3874
Ted Kremenek3064ef92010-08-27 21:34:58 +00003875 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003876 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003877
Douglas Gregor36897b02010-09-10 00:22:18 +00003878 case CXCursor_LabelRef:
3879 return getCursorLabelRef(C).second;
3880
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003881 case CXCursor_OverloadedDeclRef:
3882 return getCursorOverloadedDeclRef(C).second;
3883
Douglas Gregor011d8b92012-02-15 00:54:55 +00003884 case CXCursor_VariableRef:
3885 return getCursorVariableRef(C).second;
3886
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003887 default:
3888 // FIXME: Need a way to enumerate all non-reference cases.
3889 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003890 }
3891 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003892
3893 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003894 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003895
3896 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003897 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003898
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00003899 if (clang_isAttribute(C.kind))
3900 return getCursorAttr(C)->getRange();
3901
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003902 if (C.kind == CXCursor_PreprocessingDirective)
3903 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003904
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00003905 if (C.kind == CXCursor_MacroExpansion) {
3906 ASTUnit *TU = getCursorASTUnit(C);
3907 SourceRange Range = cxcursor::getCursorMacroExpansion(C)->getSourceRange();
3908 return TU->mapRangeFromPreamble(Range);
3909 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003910
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00003911 if (C.kind == CXCursor_MacroDefinition) {
3912 ASTUnit *TU = getCursorASTUnit(C);
3913 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
3914 return TU->mapRangeFromPreamble(Range);
3915 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003916
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00003917 if (C.kind == CXCursor_InclusionDirective) {
3918 ASTUnit *TU = getCursorASTUnit(C);
3919 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3920 return TU->mapRangeFromPreamble(Range);
3921 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003922
Argyrios Kyrtzidis0822c5f2012-03-19 23:17:58 +00003923 if (C.kind == CXCursor_TranslationUnit) {
3924 ASTUnit *TU = getCursorASTUnit(C);
3925 FileID MainID = TU->getSourceManager().getMainFileID();
3926 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
3927 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
3928 return SourceRange(Start, End);
3929 }
3930
Ted Kremenek007a7c92010-11-01 23:26:51 +00003931 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3932 Decl *D = cxcursor::getCursorDecl(C);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00003933 if (!D)
3934 return SourceRange();
3935
Ted Kremenek007a7c92010-11-01 23:26:51 +00003936 SourceRange R = D->getSourceRange();
3937 // FIXME: Multiple variables declared in a single declaration
3938 // currently lack the information needed to correctly determine their
3939 // ranges when accounting for the type-specifier. We use context
3940 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3941 // and if so, whether it is the first decl.
3942 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3943 if (!cxcursor::isFirstInDeclGroup(C))
3944 R.setBegin(VD->getLocation());
3945 }
3946 return R;
3947 }
Douglas Gregor66537982010-11-17 17:14:07 +00003948 return SourceRange();
3949}
3950
3951/// \brief Retrieves the "raw" cursor extent, which is then extended to include
3952/// the decl-specifier-seq for declarations.
3953static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
3954 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3955 Decl *D = cxcursor::getCursorDecl(C);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00003956 if (!D)
3957 return SourceRange();
3958
Douglas Gregor66537982010-11-17 17:14:07 +00003959 SourceRange R = D->getSourceRange();
Douglas Gregor66537982010-11-17 17:14:07 +00003960
Douglas Gregor2494dd02011-03-01 01:34:45 +00003961 // Adjust the start of the location for declarations preceded by
3962 // declaration specifiers.
3963 SourceLocation StartLoc;
3964 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
3965 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
Daniel Dunbar96a00142012-03-09 18:35:03 +00003966 StartLoc = TI->getTypeLoc().getLocStart();
Douglas Gregor2494dd02011-03-01 01:34:45 +00003967 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
3968 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
Daniel Dunbar96a00142012-03-09 18:35:03 +00003969 StartLoc = TI->getTypeLoc().getLocStart();
Douglas Gregor2494dd02011-03-01 01:34:45 +00003970 }
3971
3972 if (StartLoc.isValid() && R.getBegin().isValid() &&
3973 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
3974 R.setBegin(StartLoc);
3975
3976 // FIXME: Multiple variables declared in a single declaration
3977 // currently lack the information needed to correctly determine their
3978 // ranges when accounting for the type-specifier. We use context
3979 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3980 // and if so, whether it is the first decl.
3981 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3982 if (!cxcursor::isFirstInDeclGroup(C))
3983 R.setBegin(VD->getLocation());
Douglas Gregor66537982010-11-17 17:14:07 +00003984 }
3985
3986 return R;
3987 }
3988
3989 return getRawCursorExtent(C);
3990}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003991
3992extern "C" {
3993
3994CXSourceRange clang_getCursorExtent(CXCursor C) {
3995 SourceRange R = getRawCursorExtent(C);
3996 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003997 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003998
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003999 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00004000}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004001
4002CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00004003 if (clang_isInvalid(C.kind))
4004 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004005
Ted Kremeneka60ed472010-11-16 08:15:36 +00004006 CXTranslationUnit tu = getCursorTU(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004007 if (clang_isDeclaration(C.kind)) {
4008 Decl *D = getCursorDecl(C);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00004009 if (!D)
4010 return clang_getNullCursor();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004011 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004012 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Chris Lattner5f9e2722011-07-23 10:55:15 +00004013 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00004014 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
4015 return MakeCXCursor(Property, tu);
4016
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004017 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004018 }
4019
Douglas Gregor97b98722010-01-19 23:20:36 +00004020 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004021 Expr *E = getCursorExpr(C);
4022 Decl *D = getDeclFromExpr(E);
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00004023 if (D) {
4024 CXCursor declCursor = MakeCXCursor(D, tu);
4025 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
4026 declCursor);
4027 return declCursor;
4028 }
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004029
4030 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004031 return MakeCursorOverloadedDeclRef(Ovl, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004032
Douglas Gregor97b98722010-01-19 23:20:36 +00004033 return clang_getNullCursor();
4034 }
4035
Douglas Gregor36897b02010-09-10 00:22:18 +00004036 if (clang_isStatement(C.kind)) {
4037 Stmt *S = getCursorStmt(C);
4038 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Ted Kremenek37c2e962011-03-15 23:47:49 +00004039 if (LabelDecl *label = Goto->getLabel())
4040 if (LabelStmt *labelS = label->getStmt())
4041 return MakeCXCursor(labelS, getCursorDecl(C), tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00004042
4043 return clang_getNullCursor();
4044 }
4045
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004046 if (C.kind == CXCursor_MacroExpansion) {
Chandler Carruth9e5bb852011-07-14 08:20:46 +00004047 if (MacroDefinition *Def = getCursorMacroExpansion(C)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004048 return MakeMacroDefinitionCursor(Def, tu);
Douglas Gregorbf7efa22010-03-18 18:23:03 +00004049 }
4050
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004051 if (!clang_isReference(C.kind))
4052 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004053
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004054 switch (C.kind) {
4055 case CXCursor_ObjCSuperClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004056 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004057
4058 case CXCursor_ObjCProtocolRef: {
Argyrios Kyrtzidis98c16b82012-01-24 19:40:15 +00004059 ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
4060 if (ObjCProtocolDecl *Def = Prot->getDefinition())
4061 return MakeCXCursor(Def, tu);
4062
Argyrios Kyrtzidisc15707d2012-01-24 21:39:26 +00004063 return MakeCXCursor(Prot, tu);
Argyrios Kyrtzidis98c16b82012-01-24 19:40:15 +00004064 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004065
Douglas Gregor7723fec2011-12-15 20:29:51 +00004066 case CXCursor_ObjCClassRef: {
4067 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
4068 if (ObjCInterfaceDecl *Def = Class->getDefinition())
4069 return MakeCXCursor(Def, tu);
4070
Argyrios Kyrtzidisc15707d2012-01-24 21:39:26 +00004071 return MakeCXCursor(Class, tu);
Douglas Gregor7723fec2011-12-15 20:29:51 +00004072 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00004073
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004074 case CXCursor_TypeRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004075 return MakeCXCursor(getCursorTypeRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00004076
4077 case CXCursor_TemplateRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004078 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00004079
Douglas Gregor69319002010-08-31 23:48:11 +00004080 case CXCursor_NamespaceRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004081 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
Douglas Gregor69319002010-08-31 23:48:11 +00004082
Douglas Gregora67e03f2010-09-09 21:42:20 +00004083 case CXCursor_MemberRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004084 return MakeCXCursor(getCursorMemberRef(C).first, tu );
Douglas Gregora67e03f2010-09-09 21:42:20 +00004085
Ted Kremenek3064ef92010-08-27 21:34:58 +00004086 case CXCursor_CXXBaseSpecifier: {
4087 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
4088 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004089 tu ));
Ted Kremenek3064ef92010-08-27 21:34:58 +00004090 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004091
Douglas Gregor36897b02010-09-10 00:22:18 +00004092 case CXCursor_LabelRef:
4093 // FIXME: We end up faking the "parent" declaration here because we
4094 // don't want to make CXCursor larger.
4095 return MakeCXCursor(getCursorLabelRef(C).first,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004096 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
4097 .getTranslationUnitDecl(),
4098 tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00004099
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004100 case CXCursor_OverloadedDeclRef:
4101 return C;
Douglas Gregor011d8b92012-02-15 00:54:55 +00004102
4103 case CXCursor_VariableRef:
4104 return MakeCXCursor(getCursorVariableRef(C).first, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004105
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004106 default:
4107 // We would prefer to enumerate all non-reference cursor kinds here.
4108 llvm_unreachable("Unhandled reference cursor kind");
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004109 }
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004110}
4111
Douglas Gregorb6998662010-01-19 19:34:47 +00004112CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00004113 if (clang_isInvalid(C.kind))
4114 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004115
Ted Kremeneka60ed472010-11-16 08:15:36 +00004116 CXTranslationUnit TU = getCursorTU(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004117
Douglas Gregorb6998662010-01-19 19:34:47 +00004118 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00004119 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00004120 C = clang_getCursorReferenced(C);
4121 WasReference = true;
4122 }
4123
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004124 if (C.kind == CXCursor_MacroExpansion)
Douglas Gregorbf7efa22010-03-18 18:23:03 +00004125 return clang_getCursorReferenced(C);
4126
Douglas Gregorb6998662010-01-19 19:34:47 +00004127 if (!clang_isDeclaration(C.kind))
4128 return clang_getNullCursor();
4129
4130 Decl *D = getCursorDecl(C);
4131 if (!D)
4132 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004133
Douglas Gregorb6998662010-01-19 19:34:47 +00004134 switch (D->getKind()) {
4135 // Declaration kinds that don't really separate the notions of
4136 // declaration and definition.
4137 case Decl::Namespace:
4138 case Decl::Typedef:
Richard Smith162e1c12011-04-15 14:24:37 +00004139 case Decl::TypeAlias:
Richard Smith3e4c6c42011-05-05 21:57:07 +00004140 case Decl::TypeAliasTemplate:
Douglas Gregorb6998662010-01-19 19:34:47 +00004141 case Decl::TemplateTypeParm:
4142 case Decl::EnumConstant:
4143 case Decl::Field:
Benjamin Kramerd9811462010-11-21 14:11:41 +00004144 case Decl::IndirectField:
Douglas Gregorb6998662010-01-19 19:34:47 +00004145 case Decl::ObjCIvar:
4146 case Decl::ObjCAtDefsField:
4147 case Decl::ImplicitParam:
4148 case Decl::ParmVar:
4149 case Decl::NonTypeTemplateParm:
4150 case Decl::TemplateTemplateParm:
4151 case Decl::ObjCCategoryImpl:
4152 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00004153 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00004154 case Decl::LinkageSpec:
4155 case Decl::ObjCPropertyImpl:
4156 case Decl::FileScopeAsm:
4157 case Decl::StaticAssert:
4158 case Decl::Block:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00004159 case Decl::Label: // FIXME: Is this right??
Francois Pichetaf0f4d02011-08-14 03:52:19 +00004160 case Decl::ClassScopeFunctionSpecialization:
Douglas Gregor15de72c2011-12-02 23:23:56 +00004161 case Decl::Import:
Douglas Gregorb6998662010-01-19 19:34:47 +00004162 return C;
4163
4164 // Declaration kinds that don't make any sense here, but are
4165 // nonetheless harmless.
4166 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00004167 break;
4168
4169 // Declaration kinds for which the definition is not resolvable.
4170 case Decl::UnresolvedUsingTypename:
4171 case Decl::UnresolvedUsingValue:
4172 break;
4173
4174 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00004175 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004176 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004177
4178 case Decl::NamespaceAlias:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004179 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004180
4181 case Decl::Enum:
4182 case Decl::Record:
4183 case Decl::CXXRecord:
4184 case Decl::ClassTemplateSpecialization:
4185 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00004186 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004187 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004188 return clang_getNullCursor();
4189
4190 case Decl::Function:
4191 case Decl::CXXMethod:
4192 case Decl::CXXConstructor:
4193 case Decl::CXXDestructor:
4194 case Decl::CXXConversion: {
4195 const FunctionDecl *Def = 0;
4196 if (cast<FunctionDecl>(D)->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004197 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004198 return clang_getNullCursor();
4199 }
4200
4201 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00004202 // Ask the variable if it has a definition.
4203 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004204 return MakeCXCursor(Def, TU);
Sebastian Redl31310a22010-02-01 20:16:42 +00004205 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00004206 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004207
Douglas Gregorb6998662010-01-19 19:34:47 +00004208 case Decl::FunctionTemplate: {
4209 const FunctionDecl *Def = 0;
4210 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004211 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004212 return clang_getNullCursor();
4213 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004214
Douglas Gregorb6998662010-01-19 19:34:47 +00004215 case Decl::ClassTemplate: {
4216 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00004217 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00004218 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004219 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004220 return clang_getNullCursor();
4221 }
4222
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004223 case Decl::Using:
4224 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004225 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004226
4227 case Decl::UsingShadow:
4228 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004229 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004230 TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004231
4232 case Decl::ObjCMethod: {
4233 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
4234 if (Method->isThisDeclarationADefinition())
4235 return C;
4236
4237 // Dig out the method definition in the associated
4238 // @implementation, if we have it.
4239 // FIXME: The ASTs should make finding the definition easier.
4240 if (ObjCInterfaceDecl *Class
4241 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
4242 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
4243 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
4244 Method->isInstanceMethod()))
4245 if (Def->isThisDeclarationADefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004246 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004247
4248 return clang_getNullCursor();
4249 }
4250
4251 case Decl::ObjCCategory:
4252 if (ObjCCategoryImplDecl *Impl
4253 = cast<ObjCCategoryDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004254 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004255 return clang_getNullCursor();
4256
4257 case Decl::ObjCProtocol:
Douglas Gregor5e2a1ff2012-01-01 19:29:29 +00004258 if (ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
4259 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004260 return clang_getNullCursor();
4261
Douglas Gregor375bb142011-12-27 22:43:10 +00004262 case Decl::ObjCInterface: {
Douglas Gregorb6998662010-01-19 19:34:47 +00004263 // There are two notions of a "definition" for an Objective-C
4264 // class: the interface and its implementation. When we resolved a
4265 // reference to an Objective-C class, produce the @interface as
4266 // the definition; when we were provided with the interface,
4267 // produce the @implementation as the definition.
Douglas Gregor375bb142011-12-27 22:43:10 +00004268 ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
Douglas Gregorb6998662010-01-19 19:34:47 +00004269 if (WasReference) {
Douglas Gregor375bb142011-12-27 22:43:10 +00004270 if (ObjCInterfaceDecl *Def = IFace->getDefinition())
Douglas Gregor7723fec2011-12-15 20:29:51 +00004271 return MakeCXCursor(Def, TU);
Douglas Gregor375bb142011-12-27 22:43:10 +00004272 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004273 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004274 return clang_getNullCursor();
Douglas Gregor375bb142011-12-27 22:43:10 +00004275 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004276
Douglas Gregorb6998662010-01-19 19:34:47 +00004277 case Decl::ObjCProperty:
4278 // FIXME: We don't really know where to find the
4279 // ObjCPropertyImplDecls that implement this property.
4280 return clang_getNullCursor();
4281
4282 case Decl::ObjCCompatibleAlias:
4283 if (ObjCInterfaceDecl *Class
4284 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
Douglas Gregor7723fec2011-12-15 20:29:51 +00004285 if (ObjCInterfaceDecl *Def = Class->getDefinition())
4286 return MakeCXCursor(Def, TU);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004287
Douglas Gregorb6998662010-01-19 19:34:47 +00004288 return clang_getNullCursor();
4289
Douglas Gregorb6998662010-01-19 19:34:47 +00004290 case Decl::Friend:
4291 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004292 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004293 return clang_getNullCursor();
4294
4295 case Decl::FriendTemplate:
4296 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004297 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004298 return clang_getNullCursor();
4299 }
4300
4301 return clang_getNullCursor();
4302}
4303
4304unsigned clang_isCursorDefinition(CXCursor C) {
4305 if (!clang_isDeclaration(C.kind))
4306 return 0;
4307
4308 return clang_getCursorDefinition(C) == C;
4309}
4310
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004311CXCursor clang_getCanonicalCursor(CXCursor C) {
4312 if (!clang_isDeclaration(C.kind))
4313 return C;
4314
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004315 if (Decl *D = getCursorDecl(C)) {
Argyrios Kyrtzidisdebb00f2011-07-15 22:37:58 +00004316 if (ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
4317 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
4318 return MakeCXCursor(CatD, getCursorTU(C));
4319
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004320 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
4321 if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
4322 return MakeCXCursor(IFD, getCursorTU(C));
4323
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004324 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004325 }
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004326
4327 return C;
4328}
4329
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004330unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004331 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004332 return 0;
4333
4334 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
4335 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
4336 return E->getNumDecls();
4337
4338 if (OverloadedTemplateStorage *S
4339 = Storage.dyn_cast<OverloadedTemplateStorage*>())
4340 return S->size();
4341
4342 Decl *D = Storage.get<Decl*>();
4343 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00004344 return Using->shadow_size();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004345
4346 return 0;
4347}
4348
4349CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004350 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004351 return clang_getNullCursor();
4352
4353 if (index >= clang_getNumOverloadedDecls(cursor))
4354 return clang_getNullCursor();
4355
Ted Kremeneka60ed472010-11-16 08:15:36 +00004356 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004357 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
4358 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004359 return MakeCXCursor(E->decls_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004360
4361 if (OverloadedTemplateStorage *S
4362 = Storage.dyn_cast<OverloadedTemplateStorage*>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004363 return MakeCXCursor(S->begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004364
4365 Decl *D = Storage.get<Decl*>();
4366 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
4367 // FIXME: This is, unfortunately, linear time.
4368 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
4369 std::advance(Pos, index);
Ted Kremeneka60ed472010-11-16 08:15:36 +00004370 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004371 }
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004372
4373 return clang_getNullCursor();
4374}
4375
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00004376void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00004377 const char **startBuf,
4378 const char **endBuf,
4379 unsigned *startLine,
4380 unsigned *startColumn,
4381 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00004382 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00004383 assert(getCursorDecl(C) && "CXCursor has null decl");
4384 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00004385 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
4386 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004387
Steve Naroff4ade6d62009-09-23 17:52:52 +00004388 SourceManager &SM = FD->getASTContext().getSourceManager();
4389 *startBuf = SM.getCharacterData(Body->getLBracLoc());
4390 *endBuf = SM.getCharacterData(Body->getRBracLoc());
4391 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
4392 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
4393 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
4394 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
4395}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004396
Douglas Gregor430d7a12011-07-25 17:48:11 +00004397
4398CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
4399 unsigned PieceIndex) {
4400 RefNamePieces Pieces;
4401
4402 switch (C.kind) {
4403 case CXCursor_MemberRefExpr:
4404 if (MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
4405 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
4406 E->getQualifierLoc().getSourceRange());
4407 break;
4408
4409 case CXCursor_DeclRefExpr:
4410 if (DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C)))
4411 Pieces = buildPieces(NameFlags, false, E->getNameInfo(),
4412 E->getQualifierLoc().getSourceRange(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00004413 E->getOptionalExplicitTemplateArgs());
Douglas Gregor430d7a12011-07-25 17:48:11 +00004414 break;
4415
4416 case CXCursor_CallExpr:
4417 if (CXXOperatorCallExpr *OCE =
4418 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
4419 Expr *Callee = OCE->getCallee();
4420 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
4421 Callee = ICE->getSubExpr();
4422
4423 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
4424 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
4425 DRE->getQualifierLoc().getSourceRange());
4426 }
4427 break;
4428
4429 default:
4430 break;
4431 }
4432
4433 if (Pieces.empty()) {
4434 if (PieceIndex == 0)
4435 return clang_getCursorExtent(C);
4436 } else if (PieceIndex < Pieces.size()) {
4437 SourceRange R = Pieces[PieceIndex];
4438 if (R.isValid())
4439 return cxloc::translateSourceRange(getCursorContext(C), R);
4440 }
4441
4442 return clang_getNullRange();
4443}
4444
Douglas Gregor0a812cf2010-02-18 23:07:20 +00004445void clang_enableStackTraces(void) {
4446 llvm::sys::PrintStackTraceOnErrorSignal();
4447}
4448
Daniel Dunbar995aaf92010-11-04 01:26:29 +00004449void clang_executeOnThread(void (*fn)(void*), void *user_data,
4450 unsigned stack_size) {
4451 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
4452}
4453
Ted Kremenekfb480492010-01-13 21:46:36 +00004454} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00004455
Ted Kremenekfb480492010-01-13 21:46:36 +00004456//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004457// Token-based Operations.
4458//===----------------------------------------------------------------------===//
4459
4460/* CXToken layout:
4461 * int_data[0]: a CXTokenKind
4462 * int_data[1]: starting token location
4463 * int_data[2]: token length
4464 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004465 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004466 * otherwise unused.
4467 */
4468extern "C" {
4469
4470CXTokenKind clang_getTokenKind(CXToken CXTok) {
4471 return static_cast<CXTokenKind>(CXTok.int_data[0]);
4472}
4473
4474CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
4475 switch (clang_getTokenKind(CXTok)) {
4476 case CXToken_Identifier:
4477 case CXToken_Keyword:
4478 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004479 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
4480 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004481
4482 case CXToken_Literal: {
4483 // We have stashed the starting pointer in the ptr_data field. Use it.
4484 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Chris Lattner5f9e2722011-07-23 10:55:15 +00004485 return createCXString(StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004486 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004487
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004488 case CXToken_Punctuation:
4489 case CXToken_Comment:
4490 break;
4491 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004492
4493 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004494 // deconstructing the source location.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004495 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004496 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004497 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004498
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004499 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
4500 std::pair<FileID, unsigned> LocInfo
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004501 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00004502 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004503 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004504 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
4505 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00004506 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004507
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004508 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004509}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004510
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004511CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004512 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004513 if (!CXXUnit)
4514 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004515
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004516 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
4517 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4518}
4519
4520CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004521 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor5352ac02010-01-28 00:27:43 +00004522 if (!CXXUnit)
4523 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004524
4525 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004526 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4527}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004528
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004529static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
4530 SmallVectorImpl<CXToken> &CXTokens) {
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004531 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4532 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004533 = SourceMgr.getDecomposedLoc(Range.getBegin());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004534 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004535 = SourceMgr.getDecomposedLoc(Range.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004536
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004537 // Cannot tokenize across files.
4538 if (BeginLocInfo.first != EndLocInfo.first)
4539 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004540
4541 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004542 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004543 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004544 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00004545 if (Invalid)
4546 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00004547
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004548 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
David Blaikie4e4d0842012-03-11 07:00:24 +00004549 CXXUnit->getASTContext().getLangOpts(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004550 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004551 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004552
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004553 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004554 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004555 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00004556 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004557 do {
4558 // Lex the next token
4559 Lex.LexFromRawLexer(Tok);
4560 if (Tok.is(tok::eof))
4561 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004562
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004563 // Initialize the CXToken.
4564 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004565
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004566 // - Common fields
4567 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
4568 CXTok.int_data[2] = Tok.getLength();
4569 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004570
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004571 // - Kind-specific fields
4572 if (Tok.isLiteral()) {
4573 CXTok.int_data[0] = CXToken_Literal;
4574 CXTok.ptr_data = (void *)Tok.getLiteralData();
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004575 } else if (Tok.is(tok::raw_identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00004576 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004577 IdentifierInfo *II
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004578 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004579
David Chisnall096428b2010-10-13 21:44:48 +00004580 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004581 CXTok.int_data[0] = CXToken_Keyword;
4582 }
4583 else {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004584 CXTok.int_data[0] = Tok.is(tok::identifier)
4585 ? CXToken_Identifier
4586 : CXToken_Keyword;
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004587 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004588 CXTok.ptr_data = II;
4589 } else if (Tok.is(tok::comment)) {
4590 CXTok.int_data[0] = CXToken_Comment;
4591 CXTok.ptr_data = 0;
4592 } else {
4593 CXTok.int_data[0] = CXToken_Punctuation;
4594 CXTok.ptr_data = 0;
4595 }
4596 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00004597 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004598 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004599}
4600
4601void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
4602 CXToken **Tokens, unsigned *NumTokens) {
4603 if (Tokens)
4604 *Tokens = 0;
4605 if (NumTokens)
4606 *NumTokens = 0;
4607
4608 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4609 if (!CXXUnit || !Tokens || !NumTokens)
4610 return;
4611
4612 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4613
4614 SourceRange R = cxloc::translateCXSourceRange(Range);
4615 if (R.isInvalid())
4616 return;
4617
4618 SmallVector<CXToken, 32> CXTokens;
4619 getTokens(CXXUnit, R, CXTokens);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004620
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004621 if (CXTokens.empty())
4622 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004623
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004624 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
4625 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
4626 *NumTokens = CXTokens.size();
4627}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004628
Ted Kremenek6db61092010-05-05 00:55:15 +00004629void clang_disposeTokens(CXTranslationUnit TU,
4630 CXToken *Tokens, unsigned NumTokens) {
4631 free(Tokens);
4632}
4633
4634} // end: extern "C"
4635
4636//===----------------------------------------------------------------------===//
4637// Token annotation APIs.
4638//===----------------------------------------------------------------------===//
4639
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004640typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004641static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4642 CXCursor parent,
4643 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00004644namespace {
4645class AnnotateTokensWorker {
4646 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004647 CXToken *Tokens;
4648 CXCursor *Cursors;
4649 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004650 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00004651 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004652 CursorVisitor AnnotateVis;
4653 SourceManager &SrcMgr;
Douglas Gregorf5251602011-03-08 17:10:18 +00004654 bool HasContextSensitiveKeywords;
4655
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004656 bool MoreTokens() const { return TokIdx < NumTokens; }
4657 unsigned NextToken() const { return TokIdx; }
4658 void AdvanceToken() { ++TokIdx; }
4659 SourceLocation GetTokenLoc(unsigned tokI) {
4660 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4661 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004662 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004663 return Tokens[tokI].int_data[3] != 0;
4664 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004665 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004666 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[3]);
4667 }
4668
4669 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004670 void annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
4671 SourceRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004672
Ted Kremenek6db61092010-05-05 00:55:15 +00004673public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00004674 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004675 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004676 CXTranslationUnit tu, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00004677 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00004678 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004679 AnnotateVis(tu,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00004680 AnnotateTokensVisitor, this,
4681 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00004682 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00004683 RegionOfInterest),
Douglas Gregorf5251602011-03-08 17:10:18 +00004684 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()),
4685 HasContextSensitiveKeywords(false) { }
Ted Kremenek11949cb2010-05-05 00:55:17 +00004686
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004687 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00004688 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004689 void AnnotateTokens();
Douglas Gregorf5251602011-03-08 17:10:18 +00004690
4691 /// \brief Determine whether the annotator saw any cursors that have
4692 /// context-sensitive keywords.
4693 bool hasContextSensitiveKeywords() const {
4694 return HasContextSensitiveKeywords;
4695 }
Ted Kremenek6db61092010-05-05 00:55:15 +00004696};
4697}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004698
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004699void AnnotateTokensWorker::AnnotateTokens() {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004700 // Walk the AST within the region of interest, annotating tokens
4701 // along the way.
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004702 AnnotateVis.visitFileRegion();
Ted Kremenek11949cb2010-05-05 00:55:17 +00004703
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004704 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4705 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004706 if (Pos != Annotated.end() &&
4707 (clang_isInvalid(Cursors[I].kind) ||
4708 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004709 Cursors[I] = Pos->second;
4710 }
4711
4712 // Finish up annotating any tokens left.
4713 if (!MoreTokens())
4714 return;
4715
4716 const CXCursor &C = clang_getNullCursor();
4717 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004718 if (I < PreprocessingTokIdx && clang_isPreprocessing(Cursors[I].kind))
4719 continue;
4720
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004721 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4722 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004723 }
4724}
4725
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004726/// \brief It annotates and advances tokens with a cursor until the comparison
4727//// between the cursor location and the source range is the same as
4728/// \arg compResult.
4729///
4730/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
4731/// Pass RangeOverlap to annotate tokens inside a range.
4732void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
4733 RangeComparisonResult compResult,
4734 SourceRange range) {
4735 while (MoreTokens()) {
4736 const unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004737 if (isFunctionMacroToken(I))
4738 return annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004739
4740 SourceLocation TokLoc = GetTokenLoc(I);
4741 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4742 Cursors[I] = updateC;
4743 AdvanceToken();
4744 continue;
4745 }
4746 break;
4747 }
4748}
4749
4750/// \brief Special annotation handling for macro argument tokens.
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004751void AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
4752 CXCursor updateC,
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004753 RangeComparisonResult compResult,
4754 SourceRange range) {
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004755 assert(MoreTokens());
4756 assert(isFunctionMacroToken(NextToken()) &&
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004757 "Should be called only for macro arg tokens");
4758
4759 // This works differently than annotateAndAdvanceTokens; because expanded
4760 // macro arguments can have arbitrary translation-unit source order, we do not
4761 // advance the token index one by one until a token fails the range test.
4762 // We only advance once past all of the macro arg tokens if all of them
4763 // pass the range test. If one of them fails we keep the token index pointing
4764 // at the start of the macro arg tokens so that the failing token will be
4765 // annotated by a subsequent annotation try.
4766
4767 bool atLeastOneCompFail = false;
4768
4769 unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004770 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
4771 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004772 if (TokLoc.isFileID())
4773 continue; // not macro arg token, it's parens or comma.
4774 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4775 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
4776 Cursors[I] = updateC;
4777 } else
4778 atLeastOneCompFail = true;
4779 }
4780
4781 if (!atLeastOneCompFail)
4782 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
4783}
4784
Ted Kremenek6db61092010-05-05 00:55:15 +00004785enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004786AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004787 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004788 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004789 if (cursorRange.isInvalid())
4790 return CXChildVisit_Recurse;
Douglas Gregorf5251602011-03-08 17:10:18 +00004791
4792 if (!HasContextSensitiveKeywords) {
4793 // Objective-C properties can have context-sensitive keywords.
4794 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
4795 if (ObjCPropertyDecl *Property
4796 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
4797 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
4798 }
4799 // Objective-C methods can have context-sensitive keywords.
4800 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
4801 cursor.kind == CXCursor_ObjCClassMethodDecl) {
4802 if (ObjCMethodDecl *Method
4803 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
4804 if (Method->getObjCDeclQualifier())
4805 HasContextSensitiveKeywords = true;
4806 else {
4807 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
4808 PEnd = Method->param_end();
4809 P != PEnd; ++P) {
4810 if ((*P)->getObjCDeclQualifier()) {
4811 HasContextSensitiveKeywords = true;
4812 break;
4813 }
4814 }
4815 }
4816 }
4817 }
4818 // C++ methods can have context-sensitive keywords.
4819 else if (cursor.kind == CXCursor_CXXMethod) {
4820 if (CXXMethodDecl *Method
4821 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
4822 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
4823 HasContextSensitiveKeywords = true;
4824 }
4825 }
4826 // C++ classes can have context-sensitive keywords.
4827 else if (cursor.kind == CXCursor_StructDecl ||
4828 cursor.kind == CXCursor_ClassDecl ||
4829 cursor.kind == CXCursor_ClassTemplate ||
4830 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
4831 if (Decl *D = getCursorDecl(cursor))
4832 if (D->hasAttr<FinalAttr>())
4833 HasContextSensitiveKeywords = true;
4834 }
4835 }
4836
Douglas Gregor4419b672010-10-21 06:10:04 +00004837 if (clang_isPreprocessing(cursor.kind)) {
Chandler Carruthcea731a2011-07-14 16:07:57 +00004838 // For macro expansions, just note where the beginning of the macro
4839 // expansion occurs.
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004840 if (cursor.kind == CXCursor_MacroExpansion) {
Douglas Gregor4419b672010-10-21 06:10:04 +00004841 Annotated[Loc.int_data] = cursor;
4842 return CXChildVisit_Recurse;
4843 }
4844
Douglas Gregor4419b672010-10-21 06:10:04 +00004845 // Items in the preprocessing record are kept separate from items in
4846 // declarations, so we keep a separate token index.
4847 unsigned SavedTokIdx = TokIdx;
4848 TokIdx = PreprocessingTokIdx;
4849
4850 // Skip tokens up until we catch up to the beginning of the preprocessing
4851 // entry.
4852 while (MoreTokens()) {
4853 const unsigned I = NextToken();
4854 SourceLocation TokLoc = GetTokenLoc(I);
4855 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4856 case RangeBefore:
4857 AdvanceToken();
4858 continue;
4859 case RangeAfter:
4860 case RangeOverlap:
4861 break;
4862 }
4863 break;
4864 }
4865
4866 // Look at all of the tokens within this range.
4867 while (MoreTokens()) {
4868 const unsigned I = NextToken();
4869 SourceLocation TokLoc = GetTokenLoc(I);
4870 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4871 case RangeBefore:
David Blaikieb219cfc2011-09-23 05:06:16 +00004872 llvm_unreachable("Infeasible");
Douglas Gregor4419b672010-10-21 06:10:04 +00004873 case RangeAfter:
4874 break;
4875 case RangeOverlap:
4876 Cursors[I] = cursor;
4877 AdvanceToken();
4878 continue;
4879 }
4880 break;
4881 }
4882
4883 // Save the preprocessing token index; restore the non-preprocessing
4884 // token index.
4885 PreprocessingTokIdx = TokIdx;
4886 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004887 return CXChildVisit_Recurse;
4888 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004889
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004890 if (cursorRange.isInvalid())
4891 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004892
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004893 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4894
Ted Kremeneka333c662010-05-12 05:29:33 +00004895 // Adjust the annotated range based specific declarations.
4896 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4897 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004898 Decl *D = cxcursor::getCursorDecl(cursor);
Douglas Gregor2494dd02011-03-01 01:34:45 +00004899
4900 SourceLocation StartLoc;
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00004901 if (const DeclaratorDecl *DD = dyn_cast_or_null<DeclaratorDecl>(D)) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00004902 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
Daniel Dunbar96a00142012-03-09 18:35:03 +00004903 StartLoc = TI->getTypeLoc().getLocStart();
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00004904 } else if (TypedefDecl *Typedef = dyn_cast_or_null<TypedefDecl>(D)) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00004905 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
Daniel Dunbar96a00142012-03-09 18:35:03 +00004906 StartLoc = TI->getTypeLoc().getLocStart();
Ted Kremeneka333c662010-05-12 05:29:33 +00004907 }
Douglas Gregor2494dd02011-03-01 01:34:45 +00004908
4909 if (StartLoc.isValid() && L.isValid() &&
4910 SrcMgr.isBeforeInTranslationUnit(StartLoc, L))
4911 cursorRange.setBegin(StartLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004912 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004913
Ted Kremenek3f404602010-08-14 01:14:06 +00004914 // If the location of the cursor occurs within a macro instantiation, record
4915 // the spelling location of the cursor in our annotation map. We can then
4916 // paper over the token labelings during a post-processing step to try and
4917 // get cursor mappings for tokens that are the *arguments* of a macro
4918 // instantiation.
4919 if (L.isMacroID()) {
4920 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4921 // Only invalidate the old annotation if it isn't part of a preprocessing
4922 // directive. Here we assume that the default construction of CXCursor
4923 // results in CXCursor.kind being an initialized value (i.e., 0). If
4924 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004925
Ted Kremenek3f404602010-08-14 01:14:06 +00004926 CXCursor &oldC = Annotated[rawEncoding];
4927 if (!clang_isPreprocessing(oldC.kind))
4928 oldC = cursor;
4929 }
4930
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004931 const enum CXCursorKind K = clang_getCursorKind(parent);
4932 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004933 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4934 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004935
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004936 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004937
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00004938 // Avoid having the cursor of an expression "overwrite" the annotation of the
4939 // variable declaration that it belongs to.
4940 // This can happen for C++ constructor expressions whose range generally
4941 // include the variable declaration, e.g.:
4942 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
4943 if (clang_isExpression(cursorK)) {
4944 Expr *E = getCursorExpr(cursor);
Argyrios Kyrtzidis8ccac3d2011-06-29 22:20:07 +00004945 if (Decl *D = getCursorParentDecl(cursor)) {
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00004946 const unsigned I = NextToken();
4947 if (E->getLocStart().isValid() && D->getLocation().isValid() &&
4948 E->getLocStart() == D->getLocation() &&
4949 E->getLocStart() == GetTokenLoc(I)) {
4950 Cursors[I] = updateC;
4951 AdvanceToken();
4952 }
4953 }
4954 }
4955
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004956 // Visit children to get their cursor information.
4957 const unsigned BeforeChildren = NextToken();
4958 VisitChildren(cursor);
4959 const unsigned AfterChildren = NextToken();
4960
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004961 // Scan the tokens that are at the end of the cursor, but are not captured
4962 // but the child cursors.
4963 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
Ted Kremenek6db61092010-05-05 00:55:15 +00004964
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004965 // Scan the tokens that are at the beginning of the cursor, but are not
4966 // capture by the child cursors.
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004967 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4968 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4969 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004970
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004971 Cursors[I] = cursor;
4972 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004973
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004974 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004975}
4976
Ted Kremenek6db61092010-05-05 00:55:15 +00004977static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4978 CXCursor parent,
4979 CXClientData client_data) {
4980 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4981}
4982
Ted Kremenek6628a612011-03-18 22:51:30 +00004983namespace {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004984
4985/// \brief Uses the macro expansions in the preprocessing record to find
4986/// and mark tokens that are macro arguments. This info is used by the
4987/// AnnotateTokensWorker.
4988class MarkMacroArgTokensVisitor {
4989 SourceManager &SM;
4990 CXToken *Tokens;
4991 unsigned NumTokens;
4992 unsigned CurIdx;
4993
4994public:
4995 MarkMacroArgTokensVisitor(SourceManager &SM,
4996 CXToken *tokens, unsigned numTokens)
4997 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
4998
4999 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
5000 if (cursor.kind != CXCursor_MacroExpansion)
5001 return CXChildVisit_Continue;
5002
5003 SourceRange macroRange = getCursorMacroExpansion(cursor)->getSourceRange();
5004 if (macroRange.getBegin() == macroRange.getEnd())
5005 return CXChildVisit_Continue; // it's not a function macro.
5006
5007 for (; CurIdx < NumTokens; ++CurIdx) {
5008 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
5009 macroRange.getBegin()))
5010 break;
5011 }
5012
5013 if (CurIdx == NumTokens)
5014 return CXChildVisit_Break;
5015
5016 for (; CurIdx < NumTokens; ++CurIdx) {
5017 SourceLocation tokLoc = getTokenLoc(CurIdx);
5018 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
5019 break;
5020
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00005021 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005022 }
5023
5024 if (CurIdx == NumTokens)
5025 return CXChildVisit_Break;
5026
5027 return CXChildVisit_Continue;
5028 }
5029
5030private:
5031 SourceLocation getTokenLoc(unsigned tokI) {
5032 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
5033 }
5034
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00005035 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005036 // The third field is reserved and currently not used. Use it here
5037 // to mark macro arg expanded tokens with their expanded locations.
5038 Tokens[tokI].int_data[3] = loc.getRawEncoding();
5039 }
5040};
5041
5042} // end anonymous namespace
5043
5044static CXChildVisitResult
5045MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
5046 CXClientData client_data) {
5047 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
5048 parent);
5049}
5050
5051namespace {
Ted Kremenek6628a612011-03-18 22:51:30 +00005052 struct clang_annotateTokens_Data {
5053 CXTranslationUnit TU;
5054 ASTUnit *CXXUnit;
5055 CXToken *Tokens;
5056 unsigned NumTokens;
5057 CXCursor *Cursors;
5058 };
5059}
5060
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005061static void annotatePreprocessorTokens(CXTranslationUnit TU,
5062 SourceRange RegionOfInterest,
5063 AnnotateTokensData &Annotated) {
5064 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
5065
5066 SourceManager &SourceMgr = CXXUnit->getSourceManager();
5067 std::pair<FileID, unsigned> BeginLocInfo
5068 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
5069 std::pair<FileID, unsigned> EndLocInfo
5070 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
5071
5072 if (BeginLocInfo.first != EndLocInfo.first)
5073 return;
5074
5075 StringRef Buffer;
5076 bool Invalid = false;
5077 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
5078 if (Buffer.empty() || Invalid)
5079 return;
5080
5081 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
David Blaikie4e4d0842012-03-11 07:00:24 +00005082 CXXUnit->getASTContext().getLangOpts(),
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005083 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
5084 Buffer.end());
5085 Lex.SetCommentRetentionState(true);
5086
5087 // Lex tokens in raw mode until we hit the end of the range, to avoid
5088 // entering #includes or expanding macros.
5089 while (true) {
5090 Token Tok;
5091 Lex.LexFromRawLexer(Tok);
5092
5093 reprocess:
5094 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
5095 // We have found a preprocessing directive. Gobble it up so that we
5096 // don't see it while preprocessing these tokens later, but keep track
5097 // of all of the token locations inside this preprocessing directive so
5098 // that we can annotate them appropriately.
5099 //
5100 // FIXME: Some simple tests here could identify macro definitions and
5101 // #undefs, to provide specific cursor kinds for those.
5102 SmallVector<SourceLocation, 32> Locations;
5103 do {
5104 Locations.push_back(Tok.getLocation());
5105 Lex.LexFromRawLexer(Tok);
5106 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
5107
5108 using namespace cxcursor;
5109 CXCursor Cursor
5110 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
5111 Locations.back()),
5112 TU);
5113 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
5114 Annotated[Locations[I].getRawEncoding()] = Cursor;
5115 }
5116
5117 if (Tok.isAtStartOfLine())
5118 goto reprocess;
5119
5120 continue;
5121 }
5122
5123 if (Tok.is(tok::eof))
5124 break;
5125 }
5126}
5127
Ted Kremenekab979612010-11-11 08:05:23 +00005128// This gets run a separate thread to avoid stack blowout.
Ted Kremenek6628a612011-03-18 22:51:30 +00005129static void clang_annotateTokensImpl(void *UserData) {
5130 CXTranslationUnit TU = ((clang_annotateTokens_Data*)UserData)->TU;
5131 ASTUnit *CXXUnit = ((clang_annotateTokens_Data*)UserData)->CXXUnit;
5132 CXToken *Tokens = ((clang_annotateTokens_Data*)UserData)->Tokens;
5133 const unsigned NumTokens = ((clang_annotateTokens_Data*)UserData)->NumTokens;
5134 CXCursor *Cursors = ((clang_annotateTokens_Data*)UserData)->Cursors;
5135
5136 // Determine the region of interest, which contains all of the tokens.
5137 SourceRange RegionOfInterest;
5138 RegionOfInterest.setBegin(
5139 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
5140 RegionOfInterest.setEnd(
5141 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
5142 Tokens[NumTokens-1])));
5143
5144 // A mapping from the source locations found when re-lexing or traversing the
5145 // region of interest to the corresponding cursors.
5146 AnnotateTokensData Annotated;
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005147
Ted Kremenek6628a612011-03-18 22:51:30 +00005148 // Relex the tokens within the source range to look for preprocessing
5149 // directives.
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005150 annotatePreprocessorTokens(TU, RegionOfInterest, Annotated);
Ted Kremenek6628a612011-03-18 22:51:30 +00005151
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005152 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
5153 // Search and mark tokens that are macro argument expansions.
5154 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
5155 Tokens, NumTokens);
5156 CursorVisitor MacroArgMarker(TU,
5157 MarkMacroArgTokensVisitorDelegate, &Visitor,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00005158 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00005159 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00005160 RegionOfInterest);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005161 MacroArgMarker.visitPreprocessedEntitiesInRegion();
5162 }
5163
Ted Kremenek6628a612011-03-18 22:51:30 +00005164 // Annotate all of the source locations in the region of interest that map to
5165 // a specific cursor.
5166 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
5167 TU, RegionOfInterest);
5168
5169 // FIXME: We use a ridiculous stack size here because the data-recursion
5170 // algorithm uses a large stack frame than the non-data recursive version,
5171 // and AnnotationTokensWorker currently transforms the data-recursion
5172 // algorithm back into a traditional recursion by explicitly calling
5173 // VisitChildren(). We will need to remove this explicit recursive call.
5174 W.AnnotateTokens();
5175
5176 // If we ran into any entities that involve context-sensitive keywords,
5177 // take another pass through the tokens to mark them as such.
5178 if (W.hasContextSensitiveKeywords()) {
5179 for (unsigned I = 0; I != NumTokens; ++I) {
5180 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
5181 continue;
5182
5183 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
5184 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5185 if (ObjCPropertyDecl *Property
5186 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
5187 if (Property->getPropertyAttributesAsWritten() != 0 &&
5188 llvm::StringSwitch<bool>(II->getName())
5189 .Case("readonly", true)
5190 .Case("assign", true)
John McCallf85e1932011-06-15 23:02:42 +00005191 .Case("unsafe_unretained", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00005192 .Case("readwrite", true)
5193 .Case("retain", true)
5194 .Case("copy", true)
5195 .Case("nonatomic", true)
5196 .Case("atomic", true)
5197 .Case("getter", true)
5198 .Case("setter", true)
John McCallf85e1932011-06-15 23:02:42 +00005199 .Case("strong", true)
5200 .Case("weak", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00005201 .Default(false))
5202 Tokens[I].int_data[0] = CXToken_Keyword;
5203 }
5204 continue;
5205 }
5206
5207 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
5208 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
5209 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5210 if (llvm::StringSwitch<bool>(II->getName())
5211 .Case("in", true)
5212 .Case("out", true)
5213 .Case("inout", true)
5214 .Case("oneway", true)
5215 .Case("bycopy", true)
5216 .Case("byref", true)
5217 .Default(false))
5218 Tokens[I].int_data[0] = CXToken_Keyword;
5219 continue;
5220 }
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00005221
5222 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
5223 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
5224 Tokens[I].int_data[0] = CXToken_Keyword;
Ted Kremenek6628a612011-03-18 22:51:30 +00005225 continue;
5226 }
5227 }
5228 }
Ted Kremenekab979612010-11-11 08:05:23 +00005229}
5230
Ted Kremenek6db61092010-05-05 00:55:15 +00005231extern "C" {
5232
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005233void clang_annotateTokens(CXTranslationUnit TU,
5234 CXToken *Tokens, unsigned NumTokens,
5235 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005236
5237 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005238 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005239
Douglas Gregor4419b672010-10-21 06:10:04 +00005240 // Any token we don't specifically annotate will have a NULL cursor.
5241 CXCursor C = clang_getNullCursor();
5242 for (unsigned I = 0; I != NumTokens; ++I)
5243 Cursors[I] = C;
5244
Ted Kremeneka60ed472010-11-16 08:15:36 +00005245 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor4419b672010-10-21 06:10:04 +00005246 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005247 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005248
Douglas Gregorbdf60622010-03-05 21:16:25 +00005249 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenek6628a612011-03-18 22:51:30 +00005250
5251 clang_annotateTokens_Data data = { TU, CXXUnit, Tokens, NumTokens, Cursors };
Ted Kremenekab979612010-11-11 08:05:23 +00005252 llvm::CrashRecoveryContext CRC;
Ted Kremenek6628a612011-03-18 22:51:30 +00005253 if (!RunSafely(CRC, clang_annotateTokensImpl, &data,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005254 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00005255 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
5256 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005257}
Ted Kremenek6628a612011-03-18 22:51:30 +00005258
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005259} // end: extern "C"
5260
5261//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00005262// Operations for querying linkage of a cursor.
5263//===----------------------------------------------------------------------===//
5264
5265extern "C" {
5266CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00005267 if (!clang_isDeclaration(cursor.kind))
5268 return CXLinkage_Invalid;
5269
Ted Kremenek16b42592010-03-03 06:36:57 +00005270 Decl *D = cxcursor::getCursorDecl(cursor);
5271 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
5272 switch (ND->getLinkage()) {
5273 case NoLinkage: return CXLinkage_NoLinkage;
5274 case InternalLinkage: return CXLinkage_Internal;
5275 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
5276 case ExternalLinkage: return CXLinkage_External;
5277 };
5278
5279 return CXLinkage_Invalid;
5280}
5281} // end: extern "C"
5282
5283//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005284// Operations for querying language of a cursor.
5285//===----------------------------------------------------------------------===//
5286
5287static CXLanguageKind getDeclLanguage(const Decl *D) {
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00005288 if (!D)
5289 return CXLanguage_C;
5290
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005291 switch (D->getKind()) {
5292 default:
5293 break;
5294 case Decl::ImplicitParam:
5295 case Decl::ObjCAtDefsField:
5296 case Decl::ObjCCategory:
5297 case Decl::ObjCCategoryImpl:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005298 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005299 case Decl::ObjCImplementation:
5300 case Decl::ObjCInterface:
5301 case Decl::ObjCIvar:
5302 case Decl::ObjCMethod:
5303 case Decl::ObjCProperty:
5304 case Decl::ObjCPropertyImpl:
5305 case Decl::ObjCProtocol:
5306 return CXLanguage_ObjC;
5307 case Decl::CXXConstructor:
5308 case Decl::CXXConversion:
5309 case Decl::CXXDestructor:
5310 case Decl::CXXMethod:
5311 case Decl::CXXRecord:
5312 case Decl::ClassTemplate:
5313 case Decl::ClassTemplatePartialSpecialization:
5314 case Decl::ClassTemplateSpecialization:
5315 case Decl::Friend:
5316 case Decl::FriendTemplate:
5317 case Decl::FunctionTemplate:
5318 case Decl::LinkageSpec:
5319 case Decl::Namespace:
5320 case Decl::NamespaceAlias:
5321 case Decl::NonTypeTemplateParm:
5322 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005323 case Decl::TemplateTemplateParm:
5324 case Decl::TemplateTypeParm:
5325 case Decl::UnresolvedUsingTypename:
5326 case Decl::UnresolvedUsingValue:
5327 case Decl::Using:
5328 case Decl::UsingDirective:
5329 case Decl::UsingShadow:
5330 return CXLanguage_CPlusPlus;
5331 }
5332
5333 return CXLanguage_C;
5334}
5335
5336extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00005337
5338enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
5339 if (clang_isDeclaration(cursor.kind))
5340 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005341 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Douglas Gregor58ddb602010-08-23 23:00:57 +00005342 return CXAvailability_Available;
5343
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005344 switch (D->getAvailability()) {
5345 case AR_Available:
5346 case AR_NotYetIntroduced:
5347 return CXAvailability_Available;
5348
5349 case AR_Deprecated:
Douglas Gregor58ddb602010-08-23 23:00:57 +00005350 return CXAvailability_Deprecated;
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005351
5352 case AR_Unavailable:
5353 return CXAvailability_NotAvailable;
5354 }
Douglas Gregor58ddb602010-08-23 23:00:57 +00005355 }
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005356
Douglas Gregor58ddb602010-08-23 23:00:57 +00005357 return CXAvailability_Available;
5358}
5359
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005360CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
5361 if (clang_isDeclaration(cursor.kind))
5362 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
5363
5364 return CXLanguage_Invalid;
5365}
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005366
5367 /// \brief If the given cursor is the "templated" declaration
5368 /// descibing a class or function template, return the class or
5369 /// function template.
5370static Decl *maybeGetTemplateCursor(Decl *D) {
5371 if (!D)
5372 return 0;
5373
5374 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
5375 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
5376 return FunTmpl;
5377
5378 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
5379 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
5380 return ClassTmpl;
5381
5382 return D;
5383}
5384
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005385CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
5386 if (clang_isDeclaration(cursor.kind)) {
5387 if (Decl *D = getCursorDecl(cursor)) {
5388 DeclContext *DC = D->getDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005389 if (!DC)
5390 return clang_getNullCursor();
5391
5392 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5393 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005394 }
5395 }
5396
5397 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
5398 if (Decl *D = getCursorDecl(cursor))
Ted Kremeneka60ed472010-11-16 08:15:36 +00005399 return MakeCXCursor(D, getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005400 }
5401
5402 return clang_getNullCursor();
5403}
5404
5405CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
5406 if (clang_isDeclaration(cursor.kind)) {
5407 if (Decl *D = getCursorDecl(cursor)) {
5408 DeclContext *DC = D->getLexicalDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005409 if (!DC)
5410 return clang_getNullCursor();
5411
5412 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5413 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005414 }
5415 }
5416
5417 // FIXME: Note that we can't easily compute the lexical context of a
5418 // statement or expression, so we return nothing.
5419 return clang_getNullCursor();
5420}
5421
Douglas Gregor9f592342010-10-01 20:25:15 +00005422void clang_getOverriddenCursors(CXCursor cursor,
5423 CXCursor **overridden,
5424 unsigned *num_overridden) {
5425 if (overridden)
5426 *overridden = 0;
5427 if (num_overridden)
5428 *num_overridden = 0;
5429 if (!overridden || !num_overridden)
5430 return;
5431
Argyrios Kyrtzidisb11be042011-10-06 07:00:46 +00005432 SmallVector<CXCursor, 8> Overridden;
5433 cxcursor::getOverriddenCursors(cursor, Overridden);
Douglas Gregor9f592342010-10-01 20:25:15 +00005434
Ted Kremenek24077122011-11-14 23:51:37 +00005435 // Don't allocate memory if we have no overriden cursors.
5436 if (Overridden.size() == 0)
5437 return;
5438
Argyrios Kyrtzidisb11be042011-10-06 07:00:46 +00005439 *num_overridden = Overridden.size();
5440 *overridden = new CXCursor [Overridden.size()];
5441 std::copy(Overridden.begin(), Overridden.end(), *overridden);
Douglas Gregor9f592342010-10-01 20:25:15 +00005442}
5443
5444void clang_disposeOverriddenCursors(CXCursor *overridden) {
5445 delete [] overridden;
5446}
5447
Douglas Gregorecdcb882010-10-20 22:00:55 +00005448CXFile clang_getIncludedFile(CXCursor cursor) {
5449 if (cursor.kind != CXCursor_InclusionDirective)
5450 return 0;
5451
5452 InclusionDirective *ID = getCursorInclusionDirective(cursor);
5453 return (void *)ID->getFile();
5454}
5455
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005456} // end: extern "C"
5457
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005458
5459//===----------------------------------------------------------------------===//
5460// C++ AST instrospection.
5461//===----------------------------------------------------------------------===//
5462
5463extern "C" {
5464unsigned clang_CXXMethod_isStatic(CXCursor C) {
5465 if (!clang_isDeclaration(C.kind))
5466 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00005467
5468 CXXMethodDecl *Method = 0;
5469 Decl *D = cxcursor::getCursorDecl(C);
5470 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5471 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5472 else
5473 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5474 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00005475}
Ted Kremenekb12903e2010-05-18 22:32:15 +00005476
Douglas Gregor211924b2011-05-12 15:17:24 +00005477unsigned clang_CXXMethod_isVirtual(CXCursor C) {
5478 if (!clang_isDeclaration(C.kind))
5479 return 0;
5480
5481 CXXMethodDecl *Method = 0;
5482 Decl *D = cxcursor::getCursorDecl(C);
5483 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5484 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5485 else
5486 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5487 return (Method && Method->isVirtual()) ? 1 : 0;
5488}
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005489} // end: extern "C"
5490
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005491//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00005492// Attribute introspection.
5493//===----------------------------------------------------------------------===//
5494
5495extern "C" {
5496CXType clang_getIBOutletCollectionType(CXCursor C) {
5497 if (C.kind != CXCursor_IBOutletCollectionAttr)
Ted Kremeneka60ed472010-11-16 08:15:36 +00005498 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005499
5500 IBOutletCollectionAttr *A =
5501 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
5502
Argyrios Kyrtzidis18aa2ff2011-09-13 18:49:52 +00005503 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005504}
5505} // end: extern "C"
5506
5507//===----------------------------------------------------------------------===//
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005508// Inspecting memory usage.
5509//===----------------------------------------------------------------------===//
5510
Ted Kremenekf7870022011-04-20 16:41:07 +00005511typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005512
Ted Kremenekf7870022011-04-20 16:41:07 +00005513static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
5514 enum CXTUResourceUsageKind k,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005515 unsigned long amount) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005516 CXTUResourceUsageEntry entry = { k, amount };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005517 entries.push_back(entry);
5518}
5519
5520extern "C" {
5521
Ted Kremenekf7870022011-04-20 16:41:07 +00005522const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005523 const char *str = "";
5524 switch (kind) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005525 case CXTUResourceUsage_AST:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005526 str = "ASTContext: expressions, declarations, and types";
5527 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005528 case CXTUResourceUsage_Identifiers:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005529 str = "ASTContext: identifiers";
5530 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005531 case CXTUResourceUsage_Selectors:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005532 str = "ASTContext: selectors";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005533 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005534 case CXTUResourceUsage_GlobalCompletionResults:
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005535 str = "Code completion: cached global results";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005536 break;
Ted Kremenek457aaf02011-04-28 04:10:31 +00005537 case CXTUResourceUsage_SourceManagerContentCache:
5538 str = "SourceManager: content cache allocator";
5539 break;
Ted Kremenekba29bd22011-04-28 04:53:38 +00005540 case CXTUResourceUsage_AST_SideTables:
5541 str = "ASTContext: side tables";
5542 break;
Ted Kremenekf61b8312011-04-28 20:36:42 +00005543 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
5544 str = "SourceManager: malloc'ed memory buffers";
5545 break;
5546 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
5547 str = "SourceManager: mmap'ed memory buffers";
5548 break;
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005549 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
5550 str = "ExternalASTSource: malloc'ed memory buffers";
5551 break;
5552 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
5553 str = "ExternalASTSource: mmap'ed memory buffers";
5554 break;
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005555 case CXTUResourceUsage_Preprocessor:
5556 str = "Preprocessor: malloc'ed memory";
5557 break;
5558 case CXTUResourceUsage_PreprocessingRecord:
5559 str = "Preprocessor: PreprocessingRecord";
5560 break;
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005561 case CXTUResourceUsage_SourceManager_DataStructures:
5562 str = "SourceManager: data structures and tables";
5563 break;
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005564 case CXTUResourceUsage_Preprocessor_HeaderSearch:
5565 str = "Preprocessor: header search tables";
5566 break;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005567 }
5568 return str;
5569}
5570
Ted Kremenekf7870022011-04-20 16:41:07 +00005571CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005572 if (!TU) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005573 CXTUResourceUsage usage = { (void*) 0, 0, 0 };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005574 return usage;
5575 }
5576
5577 ASTUnit *astUnit = static_cast<ASTUnit*>(TU->TUData);
Dylan Noblesmith1e4c01b2012-02-13 12:32:21 +00005578 OwningPtr<MemUsageEntries> entries(new MemUsageEntries());
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005579 ASTContext &astContext = astUnit->getASTContext();
5580
5581 // How much memory is used by AST nodes and types?
Ted Kremenekf7870022011-04-20 16:41:07 +00005582 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005583 (unsigned long) astContext.getASTAllocatedMemory());
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005584
5585 // How much memory is used by identifiers?
Ted Kremenekf7870022011-04-20 16:41:07 +00005586 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005587 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
5588
5589 // How much memory is used for selectors?
Ted Kremenekf7870022011-04-20 16:41:07 +00005590 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005591 (unsigned long) astContext.Selectors.getTotalMemory());
5592
Ted Kremenekba29bd22011-04-28 04:53:38 +00005593 // How much memory is used by ASTContext's side tables?
5594 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
5595 (unsigned long) astContext.getSideTableAllocatedMemory());
5596
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005597 // How much memory is used for caching global code completion results?
5598 unsigned long completionBytes = 0;
5599 if (GlobalCodeCompletionAllocator *completionAllocator =
5600 astUnit->getCachedCompletionAllocator().getPtr()) {
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005601 completionBytes = completionAllocator->getTotalMemory();
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005602 }
Ted Kremenek457aaf02011-04-28 04:10:31 +00005603 createCXTUResourceUsageEntry(*entries,
5604 CXTUResourceUsage_GlobalCompletionResults,
5605 completionBytes);
5606
5607 // How much memory is being used by SourceManager's content cache?
5608 createCXTUResourceUsageEntry(*entries,
5609 CXTUResourceUsage_SourceManagerContentCache,
5610 (unsigned long) astContext.getSourceManager().getContentCacheSize());
Ted Kremenekf61b8312011-04-28 20:36:42 +00005611
5612 // How much memory is being used by the MemoryBuffer's in SourceManager?
5613 const SourceManager::MemoryBufferSizes &srcBufs =
5614 astUnit->getSourceManager().getMemoryBufferSizes();
5615
5616 createCXTUResourceUsageEntry(*entries,
5617 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
5618 (unsigned long) srcBufs.malloc_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005619 createCXTUResourceUsageEntry(*entries,
Ted Kremenekf61b8312011-04-28 20:36:42 +00005620 CXTUResourceUsage_SourceManager_Membuffer_MMap,
5621 (unsigned long) srcBufs.mmap_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005622 createCXTUResourceUsageEntry(*entries,
5623 CXTUResourceUsage_SourceManager_DataStructures,
5624 (unsigned long) astContext.getSourceManager()
5625 .getDataStructureSizes());
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005626
5627 // How much memory is being used by the ExternalASTSource?
5628 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
5629 const ExternalASTSource::MemoryBufferSizes &sizes =
5630 esrc->getMemoryBufferSizes();
5631
5632 createCXTUResourceUsageEntry(*entries,
5633 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
5634 (unsigned long) sizes.malloc_bytes);
5635 createCXTUResourceUsageEntry(*entries,
5636 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
5637 (unsigned long) sizes.mmap_bytes);
5638 }
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005639
5640 // How much memory is being used by the Preprocessor?
5641 Preprocessor &pp = astUnit->getPreprocessor();
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005642 createCXTUResourceUsageEntry(*entries,
5643 CXTUResourceUsage_Preprocessor,
Argyrios Kyrtzidisc5c5e922011-06-29 22:20:04 +00005644 pp.getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005645
5646 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
5647 createCXTUResourceUsageEntry(*entries,
5648 CXTUResourceUsage_PreprocessingRecord,
5649 pRec->getTotalMemory());
5650 }
5651
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005652 createCXTUResourceUsageEntry(*entries,
5653 CXTUResourceUsage_Preprocessor_HeaderSearch,
5654 pp.getHeaderSearchInfo().getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005655
Ted Kremenekf7870022011-04-20 16:41:07 +00005656 CXTUResourceUsage usage = { (void*) entries.get(),
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005657 (unsigned) entries->size(),
5658 entries->size() ? &(*entries)[0] : 0 };
5659 entries.take();
5660 return usage;
5661}
5662
Ted Kremenekf7870022011-04-20 16:41:07 +00005663void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005664 if (usage.data)
5665 delete (MemUsageEntries*) usage.data;
5666}
5667
5668} // end extern "C"
5669
Douglas Gregor6df78732011-05-05 20:27:22 +00005670void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
5671 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
5672 for (unsigned I = 0; I != Usage.numEntries; ++I)
5673 fprintf(stderr, " %s: %lu\n",
5674 clang_getTUResourceUsageName(Usage.entries[I].kind),
5675 Usage.entries[I].amount);
5676
5677 clang_disposeCXTUResourceUsage(Usage);
5678}
5679
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005680//===----------------------------------------------------------------------===//
Ted Kremenek04bb7162010-01-22 22:44:15 +00005681// Misc. utility functions.
5682//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00005683
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00005684/// Default to using an 8 MB stack size on "safety" threads.
5685static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005686
5687namespace clang {
5688
5689bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005690 void (*Fn)(void*), void *UserData,
5691 unsigned Size) {
5692 if (!Size)
5693 Size = GetSafetyThreadStackSize();
5694 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005695 return CRC.RunSafelyOnThread(Fn, UserData, Size);
5696 return CRC.RunSafely(Fn, UserData);
5697}
5698
5699unsigned GetSafetyThreadStackSize() {
5700 return SafetyStackThreadSize;
5701}
5702
5703void SetSafetyThreadStackSize(unsigned Value) {
5704 SafetyStackThreadSize = Value;
5705}
5706
5707}
5708
Ted Kremenek04bb7162010-01-22 22:44:15 +00005709extern "C" {
5710
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00005711CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00005712 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00005713}
5714
5715} // end: extern "C"
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005716