blob: bf5607b5300a96f4bae2c6fa7265fd53c9bb19b7 [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);
Douglas Gregoree8aff02011-01-04 17:33:58 +00001717
Ted Kremenek28a71942010-11-13 00:36:47 +00001718private:
Ted Kremenekf64d8032010-11-18 00:02:32 +00001719 void AddDeclarationNameInfo(Stmt *S);
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001720 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001721 void AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001722 void AddMemberRef(FieldDecl *D, SourceLocation L);
Ted Kremenek28a71942010-11-13 00:36:47 +00001723 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001724 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001725 void AddTypeLoc(TypeSourceInfo *TI);
1726 void EnqueueChildren(Stmt *S);
1727};
1728} // end anonyous namespace
1729
Ted Kremenekf64d8032010-11-18 00:02:32 +00001730void EnqueueVisitor::AddDeclarationNameInfo(Stmt *S) {
1731 // 'S' should always be non-null, since it comes from the
1732 // statement we are visiting.
1733 WL.push_back(DeclarationNameInfoVisit(S, Parent));
1734}
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001735
1736void
1737EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1738 if (Qualifier)
1739 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
1740}
1741
Ted Kremenek28a71942010-11-13 00:36:47 +00001742void EnqueueVisitor::AddStmt(Stmt *S) {
1743 if (S)
1744 WL.push_back(StmtVisit(S, Parent));
1745}
Ted Kremenek035dc412010-11-13 00:36:50 +00001746void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001747 if (D)
Ted Kremenek035dc412010-11-13 00:36:50 +00001748 WL.push_back(DeclVisit(D, Parent, isFirst));
Ted Kremenek28a71942010-11-13 00:36:47 +00001749}
Ted Kremenek60608ec2010-11-17 00:50:47 +00001750void EnqueueVisitor::
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001751 AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001752 if (A)
1753 WL.push_back(ExplicitTemplateArgsVisit(
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001754 const_cast<ASTTemplateArgumentListInfo*>(A), Parent));
Ted Kremenek60608ec2010-11-17 00:50:47 +00001755}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001756void EnqueueVisitor::AddMemberRef(FieldDecl *D, SourceLocation L) {
1757 if (D)
1758 WL.push_back(MemberRefVisit(D, L, Parent));
1759}
Ted Kremenek28a71942010-11-13 00:36:47 +00001760void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1761 if (TI)
1762 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1763 }
1764void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001765 unsigned size = WL.size();
John McCall7502c1d2011-02-13 04:07:26 +00001766 for (Stmt::child_range Child = S->children(); Child; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001767 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001768 }
1769 if (size == WL.size())
1770 return;
1771 // Now reverse the entries we just added. This will match the DFS
1772 // ordering performed by the worklist.
1773 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1774 std::reverse(I, E);
1775}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001776void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1777 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
1778}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001779void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1780 AddDecl(B->getBlockDecl());
1781}
Ted Kremenek28a71942010-11-13 00:36:47 +00001782void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1783 EnqueueChildren(E);
1784 AddTypeLoc(E->getTypeSourceInfo());
1785}
Ted Kremenek083c7e22010-11-13 05:38:03 +00001786void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1787 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1788 E = S->body_rend(); I != E; ++I) {
1789 AddStmt(*I);
1790 }
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001791}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001792void EnqueueVisitor::
Douglas Gregorba0513d2011-10-25 01:33:02 +00001793VisitMSDependentExistsStmt(MSDependentExistsStmt *S) {
1794 AddStmt(S->getSubStmt());
1795 AddDeclarationNameInfo(S);
1796 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
1797 AddNestedNameSpecifierLoc(QualifierLoc);
1798}
1799
1800void EnqueueVisitor::
Ted Kremenekf64d8032010-11-18 00:02:32 +00001801VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
1802 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1803 AddDeclarationNameInfo(E);
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001804 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1805 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001806 if (!E->isImplicitAccess())
1807 AddStmt(E->getBase());
1808}
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001809void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1810 // Enqueue the initializer or constructor arguments.
1811 for (unsigned I = E->getNumConstructorArgs(); I > 0; --I)
1812 AddStmt(E->getConstructorArg(I-1));
1813 // Enqueue the array size, if any.
1814 AddStmt(E->getArraySize());
1815 // Enqueue the allocated type.
1816 AddTypeLoc(E->getAllocatedTypeSourceInfo());
1817 // Enqueue the placement arguments.
1818 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1819 AddStmt(E->getPlacementArg(I-1));
1820}
Ted Kremenek28a71942010-11-13 00:36:47 +00001821void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
Ted Kremenek8b8d8c92010-11-13 05:55:56 +00001822 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1823 AddStmt(CE->getArg(I-1));
Ted Kremenek28a71942010-11-13 00:36:47 +00001824 AddStmt(CE->getCallee());
1825 AddStmt(CE->getArg(0));
1826}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001827void EnqueueVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1828 // Visit the name of the type being destroyed.
1829 AddTypeLoc(E->getDestroyedTypeInfo());
1830 // Visit the scope type that looks disturbingly like the nested-name-specifier
1831 // but isn't.
1832 AddTypeLoc(E->getScopeTypeInfo());
1833 // Visit the nested-name-specifier.
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001834 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1835 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001836 // Visit base expression.
1837 AddStmt(E->getBase());
1838}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001839void EnqueueVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1840 AddTypeLoc(E->getTypeSourceInfo());
1841}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001842void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1843 EnqueueChildren(E);
1844 AddTypeLoc(E->getTypeSourceInfo());
1845}
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001846void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1847 EnqueueChildren(E);
1848 if (E->isTypeOperand())
1849 AddTypeLoc(E->getTypeOperandSourceInfo());
1850}
Ted Kremenek55b933a2010-11-17 00:50:36 +00001851
1852void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
1853 *E) {
1854 EnqueueChildren(E);
1855 AddTypeLoc(E->getTypeSourceInfo());
1856}
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001857void EnqueueVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1858 EnqueueChildren(E);
1859 if (E->isTypeOperand())
1860 AddTypeLoc(E->getTypeOperandSourceInfo());
1861}
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001862void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001863 if (DR->hasExplicitTemplateArgs()) {
1864 AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
1865 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001866 WL.push_back(DeclRefExprParts(DR, Parent));
1867}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001868void EnqueueVisitor::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
1869 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1870 AddDeclarationNameInfo(E);
Douglas Gregor00cf3cc2011-02-25 20:49:16 +00001871 AddNestedNameSpecifierLoc(E->getQualifierLoc());
Ted Kremenekf64d8032010-11-18 00:02:32 +00001872}
Ted Kremenek035dc412010-11-13 00:36:50 +00001873void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1874 unsigned size = WL.size();
1875 bool isFirst = true;
1876 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1877 D != DEnd; ++D) {
1878 AddDecl(*D, isFirst);
1879 isFirst = false;
1880 }
1881 if (size == WL.size())
1882 return;
1883 // Now reverse the entries we just added. This will match the DFS
1884 // ordering performed by the worklist.
1885 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1886 std::reverse(I, E);
1887}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001888void EnqueueVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1889 AddStmt(E->getInit());
1890 typedef DesignatedInitExpr::Designator Designator;
1891 for (DesignatedInitExpr::reverse_designators_iterator
1892 D = E->designators_rbegin(), DEnd = E->designators_rend();
1893 D != DEnd; ++D) {
1894 if (D->isFieldDesignator()) {
1895 if (FieldDecl *Field = D->getField())
1896 AddMemberRef(Field, D->getFieldLoc());
1897 continue;
1898 }
1899 if (D->isArrayDesignator()) {
1900 AddStmt(E->getArrayIndex(*D));
1901 continue;
1902 }
1903 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1904 AddStmt(E->getArrayRangeEnd(*D));
1905 AddStmt(E->getArrayRangeStart(*D));
1906 }
1907}
Ted Kremenek28a71942010-11-13 00:36:47 +00001908void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1909 EnqueueChildren(E);
1910 AddTypeLoc(E->getTypeInfoAsWritten());
1911}
1912void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1913 AddStmt(FS->getBody());
1914 AddStmt(FS->getInc());
1915 AddStmt(FS->getCond());
1916 AddDecl(FS->getConditionVariable());
1917 AddStmt(FS->getInit());
1918}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001919void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) {
1920 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
1921}
Ted Kremenek28a71942010-11-13 00:36:47 +00001922void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
1923 AddStmt(If->getElse());
1924 AddStmt(If->getThen());
1925 AddStmt(If->getCond());
1926 AddDecl(If->getConditionVariable());
1927}
1928void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
1929 // We care about the syntactic form of the initializer list, only.
1930 if (InitListExpr *Syntactic = IE->getSyntacticForm())
1931 IE = Syntactic;
1932 EnqueueChildren(IE);
1933}
1934void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
Douglas Gregor89629a72010-11-17 17:15:08 +00001935 WL.push_back(MemberExprParts(M, Parent));
1936
1937 // If the base of the member access expression is an implicit 'this', don't
1938 // visit it.
1939 // FIXME: If we ever want to show these implicit accesses, this will be
1940 // unfortunate. However, clang_getCursor() relies on this behavior.
Douglas Gregor75e85042011-03-02 21:06:53 +00001941 if (!M->isImplicitAccess())
1942 AddStmt(M->getBase());
Ted Kremenek28a71942010-11-13 00:36:47 +00001943}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001944void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1945 AddTypeLoc(E->getEncodedTypeSourceInfo());
1946}
Ted Kremenek28a71942010-11-13 00:36:47 +00001947void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
1948 EnqueueChildren(M);
1949 AddTypeLoc(M->getClassReceiverTypeInfo());
1950}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001951void EnqueueVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
1952 // Visit the components of the offsetof expression.
1953 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
1954 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
1955 const OffsetOfNode &Node = E->getComponent(I-1);
1956 switch (Node.getKind()) {
1957 case OffsetOfNode::Array:
1958 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
1959 break;
1960 case OffsetOfNode::Field:
Abramo Bagnara06dec892011-03-12 09:45:03 +00001961 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
Ted Kremenekcdba6592010-11-18 00:42:18 +00001962 break;
1963 case OffsetOfNode::Identifier:
1964 case OffsetOfNode::Base:
1965 continue;
1966 }
1967 }
1968 // Visit the type into which we're computing the offset.
1969 AddTypeLoc(E->getTypeSourceInfo());
1970}
Ted Kremenek28a71942010-11-13 00:36:47 +00001971void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001972 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
Ted Kremenek60458782010-11-12 21:34:16 +00001973 WL.push_back(OverloadExprParts(E, Parent));
1974}
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001975void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
1976 UnaryExprOrTypeTraitExpr *E) {
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001977 EnqueueChildren(E);
1978 if (E->isArgumentType())
1979 AddTypeLoc(E->getArgumentTypeInfo());
1980}
Ted Kremenek28a71942010-11-13 00:36:47 +00001981void EnqueueVisitor::VisitStmt(Stmt *S) {
1982 EnqueueChildren(S);
1983}
1984void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
1985 AddStmt(S->getBody());
1986 AddStmt(S->getCond());
1987 AddDecl(S->getConditionVariable());
1988}
Ted Kremenekfafa75a2010-11-17 00:50:39 +00001989
Ted Kremenek28a71942010-11-13 00:36:47 +00001990void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
1991 AddStmt(W->getBody());
1992 AddStmt(W->getCond());
1993 AddDecl(W->getConditionVariable());
1994}
John Wiegley21ff2e52011-04-28 00:16:57 +00001995
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001996void EnqueueVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
1997 AddTypeLoc(E->getQueriedTypeSourceInfo());
1998}
Francois Pichet6ad6f282010-12-07 00:08:36 +00001999
2000void EnqueueVisitor::VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
Francois Pichet6ad6f282010-12-07 00:08:36 +00002001 AddTypeLoc(E->getRhsTypeSourceInfo());
Francois Pichet0a03a3f2010-12-08 09:11:05 +00002002 AddTypeLoc(E->getLhsTypeSourceInfo());
Francois Pichet6ad6f282010-12-07 00:08:36 +00002003}
2004
John Wiegley21ff2e52011-04-28 00:16:57 +00002005void EnqueueVisitor::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
2006 AddTypeLoc(E->getQueriedTypeSourceInfo());
2007}
2008
John Wiegley55262202011-04-25 06:54:41 +00002009void EnqueueVisitor::VisitExpressionTraitExpr(ExpressionTraitExpr *E) {
2010 EnqueueChildren(E);
2011}
2012
Ted Kremenek28a71942010-11-13 00:36:47 +00002013void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
2014 VisitOverloadExpr(U);
2015 if (!U->isImplicitAccess())
2016 AddStmt(U->getBase());
2017}
Ted Kremenek9d3bf792010-11-17 00:50:43 +00002018void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) {
2019 AddStmt(E->getSubExpr());
2020 AddTypeLoc(E->getWrittenTypeInfo());
2021}
Douglas Gregor94d96292011-01-19 20:34:17 +00002022void EnqueueVisitor::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
2023 WL.push_back(SizeOfPackExprParts(E, Parent));
2024}
Ted Kremenek60458782010-11-12 21:34:16 +00002025
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002026void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002027 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002028}
2029
2030bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2031 if (RegionOfInterest.isValid()) {
2032 SourceRange Range = getRawCursorExtent(C);
2033 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2034 return false;
2035 }
2036 return true;
2037}
2038
2039bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2040 while (!WL.empty()) {
2041 // Dequeue the worklist item.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002042 VisitorJob LI = WL.back();
2043 WL.pop_back();
2044
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002045 // Set the Parent field, then back to its old value once we're done.
2046 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2047
2048 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00002049 case VisitorJob::DeclVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002050 Decl *D = cast<DeclVisit>(&LI)->get();
Ted Kremenekf1107452010-11-12 18:26:56 +00002051 if (!D)
2052 continue;
2053
2054 // For now, perform default visitation for Decls.
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002055 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2056 cast<DeclVisit>(&LI)->isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00002057 return true;
2058
2059 continue;
2060 }
Ted Kremenek60608ec2010-11-17 00:50:47 +00002061 case VisitorJob::ExplicitTemplateArgsVisitKind: {
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00002062 const ASTTemplateArgumentListInfo *ArgList =
Ted Kremenek60608ec2010-11-17 00:50:47 +00002063 cast<ExplicitTemplateArgsVisit>(&LI)->get();
2064 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2065 *ArgEnd = Arg + ArgList->NumTemplateArgs;
2066 Arg != ArgEnd; ++Arg) {
2067 if (VisitTemplateArgumentLoc(*Arg))
2068 return true;
2069 }
2070 continue;
2071 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002072 case VisitorJob::TypeLocVisitKind: {
2073 // Perform default visitation for TypeLocs.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002074 if (Visit(cast<TypeLocVisit>(&LI)->get()))
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002075 return true;
2076 continue;
2077 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002078 case VisitorJob::LabelRefVisitKind: {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002079 LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Ted Kremeneke7455012011-02-23 04:54:51 +00002080 if (LabelStmt *stmt = LS->getStmt()) {
2081 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2082 TU))) {
2083 return true;
2084 }
2085 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002086 continue;
2087 }
Ted Kremenek47695c82011-08-18 22:25:21 +00002088
Douglas Gregorf3db29f2011-02-25 18:19:59 +00002089 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2090 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2091 if (VisitNestedNameSpecifierLoc(V->get()))
2092 return true;
2093 continue;
2094 }
2095
Ted Kremenekf64d8032010-11-18 00:02:32 +00002096 case VisitorJob::DeclarationNameInfoVisitKind: {
2097 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2098 ->get()))
2099 return true;
2100 continue;
2101 }
Ted Kremenekcdba6592010-11-18 00:42:18 +00002102 case VisitorJob::MemberRefVisitKind: {
2103 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2104 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2105 return true;
2106 continue;
2107 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002108 case VisitorJob::StmtVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002109 Stmt *S = cast<StmtVisit>(&LI)->get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00002110 if (!S)
2111 continue;
2112
Ted Kremenekf1107452010-11-12 18:26:56 +00002113 // Update the current cursor.
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002114 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
Ted Kremenekcdba6592010-11-18 00:42:18 +00002115 if (!IsInRegionOfInterest(Cursor))
2116 continue;
2117 switch (Visitor(Cursor, Parent, ClientData)) {
2118 case CXChildVisit_Break: return true;
2119 case CXChildVisit_Continue: break;
2120 case CXChildVisit_Recurse:
2121 EnqueueWorkList(WL, S);
Ted Kremenek82f3c502010-11-15 22:23:26 +00002122 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002123 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00002124 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002125 }
2126 case VisitorJob::MemberExprPartsKind: {
2127 // Handle the other pieces in the MemberExpr besides the base.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002128 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002129
2130 // Visit the nested-name-specifier
Douglas Gregor40d96a62011-02-28 21:54:11 +00002131 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
2132 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002133 return true;
2134
2135 // Visit the declaration name.
2136 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2137 return true;
2138
2139 // Visit the explicitly-specified template arguments, if any.
2140 if (M->hasExplicitTemplateArgs()) {
2141 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2142 *ArgEnd = Arg + M->getNumTemplateArgs();
2143 Arg != ArgEnd; ++Arg) {
2144 if (VisitTemplateArgumentLoc(*Arg))
2145 return true;
2146 }
2147 }
2148 continue;
2149 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002150 case VisitorJob::DeclRefExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002151 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002152 // Visit nested-name-specifier, if present.
Douglas Gregor40d96a62011-02-28 21:54:11 +00002153 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
2154 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002155 return true;
2156 // Visit declaration name.
2157 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2158 return true;
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002159 continue;
2160 }
Ted Kremenek60458782010-11-12 21:34:16 +00002161 case VisitorJob::OverloadExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002162 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Ted Kremenek60458782010-11-12 21:34:16 +00002163 // Visit the nested-name-specifier.
Douglas Gregor4c9be892011-02-28 20:01:57 +00002164 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
2165 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenek60458782010-11-12 21:34:16 +00002166 return true;
2167 // Visit the declaration name.
2168 if (VisitDeclarationNameInfo(O->getNameInfo()))
2169 return true;
2170 // Visit the overloaded declaration reference.
2171 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2172 return true;
Ted Kremenek60458782010-11-12 21:34:16 +00002173 continue;
2174 }
Douglas Gregor94d96292011-01-19 20:34:17 +00002175 case VisitorJob::SizeOfPackExprPartsKind: {
2176 SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
2177 NamedDecl *Pack = E->getPack();
2178 if (isa<TemplateTypeParmDecl>(Pack)) {
2179 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
2180 E->getPackLoc(), TU)))
2181 return true;
2182
2183 continue;
2184 }
2185
2186 if (isa<TemplateTemplateParmDecl>(Pack)) {
2187 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
2188 E->getPackLoc(), TU)))
2189 return true;
2190
2191 continue;
2192 }
2193
2194 // Non-type template parameter packs and function parameter packs are
2195 // treated like DeclRefExpr cursors.
2196 continue;
2197 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002198 }
2199 }
2200 return false;
2201}
2202
Ted Kremenekcdba6592010-11-18 00:42:18 +00002203bool CursorVisitor::Visit(Stmt *S) {
Ted Kremenekd1ded662010-11-15 23:31:32 +00002204 VisitorWorkList *WL = 0;
2205 if (!WorkListFreeList.empty()) {
2206 WL = WorkListFreeList.back();
2207 WL->clear();
2208 WorkListFreeList.pop_back();
2209 }
2210 else {
2211 WL = new VisitorWorkList();
2212 WorkListCache.push_back(WL);
2213 }
2214 EnqueueWorkList(*WL, S);
2215 bool result = RunVisitorWorkList(*WL);
2216 WorkListFreeList.push_back(WL);
2217 return result;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002218}
2219
Francois Pichet48a8d142011-07-25 22:00:44 +00002220namespace {
2221typedef llvm::SmallVector<SourceRange, 4> RefNamePieces;
2222RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
2223 const DeclarationNameInfo &NI,
2224 const SourceRange &QLoc,
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00002225 const ASTTemplateArgumentListInfo *TemplateArgs = 0){
Francois Pichet48a8d142011-07-25 22:00:44 +00002226 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
2227 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
2228 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
2229
2230 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
2231
2232 RefNamePieces Pieces;
2233
2234 if (WantQualifier && QLoc.isValid())
2235 Pieces.push_back(QLoc);
2236
2237 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
2238 Pieces.push_back(NI.getLoc());
2239
2240 if (WantTemplateArgs && TemplateArgs)
2241 Pieces.push_back(SourceRange(TemplateArgs->LAngleLoc,
2242 TemplateArgs->RAngleLoc));
2243
2244 if (Kind == DeclarationName::CXXOperatorName) {
2245 Pieces.push_back(SourceLocation::getFromRawEncoding(
2246 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
2247 Pieces.push_back(SourceLocation::getFromRawEncoding(
2248 NI.getInfo().CXXOperatorName.EndOpNameLoc));
2249 }
2250
2251 if (WantSinglePiece) {
2252 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
2253 Pieces.clear();
2254 Pieces.push_back(R);
2255 }
2256
2257 return Pieces;
2258}
2259}
2260
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002261//===----------------------------------------------------------------------===//
2262// Misc. API hooks.
2263//===----------------------------------------------------------------------===//
2264
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002265static llvm::sys::Mutex EnableMultithreadingMutex;
2266static bool EnabledMultithreading;
2267
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002268extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002269CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2270 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002271 // Disable pretty stack trace functionality, which will otherwise be a very
2272 // poor citizen of the world and set up all sorts of signal handlers.
2273 llvm::DisablePrettyStackTrace = true;
2274
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002275 // We use crash recovery to make some of our APIs more reliable, implicitly
2276 // enable it.
2277 llvm::CrashRecoveryContext::Enable();
2278
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002279 // Enable support for multithreading in LLVM.
2280 {
2281 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2282 if (!EnabledMultithreading) {
2283 llvm::llvm_start_multithreaded();
2284 EnabledMultithreading = true;
2285 }
2286 }
2287
Douglas Gregora030b7c2010-01-22 20:35:53 +00002288 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002289 if (excludeDeclarationsFromPCH)
2290 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002291 if (displayDiagnostics)
2292 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002293 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002294}
2295
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002296void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002297 if (CIdx)
2298 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002299}
2300
Ted Kremenekd2427dd2011-03-18 23:05:39 +00002301void clang_toggleCrashRecovery(unsigned isEnabled) {
2302 if (isEnabled)
2303 llvm::CrashRecoveryContext::Enable();
2304 else
2305 llvm::CrashRecoveryContext::Disable();
2306}
2307
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002308CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002309 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002310 if (!CIdx)
2311 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002312
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002313 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002314 FileSystemOptions FileSystemOpts;
2315 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002316
David Blaikied6471f72011-09-25 23:23:43 +00002317 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002318 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002319 CXXIdx->getOnlyLocalDecls(),
2320 0, 0, true);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002321 return MakeCXTranslationUnit(TU);
Steve Naroff600866c2009-08-27 19:51:58 +00002322}
2323
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002324unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002325 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregorb5af8432011-08-25 22:54:01 +00002326 CXTranslationUnit_CacheCompletionResults;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002327}
2328
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002329CXTranslationUnit
2330clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2331 const char *source_filename,
2332 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002333 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002334 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002335 struct CXUnsavedFile *unsaved_files) {
Douglas Gregordca8ee82011-05-06 16:33:08 +00002336 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord |
Chandler Carruthba7537f2011-07-14 09:02:10 +00002337 CXTranslationUnit_NestedMacroExpansions;
Douglas Gregor5a430212010-07-21 18:52:53 +00002338 return clang_parseTranslationUnit(CIdx, source_filename,
2339 command_line_args, num_command_line_args,
2340 unsaved_files, num_unsaved_files,
Douglas Gregordca8ee82011-05-06 16:33:08 +00002341 Options);
Douglas Gregor5a430212010-07-21 18:52:53 +00002342}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002343
2344struct ParseTranslationUnitInfo {
2345 CXIndex CIdx;
2346 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002347 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002348 int num_command_line_args;
2349 struct CXUnsavedFile *unsaved_files;
2350 unsigned num_unsaved_files;
2351 unsigned options;
2352 CXTranslationUnit result;
2353};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002354static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002355 ParseTranslationUnitInfo *PTUI =
2356 static_cast<ParseTranslationUnitInfo*>(UserData);
2357 CXIndex CIdx = PTUI->CIdx;
2358 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002359 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002360 int num_command_line_args = PTUI->num_command_line_args;
2361 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2362 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2363 unsigned options = PTUI->options;
2364 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002365
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002366 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002367 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002368
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002369 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2370
Douglas Gregor44c181a2010-07-23 00:33:23 +00002371 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregor467dc882011-08-25 22:30:56 +00002372 // FIXME: Add a flag for modules.
2373 TranslationUnitKind TUKind
2374 = (options & CXTranslationUnit_Incomplete)? TU_Prefix : TU_Complete;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002375 bool CacheCodeCompetionResults
2376 = options & CXTranslationUnit_CacheCompletionResults;
2377
Douglas Gregor5352ac02010-01-28 00:27:43 +00002378 // Configure the diagnostics.
2379 DiagnosticOptions DiagOpts;
David Blaikied6471f72011-09-25 23:23:43 +00002380 llvm::IntrusiveRefCntPtr<DiagnosticsEngine>
Ted Kremenek25a11e12011-03-22 01:15:24 +00002381 Diags(CompilerInstance::createDiagnostics(DiagOpts, num_command_line_args,
2382 command_line_args));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002383
Ted Kremenek25a11e12011-03-22 01:15:24 +00002384 // Recover resources if we crash before exiting this function.
David Blaikied6471f72011-09-25 23:23:43 +00002385 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
2386 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00002387 DiagCleanup(Diags.getPtr());
2388
2389 llvm::OwningPtr<std::vector<ASTUnit::RemappedFile> >
2390 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2391
2392 // Recover resources if we crash before exiting this function.
2393 llvm::CrashRecoveryContextCleanupRegistrar<
2394 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2395
Douglas Gregor4db64a42010-01-23 00:14:00 +00002396 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002397 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002398 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002399 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002400 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2401 Buffer));
Douglas Gregor4db64a42010-01-23 00:14:00 +00002402 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002403
Ted Kremenek25a11e12011-03-22 01:15:24 +00002404 llvm::OwningPtr<std::vector<const char *> >
2405 Args(new std::vector<const char*>());
2406
2407 // Recover resources if we crash before exiting this method.
2408 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
2409 ArgsCleanup(Args.get());
2410
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002411 // Since the Clang C library is primarily used by batch tools dealing with
2412 // (often very broken) source code, where spell-checking can have a
2413 // significant negative impact on performance (particularly when
2414 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002415 // Only do this if we haven't found a spell-checking-related argument.
2416 bool FoundSpellCheckingArgument = false;
2417 for (int I = 0; I != num_command_line_args; ++I) {
2418 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2419 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2420 FoundSpellCheckingArgument = true;
2421 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002422 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002423 }
2424 if (!FoundSpellCheckingArgument)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002425 Args->push_back("-fno-spell-checking");
Douglas Gregorb10daed2010-10-11 16:52:23 +00002426
Ted Kremenek25a11e12011-03-22 01:15:24 +00002427 Args->insert(Args->end(), command_line_args,
2428 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002429
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002430 // The 'source_filename' argument is optional. If the caller does not
2431 // specify it then it is assumed that the source file is specified
2432 // in the actual argument list.
2433 // Put the source file after command_line_args otherwise if '-x' flag is
2434 // present it will be unused.
2435 if (source_filename)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002436 Args->push_back(source_filename);
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002437
Douglas Gregor44c181a2010-07-23 00:33:23 +00002438 // Do we need the detailed preprocessing record?
Chandler Carruthba7537f2011-07-14 09:02:10 +00002439 bool NestedMacroExpansions = false;
Douglas Gregor44c181a2010-07-23 00:33:23 +00002440 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Ted Kremenek25a11e12011-03-22 01:15:24 +00002441 Args->push_back("-Xclang");
2442 Args->push_back("-detailed-preprocessing-record");
Chandler Carruthba7537f2011-07-14 09:02:10 +00002443 NestedMacroExpansions
2444 = (options & CXTranslationUnit_NestedMacroExpansions);
Douglas Gregor44c181a2010-07-23 00:33:23 +00002445 }
2446
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002447 unsigned NumErrors = Diags->getClient()->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002448 llvm::OwningPtr<ASTUnit> Unit(
Ted Kremenek4ee99262011-03-22 20:16:19 +00002449 ASTUnit::LoadFromCommandLine(Args->size() ? &(*Args)[0] : 0
2450 /* vector::data() not portable */,
2451 Args->size() ? (&(*Args)[0] + Args->size()) :0,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002452 Diags,
2453 CXXIdx->getClangResourcesPath(),
2454 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002455 /*CaptureDiagnostics=*/true,
Ted Kremenek4ee99262011-03-22 20:16:19 +00002456 RemappedFiles->size() ? &(*RemappedFiles)[0]:0,
Ted Kremenek25a11e12011-03-22 01:15:24 +00002457 RemappedFiles->size(),
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00002458 /*RemappedFilesKeepOriginalName=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002459 PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00002460 TUKind,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002461 CacheCodeCompetionResults,
Chandler Carruthba7537f2011-07-14 09:02:10 +00002462 NestedMacroExpansions));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002463
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002464 if (NumErrors != Diags->getClient()->getNumErrors()) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002465 // Make sure to check that 'Unit' is non-NULL.
2466 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2467 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2468 DEnd = Unit->stored_diag_end();
2469 D != DEnd; ++D) {
2470 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2471 CXString Msg = clang_formatDiagnostic(&Diag,
2472 clang_defaultDiagnosticDisplayOptions());
2473 fprintf(stderr, "%s\n", clang_getCString(Msg));
2474 clang_disposeString(Msg);
2475 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002476#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002477 // On Windows, force a flush, since there may be multiple copies of
2478 // stderr and stdout in the file system, all with different buffers
2479 // but writing to the same device.
2480 fflush(stderr);
2481#endif
2482 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002483 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002484
Ted Kremeneka60ed472010-11-16 08:15:36 +00002485 PTUI->result = MakeCXTranslationUnit(Unit.take());
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002486}
2487CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2488 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002489 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002490 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002491 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002492 unsigned num_unsaved_files,
2493 unsigned options) {
2494 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002495 num_command_line_args, unsaved_files,
2496 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002497 llvm::CrashRecoveryContext CRC;
2498
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002499 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002500 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2501 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2502 fprintf(stderr, " 'command_line_args' : [");
2503 for (int i = 0; i != num_command_line_args; ++i) {
2504 if (i)
2505 fprintf(stderr, ", ");
2506 fprintf(stderr, "'%s'", command_line_args[i]);
2507 }
2508 fprintf(stderr, "],\n");
2509 fprintf(stderr, " 'unsaved_files' : [");
2510 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2511 if (i)
2512 fprintf(stderr, ", ");
2513 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2514 unsaved_files[i].Length);
2515 }
2516 fprintf(stderr, "],\n");
2517 fprintf(stderr, " 'options' : %d,\n", options);
2518 fprintf(stderr, "}\n");
2519
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002520 return 0;
Douglas Gregor6df78732011-05-05 20:27:22 +00002521 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
2522 PrintLibclangResourceUsage(PTUI.result);
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002523 }
Douglas Gregor6df78732011-05-05 20:27:22 +00002524
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002525 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002526}
2527
Douglas Gregor19998442010-08-13 15:35:05 +00002528unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2529 return CXSaveTranslationUnit_None;
2530}
2531
2532int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2533 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002534 if (!TU)
Douglas Gregor39c411f2011-07-06 16:43:36 +00002535 return CXSaveError_InvalidTU;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002536
Douglas Gregor39c411f2011-07-06 16:43:36 +00002537 CXSaveError result = static_cast<ASTUnit *>(TU->TUData)->Save(FileName);
Douglas Gregor6df78732011-05-05 20:27:22 +00002538 if (getenv("LIBCLANG_RESOURCE_USAGE"))
2539 PrintLibclangResourceUsage(TU);
2540 return result;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002541}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002542
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002543void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002544 if (CTUnit) {
2545 // If the translation unit has been marked as unsafe to free, just discard
2546 // it.
Ted Kremeneka60ed472010-11-16 08:15:36 +00002547 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002548 return;
2549
Ted Kremeneka60ed472010-11-16 08:15:36 +00002550 delete static_cast<ASTUnit *>(CTUnit->TUData);
2551 disposeCXStringPool(CTUnit->StringPool);
2552 delete CTUnit;
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002553 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002554}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002555
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002556unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2557 return CXReparse_None;
2558}
2559
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002560struct ReparseTranslationUnitInfo {
2561 CXTranslationUnit TU;
2562 unsigned num_unsaved_files;
2563 struct CXUnsavedFile *unsaved_files;
2564 unsigned options;
2565 int result;
2566};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002567
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002568static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002569 ReparseTranslationUnitInfo *RTUI =
2570 static_cast<ReparseTranslationUnitInfo*>(UserData);
2571 CXTranslationUnit TU = RTUI->TU;
2572 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2573 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2574 unsigned options = RTUI->options;
2575 (void) options;
2576 RTUI->result = 1;
2577
Douglas Gregorabc563f2010-07-19 21:46:24 +00002578 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002579 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002580
Ted Kremeneka60ed472010-11-16 08:15:36 +00002581 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor593b0c12010-09-23 18:47:53 +00002582 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002583
Ted Kremenek25a11e12011-03-22 01:15:24 +00002584 llvm::OwningPtr<std::vector<ASTUnit::RemappedFile> >
2585 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2586
2587 // Recover resources if we crash before exiting this function.
2588 llvm::CrashRecoveryContextCleanupRegistrar<
2589 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2590
Douglas Gregorabc563f2010-07-19 21:46:24 +00002591 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002592 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002593 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002594 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002595 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2596 Buffer));
Douglas Gregorabc563f2010-07-19 21:46:24 +00002597 }
2598
Ted Kremenek4ee99262011-03-22 20:16:19 +00002599 if (!CXXUnit->Reparse(RemappedFiles->size() ? &(*RemappedFiles)[0] : 0,
2600 RemappedFiles->size()))
Douglas Gregor593b0c12010-09-23 18:47:53 +00002601 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002602}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002603
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002604int clang_reparseTranslationUnit(CXTranslationUnit TU,
2605 unsigned num_unsaved_files,
2606 struct CXUnsavedFile *unsaved_files,
2607 unsigned options) {
2608 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2609 options, 0 };
Argyrios Kyrtzidis8c4b47e2011-10-28 22:54:33 +00002610
Argyrios Kyrtzidise7de9b42011-10-29 19:32:39 +00002611 if (getenv("LIBCLANG_NOTHREADS")) {
Argyrios Kyrtzidis8c4b47e2011-10-28 22:54:33 +00002612 clang_reparseTranslationUnit_Impl(&RTUI);
2613 return RTUI.result;
2614 }
2615
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002616 llvm::CrashRecoveryContext CRC;
2617
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002618 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002619 fprintf(stderr, "libclang: crash detected during reparsing\n");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002620 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002621 return 1;
Douglas Gregor6df78732011-05-05 20:27:22 +00002622 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
2623 PrintLibclangResourceUsage(TU);
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002624
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002625 return RTUI.result;
2626}
2627
Douglas Gregordf95a132010-08-09 20:45:32 +00002628
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002629CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002630 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002631 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002632
Ted Kremeneka60ed472010-11-16 08:15:36 +00002633 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002634 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002635}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002636
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002637CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002638 CXCursor Result = { CXCursor_TranslationUnit, 0, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002639 return Result;
2640}
2641
Ted Kremenekfb480492010-01-13 21:46:36 +00002642} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002643
Ted Kremenekfb480492010-01-13 21:46:36 +00002644//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002645// CXFile Operations.
2646//===----------------------------------------------------------------------===//
2647
2648extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002649CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002650 if (!SFile)
Ted Kremeneka60ed472010-11-16 08:15:36 +00002651 return createCXString((const char*)NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002652
Steve Naroff88145032009-10-27 14:35:18 +00002653 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002654 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002655}
2656
2657time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002658 if (!SFile)
2659 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002660
Steve Naroff88145032009-10-27 14:35:18 +00002661 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2662 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002663}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002664
Douglas Gregorb9790342010-01-22 21:44:22 +00002665CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2666 if (!tu)
2667 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002668
Ted Kremeneka60ed472010-11-16 08:15:36 +00002669 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002670
Douglas Gregorb9790342010-01-22 21:44:22 +00002671 FileManager &FMgr = CXXUnit->getFileManager();
Chris Lattner39b49bc2010-11-23 08:35:12 +00002672 return const_cast<FileEntry *>(FMgr.getFile(file_name));
Douglas Gregorb9790342010-01-22 21:44:22 +00002673}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002674
Douglas Gregordd3e5542011-05-04 00:14:37 +00002675unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit tu, CXFile file) {
2676 if (!tu || !file)
2677 return 0;
2678
2679 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
2680 FileEntry *FEnt = static_cast<FileEntry *>(file);
2681 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
2682 .isFileMultipleIncludeGuarded(FEnt);
2683}
2684
Ted Kremenekfb480492010-01-13 21:46:36 +00002685} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002686
Ted Kremenekfb480492010-01-13 21:46:36 +00002687//===----------------------------------------------------------------------===//
2688// CXCursor Operations.
2689//===----------------------------------------------------------------------===//
2690
Ted Kremenekfb480492010-01-13 21:46:36 +00002691static Decl *getDeclFromExpr(Stmt *E) {
Argyrios Kyrtzidisc2954612011-09-12 22:17:26 +00002692 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Douglas Gregordb1314e2010-10-01 21:11:22 +00002693 return getDeclFromExpr(CE->getSubExpr());
2694
Ted Kremenekfb480492010-01-13 21:46:36 +00002695 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2696 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002697 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2698 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002699 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2700 return ME->getMemberDecl();
2701 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2702 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002703 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
John McCall12f78a62010-12-02 01:19:52 +00002704 return PRE->isExplicitProperty() ? PRE->getExplicitProperty() : 0;
Douglas Gregordb1314e2010-10-01 21:11:22 +00002705
Ted Kremenekfb480492010-01-13 21:46:36 +00002706 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2707 return getDeclFromExpr(CE->getCallee());
Chris Lattner5f9e2722011-07-23 10:55:15 +00002708 if (CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Douglas Gregor93798e22010-11-05 21:11:19 +00002709 if (!CE->isElidable())
2710 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002711 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2712 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002713
Douglas Gregordb1314e2010-10-01 21:11:22 +00002714 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2715 return PE->getProtocol();
Douglas Gregorc7793c72011-01-15 01:15:58 +00002716 if (SubstNonTypeTemplateParmPackExpr *NTTP
2717 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
2718 return NTTP->getParameterPack();
Douglas Gregor94d96292011-01-19 20:34:17 +00002719 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2720 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
2721 isa<ParmVarDecl>(SizeOfPack->getPack()))
2722 return SizeOfPack->getPack();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002723
Ted Kremenekfb480492010-01-13 21:46:36 +00002724 return 0;
2725}
2726
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002727static SourceLocation getLocationFromExpr(Expr *E) {
Argyrios Kyrtzidisc2954612011-09-12 22:17:26 +00002728 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
2729 return getLocationFromExpr(CE->getSubExpr());
2730
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002731 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2732 return /*FIXME:*/Msg->getLeftLoc();
2733 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2734 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002735 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2736 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002737 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2738 return Member->getMemberLoc();
2739 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2740 return Ivar->getLocation();
Douglas Gregor94d96292011-01-19 20:34:17 +00002741 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2742 return SizeOfPack->getPackLoc();
2743
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002744 return E->getLocStart();
2745}
2746
Ted Kremenekfb480492010-01-13 21:46:36 +00002747extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002748
2749unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002750 CXCursorVisitor visitor,
2751 CXClientData client_data) {
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00002752 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
2753 /*VisitPreprocessorLast=*/false);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002754 return CursorVis.VisitChildren(parent);
2755}
2756
David Chisnall3387c652010-11-03 14:12:26 +00002757#ifndef __has_feature
2758#define __has_feature(x) 0
2759#endif
2760#if __has_feature(blocks)
2761typedef enum CXChildVisitResult
2762 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2763
2764static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2765 CXClientData client_data) {
2766 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2767 return block(cursor, parent);
2768}
2769#else
2770// If we are compiled with a compiler that doesn't have native blocks support,
2771// define and call the block manually, so the
2772typedef struct _CXChildVisitResult
2773{
2774 void *isa;
2775 int flags;
2776 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002777 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2778 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00002779} *CXCursorVisitorBlock;
2780
2781static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2782 CXClientData client_data) {
2783 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2784 return block->invoke(block, cursor, parent);
2785}
2786#endif
2787
2788
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002789unsigned clang_visitChildrenWithBlock(CXCursor parent,
2790 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00002791 return clang_visitChildren(parent, visitWithBlock, block);
2792}
2793
Douglas Gregor78205d42010-01-20 21:45:58 +00002794static CXString getDeclSpelling(Decl *D) {
2795 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
Douglas Gregore3c60a72010-11-17 00:13:31 +00002796 if (!ND) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002797 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00002798 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
2799 return createCXString(Property->getIdentifier()->getName());
2800
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002801 return createCXString("");
Douglas Gregore3c60a72010-11-17 00:13:31 +00002802 }
2803
Douglas Gregor78205d42010-01-20 21:45:58 +00002804 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002805 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002806
Douglas Gregor78205d42010-01-20 21:45:58 +00002807 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2808 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2809 // and returns different names. NamedDecl returns the class name and
2810 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002811 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002812
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002813 if (isa<UsingDirectiveDecl>(D))
2814 return createCXString("");
2815
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002816 llvm::SmallString<1024> S;
2817 llvm::raw_svector_ostream os(S);
2818 ND->printName(os);
2819
2820 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002821}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002822
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002823CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002824 if (clang_isTranslationUnit(C.kind))
Ted Kremeneka60ed472010-11-16 08:15:36 +00002825 return clang_getTranslationUnitSpelling(
2826 static_cast<CXTranslationUnit>(C.data[2]));
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002827
Steve Narofff334b4e2009-09-02 18:26:48 +00002828 if (clang_isReference(C.kind)) {
2829 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002830 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002831 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002832 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002833 }
2834 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002835 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002836 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002837 }
2838 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002839 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002840 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002841 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002842 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002843 case CXCursor_CXXBaseSpecifier: {
2844 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2845 return createCXString(B->getType().getAsString());
2846 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002847 case CXCursor_TypeRef: {
2848 TypeDecl *Type = getCursorTypeRef(C).first;
2849 assert(Type && "Missing type decl");
2850
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002851 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2852 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002853 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002854 case CXCursor_TemplateRef: {
2855 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002856 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002857
2858 return createCXString(Template->getNameAsString());
2859 }
Douglas Gregor69319002010-08-31 23:48:11 +00002860
2861 case CXCursor_NamespaceRef: {
2862 NamedDecl *NS = getCursorNamespaceRef(C).first;
2863 assert(NS && "Missing namespace decl");
2864
2865 return createCXString(NS->getNameAsString());
2866 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002867
Douglas Gregora67e03f2010-09-09 21:42:20 +00002868 case CXCursor_MemberRef: {
2869 FieldDecl *Field = getCursorMemberRef(C).first;
2870 assert(Field && "Missing member decl");
2871
2872 return createCXString(Field->getNameAsString());
2873 }
2874
Douglas Gregor36897b02010-09-10 00:22:18 +00002875 case CXCursor_LabelRef: {
2876 LabelStmt *Label = getCursorLabelRef(C).first;
2877 assert(Label && "Missing label");
2878
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002879 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00002880 }
2881
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002882 case CXCursor_OverloadedDeclRef: {
2883 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2884 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2885 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2886 return createCXString(ND->getNameAsString());
2887 return createCXString("");
2888 }
2889 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2890 return createCXString(E->getName().getAsString());
2891 OverloadedTemplateStorage *Ovl
2892 = Storage.get<OverloadedTemplateStorage*>();
2893 if (Ovl->size() == 0)
2894 return createCXString("");
2895 return createCXString((*Ovl->begin())->getNameAsString());
2896 }
2897
Daniel Dunbaracca7252009-11-30 20:42:49 +00002898 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002899 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002900 }
2901 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002902
2903 if (clang_isExpression(C.kind)) {
2904 Decl *D = getDeclFromExpr(getCursorExpr(C));
2905 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002906 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002907 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002908 }
2909
Douglas Gregor36897b02010-09-10 00:22:18 +00002910 if (clang_isStatement(C.kind)) {
2911 Stmt *S = getCursorStmt(C);
2912 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002913 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00002914
2915 return createCXString("");
2916 }
2917
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00002918 if (C.kind == CXCursor_MacroExpansion)
Chandler Carruth9e5bb852011-07-14 08:20:46 +00002919 return createCXString(getCursorMacroExpansion(C)->getName()
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002920 ->getNameStart());
2921
Douglas Gregor572feb22010-03-18 18:04:21 +00002922 if (C.kind == CXCursor_MacroDefinition)
2923 return createCXString(getCursorMacroDefinition(C)->getName()
2924 ->getNameStart());
2925
Douglas Gregorecdcb882010-10-20 22:00:55 +00002926 if (C.kind == CXCursor_InclusionDirective)
2927 return createCXString(getCursorInclusionDirective(C)->getFileName());
2928
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002929 if (clang_isDeclaration(C.kind))
2930 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002931
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00002932 if (C.kind == CXCursor_AnnotateAttr) {
2933 AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
2934 return createCXString(AA->getAnnotation());
2935 }
2936
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002937 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002938}
2939
Douglas Gregor358559d2010-10-02 22:49:11 +00002940CXString clang_getCursorDisplayName(CXCursor C) {
2941 if (!clang_isDeclaration(C.kind))
2942 return clang_getCursorSpelling(C);
2943
2944 Decl *D = getCursorDecl(C);
2945 if (!D)
2946 return createCXString("");
2947
Douglas Gregor30c42402011-09-27 22:38:19 +00002948 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
Douglas Gregor358559d2010-10-02 22:49:11 +00002949 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2950 D = FunTmpl->getTemplatedDecl();
2951
2952 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
2953 llvm::SmallString<64> Str;
2954 llvm::raw_svector_ostream OS(Str);
2955 OS << Function->getNameAsString();
2956 if (Function->getPrimaryTemplate())
2957 OS << "<>";
2958 OS << "(";
2959 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
2960 if (I)
2961 OS << ", ";
2962 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
2963 }
2964
2965 if (Function->isVariadic()) {
2966 if (Function->getNumParams())
2967 OS << ", ";
2968 OS << "...";
2969 }
2970 OS << ")";
2971 return createCXString(OS.str());
2972 }
2973
2974 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
2975 llvm::SmallString<64> Str;
2976 llvm::raw_svector_ostream OS(Str);
2977 OS << ClassTemplate->getNameAsString();
2978 OS << "<";
2979 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
2980 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2981 if (I)
2982 OS << ", ";
2983
2984 NamedDecl *Param = Params->getParam(I);
2985 if (Param->getIdentifier()) {
2986 OS << Param->getIdentifier()->getName();
2987 continue;
2988 }
2989
2990 // There is no parameter name, which makes this tricky. Try to come up
2991 // with something useful that isn't too long.
2992 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2993 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
2994 else if (NonTypeTemplateParmDecl *NTTP
2995 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2996 OS << NTTP->getType().getAsString(Policy);
2997 else
2998 OS << "template<...> class";
2999 }
3000
3001 OS << ">";
3002 return createCXString(OS.str());
3003 }
3004
3005 if (ClassTemplateSpecializationDecl *ClassSpec
3006 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
3007 // If the type was explicitly written, use that.
3008 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
3009 return createCXString(TSInfo->getType().getAsString(Policy));
3010
3011 llvm::SmallString<64> Str;
3012 llvm::raw_svector_ostream OS(Str);
3013 OS << ClassSpec->getNameAsString();
3014 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00003015 ClassSpec->getTemplateArgs().data(),
3016 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00003017 Policy);
3018 return createCXString(OS.str());
3019 }
3020
3021 return clang_getCursorSpelling(C);
3022}
3023
Ted Kremeneke68fff62010-02-17 00:41:32 +00003024CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00003025 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00003026 case CXCursor_FunctionDecl:
3027 return createCXString("FunctionDecl");
3028 case CXCursor_TypedefDecl:
3029 return createCXString("TypedefDecl");
3030 case CXCursor_EnumDecl:
3031 return createCXString("EnumDecl");
3032 case CXCursor_EnumConstantDecl:
3033 return createCXString("EnumConstantDecl");
3034 case CXCursor_StructDecl:
3035 return createCXString("StructDecl");
3036 case CXCursor_UnionDecl:
3037 return createCXString("UnionDecl");
3038 case CXCursor_ClassDecl:
3039 return createCXString("ClassDecl");
3040 case CXCursor_FieldDecl:
3041 return createCXString("FieldDecl");
3042 case CXCursor_VarDecl:
3043 return createCXString("VarDecl");
3044 case CXCursor_ParmDecl:
3045 return createCXString("ParmDecl");
3046 case CXCursor_ObjCInterfaceDecl:
3047 return createCXString("ObjCInterfaceDecl");
3048 case CXCursor_ObjCCategoryDecl:
3049 return createCXString("ObjCCategoryDecl");
3050 case CXCursor_ObjCProtocolDecl:
3051 return createCXString("ObjCProtocolDecl");
3052 case CXCursor_ObjCPropertyDecl:
3053 return createCXString("ObjCPropertyDecl");
3054 case CXCursor_ObjCIvarDecl:
3055 return createCXString("ObjCIvarDecl");
3056 case CXCursor_ObjCInstanceMethodDecl:
3057 return createCXString("ObjCInstanceMethodDecl");
3058 case CXCursor_ObjCClassMethodDecl:
3059 return createCXString("ObjCClassMethodDecl");
3060 case CXCursor_ObjCImplementationDecl:
3061 return createCXString("ObjCImplementationDecl");
3062 case CXCursor_ObjCCategoryImplDecl:
3063 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00003064 case CXCursor_CXXMethod:
3065 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003066 case CXCursor_UnexposedDecl:
3067 return createCXString("UnexposedDecl");
3068 case CXCursor_ObjCSuperClassRef:
3069 return createCXString("ObjCSuperClassRef");
3070 case CXCursor_ObjCProtocolRef:
3071 return createCXString("ObjCProtocolRef");
3072 case CXCursor_ObjCClassRef:
3073 return createCXString("ObjCClassRef");
3074 case CXCursor_TypeRef:
3075 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003076 case CXCursor_TemplateRef:
3077 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00003078 case CXCursor_NamespaceRef:
3079 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00003080 case CXCursor_MemberRef:
3081 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00003082 case CXCursor_LabelRef:
3083 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003084 case CXCursor_OverloadedDeclRef:
3085 return createCXString("OverloadedDeclRef");
Douglas Gregor42b29842011-10-05 19:00:14 +00003086 case CXCursor_IntegerLiteral:
3087 return createCXString("IntegerLiteral");
3088 case CXCursor_FloatingLiteral:
3089 return createCXString("FloatingLiteral");
3090 case CXCursor_ImaginaryLiteral:
3091 return createCXString("ImaginaryLiteral");
3092 case CXCursor_StringLiteral:
3093 return createCXString("StringLiteral");
3094 case CXCursor_CharacterLiteral:
3095 return createCXString("CharacterLiteral");
3096 case CXCursor_ParenExpr:
3097 return createCXString("ParenExpr");
3098 case CXCursor_UnaryOperator:
3099 return createCXString("UnaryOperator");
3100 case CXCursor_ArraySubscriptExpr:
3101 return createCXString("ArraySubscriptExpr");
3102 case CXCursor_BinaryOperator:
3103 return createCXString("BinaryOperator");
3104 case CXCursor_CompoundAssignOperator:
3105 return createCXString("CompoundAssignOperator");
3106 case CXCursor_ConditionalOperator:
3107 return createCXString("ConditionalOperator");
3108 case CXCursor_CStyleCastExpr:
3109 return createCXString("CStyleCastExpr");
3110 case CXCursor_CompoundLiteralExpr:
3111 return createCXString("CompoundLiteralExpr");
3112 case CXCursor_InitListExpr:
3113 return createCXString("InitListExpr");
3114 case CXCursor_AddrLabelExpr:
3115 return createCXString("AddrLabelExpr");
3116 case CXCursor_StmtExpr:
3117 return createCXString("StmtExpr");
3118 case CXCursor_GenericSelectionExpr:
3119 return createCXString("GenericSelectionExpr");
3120 case CXCursor_GNUNullExpr:
3121 return createCXString("GNUNullExpr");
3122 case CXCursor_CXXStaticCastExpr:
3123 return createCXString("CXXStaticCastExpr");
3124 case CXCursor_CXXDynamicCastExpr:
3125 return createCXString("CXXDynamicCastExpr");
3126 case CXCursor_CXXReinterpretCastExpr:
3127 return createCXString("CXXReinterpretCastExpr");
3128 case CXCursor_CXXConstCastExpr:
3129 return createCXString("CXXConstCastExpr");
3130 case CXCursor_CXXFunctionalCastExpr:
3131 return createCXString("CXXFunctionalCastExpr");
3132 case CXCursor_CXXTypeidExpr:
3133 return createCXString("CXXTypeidExpr");
3134 case CXCursor_CXXBoolLiteralExpr:
3135 return createCXString("CXXBoolLiteralExpr");
3136 case CXCursor_CXXNullPtrLiteralExpr:
3137 return createCXString("CXXNullPtrLiteralExpr");
3138 case CXCursor_CXXThisExpr:
3139 return createCXString("CXXThisExpr");
3140 case CXCursor_CXXThrowExpr:
3141 return createCXString("CXXThrowExpr");
3142 case CXCursor_CXXNewExpr:
3143 return createCXString("CXXNewExpr");
3144 case CXCursor_CXXDeleteExpr:
3145 return createCXString("CXXDeleteExpr");
3146 case CXCursor_UnaryExpr:
3147 return createCXString("UnaryExpr");
3148 case CXCursor_ObjCStringLiteral:
3149 return createCXString("ObjCStringLiteral");
3150 case CXCursor_ObjCEncodeExpr:
3151 return createCXString("ObjCEncodeExpr");
3152 case CXCursor_ObjCSelectorExpr:
3153 return createCXString("ObjCSelectorExpr");
3154 case CXCursor_ObjCProtocolExpr:
3155 return createCXString("ObjCProtocolExpr");
3156 case CXCursor_ObjCBridgedCastExpr:
3157 return createCXString("ObjCBridgedCastExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00003158 case CXCursor_BlockExpr:
3159 return createCXString("BlockExpr");
Douglas Gregor42b29842011-10-05 19:00:14 +00003160 case CXCursor_PackExpansionExpr:
3161 return createCXString("PackExpansionExpr");
3162 case CXCursor_SizeOfPackExpr:
3163 return createCXString("SizeOfPackExpr");
3164 case CXCursor_UnexposedExpr:
3165 return createCXString("UnexposedExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003166 case CXCursor_DeclRefExpr:
3167 return createCXString("DeclRefExpr");
3168 case CXCursor_MemberRefExpr:
3169 return createCXString("MemberRefExpr");
3170 case CXCursor_CallExpr:
3171 return createCXString("CallExpr");
3172 case CXCursor_ObjCMessageExpr:
3173 return createCXString("ObjCMessageExpr");
3174 case CXCursor_UnexposedStmt:
3175 return createCXString("UnexposedStmt");
Douglas Gregor42b29842011-10-05 19:00:14 +00003176 case CXCursor_DeclStmt:
3177 return createCXString("DeclStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00003178 case CXCursor_LabelStmt:
3179 return createCXString("LabelStmt");
Douglas Gregor42b29842011-10-05 19:00:14 +00003180 case CXCursor_CompoundStmt:
3181 return createCXString("CompoundStmt");
3182 case CXCursor_CaseStmt:
3183 return createCXString("CaseStmt");
3184 case CXCursor_DefaultStmt:
3185 return createCXString("DefaultStmt");
3186 case CXCursor_IfStmt:
3187 return createCXString("IfStmt");
3188 case CXCursor_SwitchStmt:
3189 return createCXString("SwitchStmt");
3190 case CXCursor_WhileStmt:
3191 return createCXString("WhileStmt");
3192 case CXCursor_DoStmt:
3193 return createCXString("DoStmt");
3194 case CXCursor_ForStmt:
3195 return createCXString("ForStmt");
3196 case CXCursor_GotoStmt:
3197 return createCXString("GotoStmt");
3198 case CXCursor_IndirectGotoStmt:
3199 return createCXString("IndirectGotoStmt");
3200 case CXCursor_ContinueStmt:
3201 return createCXString("ContinueStmt");
3202 case CXCursor_BreakStmt:
3203 return createCXString("BreakStmt");
3204 case CXCursor_ReturnStmt:
3205 return createCXString("ReturnStmt");
3206 case CXCursor_AsmStmt:
3207 return createCXString("AsmStmt");
3208 case CXCursor_ObjCAtTryStmt:
3209 return createCXString("ObjCAtTryStmt");
3210 case CXCursor_ObjCAtCatchStmt:
3211 return createCXString("ObjCAtCatchStmt");
3212 case CXCursor_ObjCAtFinallyStmt:
3213 return createCXString("ObjCAtFinallyStmt");
3214 case CXCursor_ObjCAtThrowStmt:
3215 return createCXString("ObjCAtThrowStmt");
3216 case CXCursor_ObjCAtSynchronizedStmt:
3217 return createCXString("ObjCAtSynchronizedStmt");
3218 case CXCursor_ObjCAutoreleasePoolStmt:
3219 return createCXString("ObjCAutoreleasePoolStmt");
3220 case CXCursor_ObjCForCollectionStmt:
3221 return createCXString("ObjCForCollectionStmt");
3222 case CXCursor_CXXCatchStmt:
3223 return createCXString("CXXCatchStmt");
3224 case CXCursor_CXXTryStmt:
3225 return createCXString("CXXTryStmt");
3226 case CXCursor_CXXForRangeStmt:
3227 return createCXString("CXXForRangeStmt");
3228 case CXCursor_SEHTryStmt:
3229 return createCXString("SEHTryStmt");
3230 case CXCursor_SEHExceptStmt:
3231 return createCXString("SEHExceptStmt");
3232 case CXCursor_SEHFinallyStmt:
3233 return createCXString("SEHFinallyStmt");
3234 case CXCursor_NullStmt:
3235 return createCXString("NullStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003236 case CXCursor_InvalidFile:
3237 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00003238 case CXCursor_InvalidCode:
3239 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003240 case CXCursor_NoDeclFound:
3241 return createCXString("NoDeclFound");
3242 case CXCursor_NotImplemented:
3243 return createCXString("NotImplemented");
3244 case CXCursor_TranslationUnit:
3245 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00003246 case CXCursor_UnexposedAttr:
3247 return createCXString("UnexposedAttr");
3248 case CXCursor_IBActionAttr:
3249 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003250 case CXCursor_IBOutletAttr:
3251 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003252 case CXCursor_IBOutletCollectionAttr:
3253 return createCXString("attribute(iboutletcollection)");
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00003254 case CXCursor_CXXFinalAttr:
3255 return createCXString("attribute(final)");
3256 case CXCursor_CXXOverrideAttr:
3257 return createCXString("attribute(override)");
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00003258 case CXCursor_AnnotateAttr:
3259 return createCXString("attribute(annotate)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003260 case CXCursor_PreprocessingDirective:
3261 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003262 case CXCursor_MacroDefinition:
3263 return createCXString("macro definition");
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003264 case CXCursor_MacroExpansion:
3265 return createCXString("macro expansion");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003266 case CXCursor_InclusionDirective:
3267 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003268 case CXCursor_Namespace:
3269 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003270 case CXCursor_LinkageSpec:
3271 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003272 case CXCursor_CXXBaseSpecifier:
3273 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003274 case CXCursor_Constructor:
3275 return createCXString("CXXConstructor");
3276 case CXCursor_Destructor:
3277 return createCXString("CXXDestructor");
3278 case CXCursor_ConversionFunction:
3279 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003280 case CXCursor_TemplateTypeParameter:
3281 return createCXString("TemplateTypeParameter");
3282 case CXCursor_NonTypeTemplateParameter:
3283 return createCXString("NonTypeTemplateParameter");
3284 case CXCursor_TemplateTemplateParameter:
3285 return createCXString("TemplateTemplateParameter");
3286 case CXCursor_FunctionTemplate:
3287 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003288 case CXCursor_ClassTemplate:
3289 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003290 case CXCursor_ClassTemplatePartialSpecialization:
3291 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003292 case CXCursor_NamespaceAlias:
3293 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003294 case CXCursor_UsingDirective:
3295 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003296 case CXCursor_UsingDeclaration:
3297 return createCXString("UsingDeclaration");
Richard Smith162e1c12011-04-15 14:24:37 +00003298 case CXCursor_TypeAliasDecl:
Douglas Gregor352697a2011-06-03 23:08:58 +00003299 return createCXString("TypeAliasDecl");
3300 case CXCursor_ObjCSynthesizeDecl:
3301 return createCXString("ObjCSynthesizeDecl");
3302 case CXCursor_ObjCDynamicDecl:
3303 return createCXString("ObjCDynamicDecl");
Argyrios Kyrtzidis2dfdb942011-09-30 17:58:23 +00003304 case CXCursor_CXXAccessSpecifier:
3305 return createCXString("CXXAccessSpecifier");
Steve Naroff89922f82009-08-31 00:59:03 +00003306 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003307
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003308 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneka60ed472010-11-16 08:15:36 +00003309 return createCXString((const char*) 0);
Steve Naroff600866c2009-08-27 19:51:58 +00003310}
Steve Naroff89922f82009-08-31 00:59:03 +00003311
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003312struct GetCursorData {
3313 SourceLocation TokenBeginLoc;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003314 bool PointsAtMacroArgExpansion;
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003315 CXCursor &BestCursor;
3316
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003317 GetCursorData(SourceManager &SM,
3318 SourceLocation tokenBegin, CXCursor &outputCursor)
3319 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
3320 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
3321 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003322};
3323
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003324static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3325 CXCursor parent,
3326 CXClientData client_data) {
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003327 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
3328 CXCursor *BestCursor = &Data->BestCursor;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003329
3330 // If we point inside a macro argument we should provide info of what the
3331 // token is so use the actual cursor, don't replace it with a macro expansion
3332 // cursor.
3333 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
3334 return CXChildVisit_Recurse;
Argyrios Kyrtzidis65ab9072011-09-26 19:05:37 +00003335
3336 if (clang_isDeclaration(cursor.kind)) {
3337 // Avoid having the implicit methods override the property decls.
3338 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(getCursorDecl(cursor)))
3339 if (MD->isImplicit())
3340 return CXChildVisit_Break;
3341 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003342
3343 if (clang_isExpression(cursor.kind) &&
3344 clang_isDeclaration(BestCursor->kind)) {
3345 Decl *D = getCursorDecl(*BestCursor);
3346
3347 // Avoid having the cursor of an expression replace the declaration cursor
3348 // when the expression source range overlaps the declaration range.
3349 // This can happen for C++ constructor expressions whose range generally
3350 // include the variable declaration, e.g.:
3351 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
3352 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
3353 D->getLocation() == Data->TokenBeginLoc)
3354 return CXChildVisit_Break;
3355 }
3356
Douglas Gregor93798e22010-11-05 21:11:19 +00003357 // If our current best cursor is the construction of a temporary object,
3358 // don't replace that cursor with a type reference, because we want
3359 // clang_getCursor() to point at the constructor.
3360 if (clang_isExpression(BestCursor->kind) &&
3361 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003362 cursor.kind == CXCursor_TypeRef) {
3363 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
3364 // as having the actual point on the type reference.
3365 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
Douglas Gregor93798e22010-11-05 21:11:19 +00003366 return CXChildVisit_Recurse;
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003367 }
Douglas Gregor93798e22010-11-05 21:11:19 +00003368
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003369 *BestCursor = cursor;
3370 return CXChildVisit_Recurse;
3371}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003372
Douglas Gregorb9790342010-01-22 21:44:22 +00003373CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3374 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003375 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003376
Ted Kremeneka60ed472010-11-16 08:15:36 +00003377 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003378 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3379
Ted Kremeneka297de22010-01-25 22:34:44 +00003380 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003381 CXCursor Result = cxcursor::getCursor(TU, SLoc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003382
Douglas Gregor40749ee2010-11-03 00:35:38 +00003383 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregor40749ee2010-11-03 00:35:38 +00003384 if (Logging) {
3385 CXFile SearchFile;
3386 unsigned SearchLine, SearchColumn;
3387 CXFile ResultFile;
3388 unsigned ResultLine, ResultColumn;
Douglas Gregor66537982010-11-17 17:14:07 +00003389 CXString SearchFileName, ResultFileName, KindSpelling, USR;
3390 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
Douglas Gregor40749ee2010-11-03 00:35:38 +00003391 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3392
Chandler Carruth20174222011-08-31 16:53:37 +00003393 clang_getExpansionLocation(Loc, &SearchFile, &SearchLine, &SearchColumn, 0);
3394 clang_getExpansionLocation(ResultLoc, &ResultFile, &ResultLine,
3395 &ResultColumn, 0);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003396 SearchFileName = clang_getFileName(SearchFile);
3397 ResultFileName = clang_getFileName(ResultFile);
3398 KindSpelling = clang_getCursorKindSpelling(Result.kind);
Douglas Gregor66537982010-11-17 17:14:07 +00003399 USR = clang_getCursorUSR(Result);
3400 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n",
Douglas Gregor40749ee2010-11-03 00:35:38 +00003401 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3402 clang_getCString(KindSpelling),
Douglas Gregor66537982010-11-17 17:14:07 +00003403 clang_getCString(ResultFileName), ResultLine, ResultColumn,
3404 clang_getCString(USR), IsDef);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003405 clang_disposeString(SearchFileName);
3406 clang_disposeString(ResultFileName);
3407 clang_disposeString(KindSpelling);
Douglas Gregor66537982010-11-17 17:14:07 +00003408 clang_disposeString(USR);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003409
3410 CXCursor Definition = clang_getCursorDefinition(Result);
3411 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
3412 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
3413 CXString DefinitionKindSpelling
3414 = clang_getCursorKindSpelling(Definition.kind);
3415 CXFile DefinitionFile;
3416 unsigned DefinitionLine, DefinitionColumn;
Chandler Carruth20174222011-08-31 16:53:37 +00003417 clang_getExpansionLocation(DefinitionLoc, &DefinitionFile,
3418 &DefinitionLine, &DefinitionColumn, 0);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003419 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
3420 fprintf(stderr, " -> %s(%s:%d:%d)\n",
3421 clang_getCString(DefinitionKindSpelling),
3422 clang_getCString(DefinitionFileName),
3423 DefinitionLine, DefinitionColumn);
3424 clang_disposeString(DefinitionFileName);
3425 clang_disposeString(DefinitionKindSpelling);
3426 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003427 }
3428
Ted Kremeneke68fff62010-02-17 00:41:32 +00003429 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003430}
3431
Ted Kremenek73885552009-11-17 19:28:59 +00003432CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003433 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003434}
3435
3436unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003437 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003438}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003439
Douglas Gregor9ce55842010-11-20 00:09:34 +00003440unsigned clang_hashCursor(CXCursor C) {
3441 unsigned Index = 0;
3442 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
3443 Index = 1;
3444
3445 return llvm::DenseMapInfo<std::pair<unsigned, void*> >::getHashValue(
3446 std::make_pair(C.kind, C.data[Index]));
3447}
3448
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003449unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003450 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3451}
3452
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003453unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003454 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3455}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003456
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003457unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003458 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3459}
3460
Douglas Gregor97b98722010-01-19 23:20:36 +00003461unsigned clang_isExpression(enum CXCursorKind K) {
3462 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3463}
3464
3465unsigned clang_isStatement(enum CXCursorKind K) {
3466 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3467}
3468
Douglas Gregor8be80e12011-07-06 03:00:34 +00003469unsigned clang_isAttribute(enum CXCursorKind K) {
3470 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
3471}
3472
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003473unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3474 return K == CXCursor_TranslationUnit;
3475}
3476
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003477unsigned clang_isPreprocessing(enum CXCursorKind K) {
3478 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3479}
3480
Ted Kremenekad6eff62010-03-08 21:17:29 +00003481unsigned clang_isUnexposed(enum CXCursorKind K) {
3482 switch (K) {
3483 case CXCursor_UnexposedDecl:
3484 case CXCursor_UnexposedExpr:
3485 case CXCursor_UnexposedStmt:
3486 case CXCursor_UnexposedAttr:
3487 return true;
3488 default:
3489 return false;
3490 }
3491}
3492
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003493CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003494 return C.kind;
3495}
3496
Douglas Gregor98258af2010-01-18 22:46:11 +00003497CXSourceLocation clang_getCursorLocation(CXCursor C) {
3498 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003499 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003500 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003501 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3502 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003503 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003504 }
3505
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003506 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003507 std::pair<ObjCProtocolDecl *, SourceLocation> P
3508 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003509 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003510 }
3511
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003512 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003513 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3514 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003515 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003516 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003517
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003518 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003519 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003520 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003521 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003522
3523 case CXCursor_TemplateRef: {
3524 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3525 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3526 }
3527
Douglas Gregor69319002010-08-31 23:48:11 +00003528 case CXCursor_NamespaceRef: {
3529 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3530 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3531 }
3532
Douglas Gregora67e03f2010-09-09 21:42:20 +00003533 case CXCursor_MemberRef: {
3534 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3535 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3536 }
3537
Ted Kremenek3064ef92010-08-27 21:34:58 +00003538 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003539 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3540 if (!BaseSpec)
3541 return clang_getNullLocation();
3542
3543 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3544 return cxloc::translateSourceLocation(getCursorContext(C),
3545 TSInfo->getTypeLoc().getBeginLoc());
3546
3547 return cxloc::translateSourceLocation(getCursorContext(C),
3548 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003549 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003550
Douglas Gregor36897b02010-09-10 00:22:18 +00003551 case CXCursor_LabelRef: {
3552 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3553 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3554 }
3555
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003556 case CXCursor_OverloadedDeclRef:
3557 return cxloc::translateSourceLocation(getCursorContext(C),
3558 getCursorOverloadedDeclRef(C).second);
3559
Douglas Gregorf46034a2010-01-18 23:41:10 +00003560 default:
3561 // FIXME: Need a way to enumerate all non-reference cases.
3562 llvm_unreachable("Missed a reference kind");
3563 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003564 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003565
3566 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003567 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003568 getLocationFromExpr(getCursorExpr(C)));
3569
Douglas Gregor36897b02010-09-10 00:22:18 +00003570 if (clang_isStatement(C.kind))
3571 return cxloc::translateSourceLocation(getCursorContext(C),
3572 getCursorStmt(C)->getLocStart());
3573
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003574 if (C.kind == CXCursor_PreprocessingDirective) {
3575 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3576 return cxloc::translateSourceLocation(getCursorContext(C), L);
3577 }
Douglas Gregor48072312010-03-18 15:23:44 +00003578
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003579 if (C.kind == CXCursor_MacroExpansion) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003580 SourceLocation L
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003581 = cxcursor::getCursorMacroExpansion(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003582 return cxloc::translateSourceLocation(getCursorContext(C), L);
3583 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003584
3585 if (C.kind == CXCursor_MacroDefinition) {
3586 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3587 return cxloc::translateSourceLocation(getCursorContext(C), L);
3588 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003589
3590 if (C.kind == CXCursor_InclusionDirective) {
3591 SourceLocation L
3592 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3593 return cxloc::translateSourceLocation(getCursorContext(C), L);
3594 }
3595
Ted Kremenek9a700d22010-05-12 06:16:13 +00003596 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003597 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003598
Douglas Gregorf46034a2010-01-18 23:41:10 +00003599 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003600 SourceLocation Loc = D->getLocation();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003601 // FIXME: Multiple variables declared in a single declaration
3602 // currently lack the information needed to correctly determine their
3603 // ranges when accounting for the type-specifier. We use context
3604 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3605 // and if so, whether it is the first decl.
3606 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3607 if (!cxcursor::isFirstInDeclGroup(C))
3608 Loc = VD->getLocation();
3609 }
3610
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003611 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003612}
Douglas Gregora7bde202010-01-19 00:34:46 +00003613
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003614} // end extern "C"
3615
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003616CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
3617 assert(TU);
3618
3619 // Guard against an invalid SourceLocation, or we may assert in one
3620 // of the following calls.
3621 if (SLoc.isInvalid())
3622 return clang_getNullCursor();
3623
3624 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
3625
3626 // Translate the given source location to make it point at the beginning of
3627 // the token under the cursor.
3628 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3629 CXXUnit->getASTContext().getLangOptions());
3630
3631 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3632 if (SLoc.isValid()) {
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003633 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003634 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
3635 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00003636 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003637 SourceLocation(SLoc));
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00003638 CursorVis.visitFileRegion();
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003639 }
3640
3641 return Result;
3642}
3643
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003644static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003645 if (clang_isReference(C.kind)) {
3646 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003647 case CXCursor_ObjCSuperClassRef:
3648 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003649
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003650 case CXCursor_ObjCProtocolRef:
3651 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003652
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003653 case CXCursor_ObjCClassRef:
3654 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003655
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003656 case CXCursor_TypeRef:
3657 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003658
3659 case CXCursor_TemplateRef:
3660 return getCursorTemplateRef(C).second;
3661
Douglas Gregor69319002010-08-31 23:48:11 +00003662 case CXCursor_NamespaceRef:
3663 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003664
3665 case CXCursor_MemberRef:
3666 return getCursorMemberRef(C).second;
3667
Ted Kremenek3064ef92010-08-27 21:34:58 +00003668 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003669 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003670
Douglas Gregor36897b02010-09-10 00:22:18 +00003671 case CXCursor_LabelRef:
3672 return getCursorLabelRef(C).second;
3673
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003674 case CXCursor_OverloadedDeclRef:
3675 return getCursorOverloadedDeclRef(C).second;
3676
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003677 default:
3678 // FIXME: Need a way to enumerate all non-reference cases.
3679 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003680 }
3681 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003682
3683 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003684 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003685
3686 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003687 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003688
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00003689 if (clang_isAttribute(C.kind))
3690 return getCursorAttr(C)->getRange();
3691
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003692 if (C.kind == CXCursor_PreprocessingDirective)
3693 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003694
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00003695 if (C.kind == CXCursor_MacroExpansion) {
3696 ASTUnit *TU = getCursorASTUnit(C);
3697 SourceRange Range = cxcursor::getCursorMacroExpansion(C)->getSourceRange();
3698 return TU->mapRangeFromPreamble(Range);
3699 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003700
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00003701 if (C.kind == CXCursor_MacroDefinition) {
3702 ASTUnit *TU = getCursorASTUnit(C);
3703 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
3704 return TU->mapRangeFromPreamble(Range);
3705 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003706
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00003707 if (C.kind == CXCursor_InclusionDirective) {
3708 ASTUnit *TU = getCursorASTUnit(C);
3709 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3710 return TU->mapRangeFromPreamble(Range);
3711 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003712
Ted Kremenek007a7c92010-11-01 23:26:51 +00003713 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3714 Decl *D = cxcursor::getCursorDecl(C);
3715 SourceRange R = D->getSourceRange();
3716 // FIXME: Multiple variables declared in a single declaration
3717 // currently lack the information needed to correctly determine their
3718 // ranges when accounting for the type-specifier. We use context
3719 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3720 // and if so, whether it is the first decl.
3721 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3722 if (!cxcursor::isFirstInDeclGroup(C))
3723 R.setBegin(VD->getLocation());
3724 }
3725 return R;
3726 }
Douglas Gregor66537982010-11-17 17:14:07 +00003727 return SourceRange();
3728}
3729
3730/// \brief Retrieves the "raw" cursor extent, which is then extended to include
3731/// the decl-specifier-seq for declarations.
3732static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
3733 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3734 Decl *D = cxcursor::getCursorDecl(C);
3735 SourceRange R = D->getSourceRange();
Douglas Gregor66537982010-11-17 17:14:07 +00003736
Douglas Gregor2494dd02011-03-01 01:34:45 +00003737 // Adjust the start of the location for declarations preceded by
3738 // declaration specifiers.
3739 SourceLocation StartLoc;
3740 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
3741 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
3742 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
3743 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
3744 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
3745 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
3746 }
3747
3748 if (StartLoc.isValid() && R.getBegin().isValid() &&
3749 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
3750 R.setBegin(StartLoc);
3751
3752 // FIXME: Multiple variables declared in a single declaration
3753 // currently lack the information needed to correctly determine their
3754 // ranges when accounting for the type-specifier. We use context
3755 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3756 // and if so, whether it is the first decl.
3757 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3758 if (!cxcursor::isFirstInDeclGroup(C))
3759 R.setBegin(VD->getLocation());
Douglas Gregor66537982010-11-17 17:14:07 +00003760 }
3761
3762 return R;
3763 }
3764
3765 return getRawCursorExtent(C);
3766}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003767
3768extern "C" {
3769
3770CXSourceRange clang_getCursorExtent(CXCursor C) {
3771 SourceRange R = getRawCursorExtent(C);
3772 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003773 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003774
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003775 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003776}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003777
3778CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003779 if (clang_isInvalid(C.kind))
3780 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003781
Ted Kremeneka60ed472010-11-16 08:15:36 +00003782 CXTranslationUnit tu = getCursorTU(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003783 if (clang_isDeclaration(C.kind)) {
3784 Decl *D = getCursorDecl(C);
3785 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003786 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003787 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003788 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003789 if (ObjCForwardProtocolDecl *Protocols
3790 = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003791 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), tu);
Chris Lattner5f9e2722011-07-23 10:55:15 +00003792 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00003793 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3794 return MakeCXCursor(Property, tu);
3795
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003796 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003797 }
3798
Douglas Gregor97b98722010-01-19 23:20:36 +00003799 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003800 Expr *E = getCursorExpr(C);
3801 Decl *D = getDeclFromExpr(E);
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003802 if (D) {
3803 CXCursor declCursor = MakeCXCursor(D, tu);
3804 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
3805 declCursor);
3806 return declCursor;
3807 }
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003808
3809 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003810 return MakeCursorOverloadedDeclRef(Ovl, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003811
Douglas Gregor97b98722010-01-19 23:20:36 +00003812 return clang_getNullCursor();
3813 }
3814
Douglas Gregor36897b02010-09-10 00:22:18 +00003815 if (clang_isStatement(C.kind)) {
3816 Stmt *S = getCursorStmt(C);
3817 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Ted Kremenek37c2e962011-03-15 23:47:49 +00003818 if (LabelDecl *label = Goto->getLabel())
3819 if (LabelStmt *labelS = label->getStmt())
3820 return MakeCXCursor(labelS, getCursorDecl(C), tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003821
3822 return clang_getNullCursor();
3823 }
3824
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003825 if (C.kind == CXCursor_MacroExpansion) {
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003826 if (MacroDefinition *Def = getCursorMacroExpansion(C)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003827 return MakeMacroDefinitionCursor(Def, tu);
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003828 }
3829
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003830 if (!clang_isReference(C.kind))
3831 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003832
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003833 switch (C.kind) {
3834 case CXCursor_ObjCSuperClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003835 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003836
3837 case CXCursor_ObjCProtocolRef: {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003838 return MakeCXCursor(getCursorObjCProtocolRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003839
3840 case CXCursor_ObjCClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003841 return MakeCXCursor(getCursorObjCClassRef(C).first, tu );
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003842
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003843 case CXCursor_TypeRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003844 return MakeCXCursor(getCursorTypeRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003845
3846 case CXCursor_TemplateRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003847 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003848
Douglas Gregor69319002010-08-31 23:48:11 +00003849 case CXCursor_NamespaceRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003850 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
Douglas Gregor69319002010-08-31 23:48:11 +00003851
Douglas Gregora67e03f2010-09-09 21:42:20 +00003852 case CXCursor_MemberRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003853 return MakeCXCursor(getCursorMemberRef(C).first, tu );
Douglas Gregora67e03f2010-09-09 21:42:20 +00003854
Ted Kremenek3064ef92010-08-27 21:34:58 +00003855 case CXCursor_CXXBaseSpecifier: {
3856 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3857 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003858 tu ));
Ted Kremenek3064ef92010-08-27 21:34:58 +00003859 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003860
Douglas Gregor36897b02010-09-10 00:22:18 +00003861 case CXCursor_LabelRef:
3862 // FIXME: We end up faking the "parent" declaration here because we
3863 // don't want to make CXCursor larger.
3864 return MakeCXCursor(getCursorLabelRef(C).first,
Ted Kremeneka60ed472010-11-16 08:15:36 +00003865 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
3866 .getTranslationUnitDecl(),
3867 tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003868
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003869 case CXCursor_OverloadedDeclRef:
3870 return C;
3871
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003872 default:
3873 // We would prefer to enumerate all non-reference cursor kinds here.
3874 llvm_unreachable("Unhandled reference cursor kind");
3875 break;
3876 }
3877 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003878
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003879 return clang_getNullCursor();
3880}
3881
Douglas Gregorb6998662010-01-19 19:34:47 +00003882CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003883 if (clang_isInvalid(C.kind))
3884 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003885
Ted Kremeneka60ed472010-11-16 08:15:36 +00003886 CXTranslationUnit TU = getCursorTU(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003887
Douglas Gregorb6998662010-01-19 19:34:47 +00003888 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003889 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003890 C = clang_getCursorReferenced(C);
3891 WasReference = true;
3892 }
3893
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003894 if (C.kind == CXCursor_MacroExpansion)
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003895 return clang_getCursorReferenced(C);
3896
Douglas Gregorb6998662010-01-19 19:34:47 +00003897 if (!clang_isDeclaration(C.kind))
3898 return clang_getNullCursor();
3899
3900 Decl *D = getCursorDecl(C);
3901 if (!D)
3902 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003903
Douglas Gregorb6998662010-01-19 19:34:47 +00003904 switch (D->getKind()) {
3905 // Declaration kinds that don't really separate the notions of
3906 // declaration and definition.
3907 case Decl::Namespace:
3908 case Decl::Typedef:
Richard Smith162e1c12011-04-15 14:24:37 +00003909 case Decl::TypeAlias:
Richard Smith3e4c6c42011-05-05 21:57:07 +00003910 case Decl::TypeAliasTemplate:
Douglas Gregorb6998662010-01-19 19:34:47 +00003911 case Decl::TemplateTypeParm:
3912 case Decl::EnumConstant:
3913 case Decl::Field:
Benjamin Kramerd9811462010-11-21 14:11:41 +00003914 case Decl::IndirectField:
Douglas Gregorb6998662010-01-19 19:34:47 +00003915 case Decl::ObjCIvar:
3916 case Decl::ObjCAtDefsField:
3917 case Decl::ImplicitParam:
3918 case Decl::ParmVar:
3919 case Decl::NonTypeTemplateParm:
3920 case Decl::TemplateTemplateParm:
3921 case Decl::ObjCCategoryImpl:
3922 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00003923 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00003924 case Decl::LinkageSpec:
3925 case Decl::ObjCPropertyImpl:
3926 case Decl::FileScopeAsm:
3927 case Decl::StaticAssert:
3928 case Decl::Block:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003929 case Decl::Label: // FIXME: Is this right??
Francois Pichetaf0f4d02011-08-14 03:52:19 +00003930 case Decl::ClassScopeFunctionSpecialization:
Douglas Gregorb6998662010-01-19 19:34:47 +00003931 return C;
3932
3933 // Declaration kinds that don't make any sense here, but are
3934 // nonetheless harmless.
3935 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00003936 break;
3937
3938 // Declaration kinds for which the definition is not resolvable.
3939 case Decl::UnresolvedUsingTypename:
3940 case Decl::UnresolvedUsingValue:
3941 break;
3942
3943 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003944 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003945 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003946
3947 case Decl::NamespaceAlias:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003948 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003949
3950 case Decl::Enum:
3951 case Decl::Record:
3952 case Decl::CXXRecord:
3953 case Decl::ClassTemplateSpecialization:
3954 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00003955 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003956 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003957 return clang_getNullCursor();
3958
3959 case Decl::Function:
3960 case Decl::CXXMethod:
3961 case Decl::CXXConstructor:
3962 case Decl::CXXDestructor:
3963 case Decl::CXXConversion: {
3964 const FunctionDecl *Def = 0;
3965 if (cast<FunctionDecl>(D)->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003966 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003967 return clang_getNullCursor();
3968 }
3969
3970 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00003971 // Ask the variable if it has a definition.
3972 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003973 return MakeCXCursor(Def, TU);
Sebastian Redl31310a22010-02-01 20:16:42 +00003974 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00003975 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003976
Douglas Gregorb6998662010-01-19 19:34:47 +00003977 case Decl::FunctionTemplate: {
3978 const FunctionDecl *Def = 0;
3979 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003980 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003981 return clang_getNullCursor();
3982 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003983
Douglas Gregorb6998662010-01-19 19:34:47 +00003984 case Decl::ClassTemplate: {
3985 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00003986 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00003987 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003988 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003989 return clang_getNullCursor();
3990 }
3991
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003992 case Decl::Using:
3993 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003994 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003995
3996 case Decl::UsingShadow:
3997 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003998 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003999 TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004000
4001 case Decl::ObjCMethod: {
4002 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
4003 if (Method->isThisDeclarationADefinition())
4004 return C;
4005
4006 // Dig out the method definition in the associated
4007 // @implementation, if we have it.
4008 // FIXME: The ASTs should make finding the definition easier.
4009 if (ObjCInterfaceDecl *Class
4010 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
4011 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
4012 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
4013 Method->isInstanceMethod()))
4014 if (Def->isThisDeclarationADefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004015 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004016
4017 return clang_getNullCursor();
4018 }
4019
4020 case Decl::ObjCCategory:
4021 if (ObjCCategoryImplDecl *Impl
4022 = cast<ObjCCategoryDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004023 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004024 return clang_getNullCursor();
4025
4026 case Decl::ObjCProtocol:
4027 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
4028 return C;
4029 return clang_getNullCursor();
4030
4031 case Decl::ObjCInterface:
4032 // There are two notions of a "definition" for an Objective-C
4033 // class: the interface and its implementation. When we resolved a
4034 // reference to an Objective-C class, produce the @interface as
4035 // the definition; when we were provided with the interface,
4036 // produce the @implementation as the definition.
4037 if (WasReference) {
4038 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
4039 return C;
4040 } else if (ObjCImplementationDecl *Impl
4041 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004042 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004043 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004044
Douglas Gregorb6998662010-01-19 19:34:47 +00004045 case Decl::ObjCProperty:
4046 // FIXME: We don't really know where to find the
4047 // ObjCPropertyImplDecls that implement this property.
4048 return clang_getNullCursor();
4049
4050 case Decl::ObjCCompatibleAlias:
4051 if (ObjCInterfaceDecl *Class
4052 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
4053 if (!Class->isForwardDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004054 return MakeCXCursor(Class, TU);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004055
Douglas Gregorb6998662010-01-19 19:34:47 +00004056 return clang_getNullCursor();
4057
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004058 case Decl::ObjCForwardProtocol:
4059 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004060 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004061
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004062 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004063 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004064 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004065
4066 case Decl::Friend:
4067 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004068 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004069 return clang_getNullCursor();
4070
4071 case Decl::FriendTemplate:
4072 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004073 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004074 return clang_getNullCursor();
4075 }
4076
4077 return clang_getNullCursor();
4078}
4079
4080unsigned clang_isCursorDefinition(CXCursor C) {
4081 if (!clang_isDeclaration(C.kind))
4082 return 0;
4083
4084 return clang_getCursorDefinition(C) == C;
4085}
4086
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004087CXCursor clang_getCanonicalCursor(CXCursor C) {
4088 if (!clang_isDeclaration(C.kind))
4089 return C;
4090
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004091 if (Decl *D = getCursorDecl(C)) {
Argyrios Kyrtzidisdebb00f2011-07-15 22:37:58 +00004092 if (ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
4093 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
4094 return MakeCXCursor(CatD, getCursorTU(C));
4095
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004096 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
4097 if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
4098 return MakeCXCursor(IFD, getCursorTU(C));
4099
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004100 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004101 }
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004102
4103 return C;
4104}
4105
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004106unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004107 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004108 return 0;
4109
4110 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
4111 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
4112 return E->getNumDecls();
4113
4114 if (OverloadedTemplateStorage *S
4115 = Storage.dyn_cast<OverloadedTemplateStorage*>())
4116 return S->size();
4117
4118 Decl *D = Storage.get<Decl*>();
4119 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00004120 return Using->shadow_size();
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00004121 if (isa<ObjCClassDecl>(D))
4122 return 1;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004123 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
4124 return Protocols->protocol_size();
4125
4126 return 0;
4127}
4128
4129CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004130 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004131 return clang_getNullCursor();
4132
4133 if (index >= clang_getNumOverloadedDecls(cursor))
4134 return clang_getNullCursor();
4135
Ted Kremeneka60ed472010-11-16 08:15:36 +00004136 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004137 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
4138 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004139 return MakeCXCursor(E->decls_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004140
4141 if (OverloadedTemplateStorage *S
4142 = Storage.dyn_cast<OverloadedTemplateStorage*>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004143 return MakeCXCursor(S->begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004144
4145 Decl *D = Storage.get<Decl*>();
4146 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
4147 // FIXME: This is, unfortunately, linear time.
4148 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
4149 std::advance(Pos, index);
Ted Kremeneka60ed472010-11-16 08:15:36 +00004150 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004151 }
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004152 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00004153 return MakeCXCursor(Classes->getForwardInterfaceDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004154 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004155 return MakeCXCursor(Protocols->protocol_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004156
4157 return clang_getNullCursor();
4158}
4159
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00004160void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00004161 const char **startBuf,
4162 const char **endBuf,
4163 unsigned *startLine,
4164 unsigned *startColumn,
4165 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00004166 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00004167 assert(getCursorDecl(C) && "CXCursor has null decl");
4168 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00004169 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
4170 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004171
Steve Naroff4ade6d62009-09-23 17:52:52 +00004172 SourceManager &SM = FD->getASTContext().getSourceManager();
4173 *startBuf = SM.getCharacterData(Body->getLBracLoc());
4174 *endBuf = SM.getCharacterData(Body->getRBracLoc());
4175 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
4176 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
4177 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
4178 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
4179}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004180
Douglas Gregor430d7a12011-07-25 17:48:11 +00004181
4182CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
4183 unsigned PieceIndex) {
4184 RefNamePieces Pieces;
4185
4186 switch (C.kind) {
4187 case CXCursor_MemberRefExpr:
4188 if (MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
4189 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
4190 E->getQualifierLoc().getSourceRange());
4191 break;
4192
4193 case CXCursor_DeclRefExpr:
4194 if (DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C)))
4195 Pieces = buildPieces(NameFlags, false, E->getNameInfo(),
4196 E->getQualifierLoc().getSourceRange(),
4197 E->getExplicitTemplateArgsOpt());
4198 break;
4199
4200 case CXCursor_CallExpr:
4201 if (CXXOperatorCallExpr *OCE =
4202 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
4203 Expr *Callee = OCE->getCallee();
4204 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
4205 Callee = ICE->getSubExpr();
4206
4207 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
4208 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
4209 DRE->getQualifierLoc().getSourceRange());
4210 }
4211 break;
4212
4213 default:
4214 break;
4215 }
4216
4217 if (Pieces.empty()) {
4218 if (PieceIndex == 0)
4219 return clang_getCursorExtent(C);
4220 } else if (PieceIndex < Pieces.size()) {
4221 SourceRange R = Pieces[PieceIndex];
4222 if (R.isValid())
4223 return cxloc::translateSourceRange(getCursorContext(C), R);
4224 }
4225
4226 return clang_getNullRange();
4227}
4228
Douglas Gregor0a812cf2010-02-18 23:07:20 +00004229void clang_enableStackTraces(void) {
4230 llvm::sys::PrintStackTraceOnErrorSignal();
4231}
4232
Daniel Dunbar995aaf92010-11-04 01:26:29 +00004233void clang_executeOnThread(void (*fn)(void*), void *user_data,
4234 unsigned stack_size) {
4235 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
4236}
4237
Ted Kremenekfb480492010-01-13 21:46:36 +00004238} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00004239
Ted Kremenekfb480492010-01-13 21:46:36 +00004240//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004241// Token-based Operations.
4242//===----------------------------------------------------------------------===//
4243
4244/* CXToken layout:
4245 * int_data[0]: a CXTokenKind
4246 * int_data[1]: starting token location
4247 * int_data[2]: token length
4248 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004249 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004250 * otherwise unused.
4251 */
4252extern "C" {
4253
4254CXTokenKind clang_getTokenKind(CXToken CXTok) {
4255 return static_cast<CXTokenKind>(CXTok.int_data[0]);
4256}
4257
4258CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
4259 switch (clang_getTokenKind(CXTok)) {
4260 case CXToken_Identifier:
4261 case CXToken_Keyword:
4262 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004263 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
4264 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004265
4266 case CXToken_Literal: {
4267 // We have stashed the starting pointer in the ptr_data field. Use it.
4268 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Chris Lattner5f9e2722011-07-23 10:55:15 +00004269 return createCXString(StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004270 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004271
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004272 case CXToken_Punctuation:
4273 case CXToken_Comment:
4274 break;
4275 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004276
4277 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004278 // deconstructing the source location.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004279 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004280 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004281 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004282
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004283 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
4284 std::pair<FileID, unsigned> LocInfo
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004285 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00004286 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004287 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004288 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
4289 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00004290 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004291
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004292 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004293}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004294
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004295CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004296 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004297 if (!CXXUnit)
4298 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004299
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004300 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
4301 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4302}
4303
4304CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004305 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor5352ac02010-01-28 00:27:43 +00004306 if (!CXXUnit)
4307 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004308
4309 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004310 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4311}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004312
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004313static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
4314 SmallVectorImpl<CXToken> &CXTokens) {
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004315 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4316 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004317 = SourceMgr.getDecomposedLoc(Range.getBegin());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004318 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004319 = SourceMgr.getDecomposedLoc(Range.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004320
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004321 // Cannot tokenize across files.
4322 if (BeginLocInfo.first != EndLocInfo.first)
4323 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004324
4325 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004326 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004327 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004328 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00004329 if (Invalid)
4330 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00004331
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004332 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4333 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004334 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004335 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004336
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004337 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004338 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004339 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00004340 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004341 do {
4342 // Lex the next token
4343 Lex.LexFromRawLexer(Tok);
4344 if (Tok.is(tok::eof))
4345 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004346
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004347 // Initialize the CXToken.
4348 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004349
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004350 // - Common fields
4351 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
4352 CXTok.int_data[2] = Tok.getLength();
4353 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004354
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004355 // - Kind-specific fields
4356 if (Tok.isLiteral()) {
4357 CXTok.int_data[0] = CXToken_Literal;
4358 CXTok.ptr_data = (void *)Tok.getLiteralData();
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004359 } else if (Tok.is(tok::raw_identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00004360 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004361 IdentifierInfo *II
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004362 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004363
David Chisnall096428b2010-10-13 21:44:48 +00004364 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004365 CXTok.int_data[0] = CXToken_Keyword;
4366 }
4367 else {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004368 CXTok.int_data[0] = Tok.is(tok::identifier)
4369 ? CXToken_Identifier
4370 : CXToken_Keyword;
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004371 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004372 CXTok.ptr_data = II;
4373 } else if (Tok.is(tok::comment)) {
4374 CXTok.int_data[0] = CXToken_Comment;
4375 CXTok.ptr_data = 0;
4376 } else {
4377 CXTok.int_data[0] = CXToken_Punctuation;
4378 CXTok.ptr_data = 0;
4379 }
4380 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00004381 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004382 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004383}
4384
4385void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
4386 CXToken **Tokens, unsigned *NumTokens) {
4387 if (Tokens)
4388 *Tokens = 0;
4389 if (NumTokens)
4390 *NumTokens = 0;
4391
4392 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4393 if (!CXXUnit || !Tokens || !NumTokens)
4394 return;
4395
4396 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4397
4398 SourceRange R = cxloc::translateCXSourceRange(Range);
4399 if (R.isInvalid())
4400 return;
4401
4402 SmallVector<CXToken, 32> CXTokens;
4403 getTokens(CXXUnit, R, CXTokens);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004404
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004405 if (CXTokens.empty())
4406 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004407
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004408 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
4409 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
4410 *NumTokens = CXTokens.size();
4411}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004412
Ted Kremenek6db61092010-05-05 00:55:15 +00004413void clang_disposeTokens(CXTranslationUnit TU,
4414 CXToken *Tokens, unsigned NumTokens) {
4415 free(Tokens);
4416}
4417
4418} // end: extern "C"
4419
4420//===----------------------------------------------------------------------===//
4421// Token annotation APIs.
4422//===----------------------------------------------------------------------===//
4423
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004424typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004425static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4426 CXCursor parent,
4427 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00004428namespace {
4429class AnnotateTokensWorker {
4430 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004431 CXToken *Tokens;
4432 CXCursor *Cursors;
4433 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004434 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00004435 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004436 CursorVisitor AnnotateVis;
4437 SourceManager &SrcMgr;
Douglas Gregorf5251602011-03-08 17:10:18 +00004438 bool HasContextSensitiveKeywords;
4439
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004440 bool MoreTokens() const { return TokIdx < NumTokens; }
4441 unsigned NextToken() const { return TokIdx; }
4442 void AdvanceToken() { ++TokIdx; }
4443 SourceLocation GetTokenLoc(unsigned tokI) {
4444 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4445 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004446 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004447 return Tokens[tokI].int_data[3] != 0;
4448 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004449 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004450 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[3]);
4451 }
4452
4453 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004454 void annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
4455 SourceRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004456
Ted Kremenek6db61092010-05-05 00:55:15 +00004457public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00004458 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004459 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004460 CXTranslationUnit tu, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00004461 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00004462 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004463 AnnotateVis(tu,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00004464 AnnotateTokensVisitor, this,
4465 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00004466 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00004467 RegionOfInterest),
Douglas Gregorf5251602011-03-08 17:10:18 +00004468 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()),
4469 HasContextSensitiveKeywords(false) { }
Ted Kremenek11949cb2010-05-05 00:55:17 +00004470
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004471 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00004472 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004473 void AnnotateTokens(CXCursor parent);
Ted Kremenekab979612010-11-11 08:05:23 +00004474 void AnnotateTokens() {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004475 AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getTU()));
Ted Kremenekab979612010-11-11 08:05:23 +00004476 }
Douglas Gregorf5251602011-03-08 17:10:18 +00004477
4478 /// \brief Determine whether the annotator saw any cursors that have
4479 /// context-sensitive keywords.
4480 bool hasContextSensitiveKeywords() const {
4481 return HasContextSensitiveKeywords;
4482 }
Ted Kremenek6db61092010-05-05 00:55:15 +00004483};
4484}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004485
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004486void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
4487 // Walk the AST within the region of interest, annotating tokens
4488 // along the way.
4489 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00004490
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004491 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4492 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004493 if (Pos != Annotated.end() &&
4494 (clang_isInvalid(Cursors[I].kind) ||
4495 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004496 Cursors[I] = Pos->second;
4497 }
4498
4499 // Finish up annotating any tokens left.
4500 if (!MoreTokens())
4501 return;
4502
4503 const CXCursor &C = clang_getNullCursor();
4504 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
4505 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4506 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004507 }
4508}
4509
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004510/// \brief It annotates and advances tokens with a cursor until the comparison
4511//// between the cursor location and the source range is the same as
4512/// \arg compResult.
4513///
4514/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
4515/// Pass RangeOverlap to annotate tokens inside a range.
4516void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
4517 RangeComparisonResult compResult,
4518 SourceRange range) {
4519 while (MoreTokens()) {
4520 const unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004521 if (isFunctionMacroToken(I))
4522 return annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004523
4524 SourceLocation TokLoc = GetTokenLoc(I);
4525 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4526 Cursors[I] = updateC;
4527 AdvanceToken();
4528 continue;
4529 }
4530 break;
4531 }
4532}
4533
4534/// \brief Special annotation handling for macro argument tokens.
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004535void AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
4536 CXCursor updateC,
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004537 RangeComparisonResult compResult,
4538 SourceRange range) {
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004539 assert(MoreTokens());
4540 assert(isFunctionMacroToken(NextToken()) &&
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004541 "Should be called only for macro arg tokens");
4542
4543 // This works differently than annotateAndAdvanceTokens; because expanded
4544 // macro arguments can have arbitrary translation-unit source order, we do not
4545 // advance the token index one by one until a token fails the range test.
4546 // We only advance once past all of the macro arg tokens if all of them
4547 // pass the range test. If one of them fails we keep the token index pointing
4548 // at the start of the macro arg tokens so that the failing token will be
4549 // annotated by a subsequent annotation try.
4550
4551 bool atLeastOneCompFail = false;
4552
4553 unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004554 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
4555 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004556 if (TokLoc.isFileID())
4557 continue; // not macro arg token, it's parens or comma.
4558 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4559 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
4560 Cursors[I] = updateC;
4561 } else
4562 atLeastOneCompFail = true;
4563 }
4564
4565 if (!atLeastOneCompFail)
4566 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
4567}
4568
Ted Kremenek6db61092010-05-05 00:55:15 +00004569enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004570AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004571 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004572 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004573 if (cursorRange.isInvalid())
4574 return CXChildVisit_Recurse;
Douglas Gregorf5251602011-03-08 17:10:18 +00004575
4576 if (!HasContextSensitiveKeywords) {
4577 // Objective-C properties can have context-sensitive keywords.
4578 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
4579 if (ObjCPropertyDecl *Property
4580 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
4581 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
4582 }
4583 // Objective-C methods can have context-sensitive keywords.
4584 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
4585 cursor.kind == CXCursor_ObjCClassMethodDecl) {
4586 if (ObjCMethodDecl *Method
4587 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
4588 if (Method->getObjCDeclQualifier())
4589 HasContextSensitiveKeywords = true;
4590 else {
4591 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
4592 PEnd = Method->param_end();
4593 P != PEnd; ++P) {
4594 if ((*P)->getObjCDeclQualifier()) {
4595 HasContextSensitiveKeywords = true;
4596 break;
4597 }
4598 }
4599 }
4600 }
4601 }
4602 // C++ methods can have context-sensitive keywords.
4603 else if (cursor.kind == CXCursor_CXXMethod) {
4604 if (CXXMethodDecl *Method
4605 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
4606 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
4607 HasContextSensitiveKeywords = true;
4608 }
4609 }
4610 // C++ classes can have context-sensitive keywords.
4611 else if (cursor.kind == CXCursor_StructDecl ||
4612 cursor.kind == CXCursor_ClassDecl ||
4613 cursor.kind == CXCursor_ClassTemplate ||
4614 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
4615 if (Decl *D = getCursorDecl(cursor))
4616 if (D->hasAttr<FinalAttr>())
4617 HasContextSensitiveKeywords = true;
4618 }
4619 }
4620
Douglas Gregor4419b672010-10-21 06:10:04 +00004621 if (clang_isPreprocessing(cursor.kind)) {
Chandler Carruthcea731a2011-07-14 16:07:57 +00004622 // For macro expansions, just note where the beginning of the macro
4623 // expansion occurs.
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004624 if (cursor.kind == CXCursor_MacroExpansion) {
Douglas Gregor4419b672010-10-21 06:10:04 +00004625 Annotated[Loc.int_data] = cursor;
4626 return CXChildVisit_Recurse;
4627 }
4628
Douglas Gregor4419b672010-10-21 06:10:04 +00004629 // Items in the preprocessing record are kept separate from items in
4630 // declarations, so we keep a separate token index.
4631 unsigned SavedTokIdx = TokIdx;
4632 TokIdx = PreprocessingTokIdx;
4633
4634 // Skip tokens up until we catch up to the beginning of the preprocessing
4635 // entry.
4636 while (MoreTokens()) {
4637 const unsigned I = NextToken();
4638 SourceLocation TokLoc = GetTokenLoc(I);
4639 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4640 case RangeBefore:
4641 AdvanceToken();
4642 continue;
4643 case RangeAfter:
4644 case RangeOverlap:
4645 break;
4646 }
4647 break;
4648 }
4649
4650 // Look at all of the tokens within this range.
4651 while (MoreTokens()) {
4652 const unsigned I = NextToken();
4653 SourceLocation TokLoc = GetTokenLoc(I);
4654 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4655 case RangeBefore:
David Blaikieb219cfc2011-09-23 05:06:16 +00004656 llvm_unreachable("Infeasible");
Douglas Gregor4419b672010-10-21 06:10:04 +00004657 case RangeAfter:
4658 break;
4659 case RangeOverlap:
4660 Cursors[I] = cursor;
4661 AdvanceToken();
4662 continue;
4663 }
4664 break;
4665 }
4666
4667 // Save the preprocessing token index; restore the non-preprocessing
4668 // token index.
4669 PreprocessingTokIdx = TokIdx;
4670 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004671 return CXChildVisit_Recurse;
4672 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004673
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004674 if (cursorRange.isInvalid())
4675 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004676
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004677 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4678
Ted Kremeneka333c662010-05-12 05:29:33 +00004679 // Adjust the annotated range based specific declarations.
4680 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4681 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004682 Decl *D = cxcursor::getCursorDecl(cursor);
Douglas Gregor2494dd02011-03-01 01:34:45 +00004683
4684 SourceLocation StartLoc;
Ted Kremenek23173d72010-05-18 21:09:07 +00004685 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00004686 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
4687 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
4688 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
4689 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
4690 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
Ted Kremeneka333c662010-05-12 05:29:33 +00004691 }
Douglas Gregor2494dd02011-03-01 01:34:45 +00004692
4693 if (StartLoc.isValid() && L.isValid() &&
4694 SrcMgr.isBeforeInTranslationUnit(StartLoc, L))
4695 cursorRange.setBegin(StartLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004696 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004697
Ted Kremenek3f404602010-08-14 01:14:06 +00004698 // If the location of the cursor occurs within a macro instantiation, record
4699 // the spelling location of the cursor in our annotation map. We can then
4700 // paper over the token labelings during a post-processing step to try and
4701 // get cursor mappings for tokens that are the *arguments* of a macro
4702 // instantiation.
4703 if (L.isMacroID()) {
4704 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4705 // Only invalidate the old annotation if it isn't part of a preprocessing
4706 // directive. Here we assume that the default construction of CXCursor
4707 // results in CXCursor.kind being an initialized value (i.e., 0). If
4708 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004709
Ted Kremenek3f404602010-08-14 01:14:06 +00004710 CXCursor &oldC = Annotated[rawEncoding];
4711 if (!clang_isPreprocessing(oldC.kind))
4712 oldC = cursor;
4713 }
4714
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004715 const enum CXCursorKind K = clang_getCursorKind(parent);
4716 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004717 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4718 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004719
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004720 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004721
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00004722 // Avoid having the cursor of an expression "overwrite" the annotation of the
4723 // variable declaration that it belongs to.
4724 // This can happen for C++ constructor expressions whose range generally
4725 // include the variable declaration, e.g.:
4726 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
4727 if (clang_isExpression(cursorK)) {
4728 Expr *E = getCursorExpr(cursor);
Argyrios Kyrtzidis8ccac3d2011-06-29 22:20:07 +00004729 if (Decl *D = getCursorParentDecl(cursor)) {
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00004730 const unsigned I = NextToken();
4731 if (E->getLocStart().isValid() && D->getLocation().isValid() &&
4732 E->getLocStart() == D->getLocation() &&
4733 E->getLocStart() == GetTokenLoc(I)) {
4734 Cursors[I] = updateC;
4735 AdvanceToken();
4736 }
4737 }
4738 }
4739
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004740 // Visit children to get their cursor information.
4741 const unsigned BeforeChildren = NextToken();
4742 VisitChildren(cursor);
4743 const unsigned AfterChildren = NextToken();
4744
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004745 // Scan the tokens that are at the end of the cursor, but are not captured
4746 // but the child cursors.
4747 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
Ted Kremenek6db61092010-05-05 00:55:15 +00004748
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004749 // Scan the tokens that are at the beginning of the cursor, but are not
4750 // capture by the child cursors.
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004751 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4752 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4753 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004754
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004755 Cursors[I] = cursor;
4756 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004757
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004758 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004759}
4760
Ted Kremenek6db61092010-05-05 00:55:15 +00004761static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4762 CXCursor parent,
4763 CXClientData client_data) {
4764 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4765}
4766
Ted Kremenek6628a612011-03-18 22:51:30 +00004767namespace {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004768
4769/// \brief Uses the macro expansions in the preprocessing record to find
4770/// and mark tokens that are macro arguments. This info is used by the
4771/// AnnotateTokensWorker.
4772class MarkMacroArgTokensVisitor {
4773 SourceManager &SM;
4774 CXToken *Tokens;
4775 unsigned NumTokens;
4776 unsigned CurIdx;
4777
4778public:
4779 MarkMacroArgTokensVisitor(SourceManager &SM,
4780 CXToken *tokens, unsigned numTokens)
4781 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
4782
4783 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
4784 if (cursor.kind != CXCursor_MacroExpansion)
4785 return CXChildVisit_Continue;
4786
4787 SourceRange macroRange = getCursorMacroExpansion(cursor)->getSourceRange();
4788 if (macroRange.getBegin() == macroRange.getEnd())
4789 return CXChildVisit_Continue; // it's not a function macro.
4790
4791 for (; CurIdx < NumTokens; ++CurIdx) {
4792 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
4793 macroRange.getBegin()))
4794 break;
4795 }
4796
4797 if (CurIdx == NumTokens)
4798 return CXChildVisit_Break;
4799
4800 for (; CurIdx < NumTokens; ++CurIdx) {
4801 SourceLocation tokLoc = getTokenLoc(CurIdx);
4802 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
4803 break;
4804
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004805 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004806 }
4807
4808 if (CurIdx == NumTokens)
4809 return CXChildVisit_Break;
4810
4811 return CXChildVisit_Continue;
4812 }
4813
4814private:
4815 SourceLocation getTokenLoc(unsigned tokI) {
4816 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4817 }
4818
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004819 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004820 // The third field is reserved and currently not used. Use it here
4821 // to mark macro arg expanded tokens with their expanded locations.
4822 Tokens[tokI].int_data[3] = loc.getRawEncoding();
4823 }
4824};
4825
4826} // end anonymous namespace
4827
4828static CXChildVisitResult
4829MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
4830 CXClientData client_data) {
4831 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
4832 parent);
4833}
4834
4835namespace {
Ted Kremenek6628a612011-03-18 22:51:30 +00004836 struct clang_annotateTokens_Data {
4837 CXTranslationUnit TU;
4838 ASTUnit *CXXUnit;
4839 CXToken *Tokens;
4840 unsigned NumTokens;
4841 CXCursor *Cursors;
4842 };
4843}
4844
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004845static void annotatePreprocessorTokens(CXTranslationUnit TU,
4846 SourceRange RegionOfInterest,
4847 AnnotateTokensData &Annotated) {
4848 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4849
4850 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4851 std::pair<FileID, unsigned> BeginLocInfo
4852 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4853 std::pair<FileID, unsigned> EndLocInfo
4854 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
4855
4856 if (BeginLocInfo.first != EndLocInfo.first)
4857 return;
4858
4859 StringRef Buffer;
4860 bool Invalid = false;
4861 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
4862 if (Buffer.empty() || Invalid)
4863 return;
4864
4865 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4866 CXXUnit->getASTContext().getLangOptions(),
4867 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
4868 Buffer.end());
4869 Lex.SetCommentRetentionState(true);
4870
4871 // Lex tokens in raw mode until we hit the end of the range, to avoid
4872 // entering #includes or expanding macros.
4873 while (true) {
4874 Token Tok;
4875 Lex.LexFromRawLexer(Tok);
4876
4877 reprocess:
4878 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4879 // We have found a preprocessing directive. Gobble it up so that we
4880 // don't see it while preprocessing these tokens later, but keep track
4881 // of all of the token locations inside this preprocessing directive so
4882 // that we can annotate them appropriately.
4883 //
4884 // FIXME: Some simple tests here could identify macro definitions and
4885 // #undefs, to provide specific cursor kinds for those.
4886 SmallVector<SourceLocation, 32> Locations;
4887 do {
4888 Locations.push_back(Tok.getLocation());
4889 Lex.LexFromRawLexer(Tok);
4890 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
4891
4892 using namespace cxcursor;
4893 CXCursor Cursor
4894 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4895 Locations.back()),
4896 TU);
4897 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4898 Annotated[Locations[I].getRawEncoding()] = Cursor;
4899 }
4900
4901 if (Tok.isAtStartOfLine())
4902 goto reprocess;
4903
4904 continue;
4905 }
4906
4907 if (Tok.is(tok::eof))
4908 break;
4909 }
4910}
4911
Ted Kremenekab979612010-11-11 08:05:23 +00004912// This gets run a separate thread to avoid stack blowout.
Ted Kremenek6628a612011-03-18 22:51:30 +00004913static void clang_annotateTokensImpl(void *UserData) {
4914 CXTranslationUnit TU = ((clang_annotateTokens_Data*)UserData)->TU;
4915 ASTUnit *CXXUnit = ((clang_annotateTokens_Data*)UserData)->CXXUnit;
4916 CXToken *Tokens = ((clang_annotateTokens_Data*)UserData)->Tokens;
4917 const unsigned NumTokens = ((clang_annotateTokens_Data*)UserData)->NumTokens;
4918 CXCursor *Cursors = ((clang_annotateTokens_Data*)UserData)->Cursors;
4919
4920 // Determine the region of interest, which contains all of the tokens.
4921 SourceRange RegionOfInterest;
4922 RegionOfInterest.setBegin(
4923 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
4924 RegionOfInterest.setEnd(
4925 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
4926 Tokens[NumTokens-1])));
4927
4928 // A mapping from the source locations found when re-lexing or traversing the
4929 // region of interest to the corresponding cursors.
4930 AnnotateTokensData Annotated;
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004931
Ted Kremenek6628a612011-03-18 22:51:30 +00004932 // Relex the tokens within the source range to look for preprocessing
4933 // directives.
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004934 annotatePreprocessorTokens(TU, RegionOfInterest, Annotated);
Ted Kremenek6628a612011-03-18 22:51:30 +00004935
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004936 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
4937 // Search and mark tokens that are macro argument expansions.
4938 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
4939 Tokens, NumTokens);
4940 CursorVisitor MacroArgMarker(TU,
4941 MarkMacroArgTokensVisitorDelegate, &Visitor,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00004942 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00004943 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00004944 RegionOfInterest);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004945 MacroArgMarker.visitPreprocessedEntitiesInRegion();
4946 }
4947
Ted Kremenek6628a612011-03-18 22:51:30 +00004948 // Annotate all of the source locations in the region of interest that map to
4949 // a specific cursor.
4950 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
4951 TU, RegionOfInterest);
4952
4953 // FIXME: We use a ridiculous stack size here because the data-recursion
4954 // algorithm uses a large stack frame than the non-data recursive version,
4955 // and AnnotationTokensWorker currently transforms the data-recursion
4956 // algorithm back into a traditional recursion by explicitly calling
4957 // VisitChildren(). We will need to remove this explicit recursive call.
4958 W.AnnotateTokens();
4959
4960 // If we ran into any entities that involve context-sensitive keywords,
4961 // take another pass through the tokens to mark them as such.
4962 if (W.hasContextSensitiveKeywords()) {
4963 for (unsigned I = 0; I != NumTokens; ++I) {
4964 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
4965 continue;
4966
4967 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
4968 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
4969 if (ObjCPropertyDecl *Property
4970 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
4971 if (Property->getPropertyAttributesAsWritten() != 0 &&
4972 llvm::StringSwitch<bool>(II->getName())
4973 .Case("readonly", true)
4974 .Case("assign", true)
John McCallf85e1932011-06-15 23:02:42 +00004975 .Case("unsafe_unretained", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00004976 .Case("readwrite", true)
4977 .Case("retain", true)
4978 .Case("copy", true)
4979 .Case("nonatomic", true)
4980 .Case("atomic", true)
4981 .Case("getter", true)
4982 .Case("setter", true)
John McCallf85e1932011-06-15 23:02:42 +00004983 .Case("strong", true)
4984 .Case("weak", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00004985 .Default(false))
4986 Tokens[I].int_data[0] = CXToken_Keyword;
4987 }
4988 continue;
4989 }
4990
4991 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
4992 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
4993 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
4994 if (llvm::StringSwitch<bool>(II->getName())
4995 .Case("in", true)
4996 .Case("out", true)
4997 .Case("inout", true)
4998 .Case("oneway", true)
4999 .Case("bycopy", true)
5000 .Case("byref", true)
5001 .Default(false))
5002 Tokens[I].int_data[0] = CXToken_Keyword;
5003 continue;
5004 }
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00005005
5006 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
5007 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
5008 Tokens[I].int_data[0] = CXToken_Keyword;
Ted Kremenek6628a612011-03-18 22:51:30 +00005009 continue;
5010 }
5011 }
5012 }
Ted Kremenekab979612010-11-11 08:05:23 +00005013}
5014
Ted Kremenek6db61092010-05-05 00:55:15 +00005015extern "C" {
5016
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005017void clang_annotateTokens(CXTranslationUnit TU,
5018 CXToken *Tokens, unsigned NumTokens,
5019 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005020
5021 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005022 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005023
Douglas Gregor4419b672010-10-21 06:10:04 +00005024 // Any token we don't specifically annotate will have a NULL cursor.
5025 CXCursor C = clang_getNullCursor();
5026 for (unsigned I = 0; I != NumTokens; ++I)
5027 Cursors[I] = C;
5028
Ted Kremeneka60ed472010-11-16 08:15:36 +00005029 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor4419b672010-10-21 06:10:04 +00005030 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005031 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005032
Douglas Gregorbdf60622010-03-05 21:16:25 +00005033 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenek6628a612011-03-18 22:51:30 +00005034
5035 clang_annotateTokens_Data data = { TU, CXXUnit, Tokens, NumTokens, Cursors };
Ted Kremenekab979612010-11-11 08:05:23 +00005036 llvm::CrashRecoveryContext CRC;
Ted Kremenek6628a612011-03-18 22:51:30 +00005037 if (!RunSafely(CRC, clang_annotateTokensImpl, &data,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005038 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00005039 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
5040 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005041}
Ted Kremenek6628a612011-03-18 22:51:30 +00005042
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005043} // end: extern "C"
5044
5045//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00005046// Operations for querying linkage of a cursor.
5047//===----------------------------------------------------------------------===//
5048
5049extern "C" {
5050CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00005051 if (!clang_isDeclaration(cursor.kind))
5052 return CXLinkage_Invalid;
5053
Ted Kremenek16b42592010-03-03 06:36:57 +00005054 Decl *D = cxcursor::getCursorDecl(cursor);
5055 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
5056 switch (ND->getLinkage()) {
5057 case NoLinkage: return CXLinkage_NoLinkage;
5058 case InternalLinkage: return CXLinkage_Internal;
5059 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
5060 case ExternalLinkage: return CXLinkage_External;
5061 };
5062
5063 return CXLinkage_Invalid;
5064}
5065} // end: extern "C"
5066
5067//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005068// Operations for querying language of a cursor.
5069//===----------------------------------------------------------------------===//
5070
5071static CXLanguageKind getDeclLanguage(const Decl *D) {
5072 switch (D->getKind()) {
5073 default:
5074 break;
5075 case Decl::ImplicitParam:
5076 case Decl::ObjCAtDefsField:
5077 case Decl::ObjCCategory:
5078 case Decl::ObjCCategoryImpl:
5079 case Decl::ObjCClass:
5080 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005081 case Decl::ObjCForwardProtocol:
5082 case Decl::ObjCImplementation:
5083 case Decl::ObjCInterface:
5084 case Decl::ObjCIvar:
5085 case Decl::ObjCMethod:
5086 case Decl::ObjCProperty:
5087 case Decl::ObjCPropertyImpl:
5088 case Decl::ObjCProtocol:
5089 return CXLanguage_ObjC;
5090 case Decl::CXXConstructor:
5091 case Decl::CXXConversion:
5092 case Decl::CXXDestructor:
5093 case Decl::CXXMethod:
5094 case Decl::CXXRecord:
5095 case Decl::ClassTemplate:
5096 case Decl::ClassTemplatePartialSpecialization:
5097 case Decl::ClassTemplateSpecialization:
5098 case Decl::Friend:
5099 case Decl::FriendTemplate:
5100 case Decl::FunctionTemplate:
5101 case Decl::LinkageSpec:
5102 case Decl::Namespace:
5103 case Decl::NamespaceAlias:
5104 case Decl::NonTypeTemplateParm:
5105 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005106 case Decl::TemplateTemplateParm:
5107 case Decl::TemplateTypeParm:
5108 case Decl::UnresolvedUsingTypename:
5109 case Decl::UnresolvedUsingValue:
5110 case Decl::Using:
5111 case Decl::UsingDirective:
5112 case Decl::UsingShadow:
5113 return CXLanguage_CPlusPlus;
5114 }
5115
5116 return CXLanguage_C;
5117}
5118
5119extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00005120
5121enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
5122 if (clang_isDeclaration(cursor.kind))
5123 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005124 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Douglas Gregor58ddb602010-08-23 23:00:57 +00005125 return CXAvailability_Available;
5126
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005127 switch (D->getAvailability()) {
5128 case AR_Available:
5129 case AR_NotYetIntroduced:
5130 return CXAvailability_Available;
5131
5132 case AR_Deprecated:
Douglas Gregor58ddb602010-08-23 23:00:57 +00005133 return CXAvailability_Deprecated;
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005134
5135 case AR_Unavailable:
5136 return CXAvailability_NotAvailable;
5137 }
Douglas Gregor58ddb602010-08-23 23:00:57 +00005138 }
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005139
Douglas Gregor58ddb602010-08-23 23:00:57 +00005140 return CXAvailability_Available;
5141}
5142
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005143CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
5144 if (clang_isDeclaration(cursor.kind))
5145 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
5146
5147 return CXLanguage_Invalid;
5148}
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005149
5150 /// \brief If the given cursor is the "templated" declaration
5151 /// descibing a class or function template, return the class or
5152 /// function template.
5153static Decl *maybeGetTemplateCursor(Decl *D) {
5154 if (!D)
5155 return 0;
5156
5157 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
5158 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
5159 return FunTmpl;
5160
5161 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
5162 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
5163 return ClassTmpl;
5164
5165 return D;
5166}
5167
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005168CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
5169 if (clang_isDeclaration(cursor.kind)) {
5170 if (Decl *D = getCursorDecl(cursor)) {
5171 DeclContext *DC = D->getDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005172 if (!DC)
5173 return clang_getNullCursor();
5174
5175 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5176 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005177 }
5178 }
5179
5180 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
5181 if (Decl *D = getCursorDecl(cursor))
Ted Kremeneka60ed472010-11-16 08:15:36 +00005182 return MakeCXCursor(D, getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005183 }
5184
5185 return clang_getNullCursor();
5186}
5187
5188CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
5189 if (clang_isDeclaration(cursor.kind)) {
5190 if (Decl *D = getCursorDecl(cursor)) {
5191 DeclContext *DC = D->getLexicalDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005192 if (!DC)
5193 return clang_getNullCursor();
5194
5195 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5196 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005197 }
5198 }
5199
5200 // FIXME: Note that we can't easily compute the lexical context of a
5201 // statement or expression, so we return nothing.
5202 return clang_getNullCursor();
5203}
5204
Douglas Gregor9f592342010-10-01 20:25:15 +00005205void clang_getOverriddenCursors(CXCursor cursor,
5206 CXCursor **overridden,
5207 unsigned *num_overridden) {
5208 if (overridden)
5209 *overridden = 0;
5210 if (num_overridden)
5211 *num_overridden = 0;
5212 if (!overridden || !num_overridden)
5213 return;
5214
Argyrios Kyrtzidisb11be042011-10-06 07:00:46 +00005215 SmallVector<CXCursor, 8> Overridden;
5216 cxcursor::getOverriddenCursors(cursor, Overridden);
Douglas Gregor9f592342010-10-01 20:25:15 +00005217
Argyrios Kyrtzidisb11be042011-10-06 07:00:46 +00005218 *num_overridden = Overridden.size();
5219 *overridden = new CXCursor [Overridden.size()];
5220 std::copy(Overridden.begin(), Overridden.end(), *overridden);
Douglas Gregor9f592342010-10-01 20:25:15 +00005221}
5222
5223void clang_disposeOverriddenCursors(CXCursor *overridden) {
5224 delete [] overridden;
5225}
5226
Douglas Gregorecdcb882010-10-20 22:00:55 +00005227CXFile clang_getIncludedFile(CXCursor cursor) {
5228 if (cursor.kind != CXCursor_InclusionDirective)
5229 return 0;
5230
5231 InclusionDirective *ID = getCursorInclusionDirective(cursor);
5232 return (void *)ID->getFile();
5233}
5234
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005235} // end: extern "C"
5236
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005237
5238//===----------------------------------------------------------------------===//
5239// C++ AST instrospection.
5240//===----------------------------------------------------------------------===//
5241
5242extern "C" {
5243unsigned clang_CXXMethod_isStatic(CXCursor C) {
5244 if (!clang_isDeclaration(C.kind))
5245 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00005246
5247 CXXMethodDecl *Method = 0;
5248 Decl *D = cxcursor::getCursorDecl(C);
5249 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5250 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5251 else
5252 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5253 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00005254}
Ted Kremenekb12903e2010-05-18 22:32:15 +00005255
Douglas Gregor211924b2011-05-12 15:17:24 +00005256unsigned clang_CXXMethod_isVirtual(CXCursor C) {
5257 if (!clang_isDeclaration(C.kind))
5258 return 0;
5259
5260 CXXMethodDecl *Method = 0;
5261 Decl *D = cxcursor::getCursorDecl(C);
5262 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5263 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5264 else
5265 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5266 return (Method && Method->isVirtual()) ? 1 : 0;
5267}
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005268} // end: extern "C"
5269
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005270//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00005271// Attribute introspection.
5272//===----------------------------------------------------------------------===//
5273
5274extern "C" {
5275CXType clang_getIBOutletCollectionType(CXCursor C) {
5276 if (C.kind != CXCursor_IBOutletCollectionAttr)
Ted Kremeneka60ed472010-11-16 08:15:36 +00005277 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005278
5279 IBOutletCollectionAttr *A =
5280 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
5281
Argyrios Kyrtzidis18aa2ff2011-09-13 18:49:52 +00005282 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005283}
5284} // end: extern "C"
5285
5286//===----------------------------------------------------------------------===//
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005287// Inspecting memory usage.
5288//===----------------------------------------------------------------------===//
5289
Ted Kremenekf7870022011-04-20 16:41:07 +00005290typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005291
Ted Kremenekf7870022011-04-20 16:41:07 +00005292static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
5293 enum CXTUResourceUsageKind k,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005294 unsigned long amount) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005295 CXTUResourceUsageEntry entry = { k, amount };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005296 entries.push_back(entry);
5297}
5298
5299extern "C" {
5300
Ted Kremenekf7870022011-04-20 16:41:07 +00005301const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005302 const char *str = "";
5303 switch (kind) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005304 case CXTUResourceUsage_AST:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005305 str = "ASTContext: expressions, declarations, and types";
5306 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005307 case CXTUResourceUsage_Identifiers:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005308 str = "ASTContext: identifiers";
5309 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005310 case CXTUResourceUsage_Selectors:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005311 str = "ASTContext: selectors";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005312 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005313 case CXTUResourceUsage_GlobalCompletionResults:
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005314 str = "Code completion: cached global results";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005315 break;
Ted Kremenek457aaf02011-04-28 04:10:31 +00005316 case CXTUResourceUsage_SourceManagerContentCache:
5317 str = "SourceManager: content cache allocator";
5318 break;
Ted Kremenekba29bd22011-04-28 04:53:38 +00005319 case CXTUResourceUsage_AST_SideTables:
5320 str = "ASTContext: side tables";
5321 break;
Ted Kremenekf61b8312011-04-28 20:36:42 +00005322 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
5323 str = "SourceManager: malloc'ed memory buffers";
5324 break;
5325 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
5326 str = "SourceManager: mmap'ed memory buffers";
5327 break;
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005328 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
5329 str = "ExternalASTSource: malloc'ed memory buffers";
5330 break;
5331 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
5332 str = "ExternalASTSource: mmap'ed memory buffers";
5333 break;
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005334 case CXTUResourceUsage_Preprocessor:
5335 str = "Preprocessor: malloc'ed memory";
5336 break;
5337 case CXTUResourceUsage_PreprocessingRecord:
5338 str = "Preprocessor: PreprocessingRecord";
5339 break;
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005340 case CXTUResourceUsage_SourceManager_DataStructures:
5341 str = "SourceManager: data structures and tables";
5342 break;
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005343 case CXTUResourceUsage_Preprocessor_HeaderSearch:
5344 str = "Preprocessor: header search tables";
5345 break;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005346 }
5347 return str;
5348}
5349
Ted Kremenekf7870022011-04-20 16:41:07 +00005350CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005351 if (!TU) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005352 CXTUResourceUsage usage = { (void*) 0, 0, 0 };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005353 return usage;
5354 }
5355
5356 ASTUnit *astUnit = static_cast<ASTUnit*>(TU->TUData);
5357 llvm::OwningPtr<MemUsageEntries> entries(new MemUsageEntries());
5358 ASTContext &astContext = astUnit->getASTContext();
5359
5360 // How much memory is used by AST nodes and types?
Ted Kremenekf7870022011-04-20 16:41:07 +00005361 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005362 (unsigned long) astContext.getASTAllocatedMemory());
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005363
5364 // How much memory is used by identifiers?
Ted Kremenekf7870022011-04-20 16:41:07 +00005365 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005366 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
5367
5368 // How much memory is used for selectors?
Ted Kremenekf7870022011-04-20 16:41:07 +00005369 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005370 (unsigned long) astContext.Selectors.getTotalMemory());
5371
Ted Kremenekba29bd22011-04-28 04:53:38 +00005372 // How much memory is used by ASTContext's side tables?
5373 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
5374 (unsigned long) astContext.getSideTableAllocatedMemory());
5375
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005376 // How much memory is used for caching global code completion results?
5377 unsigned long completionBytes = 0;
5378 if (GlobalCodeCompletionAllocator *completionAllocator =
5379 astUnit->getCachedCompletionAllocator().getPtr()) {
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005380 completionBytes = completionAllocator->getTotalMemory();
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005381 }
Ted Kremenek457aaf02011-04-28 04:10:31 +00005382 createCXTUResourceUsageEntry(*entries,
5383 CXTUResourceUsage_GlobalCompletionResults,
5384 completionBytes);
5385
5386 // How much memory is being used by SourceManager's content cache?
5387 createCXTUResourceUsageEntry(*entries,
5388 CXTUResourceUsage_SourceManagerContentCache,
5389 (unsigned long) astContext.getSourceManager().getContentCacheSize());
Ted Kremenekf61b8312011-04-28 20:36:42 +00005390
5391 // How much memory is being used by the MemoryBuffer's in SourceManager?
5392 const SourceManager::MemoryBufferSizes &srcBufs =
5393 astUnit->getSourceManager().getMemoryBufferSizes();
5394
5395 createCXTUResourceUsageEntry(*entries,
5396 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
5397 (unsigned long) srcBufs.malloc_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005398 createCXTUResourceUsageEntry(*entries,
Ted Kremenekf61b8312011-04-28 20:36:42 +00005399 CXTUResourceUsage_SourceManager_Membuffer_MMap,
5400 (unsigned long) srcBufs.mmap_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005401 createCXTUResourceUsageEntry(*entries,
5402 CXTUResourceUsage_SourceManager_DataStructures,
5403 (unsigned long) astContext.getSourceManager()
5404 .getDataStructureSizes());
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005405
5406 // How much memory is being used by the ExternalASTSource?
5407 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
5408 const ExternalASTSource::MemoryBufferSizes &sizes =
5409 esrc->getMemoryBufferSizes();
5410
5411 createCXTUResourceUsageEntry(*entries,
5412 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
5413 (unsigned long) sizes.malloc_bytes);
5414 createCXTUResourceUsageEntry(*entries,
5415 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
5416 (unsigned long) sizes.mmap_bytes);
5417 }
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005418
5419 // How much memory is being used by the Preprocessor?
5420 Preprocessor &pp = astUnit->getPreprocessor();
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005421 createCXTUResourceUsageEntry(*entries,
5422 CXTUResourceUsage_Preprocessor,
Argyrios Kyrtzidisc5c5e922011-06-29 22:20:04 +00005423 pp.getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005424
5425 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
5426 createCXTUResourceUsageEntry(*entries,
5427 CXTUResourceUsage_PreprocessingRecord,
5428 pRec->getTotalMemory());
5429 }
5430
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005431 createCXTUResourceUsageEntry(*entries,
5432 CXTUResourceUsage_Preprocessor_HeaderSearch,
5433 pp.getHeaderSearchInfo().getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005434
Ted Kremenekf7870022011-04-20 16:41:07 +00005435 CXTUResourceUsage usage = { (void*) entries.get(),
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005436 (unsigned) entries->size(),
5437 entries->size() ? &(*entries)[0] : 0 };
5438 entries.take();
5439 return usage;
5440}
5441
Ted Kremenekf7870022011-04-20 16:41:07 +00005442void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005443 if (usage.data)
5444 delete (MemUsageEntries*) usage.data;
5445}
5446
5447} // end extern "C"
5448
Douglas Gregor6df78732011-05-05 20:27:22 +00005449void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
5450 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
5451 for (unsigned I = 0; I != Usage.numEntries; ++I)
5452 fprintf(stderr, " %s: %lu\n",
5453 clang_getTUResourceUsageName(Usage.entries[I].kind),
5454 Usage.entries[I].amount);
5455
5456 clang_disposeCXTUResourceUsage(Usage);
5457}
5458
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005459//===----------------------------------------------------------------------===//
Ted Kremenek04bb7162010-01-22 22:44:15 +00005460// Misc. utility functions.
5461//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00005462
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00005463/// Default to using an 8 MB stack size on "safety" threads.
5464static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005465
5466namespace clang {
5467
5468bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005469 void (*Fn)(void*), void *UserData,
5470 unsigned Size) {
5471 if (!Size)
5472 Size = GetSafetyThreadStackSize();
5473 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005474 return CRC.RunSafelyOnThread(Fn, UserData, Size);
5475 return CRC.RunSafely(Fn, UserData);
5476}
5477
5478unsigned GetSafetyThreadStackSize() {
5479 return SafetyStackThreadSize;
5480}
5481
5482void SetSafetyThreadStackSize(unsigned Value) {
5483 SafetyStackThreadSize = Value;
5484}
5485
5486}
5487
Ted Kremenek04bb7162010-01-22 22:44:15 +00005488extern "C" {
5489
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00005490CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00005491 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00005492}
5493
5494} // end: extern "C"
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005495