blob: 0f93931034d67317e3f2871a0ff863bb40a174bf [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"
Ted Kremenekd8c370c2010-11-02 23:10:24 +000038#include "clang/Analysis/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();
61 return D;
62}
63
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +000064cxtu::CXTUOwner::~CXTUOwner() {
65 if (TU)
66 clang_disposeTranslationUnit(TU);
67}
68
Ted Kremenekf0e23e82010-02-17 00:41:40 +000069/// \brief Compare two source ranges to determine their relative position in
Douglas Gregor33e9abd2010-01-22 19:49:59 +000070/// the translation unit.
Ted Kremenekf0e23e82010-02-17 00:41:40 +000071static RangeComparisonResult RangeCompare(SourceManager &SM,
72 SourceRange R1,
Douglas Gregor33e9abd2010-01-22 19:49:59 +000073 SourceRange R2) {
74 assert(R1.isValid() && "First range is invalid?");
75 assert(R2.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000076 if (R1.getEnd() != R2.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000077 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000078 return RangeBefore;
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000079 if (R2.getEnd() != R1.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000080 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000081 return RangeAfter;
82 return RangeOverlap;
83}
84
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000085/// \brief Determine if a source location falls within, before, or after a
86/// a given source range.
87static RangeComparisonResult LocationCompare(SourceManager &SM,
88 SourceLocation L, SourceRange R) {
89 assert(R.isValid() && "First range is invalid?");
90 assert(L.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000091 if (L == R.getBegin() || L == R.getEnd())
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000092 return RangeOverlap;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000093 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
94 return RangeBefore;
95 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
96 return RangeAfter;
97 return RangeOverlap;
98}
99
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000100/// \brief Translate a Clang source range into a CIndex source range.
101///
102/// Clang internally represents ranges where the end location points to the
103/// start of the token at the end. However, for external clients it is more
104/// useful to have a CXSourceRange be a proper half-open interval. This routine
105/// does the appropriate translation.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000106CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000107 const LangOptions &LangOpts,
Chris Lattner0a76aae2010-06-18 22:45:06 +0000108 const CharSourceRange &R) {
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000109 // We want the last character in this location, so we will adjust the
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000110 // location accordingly.
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000111 SourceLocation EndLoc = R.getEnd();
Douglas Gregora9b06d42010-11-09 06:24:54 +0000112 if (EndLoc.isValid() && EndLoc.isMacroID())
Chandler Carruthedc3dcc2011-07-25 16:56:02 +0000113 EndLoc = SM.getExpansionRange(EndLoc).second;
Chris Lattner0a76aae2010-06-18 22:45:06 +0000114 if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) {
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000115 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000116 EndLoc = EndLoc.getLocWithOffset(Length);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000117 }
118
119 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
120 R.getBegin().getRawEncoding(),
121 EndLoc.getRawEncoding() };
122 return Result;
123}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000124
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000125//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000126// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000127//===----------------------------------------------------------------------===//
128
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000129static SourceRange getRawCursorExtent(CXCursor C);
Douglas Gregor66537982010-11-17 17:14:07 +0000130static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
131
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000132
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000133RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000134 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000135}
136
Douglas Gregorb1373d02010-01-20 20:59:29 +0000137/// \brief Visit the given cursor and, if requested by the visitor,
138/// its children.
139///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000140/// \param Cursor the cursor to visit.
141///
142/// \param CheckRegionOfInterest if true, then the caller already checked that
143/// this cursor is within the region of interest.
144///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000145/// \returns true if the visitation should be aborted, false if it
146/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000147bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000148 if (clang_isInvalid(Cursor.kind))
149 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000150
Douglas Gregorb1373d02010-01-20 20:59:29 +0000151 if (clang_isDeclaration(Cursor.kind)) {
152 Decl *D = getCursorDecl(Cursor);
153 assert(D && "Invalid declaration cursor");
Argyrios Kyrtzidis65ab9072011-09-26 19:05:37 +0000154 // Ignore implicit declarations, unless it's an objc method because
155 // currently we should report implicit methods for properties when indexing.
156 if (D->isImplicit() && !isa<ObjCMethodDecl>(D))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000157 return false;
158 }
159
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000160 // If we have a range of interest, and this cursor doesn't intersect with it,
161 // we're done.
162 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000163 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000164 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000165 return false;
166 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000167
Douglas Gregorb1373d02010-01-20 20:59:29 +0000168 switch (Visitor(Cursor, Parent, ClientData)) {
169 case CXChildVisit_Break:
170 return true;
171
172 case CXChildVisit_Continue:
173 return false;
174
175 case CXChildVisit_Recurse:
176 return VisitChildren(Cursor);
177 }
178
Douglas Gregorfd643772010-01-25 16:45:46 +0000179 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000180}
181
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000182static bool visitPreprocessedEntitiesInRange(SourceRange R,
183 PreprocessingRecord &PPRec,
184 CursorVisitor &Visitor) {
185 SourceManager &SM = Visitor.getASTUnit()->getSourceManager();
186 FileID FID;
187
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +0000188 if (!Visitor.shouldVisitIncludedEntities()) {
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000189 // If the begin/end of the range lie in the same FileID, do the optimization
190 // where we skip preprocessed entities that do not come from the same FileID.
191 FID = SM.getFileID(R.getBegin());
192 if (FID != SM.getFileID(R.getEnd()))
193 FID = FileID();
194 }
195
196 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
197 Entities = PPRec.getPreprocessedEntitiesInRange(R);
198 return Visitor.visitPreprocessedEntities(Entities.first, Entities.second,
199 PPRec, FID);
200}
201
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000202void CursorVisitor::visitFileRegion() {
203 if (RegionOfInterest.isInvalid())
204 return;
205
206 ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData);
207 SourceManager &SM = Unit->getSourceManager();
208
209 std::pair<FileID, unsigned>
210 Begin = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getBegin())),
211 End = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getEnd()));
212
213 if (End.first != Begin.first) {
214 // If the end does not reside in the same file, try to recover by
215 // picking the end of the file of begin location.
216 End.first = Begin.first;
217 End.second = SM.getFileIDSize(Begin.first);
218 }
219
220 assert(Begin.first == End.first);
221 if (Begin.second > End.second)
222 return;
223
224 FileID File = Begin.first;
225 unsigned Offset = Begin.second;
226 unsigned Length = End.second - Begin.second;
227
228 if (!VisitPreprocessorLast &&
229 Unit->getPreprocessor().getPreprocessingRecord())
230 visitPreprocessedEntitiesInRegion();
231
232 visitDeclsFromFileRegion(File, Offset, Length);
233
234 if (VisitPreprocessorLast &&
235 Unit->getPreprocessor().getPreprocessingRecord())
236 visitPreprocessedEntitiesInRegion();
237}
238
239void CursorVisitor::visitDeclsFromFileRegion(FileID File,
240 unsigned Offset, unsigned Length) {
241 ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData);
242 SourceManager &SM = Unit->getSourceManager();
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000243 SourceRange Range = RegionOfInterest;
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000244
245 SmallVector<Decl *, 16> Decls;
246 Unit->findFileRegionDecls(File, Offset, Length, Decls);
247
248 // If we didn't find any file level decls for the file, try looking at the
249 // file that it was included from.
250 while (Decls.empty()) {
251 bool Invalid = false;
252 const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid);
253 if (Invalid)
254 return;
255
256 SourceLocation Outer;
257 if (SLEntry.isFile())
258 Outer = SLEntry.getFile().getIncludeLoc();
259 else
260 Outer = SLEntry.getExpansion().getExpansionLocStart();
261 if (Outer.isInvalid())
262 return;
263
264 llvm::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer);
265 Length = 0;
266 Unit->findFileRegionDecls(File, Offset, Length, Decls);
267 }
268
269 assert(!Decls.empty());
270
271 bool VisitedAtLeastOnce = false;
272 SmallVector<Decl *, 16>::iterator DIt = Decls.begin();
273 for (SmallVector<Decl *, 16>::iterator DE = Decls.end(); DIt != DE; ++DIt) {
274 Decl *D = *DIt;
275
276 // We handle forward decls via ObjCClassDecl.
277 if (ObjCInterfaceDecl *InterD = dyn_cast<ObjCInterfaceDecl>(D)) {
278 if (InterD->isForwardDecl())
279 continue;
280 // An interface that started as a forward decl may have changed location
281 // because its @interface was parsed.
282 if (InterD->isInitiallyForwardDecl() &&
283 !SM.isInFileID(SM.getFileLoc(InterD->getLocation()), File))
284 continue;
285 }
286
287 RangeComparisonResult CompRes = RangeCompare(SM, D->getSourceRange(),Range);
288 if (CompRes == RangeBefore)
289 continue;
290 if (CompRes == RangeAfter)
291 break;
292
293 assert(CompRes == RangeOverlap);
294 VisitedAtLeastOnce = true;
Argyrios Kyrtzidisba986172011-11-03 19:02:28 +0000295 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000296 break;
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000297 }
298
299 if (VisitedAtLeastOnce)
300 return;
301
302 // No Decls overlapped with the range. Move up the lexical context until there
303 // is a context that contains the range or we reach the translation unit
304 // level.
305 DeclContext *DC = DIt == Decls.begin() ? (*DIt)->getLexicalDeclContext()
306 : (*(DIt-1))->getLexicalDeclContext();
307
308 while (DC && !DC->isTranslationUnit()) {
309 Decl *D = cast<Decl>(DC);
310 SourceRange CurDeclRange = D->getSourceRange();
311 if (CurDeclRange.isInvalid())
312 break;
313
314 if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) {
Argyrios Kyrtzidisba986172011-11-03 19:02:28 +0000315 Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true);
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000316 break;
317 }
318
319 DC = D->getLexicalDeclContext();
320 }
321}
322
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000323bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
Douglas Gregor788f5a12010-03-20 00:41:21 +0000324 PreprocessingRecord &PPRec
Ted Kremeneka60ed472010-11-16 08:15:36 +0000325 = *AU->getPreprocessor().getPreprocessingRecord();
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000326 SourceManager &SM = AU->getSourceManager();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000327
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000328 if (RegionOfInterest.isValid()) {
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +0000329 SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000330 SourceLocation B = MappedRange.getBegin();
331 SourceLocation E = MappedRange.getEnd();
332
333 if (AU->isInPreambleFileID(B)) {
334 if (SM.isLoadedSourceLocation(E))
335 return visitPreprocessedEntitiesInRange(SourceRange(B, E),
336 PPRec, *this);
337
338 // Beginning of range lies in the preamble but it also extends beyond
339 // it into the main file. Split the range into 2 parts, one covering
340 // the preamble and another covering the main file. This allows subsequent
341 // calls to visitPreprocessedEntitiesInRange to accept a source range that
342 // lies in the same FileID, allowing it to skip preprocessed entities that
343 // do not come from the same FileID.
344 bool breaked =
345 visitPreprocessedEntitiesInRange(
346 SourceRange(B, AU->getEndOfPreambleFileID()),
347 PPRec, *this);
348 if (breaked) return true;
349 return visitPreprocessedEntitiesInRange(
350 SourceRange(AU->getStartOfMainFileID(), E),
351 PPRec, *this);
352 }
353
354 return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this);
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000355 }
356
Douglas Gregor788f5a12010-03-20 00:41:21 +0000357 bool OnlyLocalDecls
Douglas Gregor32038bb2010-12-21 19:07:48 +0000358 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
359
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000360 if (OnlyLocalDecls)
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000361 return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(),
362 PPRec);
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000363
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000364 return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec);
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000365}
366
367template<typename InputIterator>
368bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000369 InputIterator Last,
370 PreprocessingRecord &PPRec,
371 FileID FID) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000372 for (; First != Last; ++First) {
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000373 if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID))
374 continue;
375
376 PreprocessedEntity *PPE = *First;
377 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000378 if (Visit(MakeMacroExpansionCursor(ME, TU)))
379 return true;
380
381 continue;
382 }
383
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000384 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(PPE)) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000385 if (Visit(MakeMacroDefinitionCursor(MD, TU)))
386 return true;
387
388 continue;
389 }
390
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000391 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000392 if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
393 return true;
394
395 continue;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000396 }
397 }
398
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000399 return false;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000400}
401
Douglas Gregorb1373d02010-01-20 20:59:29 +0000402/// \brief Visit the children of the given cursor.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000403///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000404/// \returns true if the visitation should be aborted, false if it
405/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000406bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregorc314aa42011-03-02 19:17:03 +0000407 if (clang_isReference(Cursor.kind) &&
408 Cursor.kind != CXCursor_CXXBaseSpecifier) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000409 // By definition, references have no children.
410 return false;
411 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000412
413 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000414 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000415 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000416
Douglas Gregorb1373d02010-01-20 20:59:29 +0000417 if (clang_isDeclaration(Cursor.kind)) {
418 Decl *D = getCursorDecl(Cursor);
Douglas Gregor06d9b1a2011-04-14 21:41:34 +0000419 if (!D)
420 return false;
421
Ted Kremenek539311e2010-02-18 18:47:01 +0000422 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000423 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000424
Douglas Gregor06d9b1a2011-04-14 21:41:34 +0000425 if (clang_isStatement(Cursor.kind)) {
426 if (Stmt *S = getCursorStmt(Cursor))
427 return Visit(S);
428
429 return false;
430 }
431
432 if (clang_isExpression(Cursor.kind)) {
433 if (Expr *E = getCursorExpr(Cursor))
434 return Visit(E);
435
436 return false;
437 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000438
Douglas Gregorb1373d02010-01-20 20:59:29 +0000439 if (clang_isTranslationUnit(Cursor.kind)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000440 CXTranslationUnit tu = getCursorTU(Cursor);
441 ASTUnit *CXXUnit = static_cast<ASTUnit*>(tu->TUData);
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000442
443 int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
444 for (unsigned I = 0; I != 2; ++I) {
445 if (VisitOrder[I]) {
446 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
447 RegionOfInterest.isInvalid()) {
448 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
449 TLEnd = CXXUnit->top_level_end();
450 TL != TLEnd; ++TL) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000451 if (Visit(MakeCXCursor(*TL, tu, RegionOfInterest), true))
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000452 return true;
453 }
454 } else if (VisitDeclContext(
455 CXXUnit->getASTContext().getTranslationUnitDecl()))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000456 return true;
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000457 continue;
Douglas Gregor7b691f332010-01-20 21:13:59 +0000458 }
Bob Wilson3178cb62010-03-19 03:57:57 +0000459
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000460 // Walk the preprocessing record.
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000461 if (CXXUnit->getPreprocessor().getPreprocessingRecord())
462 visitPreprocessedEntitiesInRegion();
Douglas Gregor0396f462010-03-19 05:22:59 +0000463 }
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000464
Douglas Gregor7b691f332010-01-20 21:13:59 +0000465 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000466 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000467
Douglas Gregorc314aa42011-03-02 19:17:03 +0000468 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
469 if (CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
470 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
471 return Visit(BaseTSInfo->getTypeLoc());
472 }
473 }
474 }
Argyrios Kyrtzidis221d5a52011-09-13 18:49:56 +0000475
476 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
477 IBOutletCollectionAttr *A =
478 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
479 if (const ObjCInterfaceType *InterT = A->getInterface()->getAs<ObjCInterfaceType>())
480 return Visit(cxcursor::MakeCursorObjCClassRef(InterT->getInterface(),
481 A->getInterfaceLoc(), TU));
482 }
483
Douglas Gregorb1373d02010-01-20 20:59:29 +0000484 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000485 return false;
486}
487
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000488bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
Douglas Gregor13c8ccb2011-04-22 23:49:24 +0000489 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
490 if (Visit(TSInfo->getTypeLoc()))
491 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000492
Ted Kremenek664cffd2010-07-22 11:30:19 +0000493 if (Stmt *Body = B->getBody())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000494 return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest));
Ted Kremenek664cffd2010-07-22 11:30:19 +0000495
496 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000497}
498
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000499llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
500 if (RegionOfInterest.isValid()) {
Douglas Gregor66537982010-11-17 17:14:07 +0000501 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000502 if (Range.isInvalid())
503 return llvm::Optional<bool>();
Douglas Gregor66537982010-11-17 17:14:07 +0000504
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000505 switch (CompareRegionOfInterest(Range)) {
506 case RangeBefore:
507 // This declaration comes before the region of interest; skip it.
508 return llvm::Optional<bool>();
509
510 case RangeAfter:
511 // This declaration comes after the region of interest; we're done.
512 return false;
513
514 case RangeOverlap:
515 // This declaration overlaps the region of interest; visit it.
516 break;
517 }
518 }
519 return true;
520}
521
522bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
523 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
524
525 // FIXME: Eventually remove. This part of a hack to support proper
526 // iteration over all Decls contained lexically within an ObjC container.
527 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
528 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
529
530 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000531 Decl *D = *I;
532 if (D->getLexicalDeclContext() != DC)
533 continue;
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000534 CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000535 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
536 if (!V.hasValue())
537 continue;
538 if (!V.getValue())
539 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000540 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000541 return true;
542 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000543 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000544}
545
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000546bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
547 llvm_unreachable("Translation units are visited directly by Visit()");
548 return false;
549}
550
Richard Smith162e1c12011-04-15 14:24:37 +0000551bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
552 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
553 return Visit(TSInfo->getTypeLoc());
554
555 return false;
556}
557
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000558bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
559 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
560 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000561
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000562 return false;
563}
564
565bool CursorVisitor::VisitTagDecl(TagDecl *D) {
566 return VisitDeclContext(D);
567}
568
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000569bool CursorVisitor::VisitClassTemplateSpecializationDecl(
570 ClassTemplateSpecializationDecl *D) {
571 bool ShouldVisitBody = false;
572 switch (D->getSpecializationKind()) {
573 case TSK_Undeclared:
574 case TSK_ImplicitInstantiation:
575 // Nothing to visit
576 return false;
577
578 case TSK_ExplicitInstantiationDeclaration:
579 case TSK_ExplicitInstantiationDefinition:
580 break;
581
582 case TSK_ExplicitSpecialization:
583 ShouldVisitBody = true;
584 break;
585 }
586
587 // Visit the template arguments used in the specialization.
588 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
589 TypeLoc TL = SpecType->getTypeLoc();
590 if (TemplateSpecializationTypeLoc *TSTLoc
591 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
592 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
593 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
594 return true;
595 }
596 }
597
598 if (ShouldVisitBody && VisitCXXRecordDecl(D))
599 return true;
600
601 return false;
602}
603
Douglas Gregor74dbe642010-08-31 19:31:58 +0000604bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
605 ClassTemplatePartialSpecializationDecl *D) {
606 // FIXME: Visit the "outer" template parameter lists on the TagDecl
607 // before visiting these template parameters.
608 if (VisitTemplateParameters(D->getTemplateParameters()))
609 return true;
610
611 // Visit the partial specialization arguments.
612 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
613 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
614 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
615 return true;
616
617 return VisitCXXRecordDecl(D);
618}
619
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000620bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000621 // Visit the default argument.
622 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
623 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
624 if (Visit(DefArg->getTypeLoc()))
625 return true;
626
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000627 return false;
628}
629
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000630bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
631 if (Expr *Init = D->getInitExpr())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000632 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000633 return false;
634}
635
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000636bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
637 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
638 if (Visit(TSInfo->getTypeLoc()))
639 return true;
640
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000641 // Visit the nested-name-specifier, if present.
642 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
643 if (VisitNestedNameSpecifierLoc(QualifierLoc))
644 return true;
645
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000646 return false;
647}
648
Douglas Gregora67e03f2010-09-09 21:42:20 +0000649/// \brief Compare two base or member initializers based on their source order.
Sean Huntcbb67482011-01-08 20:30:50 +0000650static int CompareCXXCtorInitializers(const void* Xp, const void *Yp) {
651 CXXCtorInitializer const * const *X
652 = static_cast<CXXCtorInitializer const * const *>(Xp);
653 CXXCtorInitializer const * const *Y
654 = static_cast<CXXCtorInitializer const * const *>(Yp);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000655
656 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
657 return -1;
658 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
659 return 1;
660 else
661 return 0;
662}
663
Douglas Gregorb1373d02010-01-20 20:59:29 +0000664bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000665 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
666 // Visit the function declaration's syntactic components in the order
667 // written. This requires a bit of work.
Abramo Bagnara723df242010-12-14 22:11:44 +0000668 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
Douglas Gregor01829d32010-08-31 14:41:23 +0000669 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
670
671 // If we have a function declared directly (without the use of a typedef),
672 // visit just the return type. Otherwise, just visit the function's type
673 // now.
674 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
675 (!FTL && Visit(TL)))
676 return true;
677
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000678 // Visit the nested-name-specifier, if present.
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000679 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
680 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000681 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000682
683 // Visit the declaration name.
684 if (VisitDeclarationNameInfo(ND->getNameInfo()))
685 return true;
686
687 // FIXME: Visit explicitly-specified template arguments!
688
689 // Visit the function parameters, if we have a function type.
690 if (FTL && VisitFunctionTypeLoc(*FTL, true))
691 return true;
692
693 // FIXME: Attributes?
694 }
695
Sean Hunt10620eb2011-05-06 20:44:56 +0000696 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
Douglas Gregora67e03f2010-09-09 21:42:20 +0000697 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
698 // Find the initializers that were written in the source.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000699 SmallVector<CXXCtorInitializer *, 4> WrittenInits;
Douglas Gregora67e03f2010-09-09 21:42:20 +0000700 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
701 IEnd = Constructor->init_end();
702 I != IEnd; ++I) {
703 if (!(*I)->isWritten())
704 continue;
705
706 WrittenInits.push_back(*I);
707 }
708
709 // Sort the initializers in source order
710 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
Sean Huntcbb67482011-01-08 20:30:50 +0000711 &CompareCXXCtorInitializers);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000712
713 // Visit the initializers in source order
714 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
Sean Huntcbb67482011-01-08 20:30:50 +0000715 CXXCtorInitializer *Init = WrittenInits[I];
Francois Pichet00eb3f92010-12-04 09:14:42 +0000716 if (Init->isAnyMemberInitializer()) {
717 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
Douglas Gregora67e03f2010-09-09 21:42:20 +0000718 Init->getMemberLocation(), TU)))
719 return true;
Douglas Gregor76852c22011-11-01 01:16:03 +0000720 } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) {
721 if (Visit(TInfo->getTypeLoc()))
Douglas Gregora67e03f2010-09-09 21:42:20 +0000722 return true;
723 }
724
725 // Visit the initializer value.
726 if (Expr *Initializer = Init->getInit())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000727 if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
Douglas Gregora67e03f2010-09-09 21:42:20 +0000728 return true;
729 }
730 }
731
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000732 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
Douglas Gregora67e03f2010-09-09 21:42:20 +0000733 return true;
734 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000735
Douglas Gregorb1373d02010-01-20 20:59:29 +0000736 return false;
737}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000738
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000739bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
740 if (VisitDeclaratorDecl(D))
741 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000742
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000743 if (Expr *BitWidth = D->getBitWidth())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000744 return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000745
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000746 return false;
747}
748
749bool CursorVisitor::VisitVarDecl(VarDecl *D) {
750 if (VisitDeclaratorDecl(D))
751 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000752
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000753 if (Expr *Init = D->getInit())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000754 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000755
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000756 return false;
757}
758
Douglas Gregor84b51d72010-09-01 20:16:53 +0000759bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
760 if (VisitDeclaratorDecl(D))
761 return true;
762
763 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
764 if (Expr *DefArg = D->getDefaultArgument())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000765 return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
Douglas Gregor84b51d72010-09-01 20:16:53 +0000766
767 return false;
768}
769
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000770bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
771 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
772 // before visiting these template parameters.
773 if (VisitTemplateParameters(D->getTemplateParameters()))
774 return true;
775
776 return VisitFunctionDecl(D->getTemplatedDecl());
777}
778
Douglas Gregor39d6f072010-08-31 19:02:00 +0000779bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
780 // FIXME: Visit the "outer" template parameter lists on the TagDecl
781 // before visiting these template parameters.
782 if (VisitTemplateParameters(D->getTemplateParameters()))
783 return true;
784
785 return VisitCXXRecordDecl(D->getTemplatedDecl());
786}
787
Douglas Gregor84b51d72010-09-01 20:16:53 +0000788bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
789 if (VisitTemplateParameters(D->getTemplateParameters()))
790 return true;
791
792 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
793 VisitTemplateArgumentLoc(D->getDefaultArgument()))
794 return true;
795
796 return false;
797}
798
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000799bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000800 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
801 if (Visit(TSInfo->getTypeLoc()))
802 return true;
803
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000804 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000805 PEnd = ND->param_end();
806 P != PEnd; ++P) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000807 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000808 return true;
809 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000810
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000811 if (ND->isThisDeclarationADefinition() &&
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000812 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000813 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000814
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000815 return false;
816}
817
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000818namespace {
819 struct ContainerDeclsSort {
820 SourceManager &SM;
821 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
822 bool operator()(Decl *A, Decl *B) {
823 SourceLocation L_A = A->getLocStart();
824 SourceLocation L_B = B->getLocStart();
825 assert(L_A.isValid() && L_B.isValid());
826 return SM.isBeforeInTranslationUnit(L_A, L_B);
827 }
828 };
829}
830
Douglas Gregora59e3902010-01-21 23:27:09 +0000831bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000832 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
833 // an @implementation can lexically contain Decls that are not properly
834 // nested in the AST. When we identify such cases, we need to retrofit
835 // this nesting here.
836 if (!DI_current)
837 return VisitDeclContext(D);
838
839 // Scan the Decls that immediately come after the container
840 // in the current DeclContext. If any fall within the
841 // container's lexical region, stash them into a vector
842 // for later processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000843 SmallVector<Decl *, 24> DeclsInContainer;
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000844 SourceLocation EndLoc = D->getSourceRange().getEnd();
Ted Kremeneka60ed472010-11-16 08:15:36 +0000845 SourceManager &SM = AU->getSourceManager();
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000846 if (EndLoc.isValid()) {
847 DeclContext::decl_iterator next = *DI_current;
848 while (++next != DE_current) {
849 Decl *D_next = *next;
850 if (!D_next)
851 break;
852 SourceLocation L = D_next->getLocStart();
853 if (!L.isValid())
854 break;
855 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
856 *DI_current = next;
857 DeclsInContainer.push_back(D_next);
858 continue;
859 }
860 break;
861 }
862 }
863
864 // The common case.
865 if (DeclsInContainer.empty())
866 return VisitDeclContext(D);
867
868 // Get all the Decls in the DeclContext, and sort them with the
869 // additional ones we've collected. Then visit them.
870 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
871 I!=E; ++I) {
872 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000873 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
874 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000875 continue;
876 DeclsInContainer.push_back(subDecl);
877 }
878
879 // Now sort the Decls so that they appear in lexical order.
880 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
881 ContainerDeclsSort(SM));
882
883 // Now visit the decls.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000884 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000885 E = DeclsInContainer.end(); I != E; ++I) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000886 CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000887 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
888 if (!V.hasValue())
889 continue;
890 if (!V.getValue())
891 return false;
892 if (Visit(Cursor, true))
893 return true;
894 }
895 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000896}
897
Douglas Gregorb1373d02010-01-20 20:59:29 +0000898bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000899 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
900 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000901 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000902
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000903 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
904 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
905 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000906 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000907 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000908
Douglas Gregora59e3902010-01-21 23:27:09 +0000909 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000910}
911
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000912bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
913 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
914 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
915 E = PID->protocol_end(); I != E; ++I, ++PL)
916 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
917 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000918
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000919 return VisitObjCContainerDecl(PID);
920}
921
Ted Kremenek23173d72010-05-18 21:09:07 +0000922bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000923 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000924 return true;
925
Ted Kremenek23173d72010-05-18 21:09:07 +0000926 // FIXME: This implements a workaround with @property declarations also being
927 // installed in the DeclContext for the @interface. Eventually this code
928 // should be removed.
929 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
930 if (!CDecl || !CDecl->IsClassExtension())
931 return false;
932
933 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
934 if (!ID)
935 return false;
936
937 IdentifierInfo *PropertyId = PD->getIdentifier();
938 ObjCPropertyDecl *prevDecl =
939 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
940
941 if (!prevDecl)
942 return false;
943
944 // Visit synthesized methods since they will be skipped when visiting
945 // the @interface.
946 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000947 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000948 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
Ted Kremenek23173d72010-05-18 21:09:07 +0000949 return true;
950
951 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000952 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000953 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
Ted Kremenek23173d72010-05-18 21:09:07 +0000954 return true;
955
956 return false;
957}
958
Douglas Gregorb1373d02010-01-20 20:59:29 +0000959bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000960 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000961 if (D->getSuperClass() &&
962 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000963 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000964 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000965 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000966
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000967 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
968 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
969 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000970 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000971 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000972
Douglas Gregora59e3902010-01-21 23:27:09 +0000973 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000974}
975
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000976bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
977 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000978}
979
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000980bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +0000981 // 'ID' could be null when dealing with invalid code.
982 if (ObjCInterfaceDecl *ID = D->getClassInterface())
983 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
984 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000985
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000986 return VisitObjCImplDecl(D);
987}
988
989bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
990#if 0
991 // Issue callbacks for super class.
992 // FIXME: No source location information!
993 if (D->getSuperClass() &&
994 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000995 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000996 TU)))
997 return true;
998#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000999
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001000 return VisitObjCImplDecl(D);
1001}
1002
1003bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1004 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1005 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1006 E = D->protocol_end();
1007 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001008 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001009 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001010
1011 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001012}
1013
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001014bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00001015 if (Visit(MakeCursorObjCClassRef(D->getForwardInterfaceDecl(),
1016 D->getForwardDecl()->getLocation(), TU)))
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001017 return true;
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001018 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001019}
1020
Douglas Gregora4ffd852010-11-17 01:03:52 +00001021bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1022 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1023 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1024
1025 return false;
1026}
1027
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001028bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1029 return VisitDeclContext(D);
1030}
1031
Douglas Gregor69319002010-08-31 23:48:11 +00001032bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001033 // Visit nested-name-specifier.
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00001034 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1035 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001036 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001037
1038 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1039 D->getTargetNameLoc(), TU));
1040}
1041
Douglas Gregor7e242562010-09-01 19:52:22 +00001042bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001043 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001044 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1045 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001046 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001047 }
Douglas Gregor7e242562010-09-01 19:52:22 +00001048
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001049 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1050 return true;
1051
Douglas Gregor7e242562010-09-01 19:52:22 +00001052 return VisitDeclarationNameInfo(D->getNameInfo());
1053}
1054
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001055bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001056 // Visit nested-name-specifier.
Douglas Gregordb992412011-02-25 16:33:46 +00001057 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1058 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001059 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001060
1061 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1062 D->getIdentLocation(), TU));
1063}
1064
Douglas Gregor7e242562010-09-01 19:52:22 +00001065bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001066 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001067 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1068 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001069 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001070 }
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001071
Douglas Gregor7e242562010-09-01 19:52:22 +00001072 return VisitDeclarationNameInfo(D->getNameInfo());
1073}
1074
1075bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1076 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001077 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001078 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1079 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001080 return true;
1081
Douglas Gregor7e242562010-09-01 19:52:22 +00001082 return false;
1083}
1084
Douglas Gregor01829d32010-08-31 14:41:23 +00001085bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1086 switch (Name.getName().getNameKind()) {
1087 case clang::DeclarationName::Identifier:
1088 case clang::DeclarationName::CXXLiteralOperatorName:
1089 case clang::DeclarationName::CXXOperatorName:
1090 case clang::DeclarationName::CXXUsingDirective:
1091 return false;
1092
1093 case clang::DeclarationName::CXXConstructorName:
1094 case clang::DeclarationName::CXXDestructorName:
1095 case clang::DeclarationName::CXXConversionFunctionName:
1096 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1097 return Visit(TSInfo->getTypeLoc());
1098 return false;
1099
1100 case clang::DeclarationName::ObjCZeroArgSelector:
1101 case clang::DeclarationName::ObjCOneArgSelector:
1102 case clang::DeclarationName::ObjCMultiArgSelector:
1103 // FIXME: Per-identifier location info?
1104 return false;
1105 }
1106
1107 return false;
1108}
1109
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001110bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1111 SourceRange Range) {
1112 // FIXME: This whole routine is a hack to work around the lack of proper
1113 // source information in nested-name-specifiers (PR5791). Since we do have
1114 // a beginning source location, we can visit the first component of the
1115 // nested-name-specifier, if it's a single-token component.
1116 if (!NNS)
1117 return false;
1118
1119 // Get the first component in the nested-name-specifier.
1120 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1121 NNS = Prefix;
1122
1123 switch (NNS->getKind()) {
1124 case NestedNameSpecifier::Namespace:
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001125 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1126 TU));
1127
Douglas Gregor14aba762011-02-24 02:36:08 +00001128 case NestedNameSpecifier::NamespaceAlias:
1129 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1130 Range.getBegin(), TU));
1131
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001132 case NestedNameSpecifier::TypeSpec: {
1133 // If the type has a form where we know that the beginning of the source
1134 // range matches up with a reference cursor. Visit the appropriate reference
1135 // cursor.
John McCallf4c73712011-01-19 06:33:43 +00001136 const Type *T = NNS->getAsType();
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001137 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1138 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1139 if (const TagType *Tag = dyn_cast<TagType>(T))
1140 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1141 if (const TemplateSpecializationType *TST
1142 = dyn_cast<TemplateSpecializationType>(T))
1143 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1144 break;
1145 }
1146
1147 case NestedNameSpecifier::TypeSpecWithTemplate:
1148 case NestedNameSpecifier::Global:
1149 case NestedNameSpecifier::Identifier:
1150 break;
1151 }
1152
1153 return false;
1154}
1155
Douglas Gregordc355712011-02-25 00:36:19 +00001156bool
1157CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001158 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
Douglas Gregordc355712011-02-25 00:36:19 +00001159 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1160 Qualifiers.push_back(Qualifier);
1161
1162 while (!Qualifiers.empty()) {
1163 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1164 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1165 switch (NNS->getKind()) {
1166 case NestedNameSpecifier::Namespace:
1167 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001168 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001169 TU)))
1170 return true;
1171
1172 break;
1173
1174 case NestedNameSpecifier::NamespaceAlias:
1175 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001176 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001177 TU)))
1178 return true;
1179
1180 break;
1181
1182 case NestedNameSpecifier::TypeSpec:
1183 case NestedNameSpecifier::TypeSpecWithTemplate:
1184 if (Visit(Q.getTypeLoc()))
1185 return true;
1186
1187 break;
1188
1189 case NestedNameSpecifier::Global:
1190 case NestedNameSpecifier::Identifier:
1191 break;
1192 }
1193 }
1194
1195 return false;
1196}
1197
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001198bool CursorVisitor::VisitTemplateParameters(
1199 const TemplateParameterList *Params) {
1200 if (!Params)
1201 return false;
1202
1203 for (TemplateParameterList::const_iterator P = Params->begin(),
1204 PEnd = Params->end();
1205 P != PEnd; ++P) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001206 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001207 return true;
1208 }
1209
1210 return false;
1211}
1212
Douglas Gregor0b36e612010-08-31 20:37:03 +00001213bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1214 switch (Name.getKind()) {
1215 case TemplateName::Template:
1216 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1217
1218 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001219 // Visit the overloaded template set.
1220 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1221 return true;
1222
Douglas Gregor0b36e612010-08-31 20:37:03 +00001223 return false;
1224
1225 case TemplateName::DependentTemplate:
1226 // FIXME: Visit nested-name-specifier.
1227 return false;
1228
1229 case TemplateName::QualifiedTemplate:
1230 // FIXME: Visit nested-name-specifier.
1231 return Visit(MakeCursorTemplateRef(
1232 Name.getAsQualifiedTemplateName()->getDecl(),
1233 Loc, TU));
John McCall14606042011-06-30 08:33:18 +00001234
1235 case TemplateName::SubstTemplateTemplateParm:
1236 return Visit(MakeCursorTemplateRef(
1237 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1238 Loc, TU));
Douglas Gregor1aee05d2011-01-15 06:45:20 +00001239
1240 case TemplateName::SubstTemplateTemplateParmPack:
1241 return Visit(MakeCursorTemplateRef(
1242 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1243 Loc, TU));
Douglas Gregor0b36e612010-08-31 20:37:03 +00001244 }
1245
1246 return false;
1247}
1248
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001249bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1250 switch (TAL.getArgument().getKind()) {
1251 case TemplateArgument::Null:
1252 case TemplateArgument::Integral:
Douglas Gregor87dd6972010-12-20 16:52:59 +00001253 case TemplateArgument::Pack:
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001254 return false;
1255
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001256 case TemplateArgument::Type:
1257 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1258 return Visit(TSInfo->getTypeLoc());
1259 return false;
1260
1261 case TemplateArgument::Declaration:
1262 if (Expr *E = TAL.getSourceDeclExpression())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001263 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001264 return false;
1265
1266 case TemplateArgument::Expression:
1267 if (Expr *E = TAL.getSourceExpression())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001268 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001269 return false;
1270
1271 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001272 case TemplateArgument::TemplateExpansion:
Douglas Gregorb6744ef2011-03-02 17:09:35 +00001273 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1274 return true;
1275
Douglas Gregora7fc9012011-01-05 18:58:31 +00001276 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
Douglas Gregor0b36e612010-08-31 20:37:03 +00001277 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001278 }
1279
1280 return false;
1281}
1282
Ted Kremeneka0536d82010-05-07 01:04:29 +00001283bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1284 return VisitDeclContext(D);
1285}
1286
Douglas Gregor01829d32010-08-31 14:41:23 +00001287bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1288 return Visit(TL.getUnqualifiedLoc());
1289}
1290
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001291bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00001292 ASTContext &Context = AU->getASTContext();
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001293
1294 // Some builtin types (such as Objective-C's "id", "sel", and
1295 // "Class") have associated declarations. Create cursors for those.
1296 QualType VisitType;
John McCalle0a22d02011-10-18 21:02:43 +00001297 switch (TL.getTypePtr()->getKind()) {
John McCall2dde35b2011-10-18 22:28:37 +00001298
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001299 case BuiltinType::Void:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001300 case BuiltinType::NullPtr:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001301 case BuiltinType::Dependent:
John McCall2dde35b2011-10-18 22:28:37 +00001302#define BUILTIN_TYPE(Id, SingletonId)
1303#define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1304#define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1305#define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
1306#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
1307#include "clang/AST/BuiltinTypes.def"
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001308 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001309
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001310 case BuiltinType::ObjCId:
1311 VisitType = Context.getObjCIdType();
1312 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001313
1314 case BuiltinType::ObjCClass:
1315 VisitType = Context.getObjCClassType();
1316 break;
1317
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001318 case BuiltinType::ObjCSel:
1319 VisitType = Context.getObjCSelType();
1320 break;
1321 }
1322
1323 if (!VisitType.isNull()) {
1324 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001325 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001326 TU));
1327 }
1328
1329 return false;
1330}
1331
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001332bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
Richard Smith162e1c12011-04-15 14:24:37 +00001333 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001334}
1335
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001336bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1337 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1338}
1339
1340bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
Argyrios Kyrtzidis6f155de2011-08-25 22:24:47 +00001341 if (TL.isDefinition())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001342 return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
Argyrios Kyrtzidis6f155de2011-08-25 22:24:47 +00001343
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001344 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1345}
1346
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001347bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Chandler Carruth960d13d2011-05-01 09:53:37 +00001348 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001349}
1350
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001351bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1352 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1353 return true;
1354
John McCallc12c5bb2010-05-15 11:32:37 +00001355 return false;
1356}
1357
1358bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1359 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1360 return true;
1361
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001362 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1363 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1364 TU)))
1365 return true;
1366 }
1367
1368 return false;
1369}
1370
1371bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001372 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001373}
1374
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001375bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1376 return Visit(TL.getInnerLoc());
1377}
1378
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001379bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1380 return Visit(TL.getPointeeLoc());
1381}
1382
1383bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1384 return Visit(TL.getPointeeLoc());
1385}
1386
1387bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1388 return Visit(TL.getPointeeLoc());
1389}
1390
1391bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001392 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001393}
1394
1395bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001396 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001397}
1398
Argyrios Kyrtzidis3422fbc2011-08-15 18:44:43 +00001399bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1400 return Visit(TL.getModifiedLoc());
1401}
1402
Douglas Gregor01829d32010-08-31 14:41:23 +00001403bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1404 bool SkipResultType) {
1405 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001406 return true;
1407
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001408 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001409 if (Decl *D = TL.getArg(I))
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001410 if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001411 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001412
1413 return false;
1414}
1415
1416bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1417 if (Visit(TL.getElementLoc()))
1418 return true;
1419
1420 if (Expr *Size = TL.getSizeExpr())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001421 return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001422
1423 return false;
1424}
1425
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001426bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1427 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001428 // Visit the template name.
1429 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1430 TL.getTemplateNameLoc()))
1431 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001432
1433 // Visit the template arguments.
1434 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1435 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1436 return true;
1437
1438 return false;
1439}
1440
Douglas Gregor2332c112010-01-21 20:48:56 +00001441bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1442 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1443}
1444
1445bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1446 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1447 return Visit(TSInfo->getTypeLoc());
1448
1449 return false;
1450}
1451
Sean Huntca63c202011-05-24 22:41:36 +00001452bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1453 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1454 return Visit(TSInfo->getTypeLoc());
1455
1456 return false;
1457}
1458
Douglas Gregor2494dd02011-03-01 01:34:45 +00001459bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
1460 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1461 return true;
1462
1463 return false;
1464}
1465
Douglas Gregor94fdffa2011-03-01 20:11:18 +00001466bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1467 DependentTemplateSpecializationTypeLoc TL) {
1468 // Visit the nested-name-specifier, if there is one.
1469 if (TL.getQualifierLoc() &&
1470 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1471 return true;
1472
1473 // Visit the template arguments.
1474 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1475 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1476 return true;
1477
1478 return false;
1479}
1480
Douglas Gregor9e876872011-03-01 18:12:44 +00001481bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1482 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1483 return true;
1484
1485 return Visit(TL.getNamedTypeLoc());
1486}
1487
Douglas Gregor7536dd52010-12-20 02:24:11 +00001488bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1489 return Visit(TL.getPatternLoc());
1490}
1491
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +00001492bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1493 if (Expr *E = TL.getUnderlyingExpr())
1494 return Visit(MakeCXCursor(E, StmtParent, TU));
1495
1496 return false;
1497}
1498
1499bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1500 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1501}
1502
Eli Friedmanb001de72011-10-06 23:00:33 +00001503bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1504 return Visit(TL.getValueLoc());
1505}
1506
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +00001507#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1508bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1509 return Visit##PARENT##Loc(TL); \
1510}
1511
1512DEFAULT_TYPELOC_IMPL(Complex, Type)
1513DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1514DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1515DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1516DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
1517DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1518DEFAULT_TYPELOC_IMPL(Vector, Type)
1519DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1520DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1521DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1522DEFAULT_TYPELOC_IMPL(Record, TagType)
1523DEFAULT_TYPELOC_IMPL(Enum, TagType)
1524DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1525DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1526DEFAULT_TYPELOC_IMPL(Auto, Type)
1527
Ted Kremenek3064ef92010-08-27 21:34:58 +00001528bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001529 // Visit the nested-name-specifier, if present.
1530 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1531 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1532 return true;
1533
John McCall5e1cdac2011-10-07 06:10:15 +00001534 if (D->isCompleteDefinition()) {
Ted Kremenek3064ef92010-08-27 21:34:58 +00001535 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1536 E = D->bases_end(); I != E; ++I) {
1537 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1538 return true;
1539 }
1540 }
1541
1542 return VisitTagDecl(D);
1543}
1544
Ted Kremenek09dfa372010-02-18 05:46:33 +00001545bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001546 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1547 i != e; ++i)
1548 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001549 return true;
1550
1551 return false;
1552}
1553
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001554//===----------------------------------------------------------------------===//
1555// Data-recursive visitor methods.
1556//===----------------------------------------------------------------------===//
1557
Ted Kremenek28a71942010-11-13 00:36:47 +00001558namespace {
Ted Kremenek035dc412010-11-13 00:36:50 +00001559#define DEF_JOB(NAME, DATA, KIND)\
1560class NAME : public VisitorJob {\
1561public:\
1562 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1563 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Ted Kremenekf64d8032010-11-18 00:02:32 +00001564 DATA *get() const { return static_cast<DATA*>(data[0]); }\
Ted Kremenek035dc412010-11-13 00:36:50 +00001565};
1566
1567DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1568DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001569DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001570DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001571DEF_JOB(ExplicitTemplateArgsVisit, ASTTemplateArgumentListInfo,
Ted Kremenek60608ec2010-11-17 00:50:47 +00001572 ExplicitTemplateArgsVisitKind)
Douglas Gregor94d96292011-01-19 20:34:17 +00001573DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001574#undef DEF_JOB
1575
1576class DeclVisit : public VisitorJob {
1577public:
1578 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1579 VisitorJob(parent, VisitorJob::DeclVisitKind,
1580 d, isFirst ? (void*) 1 : (void*) 0) {}
1581 static bool classof(const VisitorJob *VJ) {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001582 return VJ->getKind() == DeclVisitKind;
Ted Kremenek035dc412010-11-13 00:36:50 +00001583 }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001584 Decl *get() const { return static_cast<Decl*>(data[0]); }
1585 bool isFirst() const { return data[1] ? true : false; }
Ted Kremenek035dc412010-11-13 00:36:50 +00001586};
Ted Kremenek035dc412010-11-13 00:36:50 +00001587class TypeLocVisit : public VisitorJob {
1588public:
1589 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1590 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1591 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1592
1593 static bool classof(const VisitorJob *VJ) {
1594 return VJ->getKind() == TypeLocVisitKind;
1595 }
1596
Ted Kremenek82f3c502010-11-15 22:23:26 +00001597 TypeLoc get() const {
Ted Kremenekf64d8032010-11-18 00:02:32 +00001598 QualType T = QualType::getFromOpaquePtr(data[0]);
1599 return TypeLoc(T, data[1]);
Ted Kremenek035dc412010-11-13 00:36:50 +00001600 }
1601};
1602
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001603class LabelRefVisit : public VisitorJob {
1604public:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001605 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1606 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001607 labelLoc.getPtrEncoding()) {}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001608
1609 static bool classof(const VisitorJob *VJ) {
1610 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1611 }
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001612 LabelDecl *get() const { return static_cast<LabelDecl*>(data[0]); }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001613 SourceLocation getLoc() const {
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001614 return SourceLocation::getFromPtrEncoding(data[1]); }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001615};
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001616
1617class NestedNameSpecifierLocVisit : public VisitorJob {
1618public:
1619 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1620 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1621 Qualifier.getNestedNameSpecifier(),
1622 Qualifier.getOpaqueData()) { }
1623
1624 static bool classof(const VisitorJob *VJ) {
1625 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1626 }
1627
1628 NestedNameSpecifierLoc get() const {
1629 return NestedNameSpecifierLoc(static_cast<NestedNameSpecifier*>(data[0]),
1630 data[1]);
1631 }
1632};
1633
Ted Kremenekf64d8032010-11-18 00:02:32 +00001634class DeclarationNameInfoVisit : public VisitorJob {
1635public:
1636 DeclarationNameInfoVisit(Stmt *S, CXCursor parent)
1637 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
1638 static bool classof(const VisitorJob *VJ) {
1639 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1640 }
1641 DeclarationNameInfo get() const {
1642 Stmt *S = static_cast<Stmt*>(data[0]);
1643 switch (S->getStmtClass()) {
1644 default:
1645 llvm_unreachable("Unhandled Stmt");
Douglas Gregorba0513d2011-10-25 01:33:02 +00001646 case clang::Stmt::MSDependentExistsStmtClass:
1647 return cast<MSDependentExistsStmt>(S)->getNameInfo();
Ted Kremenekf64d8032010-11-18 00:02:32 +00001648 case Stmt::CXXDependentScopeMemberExprClass:
1649 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1650 case Stmt::DependentScopeDeclRefExprClass:
1651 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
1652 }
1653 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001654};
Ted Kremenekcdba6592010-11-18 00:42:18 +00001655class MemberRefVisit : public VisitorJob {
1656public:
1657 MemberRefVisit(FieldDecl *D, SourceLocation L, CXCursor parent)
1658 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001659 L.getPtrEncoding()) {}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001660 static bool classof(const VisitorJob *VJ) {
1661 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1662 }
1663 FieldDecl *get() const {
1664 return static_cast<FieldDecl*>(data[0]);
1665 }
1666 SourceLocation getLoc() const {
1667 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1668 }
1669};
Ted Kremenek28a71942010-11-13 00:36:47 +00001670class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1671 VisitorWorkList &WL;
1672 CXCursor Parent;
1673public:
1674 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1675 : WL(wl), Parent(parent) {}
1676
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001677 void VisitAddrLabelExpr(AddrLabelExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001678 void VisitBlockExpr(BlockExpr *B);
Ted Kremenek28a71942010-11-13 00:36:47 +00001679 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek083c7e22010-11-13 05:38:03 +00001680 void VisitCompoundStmt(CompoundStmt *S);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001681 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
Douglas Gregorba0513d2011-10-25 01:33:02 +00001682 void VisitMSDependentExistsStmt(MSDependentExistsStmt *S);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001683 void VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001684 void VisitCXXNewExpr(CXXNewExpr *E);
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001685 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001686 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001687 void VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001688 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001689 void VisitCXXTypeidExpr(CXXTypeidExpr *E);
Ted Kremenek55b933a2010-11-17 00:50:36 +00001690 void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001691 void VisitCXXUuidofExpr(CXXUuidofExpr *E);
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001692 void VisitDeclRefExpr(DeclRefExpr *D);
Ted Kremenek035dc412010-11-13 00:36:50 +00001693 void VisitDeclStmt(DeclStmt *S);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001694 void VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001695 void VisitDesignatedInitExpr(DesignatedInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001696 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1697 void VisitForStmt(ForStmt *FS);
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001698 void VisitGotoStmt(GotoStmt *GS);
Ted Kremenek28a71942010-11-13 00:36:47 +00001699 void VisitIfStmt(IfStmt *If);
1700 void VisitInitListExpr(InitListExpr *IE);
1701 void VisitMemberExpr(MemberExpr *M);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001702 void VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001703 void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001704 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1705 void VisitOverloadExpr(OverloadExpr *E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001706 void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001707 void VisitStmt(Stmt *S);
1708 void VisitSwitchStmt(SwitchStmt *S);
1709 void VisitWhileStmt(WhileStmt *W);
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001710 void VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Francois Pichet6ad6f282010-12-07 00:08:36 +00001711 void VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E);
John Wiegley21ff2e52011-04-28 00:16:57 +00001712 void VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E);
John Wiegley55262202011-04-25 06:54:41 +00001713 void VisitExpressionTraitExpr(ExpressionTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001714 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001715 void VisitVAArgExpr(VAArgExpr *E);
Douglas Gregor94d96292011-01-19 20:34:17 +00001716 void VisitSizeOfPackExpr(SizeOfPackExpr *E);
John McCall4b9c2d22011-11-06 09:01:30 +00001717 void VisitPseudoObjectExpr(PseudoObjectExpr *E);
1718 void VisitOpaqueValueExpr(OpaqueValueExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00001719
Ted Kremenek28a71942010-11-13 00:36:47 +00001720private:
Ted Kremenekf64d8032010-11-18 00:02:32 +00001721 void AddDeclarationNameInfo(Stmt *S);
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001722 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001723 void AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001724 void AddMemberRef(FieldDecl *D, SourceLocation L);
Ted Kremenek28a71942010-11-13 00:36:47 +00001725 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001726 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001727 void AddTypeLoc(TypeSourceInfo *TI);
1728 void EnqueueChildren(Stmt *S);
1729};
1730} // end anonyous namespace
1731
Ted Kremenekf64d8032010-11-18 00:02:32 +00001732void EnqueueVisitor::AddDeclarationNameInfo(Stmt *S) {
1733 // 'S' should always be non-null, since it comes from the
1734 // statement we are visiting.
1735 WL.push_back(DeclarationNameInfoVisit(S, Parent));
1736}
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001737
1738void
1739EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1740 if (Qualifier)
1741 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
1742}
1743
Ted Kremenek28a71942010-11-13 00:36:47 +00001744void EnqueueVisitor::AddStmt(Stmt *S) {
1745 if (S)
1746 WL.push_back(StmtVisit(S, Parent));
1747}
Ted Kremenek035dc412010-11-13 00:36:50 +00001748void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001749 if (D)
Ted Kremenek035dc412010-11-13 00:36:50 +00001750 WL.push_back(DeclVisit(D, Parent, isFirst));
Ted Kremenek28a71942010-11-13 00:36:47 +00001751}
Ted Kremenek60608ec2010-11-17 00:50:47 +00001752void EnqueueVisitor::
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001753 AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001754 if (A)
1755 WL.push_back(ExplicitTemplateArgsVisit(
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001756 const_cast<ASTTemplateArgumentListInfo*>(A), Parent));
Ted Kremenek60608ec2010-11-17 00:50:47 +00001757}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001758void EnqueueVisitor::AddMemberRef(FieldDecl *D, SourceLocation L) {
1759 if (D)
1760 WL.push_back(MemberRefVisit(D, L, Parent));
1761}
Ted Kremenek28a71942010-11-13 00:36:47 +00001762void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1763 if (TI)
1764 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1765 }
1766void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001767 unsigned size = WL.size();
John McCall7502c1d2011-02-13 04:07:26 +00001768 for (Stmt::child_range Child = S->children(); Child; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001769 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001770 }
1771 if (size == WL.size())
1772 return;
1773 // Now reverse the entries we just added. This will match the DFS
1774 // ordering performed by the worklist.
1775 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1776 std::reverse(I, E);
1777}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001778void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1779 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
1780}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001781void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1782 AddDecl(B->getBlockDecl());
1783}
Ted Kremenek28a71942010-11-13 00:36:47 +00001784void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1785 EnqueueChildren(E);
1786 AddTypeLoc(E->getTypeSourceInfo());
1787}
Ted Kremenek083c7e22010-11-13 05:38:03 +00001788void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1789 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1790 E = S->body_rend(); I != E; ++I) {
1791 AddStmt(*I);
1792 }
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001793}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001794void EnqueueVisitor::
Douglas Gregorba0513d2011-10-25 01:33:02 +00001795VisitMSDependentExistsStmt(MSDependentExistsStmt *S) {
1796 AddStmt(S->getSubStmt());
1797 AddDeclarationNameInfo(S);
1798 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
1799 AddNestedNameSpecifierLoc(QualifierLoc);
1800}
1801
1802void EnqueueVisitor::
Ted Kremenekf64d8032010-11-18 00:02:32 +00001803VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
1804 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1805 AddDeclarationNameInfo(E);
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001806 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1807 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001808 if (!E->isImplicitAccess())
1809 AddStmt(E->getBase());
1810}
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001811void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1812 // Enqueue the initializer or constructor arguments.
1813 for (unsigned I = E->getNumConstructorArgs(); I > 0; --I)
1814 AddStmt(E->getConstructorArg(I-1));
1815 // Enqueue the array size, if any.
1816 AddStmt(E->getArraySize());
1817 // Enqueue the allocated type.
1818 AddTypeLoc(E->getAllocatedTypeSourceInfo());
1819 // Enqueue the placement arguments.
1820 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1821 AddStmt(E->getPlacementArg(I-1));
1822}
Ted Kremenek28a71942010-11-13 00:36:47 +00001823void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
Ted Kremenek8b8d8c92010-11-13 05:55:56 +00001824 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1825 AddStmt(CE->getArg(I-1));
Ted Kremenek28a71942010-11-13 00:36:47 +00001826 AddStmt(CE->getCallee());
1827 AddStmt(CE->getArg(0));
1828}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001829void EnqueueVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1830 // Visit the name of the type being destroyed.
1831 AddTypeLoc(E->getDestroyedTypeInfo());
1832 // Visit the scope type that looks disturbingly like the nested-name-specifier
1833 // but isn't.
1834 AddTypeLoc(E->getScopeTypeInfo());
1835 // Visit the nested-name-specifier.
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001836 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1837 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001838 // Visit base expression.
1839 AddStmt(E->getBase());
1840}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001841void EnqueueVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1842 AddTypeLoc(E->getTypeSourceInfo());
1843}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001844void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1845 EnqueueChildren(E);
1846 AddTypeLoc(E->getTypeSourceInfo());
1847}
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001848void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1849 EnqueueChildren(E);
1850 if (E->isTypeOperand())
1851 AddTypeLoc(E->getTypeOperandSourceInfo());
1852}
Ted Kremenek55b933a2010-11-17 00:50:36 +00001853
1854void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
1855 *E) {
1856 EnqueueChildren(E);
1857 AddTypeLoc(E->getTypeSourceInfo());
1858}
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001859void EnqueueVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1860 EnqueueChildren(E);
1861 if (E->isTypeOperand())
1862 AddTypeLoc(E->getTypeOperandSourceInfo());
1863}
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001864void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001865 if (DR->hasExplicitTemplateArgs()) {
1866 AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
1867 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001868 WL.push_back(DeclRefExprParts(DR, Parent));
1869}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001870void EnqueueVisitor::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
1871 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1872 AddDeclarationNameInfo(E);
Douglas Gregor00cf3cc2011-02-25 20:49:16 +00001873 AddNestedNameSpecifierLoc(E->getQualifierLoc());
Ted Kremenekf64d8032010-11-18 00:02:32 +00001874}
Ted Kremenek035dc412010-11-13 00:36:50 +00001875void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1876 unsigned size = WL.size();
1877 bool isFirst = true;
1878 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1879 D != DEnd; ++D) {
1880 AddDecl(*D, isFirst);
1881 isFirst = false;
1882 }
1883 if (size == WL.size())
1884 return;
1885 // Now reverse the entries we just added. This will match the DFS
1886 // ordering performed by the worklist.
1887 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1888 std::reverse(I, E);
1889}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001890void EnqueueVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1891 AddStmt(E->getInit());
1892 typedef DesignatedInitExpr::Designator Designator;
1893 for (DesignatedInitExpr::reverse_designators_iterator
1894 D = E->designators_rbegin(), DEnd = E->designators_rend();
1895 D != DEnd; ++D) {
1896 if (D->isFieldDesignator()) {
1897 if (FieldDecl *Field = D->getField())
1898 AddMemberRef(Field, D->getFieldLoc());
1899 continue;
1900 }
1901 if (D->isArrayDesignator()) {
1902 AddStmt(E->getArrayIndex(*D));
1903 continue;
1904 }
1905 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1906 AddStmt(E->getArrayRangeEnd(*D));
1907 AddStmt(E->getArrayRangeStart(*D));
1908 }
1909}
Ted Kremenek28a71942010-11-13 00:36:47 +00001910void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1911 EnqueueChildren(E);
1912 AddTypeLoc(E->getTypeInfoAsWritten());
1913}
1914void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1915 AddStmt(FS->getBody());
1916 AddStmt(FS->getInc());
1917 AddStmt(FS->getCond());
1918 AddDecl(FS->getConditionVariable());
1919 AddStmt(FS->getInit());
1920}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001921void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) {
1922 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
1923}
Ted Kremenek28a71942010-11-13 00:36:47 +00001924void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
1925 AddStmt(If->getElse());
1926 AddStmt(If->getThen());
1927 AddStmt(If->getCond());
1928 AddDecl(If->getConditionVariable());
1929}
1930void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
1931 // We care about the syntactic form of the initializer list, only.
1932 if (InitListExpr *Syntactic = IE->getSyntacticForm())
1933 IE = Syntactic;
1934 EnqueueChildren(IE);
1935}
1936void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
Douglas Gregor89629a72010-11-17 17:15:08 +00001937 WL.push_back(MemberExprParts(M, Parent));
1938
1939 // If the base of the member access expression is an implicit 'this', don't
1940 // visit it.
1941 // FIXME: If we ever want to show these implicit accesses, this will be
1942 // unfortunate. However, clang_getCursor() relies on this behavior.
Douglas Gregor75e85042011-03-02 21:06:53 +00001943 if (!M->isImplicitAccess())
1944 AddStmt(M->getBase());
Ted Kremenek28a71942010-11-13 00:36:47 +00001945}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001946void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1947 AddTypeLoc(E->getEncodedTypeSourceInfo());
1948}
Ted Kremenek28a71942010-11-13 00:36:47 +00001949void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
1950 EnqueueChildren(M);
1951 AddTypeLoc(M->getClassReceiverTypeInfo());
1952}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001953void EnqueueVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
1954 // Visit the components of the offsetof expression.
1955 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
1956 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
1957 const OffsetOfNode &Node = E->getComponent(I-1);
1958 switch (Node.getKind()) {
1959 case OffsetOfNode::Array:
1960 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
1961 break;
1962 case OffsetOfNode::Field:
Abramo Bagnara06dec892011-03-12 09:45:03 +00001963 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
Ted Kremenekcdba6592010-11-18 00:42:18 +00001964 break;
1965 case OffsetOfNode::Identifier:
1966 case OffsetOfNode::Base:
1967 continue;
1968 }
1969 }
1970 // Visit the type into which we're computing the offset.
1971 AddTypeLoc(E->getTypeSourceInfo());
1972}
Ted Kremenek28a71942010-11-13 00:36:47 +00001973void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001974 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
Ted Kremenek60458782010-11-12 21:34:16 +00001975 WL.push_back(OverloadExprParts(E, Parent));
1976}
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001977void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
1978 UnaryExprOrTypeTraitExpr *E) {
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001979 EnqueueChildren(E);
1980 if (E->isArgumentType())
1981 AddTypeLoc(E->getArgumentTypeInfo());
1982}
Ted Kremenek28a71942010-11-13 00:36:47 +00001983void EnqueueVisitor::VisitStmt(Stmt *S) {
1984 EnqueueChildren(S);
1985}
1986void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
1987 AddStmt(S->getBody());
1988 AddStmt(S->getCond());
1989 AddDecl(S->getConditionVariable());
1990}
Ted Kremenekfafa75a2010-11-17 00:50:39 +00001991
Ted Kremenek28a71942010-11-13 00:36:47 +00001992void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
1993 AddStmt(W->getBody());
1994 AddStmt(W->getCond());
1995 AddDecl(W->getConditionVariable());
1996}
John Wiegley21ff2e52011-04-28 00:16:57 +00001997
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001998void EnqueueVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
1999 AddTypeLoc(E->getQueriedTypeSourceInfo());
2000}
Francois Pichet6ad6f282010-12-07 00:08:36 +00002001
2002void EnqueueVisitor::VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
Francois Pichet6ad6f282010-12-07 00:08:36 +00002003 AddTypeLoc(E->getRhsTypeSourceInfo());
Francois Pichet0a03a3f2010-12-08 09:11:05 +00002004 AddTypeLoc(E->getLhsTypeSourceInfo());
Francois Pichet6ad6f282010-12-07 00:08:36 +00002005}
2006
John Wiegley21ff2e52011-04-28 00:16:57 +00002007void EnqueueVisitor::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
2008 AddTypeLoc(E->getQueriedTypeSourceInfo());
2009}
2010
John Wiegley55262202011-04-25 06:54:41 +00002011void EnqueueVisitor::VisitExpressionTraitExpr(ExpressionTraitExpr *E) {
2012 EnqueueChildren(E);
2013}
2014
Ted Kremenek28a71942010-11-13 00:36:47 +00002015void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
2016 VisitOverloadExpr(U);
2017 if (!U->isImplicitAccess())
2018 AddStmt(U->getBase());
2019}
Ted Kremenek9d3bf792010-11-17 00:50:43 +00002020void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) {
2021 AddStmt(E->getSubExpr());
2022 AddTypeLoc(E->getWrittenTypeInfo());
2023}
Douglas Gregor94d96292011-01-19 20:34:17 +00002024void EnqueueVisitor::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
2025 WL.push_back(SizeOfPackExprParts(E, Parent));
2026}
John McCall4b9c2d22011-11-06 09:01:30 +00002027void EnqueueVisitor::VisitOpaqueValueExpr(OpaqueValueExpr *E) {
2028 // If the opaque value has a source expression, just transparently
2029 // visit that. This is useful for (e.g.) pseudo-object expressions.
2030 if (Expr *SourceExpr = E->getSourceExpr())
2031 return Visit(SourceExpr);
2032 AddStmt(E);
2033}
2034void EnqueueVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *E) {
2035 // Treat the expression like its syntactic form.
2036 Visit(E->getSyntacticForm());
2037}
Ted Kremenek60458782010-11-12 21:34:16 +00002038
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002039void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002040 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002041}
2042
2043bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2044 if (RegionOfInterest.isValid()) {
2045 SourceRange Range = getRawCursorExtent(C);
2046 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2047 return false;
2048 }
2049 return true;
2050}
2051
2052bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2053 while (!WL.empty()) {
2054 // Dequeue the worklist item.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002055 VisitorJob LI = WL.back();
2056 WL.pop_back();
2057
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002058 // Set the Parent field, then back to its old value once we're done.
2059 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2060
2061 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00002062 case VisitorJob::DeclVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002063 Decl *D = cast<DeclVisit>(&LI)->get();
Ted Kremenekf1107452010-11-12 18:26:56 +00002064 if (!D)
2065 continue;
2066
2067 // For now, perform default visitation for Decls.
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002068 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2069 cast<DeclVisit>(&LI)->isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00002070 return true;
2071
2072 continue;
2073 }
Ted Kremenek60608ec2010-11-17 00:50:47 +00002074 case VisitorJob::ExplicitTemplateArgsVisitKind: {
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00002075 const ASTTemplateArgumentListInfo *ArgList =
Ted Kremenek60608ec2010-11-17 00:50:47 +00002076 cast<ExplicitTemplateArgsVisit>(&LI)->get();
2077 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2078 *ArgEnd = Arg + ArgList->NumTemplateArgs;
2079 Arg != ArgEnd; ++Arg) {
2080 if (VisitTemplateArgumentLoc(*Arg))
2081 return true;
2082 }
2083 continue;
2084 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002085 case VisitorJob::TypeLocVisitKind: {
2086 // Perform default visitation for TypeLocs.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002087 if (Visit(cast<TypeLocVisit>(&LI)->get()))
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002088 return true;
2089 continue;
2090 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002091 case VisitorJob::LabelRefVisitKind: {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002092 LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Ted Kremeneke7455012011-02-23 04:54:51 +00002093 if (LabelStmt *stmt = LS->getStmt()) {
2094 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2095 TU))) {
2096 return true;
2097 }
2098 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002099 continue;
2100 }
Ted Kremenek47695c82011-08-18 22:25:21 +00002101
Douglas Gregorf3db29f2011-02-25 18:19:59 +00002102 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2103 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2104 if (VisitNestedNameSpecifierLoc(V->get()))
2105 return true;
2106 continue;
2107 }
2108
Ted Kremenekf64d8032010-11-18 00:02:32 +00002109 case VisitorJob::DeclarationNameInfoVisitKind: {
2110 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2111 ->get()))
2112 return true;
2113 continue;
2114 }
Ted Kremenekcdba6592010-11-18 00:42:18 +00002115 case VisitorJob::MemberRefVisitKind: {
2116 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2117 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2118 return true;
2119 continue;
2120 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002121 case VisitorJob::StmtVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002122 Stmt *S = cast<StmtVisit>(&LI)->get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00002123 if (!S)
2124 continue;
2125
Ted Kremenekf1107452010-11-12 18:26:56 +00002126 // Update the current cursor.
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002127 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
Ted Kremenekcdba6592010-11-18 00:42:18 +00002128 if (!IsInRegionOfInterest(Cursor))
2129 continue;
2130 switch (Visitor(Cursor, Parent, ClientData)) {
2131 case CXChildVisit_Break: return true;
2132 case CXChildVisit_Continue: break;
2133 case CXChildVisit_Recurse:
2134 EnqueueWorkList(WL, S);
Ted Kremenek82f3c502010-11-15 22:23:26 +00002135 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002136 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00002137 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002138 }
2139 case VisitorJob::MemberExprPartsKind: {
2140 // Handle the other pieces in the MemberExpr besides the base.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002141 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002142
2143 // Visit the nested-name-specifier
Douglas Gregor40d96a62011-02-28 21:54:11 +00002144 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
2145 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002146 return true;
2147
2148 // Visit the declaration name.
2149 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2150 return true;
2151
2152 // Visit the explicitly-specified template arguments, if any.
2153 if (M->hasExplicitTemplateArgs()) {
2154 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2155 *ArgEnd = Arg + M->getNumTemplateArgs();
2156 Arg != ArgEnd; ++Arg) {
2157 if (VisitTemplateArgumentLoc(*Arg))
2158 return true;
2159 }
2160 }
2161 continue;
2162 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002163 case VisitorJob::DeclRefExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002164 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002165 // Visit nested-name-specifier, if present.
Douglas Gregor40d96a62011-02-28 21:54:11 +00002166 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
2167 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002168 return true;
2169 // Visit declaration name.
2170 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2171 return true;
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002172 continue;
2173 }
Ted Kremenek60458782010-11-12 21:34:16 +00002174 case VisitorJob::OverloadExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002175 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Ted Kremenek60458782010-11-12 21:34:16 +00002176 // Visit the nested-name-specifier.
Douglas Gregor4c9be892011-02-28 20:01:57 +00002177 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
2178 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenek60458782010-11-12 21:34:16 +00002179 return true;
2180 // Visit the declaration name.
2181 if (VisitDeclarationNameInfo(O->getNameInfo()))
2182 return true;
2183 // Visit the overloaded declaration reference.
2184 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2185 return true;
Ted Kremenek60458782010-11-12 21:34:16 +00002186 continue;
2187 }
Douglas Gregor94d96292011-01-19 20:34:17 +00002188 case VisitorJob::SizeOfPackExprPartsKind: {
2189 SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
2190 NamedDecl *Pack = E->getPack();
2191 if (isa<TemplateTypeParmDecl>(Pack)) {
2192 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
2193 E->getPackLoc(), TU)))
2194 return true;
2195
2196 continue;
2197 }
2198
2199 if (isa<TemplateTemplateParmDecl>(Pack)) {
2200 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
2201 E->getPackLoc(), TU)))
2202 return true;
2203
2204 continue;
2205 }
2206
2207 // Non-type template parameter packs and function parameter packs are
2208 // treated like DeclRefExpr cursors.
2209 continue;
2210 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002211 }
2212 }
2213 return false;
2214}
2215
Ted Kremenekcdba6592010-11-18 00:42:18 +00002216bool CursorVisitor::Visit(Stmt *S) {
Ted Kremenekd1ded662010-11-15 23:31:32 +00002217 VisitorWorkList *WL = 0;
2218 if (!WorkListFreeList.empty()) {
2219 WL = WorkListFreeList.back();
2220 WL->clear();
2221 WorkListFreeList.pop_back();
2222 }
2223 else {
2224 WL = new VisitorWorkList();
2225 WorkListCache.push_back(WL);
2226 }
2227 EnqueueWorkList(*WL, S);
2228 bool result = RunVisitorWorkList(*WL);
2229 WorkListFreeList.push_back(WL);
2230 return result;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002231}
2232
Francois Pichet48a8d142011-07-25 22:00:44 +00002233namespace {
2234typedef llvm::SmallVector<SourceRange, 4> RefNamePieces;
2235RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
2236 const DeclarationNameInfo &NI,
2237 const SourceRange &QLoc,
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00002238 const ASTTemplateArgumentListInfo *TemplateArgs = 0){
Francois Pichet48a8d142011-07-25 22:00:44 +00002239 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
2240 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
2241 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
2242
2243 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
2244
2245 RefNamePieces Pieces;
2246
2247 if (WantQualifier && QLoc.isValid())
2248 Pieces.push_back(QLoc);
2249
2250 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
2251 Pieces.push_back(NI.getLoc());
2252
2253 if (WantTemplateArgs && TemplateArgs)
2254 Pieces.push_back(SourceRange(TemplateArgs->LAngleLoc,
2255 TemplateArgs->RAngleLoc));
2256
2257 if (Kind == DeclarationName::CXXOperatorName) {
2258 Pieces.push_back(SourceLocation::getFromRawEncoding(
2259 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
2260 Pieces.push_back(SourceLocation::getFromRawEncoding(
2261 NI.getInfo().CXXOperatorName.EndOpNameLoc));
2262 }
2263
2264 if (WantSinglePiece) {
2265 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
2266 Pieces.clear();
2267 Pieces.push_back(R);
2268 }
2269
2270 return Pieces;
2271}
2272}
2273
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002274//===----------------------------------------------------------------------===//
2275// Misc. API hooks.
2276//===----------------------------------------------------------------------===//
2277
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002278static llvm::sys::Mutex EnableMultithreadingMutex;
2279static bool EnabledMultithreading;
2280
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002281extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002282CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2283 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002284 // Disable pretty stack trace functionality, which will otherwise be a very
2285 // poor citizen of the world and set up all sorts of signal handlers.
2286 llvm::DisablePrettyStackTrace = true;
2287
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002288 // We use crash recovery to make some of our APIs more reliable, implicitly
2289 // enable it.
2290 llvm::CrashRecoveryContext::Enable();
2291
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002292 // Enable support for multithreading in LLVM.
2293 {
2294 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2295 if (!EnabledMultithreading) {
2296 llvm::llvm_start_multithreaded();
2297 EnabledMultithreading = true;
2298 }
2299 }
2300
Douglas Gregora030b7c2010-01-22 20:35:53 +00002301 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002302 if (excludeDeclarationsFromPCH)
2303 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002304 if (displayDiagnostics)
2305 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002306 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002307}
2308
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002309void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002310 if (CIdx)
2311 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002312}
2313
Ted Kremenekd2427dd2011-03-18 23:05:39 +00002314void clang_toggleCrashRecovery(unsigned isEnabled) {
2315 if (isEnabled)
2316 llvm::CrashRecoveryContext::Enable();
2317 else
2318 llvm::CrashRecoveryContext::Disable();
2319}
2320
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002321CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002322 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002323 if (!CIdx)
2324 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002325
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002326 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002327 FileSystemOptions FileSystemOpts;
2328 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002329
David Blaikied6471f72011-09-25 23:23:43 +00002330 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002331 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002332 CXXIdx->getOnlyLocalDecls(),
2333 0, 0, true);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002334 return MakeCXTranslationUnit(TU);
Steve Naroff600866c2009-08-27 19:51:58 +00002335}
2336
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002337unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002338 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregorb5af8432011-08-25 22:54:01 +00002339 CXTranslationUnit_CacheCompletionResults;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002340}
2341
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002342CXTranslationUnit
2343clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2344 const char *source_filename,
2345 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002346 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002347 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002348 struct CXUnsavedFile *unsaved_files) {
Douglas Gregordca8ee82011-05-06 16:33:08 +00002349 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord |
Chandler Carruthba7537f2011-07-14 09:02:10 +00002350 CXTranslationUnit_NestedMacroExpansions;
Douglas Gregor5a430212010-07-21 18:52:53 +00002351 return clang_parseTranslationUnit(CIdx, source_filename,
2352 command_line_args, num_command_line_args,
2353 unsaved_files, num_unsaved_files,
Douglas Gregordca8ee82011-05-06 16:33:08 +00002354 Options);
Douglas Gregor5a430212010-07-21 18:52:53 +00002355}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002356
2357struct ParseTranslationUnitInfo {
2358 CXIndex CIdx;
2359 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002360 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002361 int num_command_line_args;
2362 struct CXUnsavedFile *unsaved_files;
2363 unsigned num_unsaved_files;
2364 unsigned options;
2365 CXTranslationUnit result;
2366};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002367static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002368 ParseTranslationUnitInfo *PTUI =
2369 static_cast<ParseTranslationUnitInfo*>(UserData);
2370 CXIndex CIdx = PTUI->CIdx;
2371 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002372 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002373 int num_command_line_args = PTUI->num_command_line_args;
2374 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2375 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2376 unsigned options = PTUI->options;
2377 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002378
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002379 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002380 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002381
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002382 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2383
Douglas Gregor44c181a2010-07-23 00:33:23 +00002384 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregor467dc882011-08-25 22:30:56 +00002385 // FIXME: Add a flag for modules.
2386 TranslationUnitKind TUKind
2387 = (options & CXTranslationUnit_Incomplete)? TU_Prefix : TU_Complete;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002388 bool CacheCodeCompetionResults
2389 = options & CXTranslationUnit_CacheCompletionResults;
2390
Douglas Gregor5352ac02010-01-28 00:27:43 +00002391 // Configure the diagnostics.
2392 DiagnosticOptions DiagOpts;
David Blaikied6471f72011-09-25 23:23:43 +00002393 llvm::IntrusiveRefCntPtr<DiagnosticsEngine>
Ted Kremenek25a11e12011-03-22 01:15:24 +00002394 Diags(CompilerInstance::createDiagnostics(DiagOpts, num_command_line_args,
2395 command_line_args));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002396
Ted Kremenek25a11e12011-03-22 01:15:24 +00002397 // Recover resources if we crash before exiting this function.
David Blaikied6471f72011-09-25 23:23:43 +00002398 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
2399 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00002400 DiagCleanup(Diags.getPtr());
2401
2402 llvm::OwningPtr<std::vector<ASTUnit::RemappedFile> >
2403 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2404
2405 // Recover resources if we crash before exiting this function.
2406 llvm::CrashRecoveryContextCleanupRegistrar<
2407 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2408
Douglas Gregor4db64a42010-01-23 00:14:00 +00002409 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002410 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002411 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002412 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002413 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2414 Buffer));
Douglas Gregor4db64a42010-01-23 00:14:00 +00002415 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002416
Ted Kremenek25a11e12011-03-22 01:15:24 +00002417 llvm::OwningPtr<std::vector<const char *> >
2418 Args(new std::vector<const char*>());
2419
2420 // Recover resources if we crash before exiting this method.
2421 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
2422 ArgsCleanup(Args.get());
2423
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002424 // Since the Clang C library is primarily used by batch tools dealing with
2425 // (often very broken) source code, where spell-checking can have a
2426 // significant negative impact on performance (particularly when
2427 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002428 // Only do this if we haven't found a spell-checking-related argument.
2429 bool FoundSpellCheckingArgument = false;
2430 for (int I = 0; I != num_command_line_args; ++I) {
2431 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2432 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2433 FoundSpellCheckingArgument = true;
2434 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002435 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002436 }
2437 if (!FoundSpellCheckingArgument)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002438 Args->push_back("-fno-spell-checking");
Douglas Gregorb10daed2010-10-11 16:52:23 +00002439
Ted Kremenek25a11e12011-03-22 01:15:24 +00002440 Args->insert(Args->end(), command_line_args,
2441 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002442
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002443 // The 'source_filename' argument is optional. If the caller does not
2444 // specify it then it is assumed that the source file is specified
2445 // in the actual argument list.
2446 // Put the source file after command_line_args otherwise if '-x' flag is
2447 // present it will be unused.
2448 if (source_filename)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002449 Args->push_back(source_filename);
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002450
Douglas Gregor44c181a2010-07-23 00:33:23 +00002451 // Do we need the detailed preprocessing record?
Chandler Carruthba7537f2011-07-14 09:02:10 +00002452 bool NestedMacroExpansions = false;
Douglas Gregor44c181a2010-07-23 00:33:23 +00002453 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Ted Kremenek25a11e12011-03-22 01:15:24 +00002454 Args->push_back("-Xclang");
2455 Args->push_back("-detailed-preprocessing-record");
Chandler Carruthba7537f2011-07-14 09:02:10 +00002456 NestedMacroExpansions
2457 = (options & CXTranslationUnit_NestedMacroExpansions);
Douglas Gregor44c181a2010-07-23 00:33:23 +00002458 }
2459
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002460 unsigned NumErrors = Diags->getClient()->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002461 llvm::OwningPtr<ASTUnit> Unit(
Ted Kremenek4ee99262011-03-22 20:16:19 +00002462 ASTUnit::LoadFromCommandLine(Args->size() ? &(*Args)[0] : 0
2463 /* vector::data() not portable */,
2464 Args->size() ? (&(*Args)[0] + Args->size()) :0,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002465 Diags,
2466 CXXIdx->getClangResourcesPath(),
2467 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002468 /*CaptureDiagnostics=*/true,
Ted Kremenek4ee99262011-03-22 20:16:19 +00002469 RemappedFiles->size() ? &(*RemappedFiles)[0]:0,
Ted Kremenek25a11e12011-03-22 01:15:24 +00002470 RemappedFiles->size(),
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00002471 /*RemappedFilesKeepOriginalName=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002472 PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00002473 TUKind,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002474 CacheCodeCompetionResults,
Chandler Carruthba7537f2011-07-14 09:02:10 +00002475 NestedMacroExpansions));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002476
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002477 if (NumErrors != Diags->getClient()->getNumErrors()) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002478 // Make sure to check that 'Unit' is non-NULL.
2479 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2480 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2481 DEnd = Unit->stored_diag_end();
2482 D != DEnd; ++D) {
2483 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2484 CXString Msg = clang_formatDiagnostic(&Diag,
2485 clang_defaultDiagnosticDisplayOptions());
2486 fprintf(stderr, "%s\n", clang_getCString(Msg));
2487 clang_disposeString(Msg);
2488 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002489#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002490 // On Windows, force a flush, since there may be multiple copies of
2491 // stderr and stdout in the file system, all with different buffers
2492 // but writing to the same device.
2493 fflush(stderr);
2494#endif
2495 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002496 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002497
Ted Kremeneka60ed472010-11-16 08:15:36 +00002498 PTUI->result = MakeCXTranslationUnit(Unit.take());
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002499}
2500CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2501 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002502 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002503 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002504 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002505 unsigned num_unsaved_files,
2506 unsigned options) {
2507 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002508 num_command_line_args, unsaved_files,
2509 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002510 llvm::CrashRecoveryContext CRC;
2511
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002512 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002513 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2514 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2515 fprintf(stderr, " 'command_line_args' : [");
2516 for (int i = 0; i != num_command_line_args; ++i) {
2517 if (i)
2518 fprintf(stderr, ", ");
2519 fprintf(stderr, "'%s'", command_line_args[i]);
2520 }
2521 fprintf(stderr, "],\n");
2522 fprintf(stderr, " 'unsaved_files' : [");
2523 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2524 if (i)
2525 fprintf(stderr, ", ");
2526 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2527 unsaved_files[i].Length);
2528 }
2529 fprintf(stderr, "],\n");
2530 fprintf(stderr, " 'options' : %d,\n", options);
2531 fprintf(stderr, "}\n");
2532
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002533 return 0;
Douglas Gregor6df78732011-05-05 20:27:22 +00002534 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
2535 PrintLibclangResourceUsage(PTUI.result);
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002536 }
Douglas Gregor6df78732011-05-05 20:27:22 +00002537
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002538 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002539}
2540
Douglas Gregor19998442010-08-13 15:35:05 +00002541unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2542 return CXSaveTranslationUnit_None;
2543}
2544
2545int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2546 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002547 if (!TU)
Douglas Gregor39c411f2011-07-06 16:43:36 +00002548 return CXSaveError_InvalidTU;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002549
Douglas Gregor39c411f2011-07-06 16:43:36 +00002550 CXSaveError result = static_cast<ASTUnit *>(TU->TUData)->Save(FileName);
Douglas Gregor6df78732011-05-05 20:27:22 +00002551 if (getenv("LIBCLANG_RESOURCE_USAGE"))
2552 PrintLibclangResourceUsage(TU);
2553 return result;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002554}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002555
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002556void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002557 if (CTUnit) {
2558 // If the translation unit has been marked as unsafe to free, just discard
2559 // it.
Ted Kremeneka60ed472010-11-16 08:15:36 +00002560 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002561 return;
2562
Ted Kremeneka60ed472010-11-16 08:15:36 +00002563 delete static_cast<ASTUnit *>(CTUnit->TUData);
2564 disposeCXStringPool(CTUnit->StringPool);
2565 delete CTUnit;
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002566 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002567}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002568
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002569unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2570 return CXReparse_None;
2571}
2572
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002573struct ReparseTranslationUnitInfo {
2574 CXTranslationUnit TU;
2575 unsigned num_unsaved_files;
2576 struct CXUnsavedFile *unsaved_files;
2577 unsigned options;
2578 int result;
2579};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002580
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002581static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002582 ReparseTranslationUnitInfo *RTUI =
2583 static_cast<ReparseTranslationUnitInfo*>(UserData);
2584 CXTranslationUnit TU = RTUI->TU;
2585 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2586 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2587 unsigned options = RTUI->options;
2588 (void) options;
2589 RTUI->result = 1;
2590
Douglas Gregorabc563f2010-07-19 21:46:24 +00002591 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002592 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002593
Ted Kremeneka60ed472010-11-16 08:15:36 +00002594 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor593b0c12010-09-23 18:47:53 +00002595 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002596
Ted Kremenek25a11e12011-03-22 01:15:24 +00002597 llvm::OwningPtr<std::vector<ASTUnit::RemappedFile> >
2598 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2599
2600 // Recover resources if we crash before exiting this function.
2601 llvm::CrashRecoveryContextCleanupRegistrar<
2602 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2603
Douglas Gregorabc563f2010-07-19 21:46:24 +00002604 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002605 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002606 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002607 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002608 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2609 Buffer));
Douglas Gregorabc563f2010-07-19 21:46:24 +00002610 }
2611
Ted Kremenek4ee99262011-03-22 20:16:19 +00002612 if (!CXXUnit->Reparse(RemappedFiles->size() ? &(*RemappedFiles)[0] : 0,
2613 RemappedFiles->size()))
Douglas Gregor593b0c12010-09-23 18:47:53 +00002614 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002615}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002616
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002617int clang_reparseTranslationUnit(CXTranslationUnit TU,
2618 unsigned num_unsaved_files,
2619 struct CXUnsavedFile *unsaved_files,
2620 unsigned options) {
2621 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2622 options, 0 };
Argyrios Kyrtzidis8c4b47e2011-10-28 22:54:33 +00002623
Argyrios Kyrtzidise7de9b42011-10-29 19:32:39 +00002624 if (getenv("LIBCLANG_NOTHREADS")) {
Argyrios Kyrtzidis8c4b47e2011-10-28 22:54:33 +00002625 clang_reparseTranslationUnit_Impl(&RTUI);
2626 return RTUI.result;
2627 }
2628
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002629 llvm::CrashRecoveryContext CRC;
2630
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002631 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002632 fprintf(stderr, "libclang: crash detected during reparsing\n");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002633 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002634 return 1;
Douglas Gregor6df78732011-05-05 20:27:22 +00002635 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
2636 PrintLibclangResourceUsage(TU);
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002637
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002638 return RTUI.result;
2639}
2640
Douglas Gregordf95a132010-08-09 20:45:32 +00002641
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002642CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002643 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002644 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002645
Ted Kremeneka60ed472010-11-16 08:15:36 +00002646 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002647 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002648}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002649
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002650CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002651 CXCursor Result = { CXCursor_TranslationUnit, 0, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002652 return Result;
2653}
2654
Ted Kremenekfb480492010-01-13 21:46:36 +00002655} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002656
Ted Kremenekfb480492010-01-13 21:46:36 +00002657//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002658// CXFile Operations.
2659//===----------------------------------------------------------------------===//
2660
2661extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002662CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002663 if (!SFile)
Ted Kremeneka60ed472010-11-16 08:15:36 +00002664 return createCXString((const char*)NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002665
Steve Naroff88145032009-10-27 14:35:18 +00002666 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002667 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002668}
2669
2670time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002671 if (!SFile)
2672 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002673
Steve Naroff88145032009-10-27 14:35:18 +00002674 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2675 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002676}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002677
Douglas Gregorb9790342010-01-22 21:44:22 +00002678CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2679 if (!tu)
2680 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002681
Ted Kremeneka60ed472010-11-16 08:15:36 +00002682 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002683
Douglas Gregorb9790342010-01-22 21:44:22 +00002684 FileManager &FMgr = CXXUnit->getFileManager();
Chris Lattner39b49bc2010-11-23 08:35:12 +00002685 return const_cast<FileEntry *>(FMgr.getFile(file_name));
Douglas Gregorb9790342010-01-22 21:44:22 +00002686}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002687
Douglas Gregordd3e5542011-05-04 00:14:37 +00002688unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit tu, CXFile file) {
2689 if (!tu || !file)
2690 return 0;
2691
2692 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
2693 FileEntry *FEnt = static_cast<FileEntry *>(file);
2694 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
2695 .isFileMultipleIncludeGuarded(FEnt);
2696}
2697
Ted Kremenekfb480492010-01-13 21:46:36 +00002698} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002699
Ted Kremenekfb480492010-01-13 21:46:36 +00002700//===----------------------------------------------------------------------===//
2701// CXCursor Operations.
2702//===----------------------------------------------------------------------===//
2703
Ted Kremenekfb480492010-01-13 21:46:36 +00002704static Decl *getDeclFromExpr(Stmt *E) {
Argyrios Kyrtzidisc2954612011-09-12 22:17:26 +00002705 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Douglas Gregordb1314e2010-10-01 21:11:22 +00002706 return getDeclFromExpr(CE->getSubExpr());
2707
Ted Kremenekfb480492010-01-13 21:46:36 +00002708 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2709 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002710 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2711 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002712 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2713 return ME->getMemberDecl();
2714 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2715 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002716 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
John McCall12f78a62010-12-02 01:19:52 +00002717 return PRE->isExplicitProperty() ? PRE->getExplicitProperty() : 0;
John McCall4b9c2d22011-11-06 09:01:30 +00002718 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
2719 return getDeclFromExpr(POE->getSyntacticForm());
2720 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
2721 if (Expr *Src = OVE->getSourceExpr())
2722 return getDeclFromExpr(Src);
Douglas Gregordb1314e2010-10-01 21:11:22 +00002723
Ted Kremenekfb480492010-01-13 21:46:36 +00002724 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2725 return getDeclFromExpr(CE->getCallee());
Chris Lattner5f9e2722011-07-23 10:55:15 +00002726 if (CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Douglas Gregor93798e22010-11-05 21:11:19 +00002727 if (!CE->isElidable())
2728 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002729 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2730 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002731
Douglas Gregordb1314e2010-10-01 21:11:22 +00002732 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2733 return PE->getProtocol();
Douglas Gregorc7793c72011-01-15 01:15:58 +00002734 if (SubstNonTypeTemplateParmPackExpr *NTTP
2735 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
2736 return NTTP->getParameterPack();
Douglas Gregor94d96292011-01-19 20:34:17 +00002737 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2738 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
2739 isa<ParmVarDecl>(SizeOfPack->getPack()))
2740 return SizeOfPack->getPack();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002741
Ted Kremenekfb480492010-01-13 21:46:36 +00002742 return 0;
2743}
2744
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002745static SourceLocation getLocationFromExpr(Expr *E) {
Argyrios Kyrtzidisc2954612011-09-12 22:17:26 +00002746 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
2747 return getLocationFromExpr(CE->getSubExpr());
2748
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002749 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2750 return /*FIXME:*/Msg->getLeftLoc();
2751 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2752 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002753 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2754 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002755 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2756 return Member->getMemberLoc();
2757 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2758 return Ivar->getLocation();
Douglas Gregor94d96292011-01-19 20:34:17 +00002759 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2760 return SizeOfPack->getPackLoc();
2761
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002762 return E->getLocStart();
2763}
2764
Ted Kremenekfb480492010-01-13 21:46:36 +00002765extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002766
2767unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002768 CXCursorVisitor visitor,
2769 CXClientData client_data) {
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00002770 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
2771 /*VisitPreprocessorLast=*/false);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002772 return CursorVis.VisitChildren(parent);
2773}
2774
David Chisnall3387c652010-11-03 14:12:26 +00002775#ifndef __has_feature
2776#define __has_feature(x) 0
2777#endif
2778#if __has_feature(blocks)
2779typedef enum CXChildVisitResult
2780 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2781
2782static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2783 CXClientData client_data) {
2784 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2785 return block(cursor, parent);
2786}
2787#else
2788// If we are compiled with a compiler that doesn't have native blocks support,
2789// define and call the block manually, so the
2790typedef struct _CXChildVisitResult
2791{
2792 void *isa;
2793 int flags;
2794 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002795 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2796 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00002797} *CXCursorVisitorBlock;
2798
2799static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2800 CXClientData client_data) {
2801 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2802 return block->invoke(block, cursor, parent);
2803}
2804#endif
2805
2806
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002807unsigned clang_visitChildrenWithBlock(CXCursor parent,
2808 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00002809 return clang_visitChildren(parent, visitWithBlock, block);
2810}
2811
Douglas Gregor78205d42010-01-20 21:45:58 +00002812static CXString getDeclSpelling(Decl *D) {
2813 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
Douglas Gregore3c60a72010-11-17 00:13:31 +00002814 if (!ND) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002815 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00002816 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
2817 return createCXString(Property->getIdentifier()->getName());
2818
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002819 return createCXString("");
Douglas Gregore3c60a72010-11-17 00:13:31 +00002820 }
2821
Douglas Gregor78205d42010-01-20 21:45:58 +00002822 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002823 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002824
Douglas Gregor78205d42010-01-20 21:45:58 +00002825 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2826 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2827 // and returns different names. NamedDecl returns the class name and
2828 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002829 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002830
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002831 if (isa<UsingDirectiveDecl>(D))
2832 return createCXString("");
2833
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002834 llvm::SmallString<1024> S;
2835 llvm::raw_svector_ostream os(S);
2836 ND->printName(os);
2837
2838 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002839}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002840
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002841CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002842 if (clang_isTranslationUnit(C.kind))
Ted Kremeneka60ed472010-11-16 08:15:36 +00002843 return clang_getTranslationUnitSpelling(
2844 static_cast<CXTranslationUnit>(C.data[2]));
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002845
Steve Narofff334b4e2009-09-02 18:26:48 +00002846 if (clang_isReference(C.kind)) {
2847 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002848 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002849 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002850 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002851 }
2852 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002853 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002854 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002855 }
2856 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002857 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002858 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002859 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002860 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002861 case CXCursor_CXXBaseSpecifier: {
2862 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2863 return createCXString(B->getType().getAsString());
2864 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002865 case CXCursor_TypeRef: {
2866 TypeDecl *Type = getCursorTypeRef(C).first;
2867 assert(Type && "Missing type decl");
2868
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002869 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2870 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002871 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002872 case CXCursor_TemplateRef: {
2873 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002874 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002875
2876 return createCXString(Template->getNameAsString());
2877 }
Douglas Gregor69319002010-08-31 23:48:11 +00002878
2879 case CXCursor_NamespaceRef: {
2880 NamedDecl *NS = getCursorNamespaceRef(C).first;
2881 assert(NS && "Missing namespace decl");
2882
2883 return createCXString(NS->getNameAsString());
2884 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002885
Douglas Gregora67e03f2010-09-09 21:42:20 +00002886 case CXCursor_MemberRef: {
2887 FieldDecl *Field = getCursorMemberRef(C).first;
2888 assert(Field && "Missing member decl");
2889
2890 return createCXString(Field->getNameAsString());
2891 }
2892
Douglas Gregor36897b02010-09-10 00:22:18 +00002893 case CXCursor_LabelRef: {
2894 LabelStmt *Label = getCursorLabelRef(C).first;
2895 assert(Label && "Missing label");
2896
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002897 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00002898 }
2899
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002900 case CXCursor_OverloadedDeclRef: {
2901 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2902 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2903 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2904 return createCXString(ND->getNameAsString());
2905 return createCXString("");
2906 }
2907 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2908 return createCXString(E->getName().getAsString());
2909 OverloadedTemplateStorage *Ovl
2910 = Storage.get<OverloadedTemplateStorage*>();
2911 if (Ovl->size() == 0)
2912 return createCXString("");
2913 return createCXString((*Ovl->begin())->getNameAsString());
2914 }
2915
Daniel Dunbaracca7252009-11-30 20:42:49 +00002916 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002917 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002918 }
2919 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002920
2921 if (clang_isExpression(C.kind)) {
2922 Decl *D = getDeclFromExpr(getCursorExpr(C));
2923 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002924 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002925 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002926 }
2927
Douglas Gregor36897b02010-09-10 00:22:18 +00002928 if (clang_isStatement(C.kind)) {
2929 Stmt *S = getCursorStmt(C);
2930 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002931 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00002932
2933 return createCXString("");
2934 }
2935
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00002936 if (C.kind == CXCursor_MacroExpansion)
Chandler Carruth9e5bb852011-07-14 08:20:46 +00002937 return createCXString(getCursorMacroExpansion(C)->getName()
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002938 ->getNameStart());
2939
Douglas Gregor572feb22010-03-18 18:04:21 +00002940 if (C.kind == CXCursor_MacroDefinition)
2941 return createCXString(getCursorMacroDefinition(C)->getName()
2942 ->getNameStart());
2943
Douglas Gregorecdcb882010-10-20 22:00:55 +00002944 if (C.kind == CXCursor_InclusionDirective)
2945 return createCXString(getCursorInclusionDirective(C)->getFileName());
2946
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002947 if (clang_isDeclaration(C.kind))
2948 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002949
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00002950 if (C.kind == CXCursor_AnnotateAttr) {
2951 AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
2952 return createCXString(AA->getAnnotation());
2953 }
2954
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002955 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002956}
2957
Douglas Gregor358559d2010-10-02 22:49:11 +00002958CXString clang_getCursorDisplayName(CXCursor C) {
2959 if (!clang_isDeclaration(C.kind))
2960 return clang_getCursorSpelling(C);
2961
2962 Decl *D = getCursorDecl(C);
2963 if (!D)
2964 return createCXString("");
2965
Douglas Gregor30c42402011-09-27 22:38:19 +00002966 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
Douglas Gregor358559d2010-10-02 22:49:11 +00002967 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2968 D = FunTmpl->getTemplatedDecl();
2969
2970 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
2971 llvm::SmallString<64> Str;
2972 llvm::raw_svector_ostream OS(Str);
2973 OS << Function->getNameAsString();
2974 if (Function->getPrimaryTemplate())
2975 OS << "<>";
2976 OS << "(";
2977 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
2978 if (I)
2979 OS << ", ";
2980 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
2981 }
2982
2983 if (Function->isVariadic()) {
2984 if (Function->getNumParams())
2985 OS << ", ";
2986 OS << "...";
2987 }
2988 OS << ")";
2989 return createCXString(OS.str());
2990 }
2991
2992 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
2993 llvm::SmallString<64> Str;
2994 llvm::raw_svector_ostream OS(Str);
2995 OS << ClassTemplate->getNameAsString();
2996 OS << "<";
2997 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
2998 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2999 if (I)
3000 OS << ", ";
3001
3002 NamedDecl *Param = Params->getParam(I);
3003 if (Param->getIdentifier()) {
3004 OS << Param->getIdentifier()->getName();
3005 continue;
3006 }
3007
3008 // There is no parameter name, which makes this tricky. Try to come up
3009 // with something useful that isn't too long.
3010 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3011 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
3012 else if (NonTypeTemplateParmDecl *NTTP
3013 = dyn_cast<NonTypeTemplateParmDecl>(Param))
3014 OS << NTTP->getType().getAsString(Policy);
3015 else
3016 OS << "template<...> class";
3017 }
3018
3019 OS << ">";
3020 return createCXString(OS.str());
3021 }
3022
3023 if (ClassTemplateSpecializationDecl *ClassSpec
3024 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
3025 // If the type was explicitly written, use that.
3026 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
3027 return createCXString(TSInfo->getType().getAsString(Policy));
3028
3029 llvm::SmallString<64> Str;
3030 llvm::raw_svector_ostream OS(Str);
3031 OS << ClassSpec->getNameAsString();
3032 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00003033 ClassSpec->getTemplateArgs().data(),
3034 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00003035 Policy);
3036 return createCXString(OS.str());
3037 }
3038
3039 return clang_getCursorSpelling(C);
3040}
3041
Ted Kremeneke68fff62010-02-17 00:41:32 +00003042CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00003043 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00003044 case CXCursor_FunctionDecl:
3045 return createCXString("FunctionDecl");
3046 case CXCursor_TypedefDecl:
3047 return createCXString("TypedefDecl");
3048 case CXCursor_EnumDecl:
3049 return createCXString("EnumDecl");
3050 case CXCursor_EnumConstantDecl:
3051 return createCXString("EnumConstantDecl");
3052 case CXCursor_StructDecl:
3053 return createCXString("StructDecl");
3054 case CXCursor_UnionDecl:
3055 return createCXString("UnionDecl");
3056 case CXCursor_ClassDecl:
3057 return createCXString("ClassDecl");
3058 case CXCursor_FieldDecl:
3059 return createCXString("FieldDecl");
3060 case CXCursor_VarDecl:
3061 return createCXString("VarDecl");
3062 case CXCursor_ParmDecl:
3063 return createCXString("ParmDecl");
3064 case CXCursor_ObjCInterfaceDecl:
3065 return createCXString("ObjCInterfaceDecl");
3066 case CXCursor_ObjCCategoryDecl:
3067 return createCXString("ObjCCategoryDecl");
3068 case CXCursor_ObjCProtocolDecl:
3069 return createCXString("ObjCProtocolDecl");
3070 case CXCursor_ObjCPropertyDecl:
3071 return createCXString("ObjCPropertyDecl");
3072 case CXCursor_ObjCIvarDecl:
3073 return createCXString("ObjCIvarDecl");
3074 case CXCursor_ObjCInstanceMethodDecl:
3075 return createCXString("ObjCInstanceMethodDecl");
3076 case CXCursor_ObjCClassMethodDecl:
3077 return createCXString("ObjCClassMethodDecl");
3078 case CXCursor_ObjCImplementationDecl:
3079 return createCXString("ObjCImplementationDecl");
3080 case CXCursor_ObjCCategoryImplDecl:
3081 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00003082 case CXCursor_CXXMethod:
3083 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003084 case CXCursor_UnexposedDecl:
3085 return createCXString("UnexposedDecl");
3086 case CXCursor_ObjCSuperClassRef:
3087 return createCXString("ObjCSuperClassRef");
3088 case CXCursor_ObjCProtocolRef:
3089 return createCXString("ObjCProtocolRef");
3090 case CXCursor_ObjCClassRef:
3091 return createCXString("ObjCClassRef");
3092 case CXCursor_TypeRef:
3093 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003094 case CXCursor_TemplateRef:
3095 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00003096 case CXCursor_NamespaceRef:
3097 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00003098 case CXCursor_MemberRef:
3099 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00003100 case CXCursor_LabelRef:
3101 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003102 case CXCursor_OverloadedDeclRef:
3103 return createCXString("OverloadedDeclRef");
Douglas Gregor42b29842011-10-05 19:00:14 +00003104 case CXCursor_IntegerLiteral:
3105 return createCXString("IntegerLiteral");
3106 case CXCursor_FloatingLiteral:
3107 return createCXString("FloatingLiteral");
3108 case CXCursor_ImaginaryLiteral:
3109 return createCXString("ImaginaryLiteral");
3110 case CXCursor_StringLiteral:
3111 return createCXString("StringLiteral");
3112 case CXCursor_CharacterLiteral:
3113 return createCXString("CharacterLiteral");
3114 case CXCursor_ParenExpr:
3115 return createCXString("ParenExpr");
3116 case CXCursor_UnaryOperator:
3117 return createCXString("UnaryOperator");
3118 case CXCursor_ArraySubscriptExpr:
3119 return createCXString("ArraySubscriptExpr");
3120 case CXCursor_BinaryOperator:
3121 return createCXString("BinaryOperator");
3122 case CXCursor_CompoundAssignOperator:
3123 return createCXString("CompoundAssignOperator");
3124 case CXCursor_ConditionalOperator:
3125 return createCXString("ConditionalOperator");
3126 case CXCursor_CStyleCastExpr:
3127 return createCXString("CStyleCastExpr");
3128 case CXCursor_CompoundLiteralExpr:
3129 return createCXString("CompoundLiteralExpr");
3130 case CXCursor_InitListExpr:
3131 return createCXString("InitListExpr");
3132 case CXCursor_AddrLabelExpr:
3133 return createCXString("AddrLabelExpr");
3134 case CXCursor_StmtExpr:
3135 return createCXString("StmtExpr");
3136 case CXCursor_GenericSelectionExpr:
3137 return createCXString("GenericSelectionExpr");
3138 case CXCursor_GNUNullExpr:
3139 return createCXString("GNUNullExpr");
3140 case CXCursor_CXXStaticCastExpr:
3141 return createCXString("CXXStaticCastExpr");
3142 case CXCursor_CXXDynamicCastExpr:
3143 return createCXString("CXXDynamicCastExpr");
3144 case CXCursor_CXXReinterpretCastExpr:
3145 return createCXString("CXXReinterpretCastExpr");
3146 case CXCursor_CXXConstCastExpr:
3147 return createCXString("CXXConstCastExpr");
3148 case CXCursor_CXXFunctionalCastExpr:
3149 return createCXString("CXXFunctionalCastExpr");
3150 case CXCursor_CXXTypeidExpr:
3151 return createCXString("CXXTypeidExpr");
3152 case CXCursor_CXXBoolLiteralExpr:
3153 return createCXString("CXXBoolLiteralExpr");
3154 case CXCursor_CXXNullPtrLiteralExpr:
3155 return createCXString("CXXNullPtrLiteralExpr");
3156 case CXCursor_CXXThisExpr:
3157 return createCXString("CXXThisExpr");
3158 case CXCursor_CXXThrowExpr:
3159 return createCXString("CXXThrowExpr");
3160 case CXCursor_CXXNewExpr:
3161 return createCXString("CXXNewExpr");
3162 case CXCursor_CXXDeleteExpr:
3163 return createCXString("CXXDeleteExpr");
3164 case CXCursor_UnaryExpr:
3165 return createCXString("UnaryExpr");
3166 case CXCursor_ObjCStringLiteral:
3167 return createCXString("ObjCStringLiteral");
3168 case CXCursor_ObjCEncodeExpr:
3169 return createCXString("ObjCEncodeExpr");
3170 case CXCursor_ObjCSelectorExpr:
3171 return createCXString("ObjCSelectorExpr");
3172 case CXCursor_ObjCProtocolExpr:
3173 return createCXString("ObjCProtocolExpr");
3174 case CXCursor_ObjCBridgedCastExpr:
3175 return createCXString("ObjCBridgedCastExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00003176 case CXCursor_BlockExpr:
3177 return createCXString("BlockExpr");
Douglas Gregor42b29842011-10-05 19:00:14 +00003178 case CXCursor_PackExpansionExpr:
3179 return createCXString("PackExpansionExpr");
3180 case CXCursor_SizeOfPackExpr:
3181 return createCXString("SizeOfPackExpr");
3182 case CXCursor_UnexposedExpr:
3183 return createCXString("UnexposedExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003184 case CXCursor_DeclRefExpr:
3185 return createCXString("DeclRefExpr");
3186 case CXCursor_MemberRefExpr:
3187 return createCXString("MemberRefExpr");
3188 case CXCursor_CallExpr:
3189 return createCXString("CallExpr");
3190 case CXCursor_ObjCMessageExpr:
3191 return createCXString("ObjCMessageExpr");
3192 case CXCursor_UnexposedStmt:
3193 return createCXString("UnexposedStmt");
Douglas Gregor42b29842011-10-05 19:00:14 +00003194 case CXCursor_DeclStmt:
3195 return createCXString("DeclStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00003196 case CXCursor_LabelStmt:
3197 return createCXString("LabelStmt");
Douglas Gregor42b29842011-10-05 19:00:14 +00003198 case CXCursor_CompoundStmt:
3199 return createCXString("CompoundStmt");
3200 case CXCursor_CaseStmt:
3201 return createCXString("CaseStmt");
3202 case CXCursor_DefaultStmt:
3203 return createCXString("DefaultStmt");
3204 case CXCursor_IfStmt:
3205 return createCXString("IfStmt");
3206 case CXCursor_SwitchStmt:
3207 return createCXString("SwitchStmt");
3208 case CXCursor_WhileStmt:
3209 return createCXString("WhileStmt");
3210 case CXCursor_DoStmt:
3211 return createCXString("DoStmt");
3212 case CXCursor_ForStmt:
3213 return createCXString("ForStmt");
3214 case CXCursor_GotoStmt:
3215 return createCXString("GotoStmt");
3216 case CXCursor_IndirectGotoStmt:
3217 return createCXString("IndirectGotoStmt");
3218 case CXCursor_ContinueStmt:
3219 return createCXString("ContinueStmt");
3220 case CXCursor_BreakStmt:
3221 return createCXString("BreakStmt");
3222 case CXCursor_ReturnStmt:
3223 return createCXString("ReturnStmt");
3224 case CXCursor_AsmStmt:
3225 return createCXString("AsmStmt");
3226 case CXCursor_ObjCAtTryStmt:
3227 return createCXString("ObjCAtTryStmt");
3228 case CXCursor_ObjCAtCatchStmt:
3229 return createCXString("ObjCAtCatchStmt");
3230 case CXCursor_ObjCAtFinallyStmt:
3231 return createCXString("ObjCAtFinallyStmt");
3232 case CXCursor_ObjCAtThrowStmt:
3233 return createCXString("ObjCAtThrowStmt");
3234 case CXCursor_ObjCAtSynchronizedStmt:
3235 return createCXString("ObjCAtSynchronizedStmt");
3236 case CXCursor_ObjCAutoreleasePoolStmt:
3237 return createCXString("ObjCAutoreleasePoolStmt");
3238 case CXCursor_ObjCForCollectionStmt:
3239 return createCXString("ObjCForCollectionStmt");
3240 case CXCursor_CXXCatchStmt:
3241 return createCXString("CXXCatchStmt");
3242 case CXCursor_CXXTryStmt:
3243 return createCXString("CXXTryStmt");
3244 case CXCursor_CXXForRangeStmt:
3245 return createCXString("CXXForRangeStmt");
3246 case CXCursor_SEHTryStmt:
3247 return createCXString("SEHTryStmt");
3248 case CXCursor_SEHExceptStmt:
3249 return createCXString("SEHExceptStmt");
3250 case CXCursor_SEHFinallyStmt:
3251 return createCXString("SEHFinallyStmt");
3252 case CXCursor_NullStmt:
3253 return createCXString("NullStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003254 case CXCursor_InvalidFile:
3255 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00003256 case CXCursor_InvalidCode:
3257 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003258 case CXCursor_NoDeclFound:
3259 return createCXString("NoDeclFound");
3260 case CXCursor_NotImplemented:
3261 return createCXString("NotImplemented");
3262 case CXCursor_TranslationUnit:
3263 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00003264 case CXCursor_UnexposedAttr:
3265 return createCXString("UnexposedAttr");
3266 case CXCursor_IBActionAttr:
3267 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003268 case CXCursor_IBOutletAttr:
3269 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003270 case CXCursor_IBOutletCollectionAttr:
3271 return createCXString("attribute(iboutletcollection)");
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00003272 case CXCursor_CXXFinalAttr:
3273 return createCXString("attribute(final)");
3274 case CXCursor_CXXOverrideAttr:
3275 return createCXString("attribute(override)");
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00003276 case CXCursor_AnnotateAttr:
3277 return createCXString("attribute(annotate)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003278 case CXCursor_PreprocessingDirective:
3279 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003280 case CXCursor_MacroDefinition:
3281 return createCXString("macro definition");
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003282 case CXCursor_MacroExpansion:
3283 return createCXString("macro expansion");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003284 case CXCursor_InclusionDirective:
3285 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003286 case CXCursor_Namespace:
3287 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003288 case CXCursor_LinkageSpec:
3289 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003290 case CXCursor_CXXBaseSpecifier:
3291 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003292 case CXCursor_Constructor:
3293 return createCXString("CXXConstructor");
3294 case CXCursor_Destructor:
3295 return createCXString("CXXDestructor");
3296 case CXCursor_ConversionFunction:
3297 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003298 case CXCursor_TemplateTypeParameter:
3299 return createCXString("TemplateTypeParameter");
3300 case CXCursor_NonTypeTemplateParameter:
3301 return createCXString("NonTypeTemplateParameter");
3302 case CXCursor_TemplateTemplateParameter:
3303 return createCXString("TemplateTemplateParameter");
3304 case CXCursor_FunctionTemplate:
3305 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003306 case CXCursor_ClassTemplate:
3307 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003308 case CXCursor_ClassTemplatePartialSpecialization:
3309 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003310 case CXCursor_NamespaceAlias:
3311 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003312 case CXCursor_UsingDirective:
3313 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003314 case CXCursor_UsingDeclaration:
3315 return createCXString("UsingDeclaration");
Richard Smith162e1c12011-04-15 14:24:37 +00003316 case CXCursor_TypeAliasDecl:
Douglas Gregor352697a2011-06-03 23:08:58 +00003317 return createCXString("TypeAliasDecl");
3318 case CXCursor_ObjCSynthesizeDecl:
3319 return createCXString("ObjCSynthesizeDecl");
3320 case CXCursor_ObjCDynamicDecl:
3321 return createCXString("ObjCDynamicDecl");
Argyrios Kyrtzidis2dfdb942011-09-30 17:58:23 +00003322 case CXCursor_CXXAccessSpecifier:
3323 return createCXString("CXXAccessSpecifier");
Steve Naroff89922f82009-08-31 00:59:03 +00003324 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003325
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003326 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneka60ed472010-11-16 08:15:36 +00003327 return createCXString((const char*) 0);
Steve Naroff600866c2009-08-27 19:51:58 +00003328}
Steve Naroff89922f82009-08-31 00:59:03 +00003329
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003330struct GetCursorData {
3331 SourceLocation TokenBeginLoc;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003332 bool PointsAtMacroArgExpansion;
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003333 CXCursor &BestCursor;
3334
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003335 GetCursorData(SourceManager &SM,
3336 SourceLocation tokenBegin, CXCursor &outputCursor)
3337 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
3338 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
3339 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003340};
3341
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003342static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3343 CXCursor parent,
3344 CXClientData client_data) {
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003345 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
3346 CXCursor *BestCursor = &Data->BestCursor;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003347
3348 // If we point inside a macro argument we should provide info of what the
3349 // token is so use the actual cursor, don't replace it with a macro expansion
3350 // cursor.
3351 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
3352 return CXChildVisit_Recurse;
Argyrios Kyrtzidis65ab9072011-09-26 19:05:37 +00003353
3354 if (clang_isDeclaration(cursor.kind)) {
3355 // Avoid having the implicit methods override the property decls.
3356 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(getCursorDecl(cursor)))
3357 if (MD->isImplicit())
3358 return CXChildVisit_Break;
3359 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003360
3361 if (clang_isExpression(cursor.kind) &&
3362 clang_isDeclaration(BestCursor->kind)) {
3363 Decl *D = getCursorDecl(*BestCursor);
3364
3365 // Avoid having the cursor of an expression replace the declaration cursor
3366 // when the expression source range overlaps the declaration range.
3367 // This can happen for C++ constructor expressions whose range generally
3368 // include the variable declaration, e.g.:
3369 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
3370 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
3371 D->getLocation() == Data->TokenBeginLoc)
3372 return CXChildVisit_Break;
3373 }
3374
Douglas Gregor93798e22010-11-05 21:11:19 +00003375 // If our current best cursor is the construction of a temporary object,
3376 // don't replace that cursor with a type reference, because we want
3377 // clang_getCursor() to point at the constructor.
3378 if (clang_isExpression(BestCursor->kind) &&
3379 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003380 cursor.kind == CXCursor_TypeRef) {
3381 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
3382 // as having the actual point on the type reference.
3383 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
Douglas Gregor93798e22010-11-05 21:11:19 +00003384 return CXChildVisit_Recurse;
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003385 }
Douglas Gregor93798e22010-11-05 21:11:19 +00003386
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003387 *BestCursor = cursor;
3388 return CXChildVisit_Recurse;
3389}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003390
Douglas Gregorb9790342010-01-22 21:44:22 +00003391CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3392 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003393 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003394
Ted Kremeneka60ed472010-11-16 08:15:36 +00003395 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003396 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3397
Ted Kremeneka297de22010-01-25 22:34:44 +00003398 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003399 CXCursor Result = cxcursor::getCursor(TU, SLoc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003400
Douglas Gregor40749ee2010-11-03 00:35:38 +00003401 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregor40749ee2010-11-03 00:35:38 +00003402 if (Logging) {
3403 CXFile SearchFile;
3404 unsigned SearchLine, SearchColumn;
3405 CXFile ResultFile;
3406 unsigned ResultLine, ResultColumn;
Douglas Gregor66537982010-11-17 17:14:07 +00003407 CXString SearchFileName, ResultFileName, KindSpelling, USR;
3408 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
Douglas Gregor40749ee2010-11-03 00:35:38 +00003409 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3410
Chandler Carruth20174222011-08-31 16:53:37 +00003411 clang_getExpansionLocation(Loc, &SearchFile, &SearchLine, &SearchColumn, 0);
3412 clang_getExpansionLocation(ResultLoc, &ResultFile, &ResultLine,
3413 &ResultColumn, 0);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003414 SearchFileName = clang_getFileName(SearchFile);
3415 ResultFileName = clang_getFileName(ResultFile);
3416 KindSpelling = clang_getCursorKindSpelling(Result.kind);
Douglas Gregor66537982010-11-17 17:14:07 +00003417 USR = clang_getCursorUSR(Result);
3418 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n",
Douglas Gregor40749ee2010-11-03 00:35:38 +00003419 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3420 clang_getCString(KindSpelling),
Douglas Gregor66537982010-11-17 17:14:07 +00003421 clang_getCString(ResultFileName), ResultLine, ResultColumn,
3422 clang_getCString(USR), IsDef);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003423 clang_disposeString(SearchFileName);
3424 clang_disposeString(ResultFileName);
3425 clang_disposeString(KindSpelling);
Douglas Gregor66537982010-11-17 17:14:07 +00003426 clang_disposeString(USR);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003427
3428 CXCursor Definition = clang_getCursorDefinition(Result);
3429 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
3430 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
3431 CXString DefinitionKindSpelling
3432 = clang_getCursorKindSpelling(Definition.kind);
3433 CXFile DefinitionFile;
3434 unsigned DefinitionLine, DefinitionColumn;
Chandler Carruth20174222011-08-31 16:53:37 +00003435 clang_getExpansionLocation(DefinitionLoc, &DefinitionFile,
3436 &DefinitionLine, &DefinitionColumn, 0);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003437 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
3438 fprintf(stderr, " -> %s(%s:%d:%d)\n",
3439 clang_getCString(DefinitionKindSpelling),
3440 clang_getCString(DefinitionFileName),
3441 DefinitionLine, DefinitionColumn);
3442 clang_disposeString(DefinitionFileName);
3443 clang_disposeString(DefinitionKindSpelling);
3444 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003445 }
3446
Ted Kremeneke68fff62010-02-17 00:41:32 +00003447 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003448}
3449
Ted Kremenek73885552009-11-17 19:28:59 +00003450CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003451 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003452}
3453
3454unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003455 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003456}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003457
Douglas Gregor9ce55842010-11-20 00:09:34 +00003458unsigned clang_hashCursor(CXCursor C) {
3459 unsigned Index = 0;
3460 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
3461 Index = 1;
3462
3463 return llvm::DenseMapInfo<std::pair<unsigned, void*> >::getHashValue(
3464 std::make_pair(C.kind, C.data[Index]));
3465}
3466
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003467unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003468 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3469}
3470
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003471unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003472 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3473}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003474
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003475unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003476 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3477}
3478
Douglas Gregor97b98722010-01-19 23:20:36 +00003479unsigned clang_isExpression(enum CXCursorKind K) {
3480 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3481}
3482
3483unsigned clang_isStatement(enum CXCursorKind K) {
3484 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3485}
3486
Douglas Gregor8be80e12011-07-06 03:00:34 +00003487unsigned clang_isAttribute(enum CXCursorKind K) {
3488 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
3489}
3490
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003491unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3492 return K == CXCursor_TranslationUnit;
3493}
3494
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003495unsigned clang_isPreprocessing(enum CXCursorKind K) {
3496 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3497}
3498
Ted Kremenekad6eff62010-03-08 21:17:29 +00003499unsigned clang_isUnexposed(enum CXCursorKind K) {
3500 switch (K) {
3501 case CXCursor_UnexposedDecl:
3502 case CXCursor_UnexposedExpr:
3503 case CXCursor_UnexposedStmt:
3504 case CXCursor_UnexposedAttr:
3505 return true;
3506 default:
3507 return false;
3508 }
3509}
3510
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003511CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003512 return C.kind;
3513}
3514
Douglas Gregor98258af2010-01-18 22:46:11 +00003515CXSourceLocation clang_getCursorLocation(CXCursor C) {
3516 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003517 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003518 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003519 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3520 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003521 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003522 }
3523
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003524 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003525 std::pair<ObjCProtocolDecl *, SourceLocation> P
3526 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003527 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003528 }
3529
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003530 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003531 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3532 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003533 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003534 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003535
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003536 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003537 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003538 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003539 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003540
3541 case CXCursor_TemplateRef: {
3542 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3543 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3544 }
3545
Douglas Gregor69319002010-08-31 23:48:11 +00003546 case CXCursor_NamespaceRef: {
3547 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3548 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3549 }
3550
Douglas Gregora67e03f2010-09-09 21:42:20 +00003551 case CXCursor_MemberRef: {
3552 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3553 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3554 }
3555
Ted Kremenek3064ef92010-08-27 21:34:58 +00003556 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003557 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3558 if (!BaseSpec)
3559 return clang_getNullLocation();
3560
3561 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3562 return cxloc::translateSourceLocation(getCursorContext(C),
3563 TSInfo->getTypeLoc().getBeginLoc());
3564
3565 return cxloc::translateSourceLocation(getCursorContext(C),
3566 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003567 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003568
Douglas Gregor36897b02010-09-10 00:22:18 +00003569 case CXCursor_LabelRef: {
3570 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3571 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3572 }
3573
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003574 case CXCursor_OverloadedDeclRef:
3575 return cxloc::translateSourceLocation(getCursorContext(C),
3576 getCursorOverloadedDeclRef(C).second);
3577
Douglas Gregorf46034a2010-01-18 23:41:10 +00003578 default:
3579 // FIXME: Need a way to enumerate all non-reference cases.
3580 llvm_unreachable("Missed a reference kind");
3581 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003582 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003583
3584 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003585 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003586 getLocationFromExpr(getCursorExpr(C)));
3587
Douglas Gregor36897b02010-09-10 00:22:18 +00003588 if (clang_isStatement(C.kind))
3589 return cxloc::translateSourceLocation(getCursorContext(C),
3590 getCursorStmt(C)->getLocStart());
3591
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003592 if (C.kind == CXCursor_PreprocessingDirective) {
3593 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3594 return cxloc::translateSourceLocation(getCursorContext(C), L);
3595 }
Douglas Gregor48072312010-03-18 15:23:44 +00003596
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003597 if (C.kind == CXCursor_MacroExpansion) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003598 SourceLocation L
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003599 = cxcursor::getCursorMacroExpansion(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003600 return cxloc::translateSourceLocation(getCursorContext(C), L);
3601 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003602
3603 if (C.kind == CXCursor_MacroDefinition) {
3604 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3605 return cxloc::translateSourceLocation(getCursorContext(C), L);
3606 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003607
3608 if (C.kind == CXCursor_InclusionDirective) {
3609 SourceLocation L
3610 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3611 return cxloc::translateSourceLocation(getCursorContext(C), L);
3612 }
3613
Ted Kremenek9a700d22010-05-12 06:16:13 +00003614 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003615 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003616
Douglas Gregorf46034a2010-01-18 23:41:10 +00003617 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003618 SourceLocation Loc = D->getLocation();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003619 // FIXME: Multiple variables declared in a single declaration
3620 // currently lack the information needed to correctly determine their
3621 // ranges when accounting for the type-specifier. We use context
3622 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3623 // and if so, whether it is the first decl.
3624 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3625 if (!cxcursor::isFirstInDeclGroup(C))
3626 Loc = VD->getLocation();
3627 }
3628
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003629 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003630}
Douglas Gregora7bde202010-01-19 00:34:46 +00003631
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003632} // end extern "C"
3633
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003634CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
3635 assert(TU);
3636
3637 // Guard against an invalid SourceLocation, or we may assert in one
3638 // of the following calls.
3639 if (SLoc.isInvalid())
3640 return clang_getNullCursor();
3641
3642 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
3643
3644 // Translate the given source location to make it point at the beginning of
3645 // the token under the cursor.
3646 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3647 CXXUnit->getASTContext().getLangOptions());
3648
3649 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3650 if (SLoc.isValid()) {
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003651 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003652 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
3653 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00003654 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003655 SourceLocation(SLoc));
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00003656 CursorVis.visitFileRegion();
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003657 }
3658
3659 return Result;
3660}
3661
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003662static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003663 if (clang_isReference(C.kind)) {
3664 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003665 case CXCursor_ObjCSuperClassRef:
3666 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003667
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003668 case CXCursor_ObjCProtocolRef:
3669 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003670
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003671 case CXCursor_ObjCClassRef:
3672 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003673
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003674 case CXCursor_TypeRef:
3675 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003676
3677 case CXCursor_TemplateRef:
3678 return getCursorTemplateRef(C).second;
3679
Douglas Gregor69319002010-08-31 23:48:11 +00003680 case CXCursor_NamespaceRef:
3681 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003682
3683 case CXCursor_MemberRef:
3684 return getCursorMemberRef(C).second;
3685
Ted Kremenek3064ef92010-08-27 21:34:58 +00003686 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003687 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003688
Douglas Gregor36897b02010-09-10 00:22:18 +00003689 case CXCursor_LabelRef:
3690 return getCursorLabelRef(C).second;
3691
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003692 case CXCursor_OverloadedDeclRef:
3693 return getCursorOverloadedDeclRef(C).second;
3694
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003695 default:
3696 // FIXME: Need a way to enumerate all non-reference cases.
3697 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003698 }
3699 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003700
3701 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003702 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003703
3704 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003705 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003706
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00003707 if (clang_isAttribute(C.kind))
3708 return getCursorAttr(C)->getRange();
3709
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003710 if (C.kind == CXCursor_PreprocessingDirective)
3711 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003712
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00003713 if (C.kind == CXCursor_MacroExpansion) {
3714 ASTUnit *TU = getCursorASTUnit(C);
3715 SourceRange Range = cxcursor::getCursorMacroExpansion(C)->getSourceRange();
3716 return TU->mapRangeFromPreamble(Range);
3717 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003718
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00003719 if (C.kind == CXCursor_MacroDefinition) {
3720 ASTUnit *TU = getCursorASTUnit(C);
3721 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
3722 return TU->mapRangeFromPreamble(Range);
3723 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003724
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00003725 if (C.kind == CXCursor_InclusionDirective) {
3726 ASTUnit *TU = getCursorASTUnit(C);
3727 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3728 return TU->mapRangeFromPreamble(Range);
3729 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003730
Ted Kremenek007a7c92010-11-01 23:26:51 +00003731 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3732 Decl *D = cxcursor::getCursorDecl(C);
3733 SourceRange R = D->getSourceRange();
3734 // FIXME: Multiple variables declared in a single declaration
3735 // currently lack the information needed to correctly determine their
3736 // ranges when accounting for the type-specifier. We use context
3737 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3738 // and if so, whether it is the first decl.
3739 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3740 if (!cxcursor::isFirstInDeclGroup(C))
3741 R.setBegin(VD->getLocation());
3742 }
3743 return R;
3744 }
Douglas Gregor66537982010-11-17 17:14:07 +00003745 return SourceRange();
3746}
3747
3748/// \brief Retrieves the "raw" cursor extent, which is then extended to include
3749/// the decl-specifier-seq for declarations.
3750static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
3751 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3752 Decl *D = cxcursor::getCursorDecl(C);
3753 SourceRange R = D->getSourceRange();
Douglas Gregor66537982010-11-17 17:14:07 +00003754
Douglas Gregor2494dd02011-03-01 01:34:45 +00003755 // Adjust the start of the location for declarations preceded by
3756 // declaration specifiers.
3757 SourceLocation StartLoc;
3758 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
3759 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
3760 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
3761 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
3762 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
3763 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
3764 }
3765
3766 if (StartLoc.isValid() && R.getBegin().isValid() &&
3767 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
3768 R.setBegin(StartLoc);
3769
3770 // FIXME: Multiple variables declared in a single declaration
3771 // currently lack the information needed to correctly determine their
3772 // ranges when accounting for the type-specifier. We use context
3773 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3774 // and if so, whether it is the first decl.
3775 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3776 if (!cxcursor::isFirstInDeclGroup(C))
3777 R.setBegin(VD->getLocation());
Douglas Gregor66537982010-11-17 17:14:07 +00003778 }
3779
3780 return R;
3781 }
3782
3783 return getRawCursorExtent(C);
3784}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003785
3786extern "C" {
3787
3788CXSourceRange clang_getCursorExtent(CXCursor C) {
3789 SourceRange R = getRawCursorExtent(C);
3790 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003791 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003792
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003793 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003794}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003795
3796CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003797 if (clang_isInvalid(C.kind))
3798 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003799
Ted Kremeneka60ed472010-11-16 08:15:36 +00003800 CXTranslationUnit tu = getCursorTU(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003801 if (clang_isDeclaration(C.kind)) {
3802 Decl *D = getCursorDecl(C);
3803 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003804 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003805 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003806 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003807 if (ObjCForwardProtocolDecl *Protocols
3808 = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003809 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), tu);
Chris Lattner5f9e2722011-07-23 10:55:15 +00003810 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00003811 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3812 return MakeCXCursor(Property, tu);
3813
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003814 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003815 }
3816
Douglas Gregor97b98722010-01-19 23:20:36 +00003817 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003818 Expr *E = getCursorExpr(C);
3819 Decl *D = getDeclFromExpr(E);
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003820 if (D) {
3821 CXCursor declCursor = MakeCXCursor(D, tu);
3822 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
3823 declCursor);
3824 return declCursor;
3825 }
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003826
3827 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003828 return MakeCursorOverloadedDeclRef(Ovl, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003829
Douglas Gregor97b98722010-01-19 23:20:36 +00003830 return clang_getNullCursor();
3831 }
3832
Douglas Gregor36897b02010-09-10 00:22:18 +00003833 if (clang_isStatement(C.kind)) {
3834 Stmt *S = getCursorStmt(C);
3835 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Ted Kremenek37c2e962011-03-15 23:47:49 +00003836 if (LabelDecl *label = Goto->getLabel())
3837 if (LabelStmt *labelS = label->getStmt())
3838 return MakeCXCursor(labelS, getCursorDecl(C), tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003839
3840 return clang_getNullCursor();
3841 }
3842
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003843 if (C.kind == CXCursor_MacroExpansion) {
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003844 if (MacroDefinition *Def = getCursorMacroExpansion(C)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003845 return MakeMacroDefinitionCursor(Def, tu);
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003846 }
3847
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003848 if (!clang_isReference(C.kind))
3849 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003850
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003851 switch (C.kind) {
3852 case CXCursor_ObjCSuperClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003853 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003854
3855 case CXCursor_ObjCProtocolRef: {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003856 return MakeCXCursor(getCursorObjCProtocolRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003857
3858 case CXCursor_ObjCClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003859 return MakeCXCursor(getCursorObjCClassRef(C).first, tu );
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003860
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003861 case CXCursor_TypeRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003862 return MakeCXCursor(getCursorTypeRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003863
3864 case CXCursor_TemplateRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003865 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003866
Douglas Gregor69319002010-08-31 23:48:11 +00003867 case CXCursor_NamespaceRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003868 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
Douglas Gregor69319002010-08-31 23:48:11 +00003869
Douglas Gregora67e03f2010-09-09 21:42:20 +00003870 case CXCursor_MemberRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003871 return MakeCXCursor(getCursorMemberRef(C).first, tu );
Douglas Gregora67e03f2010-09-09 21:42:20 +00003872
Ted Kremenek3064ef92010-08-27 21:34:58 +00003873 case CXCursor_CXXBaseSpecifier: {
3874 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3875 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003876 tu ));
Ted Kremenek3064ef92010-08-27 21:34:58 +00003877 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003878
Douglas Gregor36897b02010-09-10 00:22:18 +00003879 case CXCursor_LabelRef:
3880 // FIXME: We end up faking the "parent" declaration here because we
3881 // don't want to make CXCursor larger.
3882 return MakeCXCursor(getCursorLabelRef(C).first,
Ted Kremeneka60ed472010-11-16 08:15:36 +00003883 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
3884 .getTranslationUnitDecl(),
3885 tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003886
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003887 case CXCursor_OverloadedDeclRef:
3888 return C;
3889
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003890 default:
3891 // We would prefer to enumerate all non-reference cursor kinds here.
3892 llvm_unreachable("Unhandled reference cursor kind");
3893 break;
3894 }
3895 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003896
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003897 return clang_getNullCursor();
3898}
3899
Douglas Gregorb6998662010-01-19 19:34:47 +00003900CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003901 if (clang_isInvalid(C.kind))
3902 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003903
Ted Kremeneka60ed472010-11-16 08:15:36 +00003904 CXTranslationUnit TU = getCursorTU(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003905
Douglas Gregorb6998662010-01-19 19:34:47 +00003906 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003907 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003908 C = clang_getCursorReferenced(C);
3909 WasReference = true;
3910 }
3911
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003912 if (C.kind == CXCursor_MacroExpansion)
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003913 return clang_getCursorReferenced(C);
3914
Douglas Gregorb6998662010-01-19 19:34:47 +00003915 if (!clang_isDeclaration(C.kind))
3916 return clang_getNullCursor();
3917
3918 Decl *D = getCursorDecl(C);
3919 if (!D)
3920 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003921
Douglas Gregorb6998662010-01-19 19:34:47 +00003922 switch (D->getKind()) {
3923 // Declaration kinds that don't really separate the notions of
3924 // declaration and definition.
3925 case Decl::Namespace:
3926 case Decl::Typedef:
Richard Smith162e1c12011-04-15 14:24:37 +00003927 case Decl::TypeAlias:
Richard Smith3e4c6c42011-05-05 21:57:07 +00003928 case Decl::TypeAliasTemplate:
Douglas Gregorb6998662010-01-19 19:34:47 +00003929 case Decl::TemplateTypeParm:
3930 case Decl::EnumConstant:
3931 case Decl::Field:
Benjamin Kramerd9811462010-11-21 14:11:41 +00003932 case Decl::IndirectField:
Douglas Gregorb6998662010-01-19 19:34:47 +00003933 case Decl::ObjCIvar:
3934 case Decl::ObjCAtDefsField:
3935 case Decl::ImplicitParam:
3936 case Decl::ParmVar:
3937 case Decl::NonTypeTemplateParm:
3938 case Decl::TemplateTemplateParm:
3939 case Decl::ObjCCategoryImpl:
3940 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00003941 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00003942 case Decl::LinkageSpec:
3943 case Decl::ObjCPropertyImpl:
3944 case Decl::FileScopeAsm:
3945 case Decl::StaticAssert:
3946 case Decl::Block:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003947 case Decl::Label: // FIXME: Is this right??
Francois Pichetaf0f4d02011-08-14 03:52:19 +00003948 case Decl::ClassScopeFunctionSpecialization:
Douglas Gregorb6998662010-01-19 19:34:47 +00003949 return C;
3950
3951 // Declaration kinds that don't make any sense here, but are
3952 // nonetheless harmless.
3953 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00003954 break;
3955
3956 // Declaration kinds for which the definition is not resolvable.
3957 case Decl::UnresolvedUsingTypename:
3958 case Decl::UnresolvedUsingValue:
3959 break;
3960
3961 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003962 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003963 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003964
3965 case Decl::NamespaceAlias:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003966 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003967
3968 case Decl::Enum:
3969 case Decl::Record:
3970 case Decl::CXXRecord:
3971 case Decl::ClassTemplateSpecialization:
3972 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00003973 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003974 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003975 return clang_getNullCursor();
3976
3977 case Decl::Function:
3978 case Decl::CXXMethod:
3979 case Decl::CXXConstructor:
3980 case Decl::CXXDestructor:
3981 case Decl::CXXConversion: {
3982 const FunctionDecl *Def = 0;
3983 if (cast<FunctionDecl>(D)->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003984 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003985 return clang_getNullCursor();
3986 }
3987
3988 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00003989 // Ask the variable if it has a definition.
3990 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003991 return MakeCXCursor(Def, TU);
Sebastian Redl31310a22010-02-01 20:16:42 +00003992 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00003993 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003994
Douglas Gregorb6998662010-01-19 19:34:47 +00003995 case Decl::FunctionTemplate: {
3996 const FunctionDecl *Def = 0;
3997 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003998 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003999 return clang_getNullCursor();
4000 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004001
Douglas Gregorb6998662010-01-19 19:34:47 +00004002 case Decl::ClassTemplate: {
4003 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00004004 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00004005 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004006 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004007 return clang_getNullCursor();
4008 }
4009
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004010 case Decl::Using:
4011 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004012 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004013
4014 case Decl::UsingShadow:
4015 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004016 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004017 TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004018
4019 case Decl::ObjCMethod: {
4020 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
4021 if (Method->isThisDeclarationADefinition())
4022 return C;
4023
4024 // Dig out the method definition in the associated
4025 // @implementation, if we have it.
4026 // FIXME: The ASTs should make finding the definition easier.
4027 if (ObjCInterfaceDecl *Class
4028 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
4029 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
4030 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
4031 Method->isInstanceMethod()))
4032 if (Def->isThisDeclarationADefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004033 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004034
4035 return clang_getNullCursor();
4036 }
4037
4038 case Decl::ObjCCategory:
4039 if (ObjCCategoryImplDecl *Impl
4040 = cast<ObjCCategoryDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004041 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004042 return clang_getNullCursor();
4043
4044 case Decl::ObjCProtocol:
4045 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
4046 return C;
4047 return clang_getNullCursor();
4048
4049 case Decl::ObjCInterface:
4050 // There are two notions of a "definition" for an Objective-C
4051 // class: the interface and its implementation. When we resolved a
4052 // reference to an Objective-C class, produce the @interface as
4053 // the definition; when we were provided with the interface,
4054 // produce the @implementation as the definition.
4055 if (WasReference) {
4056 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
4057 return C;
4058 } else if (ObjCImplementationDecl *Impl
4059 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004060 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004061 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004062
Douglas Gregorb6998662010-01-19 19:34:47 +00004063 case Decl::ObjCProperty:
4064 // FIXME: We don't really know where to find the
4065 // ObjCPropertyImplDecls that implement this property.
4066 return clang_getNullCursor();
4067
4068 case Decl::ObjCCompatibleAlias:
4069 if (ObjCInterfaceDecl *Class
4070 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
4071 if (!Class->isForwardDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004072 return MakeCXCursor(Class, TU);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004073
Douglas Gregorb6998662010-01-19 19:34:47 +00004074 return clang_getNullCursor();
4075
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004076 case Decl::ObjCForwardProtocol:
4077 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004078 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004079
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004080 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004081 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004082 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004083
4084 case Decl::Friend:
4085 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004086 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004087 return clang_getNullCursor();
4088
4089 case Decl::FriendTemplate:
4090 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004091 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004092 return clang_getNullCursor();
4093 }
4094
4095 return clang_getNullCursor();
4096}
4097
4098unsigned clang_isCursorDefinition(CXCursor C) {
4099 if (!clang_isDeclaration(C.kind))
4100 return 0;
4101
4102 return clang_getCursorDefinition(C) == C;
4103}
4104
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004105CXCursor clang_getCanonicalCursor(CXCursor C) {
4106 if (!clang_isDeclaration(C.kind))
4107 return C;
4108
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004109 if (Decl *D = getCursorDecl(C)) {
Argyrios Kyrtzidisdebb00f2011-07-15 22:37:58 +00004110 if (ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
4111 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
4112 return MakeCXCursor(CatD, getCursorTU(C));
4113
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004114 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
4115 if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
4116 return MakeCXCursor(IFD, getCursorTU(C));
4117
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004118 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004119 }
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004120
4121 return C;
4122}
4123
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004124unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004125 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004126 return 0;
4127
4128 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
4129 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
4130 return E->getNumDecls();
4131
4132 if (OverloadedTemplateStorage *S
4133 = Storage.dyn_cast<OverloadedTemplateStorage*>())
4134 return S->size();
4135
4136 Decl *D = Storage.get<Decl*>();
4137 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00004138 return Using->shadow_size();
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00004139 if (isa<ObjCClassDecl>(D))
4140 return 1;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004141 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
4142 return Protocols->protocol_size();
4143
4144 return 0;
4145}
4146
4147CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004148 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004149 return clang_getNullCursor();
4150
4151 if (index >= clang_getNumOverloadedDecls(cursor))
4152 return clang_getNullCursor();
4153
Ted Kremeneka60ed472010-11-16 08:15:36 +00004154 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004155 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
4156 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004157 return MakeCXCursor(E->decls_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004158
4159 if (OverloadedTemplateStorage *S
4160 = Storage.dyn_cast<OverloadedTemplateStorage*>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004161 return MakeCXCursor(S->begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004162
4163 Decl *D = Storage.get<Decl*>();
4164 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
4165 // FIXME: This is, unfortunately, linear time.
4166 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
4167 std::advance(Pos, index);
Ted Kremeneka60ed472010-11-16 08:15:36 +00004168 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004169 }
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004170 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00004171 return MakeCXCursor(Classes->getForwardInterfaceDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004172 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004173 return MakeCXCursor(Protocols->protocol_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004174
4175 return clang_getNullCursor();
4176}
4177
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00004178void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00004179 const char **startBuf,
4180 const char **endBuf,
4181 unsigned *startLine,
4182 unsigned *startColumn,
4183 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00004184 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00004185 assert(getCursorDecl(C) && "CXCursor has null decl");
4186 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00004187 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
4188 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004189
Steve Naroff4ade6d62009-09-23 17:52:52 +00004190 SourceManager &SM = FD->getASTContext().getSourceManager();
4191 *startBuf = SM.getCharacterData(Body->getLBracLoc());
4192 *endBuf = SM.getCharacterData(Body->getRBracLoc());
4193 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
4194 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
4195 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
4196 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
4197}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004198
Douglas Gregor430d7a12011-07-25 17:48:11 +00004199
4200CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
4201 unsigned PieceIndex) {
4202 RefNamePieces Pieces;
4203
4204 switch (C.kind) {
4205 case CXCursor_MemberRefExpr:
4206 if (MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
4207 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
4208 E->getQualifierLoc().getSourceRange());
4209 break;
4210
4211 case CXCursor_DeclRefExpr:
4212 if (DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C)))
4213 Pieces = buildPieces(NameFlags, false, E->getNameInfo(),
4214 E->getQualifierLoc().getSourceRange(),
4215 E->getExplicitTemplateArgsOpt());
4216 break;
4217
4218 case CXCursor_CallExpr:
4219 if (CXXOperatorCallExpr *OCE =
4220 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
4221 Expr *Callee = OCE->getCallee();
4222 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
4223 Callee = ICE->getSubExpr();
4224
4225 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
4226 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
4227 DRE->getQualifierLoc().getSourceRange());
4228 }
4229 break;
4230
4231 default:
4232 break;
4233 }
4234
4235 if (Pieces.empty()) {
4236 if (PieceIndex == 0)
4237 return clang_getCursorExtent(C);
4238 } else if (PieceIndex < Pieces.size()) {
4239 SourceRange R = Pieces[PieceIndex];
4240 if (R.isValid())
4241 return cxloc::translateSourceRange(getCursorContext(C), R);
4242 }
4243
4244 return clang_getNullRange();
4245}
4246
Douglas Gregor0a812cf2010-02-18 23:07:20 +00004247void clang_enableStackTraces(void) {
4248 llvm::sys::PrintStackTraceOnErrorSignal();
4249}
4250
Daniel Dunbar995aaf92010-11-04 01:26:29 +00004251void clang_executeOnThread(void (*fn)(void*), void *user_data,
4252 unsigned stack_size) {
4253 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
4254}
4255
Ted Kremenekfb480492010-01-13 21:46:36 +00004256} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00004257
Ted Kremenekfb480492010-01-13 21:46:36 +00004258//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004259// Token-based Operations.
4260//===----------------------------------------------------------------------===//
4261
4262/* CXToken layout:
4263 * int_data[0]: a CXTokenKind
4264 * int_data[1]: starting token location
4265 * int_data[2]: token length
4266 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004267 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004268 * otherwise unused.
4269 */
4270extern "C" {
4271
4272CXTokenKind clang_getTokenKind(CXToken CXTok) {
4273 return static_cast<CXTokenKind>(CXTok.int_data[0]);
4274}
4275
4276CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
4277 switch (clang_getTokenKind(CXTok)) {
4278 case CXToken_Identifier:
4279 case CXToken_Keyword:
4280 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004281 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
4282 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004283
4284 case CXToken_Literal: {
4285 // We have stashed the starting pointer in the ptr_data field. Use it.
4286 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Chris Lattner5f9e2722011-07-23 10:55:15 +00004287 return createCXString(StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004288 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004289
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004290 case CXToken_Punctuation:
4291 case CXToken_Comment:
4292 break;
4293 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004294
4295 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004296 // deconstructing the source location.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004297 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004298 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004299 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004300
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004301 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
4302 std::pair<FileID, unsigned> LocInfo
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004303 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00004304 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004305 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004306 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
4307 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00004308 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004309
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004310 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004311}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004312
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004313CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004314 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004315 if (!CXXUnit)
4316 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004317
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004318 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
4319 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4320}
4321
4322CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004323 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor5352ac02010-01-28 00:27:43 +00004324 if (!CXXUnit)
4325 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004326
4327 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004328 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4329}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004330
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004331static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
4332 SmallVectorImpl<CXToken> &CXTokens) {
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004333 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4334 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004335 = SourceMgr.getDecomposedLoc(Range.getBegin());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004336 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004337 = SourceMgr.getDecomposedLoc(Range.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004338
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004339 // Cannot tokenize across files.
4340 if (BeginLocInfo.first != EndLocInfo.first)
4341 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004342
4343 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004344 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004345 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004346 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00004347 if (Invalid)
4348 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00004349
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004350 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4351 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004352 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004353 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004354
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004355 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004356 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004357 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00004358 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004359 do {
4360 // Lex the next token
4361 Lex.LexFromRawLexer(Tok);
4362 if (Tok.is(tok::eof))
4363 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004364
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004365 // Initialize the CXToken.
4366 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004367
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004368 // - Common fields
4369 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
4370 CXTok.int_data[2] = Tok.getLength();
4371 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004372
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004373 // - Kind-specific fields
4374 if (Tok.isLiteral()) {
4375 CXTok.int_data[0] = CXToken_Literal;
4376 CXTok.ptr_data = (void *)Tok.getLiteralData();
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004377 } else if (Tok.is(tok::raw_identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00004378 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004379 IdentifierInfo *II
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004380 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004381
David Chisnall096428b2010-10-13 21:44:48 +00004382 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004383 CXTok.int_data[0] = CXToken_Keyword;
4384 }
4385 else {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004386 CXTok.int_data[0] = Tok.is(tok::identifier)
4387 ? CXToken_Identifier
4388 : CXToken_Keyword;
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004389 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004390 CXTok.ptr_data = II;
4391 } else if (Tok.is(tok::comment)) {
4392 CXTok.int_data[0] = CXToken_Comment;
4393 CXTok.ptr_data = 0;
4394 } else {
4395 CXTok.int_data[0] = CXToken_Punctuation;
4396 CXTok.ptr_data = 0;
4397 }
4398 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00004399 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004400 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004401}
4402
4403void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
4404 CXToken **Tokens, unsigned *NumTokens) {
4405 if (Tokens)
4406 *Tokens = 0;
4407 if (NumTokens)
4408 *NumTokens = 0;
4409
4410 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4411 if (!CXXUnit || !Tokens || !NumTokens)
4412 return;
4413
4414 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4415
4416 SourceRange R = cxloc::translateCXSourceRange(Range);
4417 if (R.isInvalid())
4418 return;
4419
4420 SmallVector<CXToken, 32> CXTokens;
4421 getTokens(CXXUnit, R, CXTokens);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004422
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004423 if (CXTokens.empty())
4424 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004425
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004426 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
4427 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
4428 *NumTokens = CXTokens.size();
4429}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004430
Ted Kremenek6db61092010-05-05 00:55:15 +00004431void clang_disposeTokens(CXTranslationUnit TU,
4432 CXToken *Tokens, unsigned NumTokens) {
4433 free(Tokens);
4434}
4435
4436} // end: extern "C"
4437
4438//===----------------------------------------------------------------------===//
4439// Token annotation APIs.
4440//===----------------------------------------------------------------------===//
4441
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004442typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004443static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4444 CXCursor parent,
4445 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00004446namespace {
4447class AnnotateTokensWorker {
4448 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004449 CXToken *Tokens;
4450 CXCursor *Cursors;
4451 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004452 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00004453 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004454 CursorVisitor AnnotateVis;
4455 SourceManager &SrcMgr;
Douglas Gregorf5251602011-03-08 17:10:18 +00004456 bool HasContextSensitiveKeywords;
4457
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004458 bool MoreTokens() const { return TokIdx < NumTokens; }
4459 unsigned NextToken() const { return TokIdx; }
4460 void AdvanceToken() { ++TokIdx; }
4461 SourceLocation GetTokenLoc(unsigned tokI) {
4462 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4463 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004464 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004465 return Tokens[tokI].int_data[3] != 0;
4466 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004467 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004468 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[3]);
4469 }
4470
4471 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004472 void annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
4473 SourceRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004474
Ted Kremenek6db61092010-05-05 00:55:15 +00004475public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00004476 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004477 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004478 CXTranslationUnit tu, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00004479 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00004480 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004481 AnnotateVis(tu,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00004482 AnnotateTokensVisitor, this,
4483 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00004484 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00004485 RegionOfInterest),
Douglas Gregorf5251602011-03-08 17:10:18 +00004486 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()),
4487 HasContextSensitiveKeywords(false) { }
Ted Kremenek11949cb2010-05-05 00:55:17 +00004488
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004489 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00004490 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004491 void AnnotateTokens(CXCursor parent);
Ted Kremenekab979612010-11-11 08:05:23 +00004492 void AnnotateTokens() {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004493 AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getTU()));
Ted Kremenekab979612010-11-11 08:05:23 +00004494 }
Douglas Gregorf5251602011-03-08 17:10:18 +00004495
4496 /// \brief Determine whether the annotator saw any cursors that have
4497 /// context-sensitive keywords.
4498 bool hasContextSensitiveKeywords() const {
4499 return HasContextSensitiveKeywords;
4500 }
Ted Kremenek6db61092010-05-05 00:55:15 +00004501};
4502}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004503
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004504void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
4505 // Walk the AST within the region of interest, annotating tokens
4506 // along the way.
4507 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00004508
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004509 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4510 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004511 if (Pos != Annotated.end() &&
4512 (clang_isInvalid(Cursors[I].kind) ||
4513 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004514 Cursors[I] = Pos->second;
4515 }
4516
4517 // Finish up annotating any tokens left.
4518 if (!MoreTokens())
4519 return;
4520
4521 const CXCursor &C = clang_getNullCursor();
4522 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
4523 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4524 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004525 }
4526}
4527
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004528/// \brief It annotates and advances tokens with a cursor until the comparison
4529//// between the cursor location and the source range is the same as
4530/// \arg compResult.
4531///
4532/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
4533/// Pass RangeOverlap to annotate tokens inside a range.
4534void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
4535 RangeComparisonResult compResult,
4536 SourceRange range) {
4537 while (MoreTokens()) {
4538 const unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004539 if (isFunctionMacroToken(I))
4540 return annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004541
4542 SourceLocation TokLoc = GetTokenLoc(I);
4543 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4544 Cursors[I] = updateC;
4545 AdvanceToken();
4546 continue;
4547 }
4548 break;
4549 }
4550}
4551
4552/// \brief Special annotation handling for macro argument tokens.
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004553void AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
4554 CXCursor updateC,
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004555 RangeComparisonResult compResult,
4556 SourceRange range) {
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004557 assert(MoreTokens());
4558 assert(isFunctionMacroToken(NextToken()) &&
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004559 "Should be called only for macro arg tokens");
4560
4561 // This works differently than annotateAndAdvanceTokens; because expanded
4562 // macro arguments can have arbitrary translation-unit source order, we do not
4563 // advance the token index one by one until a token fails the range test.
4564 // We only advance once past all of the macro arg tokens if all of them
4565 // pass the range test. If one of them fails we keep the token index pointing
4566 // at the start of the macro arg tokens so that the failing token will be
4567 // annotated by a subsequent annotation try.
4568
4569 bool atLeastOneCompFail = false;
4570
4571 unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004572 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
4573 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004574 if (TokLoc.isFileID())
4575 continue; // not macro arg token, it's parens or comma.
4576 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4577 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
4578 Cursors[I] = updateC;
4579 } else
4580 atLeastOneCompFail = true;
4581 }
4582
4583 if (!atLeastOneCompFail)
4584 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
4585}
4586
Ted Kremenek6db61092010-05-05 00:55:15 +00004587enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004588AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004589 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004590 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004591 if (cursorRange.isInvalid())
4592 return CXChildVisit_Recurse;
Douglas Gregorf5251602011-03-08 17:10:18 +00004593
4594 if (!HasContextSensitiveKeywords) {
4595 // Objective-C properties can have context-sensitive keywords.
4596 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
4597 if (ObjCPropertyDecl *Property
4598 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
4599 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
4600 }
4601 // Objective-C methods can have context-sensitive keywords.
4602 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
4603 cursor.kind == CXCursor_ObjCClassMethodDecl) {
4604 if (ObjCMethodDecl *Method
4605 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
4606 if (Method->getObjCDeclQualifier())
4607 HasContextSensitiveKeywords = true;
4608 else {
4609 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
4610 PEnd = Method->param_end();
4611 P != PEnd; ++P) {
4612 if ((*P)->getObjCDeclQualifier()) {
4613 HasContextSensitiveKeywords = true;
4614 break;
4615 }
4616 }
4617 }
4618 }
4619 }
4620 // C++ methods can have context-sensitive keywords.
4621 else if (cursor.kind == CXCursor_CXXMethod) {
4622 if (CXXMethodDecl *Method
4623 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
4624 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
4625 HasContextSensitiveKeywords = true;
4626 }
4627 }
4628 // C++ classes can have context-sensitive keywords.
4629 else if (cursor.kind == CXCursor_StructDecl ||
4630 cursor.kind == CXCursor_ClassDecl ||
4631 cursor.kind == CXCursor_ClassTemplate ||
4632 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
4633 if (Decl *D = getCursorDecl(cursor))
4634 if (D->hasAttr<FinalAttr>())
4635 HasContextSensitiveKeywords = true;
4636 }
4637 }
4638
Douglas Gregor4419b672010-10-21 06:10:04 +00004639 if (clang_isPreprocessing(cursor.kind)) {
Chandler Carruthcea731a2011-07-14 16:07:57 +00004640 // For macro expansions, just note where the beginning of the macro
4641 // expansion occurs.
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004642 if (cursor.kind == CXCursor_MacroExpansion) {
Douglas Gregor4419b672010-10-21 06:10:04 +00004643 Annotated[Loc.int_data] = cursor;
4644 return CXChildVisit_Recurse;
4645 }
4646
Douglas Gregor4419b672010-10-21 06:10:04 +00004647 // Items in the preprocessing record are kept separate from items in
4648 // declarations, so we keep a separate token index.
4649 unsigned SavedTokIdx = TokIdx;
4650 TokIdx = PreprocessingTokIdx;
4651
4652 // Skip tokens up until we catch up to the beginning of the preprocessing
4653 // entry.
4654 while (MoreTokens()) {
4655 const unsigned I = NextToken();
4656 SourceLocation TokLoc = GetTokenLoc(I);
4657 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4658 case RangeBefore:
4659 AdvanceToken();
4660 continue;
4661 case RangeAfter:
4662 case RangeOverlap:
4663 break;
4664 }
4665 break;
4666 }
4667
4668 // Look at all of the tokens within this range.
4669 while (MoreTokens()) {
4670 const unsigned I = NextToken();
4671 SourceLocation TokLoc = GetTokenLoc(I);
4672 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4673 case RangeBefore:
David Blaikieb219cfc2011-09-23 05:06:16 +00004674 llvm_unreachable("Infeasible");
Douglas Gregor4419b672010-10-21 06:10:04 +00004675 case RangeAfter:
4676 break;
4677 case RangeOverlap:
4678 Cursors[I] = cursor;
4679 AdvanceToken();
4680 continue;
4681 }
4682 break;
4683 }
4684
4685 // Save the preprocessing token index; restore the non-preprocessing
4686 // token index.
4687 PreprocessingTokIdx = TokIdx;
4688 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004689 return CXChildVisit_Recurse;
4690 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004691
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004692 if (cursorRange.isInvalid())
4693 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004694
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004695 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4696
Ted Kremeneka333c662010-05-12 05:29:33 +00004697 // Adjust the annotated range based specific declarations.
4698 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4699 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004700 Decl *D = cxcursor::getCursorDecl(cursor);
Douglas Gregor2494dd02011-03-01 01:34:45 +00004701
4702 SourceLocation StartLoc;
Ted Kremenek23173d72010-05-18 21:09:07 +00004703 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00004704 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
4705 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
4706 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
4707 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
4708 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
Ted Kremeneka333c662010-05-12 05:29:33 +00004709 }
Douglas Gregor2494dd02011-03-01 01:34:45 +00004710
4711 if (StartLoc.isValid() && L.isValid() &&
4712 SrcMgr.isBeforeInTranslationUnit(StartLoc, L))
4713 cursorRange.setBegin(StartLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004714 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004715
Ted Kremenek3f404602010-08-14 01:14:06 +00004716 // If the location of the cursor occurs within a macro instantiation, record
4717 // the spelling location of the cursor in our annotation map. We can then
4718 // paper over the token labelings during a post-processing step to try and
4719 // get cursor mappings for tokens that are the *arguments* of a macro
4720 // instantiation.
4721 if (L.isMacroID()) {
4722 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4723 // Only invalidate the old annotation if it isn't part of a preprocessing
4724 // directive. Here we assume that the default construction of CXCursor
4725 // results in CXCursor.kind being an initialized value (i.e., 0). If
4726 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004727
Ted Kremenek3f404602010-08-14 01:14:06 +00004728 CXCursor &oldC = Annotated[rawEncoding];
4729 if (!clang_isPreprocessing(oldC.kind))
4730 oldC = cursor;
4731 }
4732
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004733 const enum CXCursorKind K = clang_getCursorKind(parent);
4734 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004735 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4736 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004737
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004738 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004739
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00004740 // Avoid having the cursor of an expression "overwrite" the annotation of the
4741 // variable declaration that it belongs to.
4742 // This can happen for C++ constructor expressions whose range generally
4743 // include the variable declaration, e.g.:
4744 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
4745 if (clang_isExpression(cursorK)) {
4746 Expr *E = getCursorExpr(cursor);
Argyrios Kyrtzidis8ccac3d2011-06-29 22:20:07 +00004747 if (Decl *D = getCursorParentDecl(cursor)) {
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00004748 const unsigned I = NextToken();
4749 if (E->getLocStart().isValid() && D->getLocation().isValid() &&
4750 E->getLocStart() == D->getLocation() &&
4751 E->getLocStart() == GetTokenLoc(I)) {
4752 Cursors[I] = updateC;
4753 AdvanceToken();
4754 }
4755 }
4756 }
4757
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004758 // Visit children to get their cursor information.
4759 const unsigned BeforeChildren = NextToken();
4760 VisitChildren(cursor);
4761 const unsigned AfterChildren = NextToken();
4762
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004763 // Scan the tokens that are at the end of the cursor, but are not captured
4764 // but the child cursors.
4765 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
Ted Kremenek6db61092010-05-05 00:55:15 +00004766
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004767 // Scan the tokens that are at the beginning of the cursor, but are not
4768 // capture by the child cursors.
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004769 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4770 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4771 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004772
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004773 Cursors[I] = cursor;
4774 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004775
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004776 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004777}
4778
Ted Kremenek6db61092010-05-05 00:55:15 +00004779static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4780 CXCursor parent,
4781 CXClientData client_data) {
4782 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4783}
4784
Ted Kremenek6628a612011-03-18 22:51:30 +00004785namespace {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004786
4787/// \brief Uses the macro expansions in the preprocessing record to find
4788/// and mark tokens that are macro arguments. This info is used by the
4789/// AnnotateTokensWorker.
4790class MarkMacroArgTokensVisitor {
4791 SourceManager &SM;
4792 CXToken *Tokens;
4793 unsigned NumTokens;
4794 unsigned CurIdx;
4795
4796public:
4797 MarkMacroArgTokensVisitor(SourceManager &SM,
4798 CXToken *tokens, unsigned numTokens)
4799 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
4800
4801 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
4802 if (cursor.kind != CXCursor_MacroExpansion)
4803 return CXChildVisit_Continue;
4804
4805 SourceRange macroRange = getCursorMacroExpansion(cursor)->getSourceRange();
4806 if (macroRange.getBegin() == macroRange.getEnd())
4807 return CXChildVisit_Continue; // it's not a function macro.
4808
4809 for (; CurIdx < NumTokens; ++CurIdx) {
4810 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
4811 macroRange.getBegin()))
4812 break;
4813 }
4814
4815 if (CurIdx == NumTokens)
4816 return CXChildVisit_Break;
4817
4818 for (; CurIdx < NumTokens; ++CurIdx) {
4819 SourceLocation tokLoc = getTokenLoc(CurIdx);
4820 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
4821 break;
4822
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004823 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004824 }
4825
4826 if (CurIdx == NumTokens)
4827 return CXChildVisit_Break;
4828
4829 return CXChildVisit_Continue;
4830 }
4831
4832private:
4833 SourceLocation getTokenLoc(unsigned tokI) {
4834 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4835 }
4836
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004837 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004838 // The third field is reserved and currently not used. Use it here
4839 // to mark macro arg expanded tokens with their expanded locations.
4840 Tokens[tokI].int_data[3] = loc.getRawEncoding();
4841 }
4842};
4843
4844} // end anonymous namespace
4845
4846static CXChildVisitResult
4847MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
4848 CXClientData client_data) {
4849 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
4850 parent);
4851}
4852
4853namespace {
Ted Kremenek6628a612011-03-18 22:51:30 +00004854 struct clang_annotateTokens_Data {
4855 CXTranslationUnit TU;
4856 ASTUnit *CXXUnit;
4857 CXToken *Tokens;
4858 unsigned NumTokens;
4859 CXCursor *Cursors;
4860 };
4861}
4862
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004863static void annotatePreprocessorTokens(CXTranslationUnit TU,
4864 SourceRange RegionOfInterest,
4865 AnnotateTokensData &Annotated) {
4866 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4867
4868 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4869 std::pair<FileID, unsigned> BeginLocInfo
4870 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4871 std::pair<FileID, unsigned> EndLocInfo
4872 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
4873
4874 if (BeginLocInfo.first != EndLocInfo.first)
4875 return;
4876
4877 StringRef Buffer;
4878 bool Invalid = false;
4879 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
4880 if (Buffer.empty() || Invalid)
4881 return;
4882
4883 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4884 CXXUnit->getASTContext().getLangOptions(),
4885 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
4886 Buffer.end());
4887 Lex.SetCommentRetentionState(true);
4888
4889 // Lex tokens in raw mode until we hit the end of the range, to avoid
4890 // entering #includes or expanding macros.
4891 while (true) {
4892 Token Tok;
4893 Lex.LexFromRawLexer(Tok);
4894
4895 reprocess:
4896 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4897 // We have found a preprocessing directive. Gobble it up so that we
4898 // don't see it while preprocessing these tokens later, but keep track
4899 // of all of the token locations inside this preprocessing directive so
4900 // that we can annotate them appropriately.
4901 //
4902 // FIXME: Some simple tests here could identify macro definitions and
4903 // #undefs, to provide specific cursor kinds for those.
4904 SmallVector<SourceLocation, 32> Locations;
4905 do {
4906 Locations.push_back(Tok.getLocation());
4907 Lex.LexFromRawLexer(Tok);
4908 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
4909
4910 using namespace cxcursor;
4911 CXCursor Cursor
4912 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4913 Locations.back()),
4914 TU);
4915 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4916 Annotated[Locations[I].getRawEncoding()] = Cursor;
4917 }
4918
4919 if (Tok.isAtStartOfLine())
4920 goto reprocess;
4921
4922 continue;
4923 }
4924
4925 if (Tok.is(tok::eof))
4926 break;
4927 }
4928}
4929
Ted Kremenekab979612010-11-11 08:05:23 +00004930// This gets run a separate thread to avoid stack blowout.
Ted Kremenek6628a612011-03-18 22:51:30 +00004931static void clang_annotateTokensImpl(void *UserData) {
4932 CXTranslationUnit TU = ((clang_annotateTokens_Data*)UserData)->TU;
4933 ASTUnit *CXXUnit = ((clang_annotateTokens_Data*)UserData)->CXXUnit;
4934 CXToken *Tokens = ((clang_annotateTokens_Data*)UserData)->Tokens;
4935 const unsigned NumTokens = ((clang_annotateTokens_Data*)UserData)->NumTokens;
4936 CXCursor *Cursors = ((clang_annotateTokens_Data*)UserData)->Cursors;
4937
4938 // Determine the region of interest, which contains all of the tokens.
4939 SourceRange RegionOfInterest;
4940 RegionOfInterest.setBegin(
4941 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
4942 RegionOfInterest.setEnd(
4943 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
4944 Tokens[NumTokens-1])));
4945
4946 // A mapping from the source locations found when re-lexing or traversing the
4947 // region of interest to the corresponding cursors.
4948 AnnotateTokensData Annotated;
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004949
Ted Kremenek6628a612011-03-18 22:51:30 +00004950 // Relex the tokens within the source range to look for preprocessing
4951 // directives.
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004952 annotatePreprocessorTokens(TU, RegionOfInterest, Annotated);
Ted Kremenek6628a612011-03-18 22:51:30 +00004953
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004954 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
4955 // Search and mark tokens that are macro argument expansions.
4956 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
4957 Tokens, NumTokens);
4958 CursorVisitor MacroArgMarker(TU,
4959 MarkMacroArgTokensVisitorDelegate, &Visitor,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00004960 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00004961 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00004962 RegionOfInterest);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004963 MacroArgMarker.visitPreprocessedEntitiesInRegion();
4964 }
4965
Ted Kremenek6628a612011-03-18 22:51:30 +00004966 // Annotate all of the source locations in the region of interest that map to
4967 // a specific cursor.
4968 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
4969 TU, RegionOfInterest);
4970
4971 // FIXME: We use a ridiculous stack size here because the data-recursion
4972 // algorithm uses a large stack frame than the non-data recursive version,
4973 // and AnnotationTokensWorker currently transforms the data-recursion
4974 // algorithm back into a traditional recursion by explicitly calling
4975 // VisitChildren(). We will need to remove this explicit recursive call.
4976 W.AnnotateTokens();
4977
4978 // If we ran into any entities that involve context-sensitive keywords,
4979 // take another pass through the tokens to mark them as such.
4980 if (W.hasContextSensitiveKeywords()) {
4981 for (unsigned I = 0; I != NumTokens; ++I) {
4982 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
4983 continue;
4984
4985 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
4986 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
4987 if (ObjCPropertyDecl *Property
4988 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
4989 if (Property->getPropertyAttributesAsWritten() != 0 &&
4990 llvm::StringSwitch<bool>(II->getName())
4991 .Case("readonly", true)
4992 .Case("assign", true)
John McCallf85e1932011-06-15 23:02:42 +00004993 .Case("unsafe_unretained", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00004994 .Case("readwrite", true)
4995 .Case("retain", true)
4996 .Case("copy", true)
4997 .Case("nonatomic", true)
4998 .Case("atomic", true)
4999 .Case("getter", true)
5000 .Case("setter", true)
John McCallf85e1932011-06-15 23:02:42 +00005001 .Case("strong", true)
5002 .Case("weak", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00005003 .Default(false))
5004 Tokens[I].int_data[0] = CXToken_Keyword;
5005 }
5006 continue;
5007 }
5008
5009 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
5010 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
5011 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5012 if (llvm::StringSwitch<bool>(II->getName())
5013 .Case("in", true)
5014 .Case("out", true)
5015 .Case("inout", true)
5016 .Case("oneway", true)
5017 .Case("bycopy", true)
5018 .Case("byref", true)
5019 .Default(false))
5020 Tokens[I].int_data[0] = CXToken_Keyword;
5021 continue;
5022 }
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00005023
5024 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
5025 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
5026 Tokens[I].int_data[0] = CXToken_Keyword;
Ted Kremenek6628a612011-03-18 22:51:30 +00005027 continue;
5028 }
5029 }
5030 }
Ted Kremenekab979612010-11-11 08:05:23 +00005031}
5032
Ted Kremenek6db61092010-05-05 00:55:15 +00005033extern "C" {
5034
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005035void clang_annotateTokens(CXTranslationUnit TU,
5036 CXToken *Tokens, unsigned NumTokens,
5037 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005038
5039 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005040 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005041
Douglas Gregor4419b672010-10-21 06:10:04 +00005042 // Any token we don't specifically annotate will have a NULL cursor.
5043 CXCursor C = clang_getNullCursor();
5044 for (unsigned I = 0; I != NumTokens; ++I)
5045 Cursors[I] = C;
5046
Ted Kremeneka60ed472010-11-16 08:15:36 +00005047 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor4419b672010-10-21 06:10:04 +00005048 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005049 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005050
Douglas Gregorbdf60622010-03-05 21:16:25 +00005051 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenek6628a612011-03-18 22:51:30 +00005052
5053 clang_annotateTokens_Data data = { TU, CXXUnit, Tokens, NumTokens, Cursors };
Ted Kremenekab979612010-11-11 08:05:23 +00005054 llvm::CrashRecoveryContext CRC;
Ted Kremenek6628a612011-03-18 22:51:30 +00005055 if (!RunSafely(CRC, clang_annotateTokensImpl, &data,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005056 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00005057 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
5058 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005059}
Ted Kremenek6628a612011-03-18 22:51:30 +00005060
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005061} // end: extern "C"
5062
5063//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00005064// Operations for querying linkage of a cursor.
5065//===----------------------------------------------------------------------===//
5066
5067extern "C" {
5068CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00005069 if (!clang_isDeclaration(cursor.kind))
5070 return CXLinkage_Invalid;
5071
Ted Kremenek16b42592010-03-03 06:36:57 +00005072 Decl *D = cxcursor::getCursorDecl(cursor);
5073 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
5074 switch (ND->getLinkage()) {
5075 case NoLinkage: return CXLinkage_NoLinkage;
5076 case InternalLinkage: return CXLinkage_Internal;
5077 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
5078 case ExternalLinkage: return CXLinkage_External;
5079 };
5080
5081 return CXLinkage_Invalid;
5082}
5083} // end: extern "C"
5084
5085//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005086// Operations for querying language of a cursor.
5087//===----------------------------------------------------------------------===//
5088
5089static CXLanguageKind getDeclLanguage(const Decl *D) {
5090 switch (D->getKind()) {
5091 default:
5092 break;
5093 case Decl::ImplicitParam:
5094 case Decl::ObjCAtDefsField:
5095 case Decl::ObjCCategory:
5096 case Decl::ObjCCategoryImpl:
5097 case Decl::ObjCClass:
5098 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005099 case Decl::ObjCForwardProtocol:
5100 case Decl::ObjCImplementation:
5101 case Decl::ObjCInterface:
5102 case Decl::ObjCIvar:
5103 case Decl::ObjCMethod:
5104 case Decl::ObjCProperty:
5105 case Decl::ObjCPropertyImpl:
5106 case Decl::ObjCProtocol:
5107 return CXLanguage_ObjC;
5108 case Decl::CXXConstructor:
5109 case Decl::CXXConversion:
5110 case Decl::CXXDestructor:
5111 case Decl::CXXMethod:
5112 case Decl::CXXRecord:
5113 case Decl::ClassTemplate:
5114 case Decl::ClassTemplatePartialSpecialization:
5115 case Decl::ClassTemplateSpecialization:
5116 case Decl::Friend:
5117 case Decl::FriendTemplate:
5118 case Decl::FunctionTemplate:
5119 case Decl::LinkageSpec:
5120 case Decl::Namespace:
5121 case Decl::NamespaceAlias:
5122 case Decl::NonTypeTemplateParm:
5123 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005124 case Decl::TemplateTemplateParm:
5125 case Decl::TemplateTypeParm:
5126 case Decl::UnresolvedUsingTypename:
5127 case Decl::UnresolvedUsingValue:
5128 case Decl::Using:
5129 case Decl::UsingDirective:
5130 case Decl::UsingShadow:
5131 return CXLanguage_CPlusPlus;
5132 }
5133
5134 return CXLanguage_C;
5135}
5136
5137extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00005138
5139enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
5140 if (clang_isDeclaration(cursor.kind))
5141 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005142 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Douglas Gregor58ddb602010-08-23 23:00:57 +00005143 return CXAvailability_Available;
5144
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005145 switch (D->getAvailability()) {
5146 case AR_Available:
5147 case AR_NotYetIntroduced:
5148 return CXAvailability_Available;
5149
5150 case AR_Deprecated:
Douglas Gregor58ddb602010-08-23 23:00:57 +00005151 return CXAvailability_Deprecated;
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005152
5153 case AR_Unavailable:
5154 return CXAvailability_NotAvailable;
5155 }
Douglas Gregor58ddb602010-08-23 23:00:57 +00005156 }
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005157
Douglas Gregor58ddb602010-08-23 23:00:57 +00005158 return CXAvailability_Available;
5159}
5160
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005161CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
5162 if (clang_isDeclaration(cursor.kind))
5163 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
5164
5165 return CXLanguage_Invalid;
5166}
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005167
5168 /// \brief If the given cursor is the "templated" declaration
5169 /// descibing a class or function template, return the class or
5170 /// function template.
5171static Decl *maybeGetTemplateCursor(Decl *D) {
5172 if (!D)
5173 return 0;
5174
5175 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
5176 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
5177 return FunTmpl;
5178
5179 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
5180 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
5181 return ClassTmpl;
5182
5183 return D;
5184}
5185
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005186CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
5187 if (clang_isDeclaration(cursor.kind)) {
5188 if (Decl *D = getCursorDecl(cursor)) {
5189 DeclContext *DC = D->getDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005190 if (!DC)
5191 return clang_getNullCursor();
5192
5193 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5194 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005195 }
5196 }
5197
5198 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
5199 if (Decl *D = getCursorDecl(cursor))
Ted Kremeneka60ed472010-11-16 08:15:36 +00005200 return MakeCXCursor(D, getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005201 }
5202
5203 return clang_getNullCursor();
5204}
5205
5206CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
5207 if (clang_isDeclaration(cursor.kind)) {
5208 if (Decl *D = getCursorDecl(cursor)) {
5209 DeclContext *DC = D->getLexicalDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005210 if (!DC)
5211 return clang_getNullCursor();
5212
5213 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5214 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005215 }
5216 }
5217
5218 // FIXME: Note that we can't easily compute the lexical context of a
5219 // statement or expression, so we return nothing.
5220 return clang_getNullCursor();
5221}
5222
Douglas Gregor9f592342010-10-01 20:25:15 +00005223void clang_getOverriddenCursors(CXCursor cursor,
5224 CXCursor **overridden,
5225 unsigned *num_overridden) {
5226 if (overridden)
5227 *overridden = 0;
5228 if (num_overridden)
5229 *num_overridden = 0;
5230 if (!overridden || !num_overridden)
5231 return;
5232
Argyrios Kyrtzidisb11be042011-10-06 07:00:46 +00005233 SmallVector<CXCursor, 8> Overridden;
5234 cxcursor::getOverriddenCursors(cursor, Overridden);
Douglas Gregor9f592342010-10-01 20:25:15 +00005235
Argyrios Kyrtzidisb11be042011-10-06 07:00:46 +00005236 *num_overridden = Overridden.size();
5237 *overridden = new CXCursor [Overridden.size()];
5238 std::copy(Overridden.begin(), Overridden.end(), *overridden);
Douglas Gregor9f592342010-10-01 20:25:15 +00005239}
5240
5241void clang_disposeOverriddenCursors(CXCursor *overridden) {
5242 delete [] overridden;
5243}
5244
Douglas Gregorecdcb882010-10-20 22:00:55 +00005245CXFile clang_getIncludedFile(CXCursor cursor) {
5246 if (cursor.kind != CXCursor_InclusionDirective)
5247 return 0;
5248
5249 InclusionDirective *ID = getCursorInclusionDirective(cursor);
5250 return (void *)ID->getFile();
5251}
5252
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005253} // end: extern "C"
5254
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005255
5256//===----------------------------------------------------------------------===//
5257// C++ AST instrospection.
5258//===----------------------------------------------------------------------===//
5259
5260extern "C" {
5261unsigned clang_CXXMethod_isStatic(CXCursor C) {
5262 if (!clang_isDeclaration(C.kind))
5263 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00005264
5265 CXXMethodDecl *Method = 0;
5266 Decl *D = cxcursor::getCursorDecl(C);
5267 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5268 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5269 else
5270 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5271 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00005272}
Ted Kremenekb12903e2010-05-18 22:32:15 +00005273
Douglas Gregor211924b2011-05-12 15:17:24 +00005274unsigned clang_CXXMethod_isVirtual(CXCursor C) {
5275 if (!clang_isDeclaration(C.kind))
5276 return 0;
5277
5278 CXXMethodDecl *Method = 0;
5279 Decl *D = cxcursor::getCursorDecl(C);
5280 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5281 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5282 else
5283 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5284 return (Method && Method->isVirtual()) ? 1 : 0;
5285}
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005286} // end: extern "C"
5287
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005288//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00005289// Attribute introspection.
5290//===----------------------------------------------------------------------===//
5291
5292extern "C" {
5293CXType clang_getIBOutletCollectionType(CXCursor C) {
5294 if (C.kind != CXCursor_IBOutletCollectionAttr)
Ted Kremeneka60ed472010-11-16 08:15:36 +00005295 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005296
5297 IBOutletCollectionAttr *A =
5298 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
5299
Argyrios Kyrtzidis18aa2ff2011-09-13 18:49:52 +00005300 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005301}
5302} // end: extern "C"
5303
5304//===----------------------------------------------------------------------===//
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005305// Inspecting memory usage.
5306//===----------------------------------------------------------------------===//
5307
Ted Kremenekf7870022011-04-20 16:41:07 +00005308typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005309
Ted Kremenekf7870022011-04-20 16:41:07 +00005310static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
5311 enum CXTUResourceUsageKind k,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005312 unsigned long amount) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005313 CXTUResourceUsageEntry entry = { k, amount };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005314 entries.push_back(entry);
5315}
5316
5317extern "C" {
5318
Ted Kremenekf7870022011-04-20 16:41:07 +00005319const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005320 const char *str = "";
5321 switch (kind) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005322 case CXTUResourceUsage_AST:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005323 str = "ASTContext: expressions, declarations, and types";
5324 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005325 case CXTUResourceUsage_Identifiers:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005326 str = "ASTContext: identifiers";
5327 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005328 case CXTUResourceUsage_Selectors:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005329 str = "ASTContext: selectors";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005330 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005331 case CXTUResourceUsage_GlobalCompletionResults:
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005332 str = "Code completion: cached global results";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005333 break;
Ted Kremenek457aaf02011-04-28 04:10:31 +00005334 case CXTUResourceUsage_SourceManagerContentCache:
5335 str = "SourceManager: content cache allocator";
5336 break;
Ted Kremenekba29bd22011-04-28 04:53:38 +00005337 case CXTUResourceUsage_AST_SideTables:
5338 str = "ASTContext: side tables";
5339 break;
Ted Kremenekf61b8312011-04-28 20:36:42 +00005340 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
5341 str = "SourceManager: malloc'ed memory buffers";
5342 break;
5343 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
5344 str = "SourceManager: mmap'ed memory buffers";
5345 break;
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005346 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
5347 str = "ExternalASTSource: malloc'ed memory buffers";
5348 break;
5349 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
5350 str = "ExternalASTSource: mmap'ed memory buffers";
5351 break;
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005352 case CXTUResourceUsage_Preprocessor:
5353 str = "Preprocessor: malloc'ed memory";
5354 break;
5355 case CXTUResourceUsage_PreprocessingRecord:
5356 str = "Preprocessor: PreprocessingRecord";
5357 break;
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005358 case CXTUResourceUsage_SourceManager_DataStructures:
5359 str = "SourceManager: data structures and tables";
5360 break;
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005361 case CXTUResourceUsage_Preprocessor_HeaderSearch:
5362 str = "Preprocessor: header search tables";
5363 break;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005364 }
5365 return str;
5366}
5367
Ted Kremenekf7870022011-04-20 16:41:07 +00005368CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005369 if (!TU) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005370 CXTUResourceUsage usage = { (void*) 0, 0, 0 };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005371 return usage;
5372 }
5373
5374 ASTUnit *astUnit = static_cast<ASTUnit*>(TU->TUData);
5375 llvm::OwningPtr<MemUsageEntries> entries(new MemUsageEntries());
5376 ASTContext &astContext = astUnit->getASTContext();
5377
5378 // How much memory is used by AST nodes and types?
Ted Kremenekf7870022011-04-20 16:41:07 +00005379 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005380 (unsigned long) astContext.getASTAllocatedMemory());
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005381
5382 // How much memory is used by identifiers?
Ted Kremenekf7870022011-04-20 16:41:07 +00005383 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005384 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
5385
5386 // How much memory is used for selectors?
Ted Kremenekf7870022011-04-20 16:41:07 +00005387 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005388 (unsigned long) astContext.Selectors.getTotalMemory());
5389
Ted Kremenekba29bd22011-04-28 04:53:38 +00005390 // How much memory is used by ASTContext's side tables?
5391 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
5392 (unsigned long) astContext.getSideTableAllocatedMemory());
5393
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005394 // How much memory is used for caching global code completion results?
5395 unsigned long completionBytes = 0;
5396 if (GlobalCodeCompletionAllocator *completionAllocator =
5397 astUnit->getCachedCompletionAllocator().getPtr()) {
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005398 completionBytes = completionAllocator->getTotalMemory();
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005399 }
Ted Kremenek457aaf02011-04-28 04:10:31 +00005400 createCXTUResourceUsageEntry(*entries,
5401 CXTUResourceUsage_GlobalCompletionResults,
5402 completionBytes);
5403
5404 // How much memory is being used by SourceManager's content cache?
5405 createCXTUResourceUsageEntry(*entries,
5406 CXTUResourceUsage_SourceManagerContentCache,
5407 (unsigned long) astContext.getSourceManager().getContentCacheSize());
Ted Kremenekf61b8312011-04-28 20:36:42 +00005408
5409 // How much memory is being used by the MemoryBuffer's in SourceManager?
5410 const SourceManager::MemoryBufferSizes &srcBufs =
5411 astUnit->getSourceManager().getMemoryBufferSizes();
5412
5413 createCXTUResourceUsageEntry(*entries,
5414 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
5415 (unsigned long) srcBufs.malloc_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005416 createCXTUResourceUsageEntry(*entries,
Ted Kremenekf61b8312011-04-28 20:36:42 +00005417 CXTUResourceUsage_SourceManager_Membuffer_MMap,
5418 (unsigned long) srcBufs.mmap_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005419 createCXTUResourceUsageEntry(*entries,
5420 CXTUResourceUsage_SourceManager_DataStructures,
5421 (unsigned long) astContext.getSourceManager()
5422 .getDataStructureSizes());
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005423
5424 // How much memory is being used by the ExternalASTSource?
5425 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
5426 const ExternalASTSource::MemoryBufferSizes &sizes =
5427 esrc->getMemoryBufferSizes();
5428
5429 createCXTUResourceUsageEntry(*entries,
5430 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
5431 (unsigned long) sizes.malloc_bytes);
5432 createCXTUResourceUsageEntry(*entries,
5433 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
5434 (unsigned long) sizes.mmap_bytes);
5435 }
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005436
5437 // How much memory is being used by the Preprocessor?
5438 Preprocessor &pp = astUnit->getPreprocessor();
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005439 createCXTUResourceUsageEntry(*entries,
5440 CXTUResourceUsage_Preprocessor,
Argyrios Kyrtzidisc5c5e922011-06-29 22:20:04 +00005441 pp.getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005442
5443 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
5444 createCXTUResourceUsageEntry(*entries,
5445 CXTUResourceUsage_PreprocessingRecord,
5446 pRec->getTotalMemory());
5447 }
5448
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005449 createCXTUResourceUsageEntry(*entries,
5450 CXTUResourceUsage_Preprocessor_HeaderSearch,
5451 pp.getHeaderSearchInfo().getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005452
Ted Kremenekf7870022011-04-20 16:41:07 +00005453 CXTUResourceUsage usage = { (void*) entries.get(),
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005454 (unsigned) entries->size(),
5455 entries->size() ? &(*entries)[0] : 0 };
5456 entries.take();
5457 return usage;
5458}
5459
Ted Kremenekf7870022011-04-20 16:41:07 +00005460void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005461 if (usage.data)
5462 delete (MemUsageEntries*) usage.data;
5463}
5464
5465} // end extern "C"
5466
Douglas Gregor6df78732011-05-05 20:27:22 +00005467void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
5468 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
5469 for (unsigned I = 0; I != Usage.numEntries; ++I)
5470 fprintf(stderr, " %s: %lu\n",
5471 clang_getTUResourceUsageName(Usage.entries[I].kind),
5472 Usage.entries[I].amount);
5473
5474 clang_disposeCXTUResourceUsage(Usage);
5475}
5476
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005477//===----------------------------------------------------------------------===//
Ted Kremenek04bb7162010-01-22 22:44:15 +00005478// Misc. utility functions.
5479//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00005480
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00005481/// Default to using an 8 MB stack size on "safety" threads.
5482static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005483
5484namespace clang {
5485
5486bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005487 void (*Fn)(void*), void *UserData,
5488 unsigned Size) {
5489 if (!Size)
5490 Size = GetSafetyThreadStackSize();
5491 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005492 return CRC.RunSafelyOnThread(Fn, UserData, Size);
5493 return CRC.RunSafely(Fn, UserData);
5494}
5495
5496unsigned GetSafetyThreadStackSize() {
5497 return SafetyStackThreadSize;
5498}
5499
5500void SetSafetyThreadStackSize(unsigned Value) {
5501 SafetyStackThreadSize = Value;
5502}
5503
5504}
5505
Ted Kremenek04bb7162010-01-22 22:44:15 +00005506extern "C" {
5507
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00005508CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00005509 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00005510}
5511
5512} // end: extern "C"
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005513