blob: 8f4b0471f88dc8a97892b65fa784ef3f8a7e8f9f [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();
Ted Kremenek15322172011-11-10 08:43:12 +000061 D->Diagnostics = 0;
Ted Kremeneka60ed472010-11-16 08:15:36 +000062 return D;
63}
64
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +000065cxtu::CXTUOwner::~CXTUOwner() {
66 if (TU)
67 clang_disposeTranslationUnit(TU);
68}
69
Ted Kremenekf0e23e82010-02-17 00:41:40 +000070/// \brief Compare two source ranges to determine their relative position in
Douglas Gregor33e9abd2010-01-22 19:49:59 +000071/// the translation unit.
Ted Kremenekf0e23e82010-02-17 00:41:40 +000072static RangeComparisonResult RangeCompare(SourceManager &SM,
73 SourceRange R1,
Douglas Gregor33e9abd2010-01-22 19:49:59 +000074 SourceRange R2) {
75 assert(R1.isValid() && "First range is invalid?");
76 assert(R2.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000077 if (R1.getEnd() != R2.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000078 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000079 return RangeBefore;
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000080 if (R2.getEnd() != R1.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000081 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000082 return RangeAfter;
83 return RangeOverlap;
84}
85
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000086/// \brief Determine if a source location falls within, before, or after a
87/// a given source range.
88static RangeComparisonResult LocationCompare(SourceManager &SM,
89 SourceLocation L, SourceRange R) {
90 assert(R.isValid() && "First range is invalid?");
91 assert(L.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000092 if (L == R.getBegin() || L == R.getEnd())
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000093 return RangeOverlap;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000094 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
95 return RangeBefore;
96 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
97 return RangeAfter;
98 return RangeOverlap;
99}
100
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000101/// \brief Translate a Clang source range into a CIndex source range.
102///
103/// Clang internally represents ranges where the end location points to the
104/// start of the token at the end. However, for external clients it is more
105/// useful to have a CXSourceRange be a proper half-open interval. This routine
106/// does the appropriate translation.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000107CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000108 const LangOptions &LangOpts,
Chris Lattner0a76aae2010-06-18 22:45:06 +0000109 const CharSourceRange &R) {
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000110 // We want the last character in this location, so we will adjust the
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000111 // location accordingly.
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000112 SourceLocation EndLoc = R.getEnd();
Douglas Gregora9b06d42010-11-09 06:24:54 +0000113 if (EndLoc.isValid() && EndLoc.isMacroID())
Chandler Carruthedc3dcc2011-07-25 16:56:02 +0000114 EndLoc = SM.getExpansionRange(EndLoc).second;
Chris Lattner0a76aae2010-06-18 22:45:06 +0000115 if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) {
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000116 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000117 EndLoc = EndLoc.getLocWithOffset(Length);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000118 }
119
120 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
121 R.getBegin().getRawEncoding(),
122 EndLoc.getRawEncoding() };
123 return Result;
124}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000125
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000126//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000127// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000128//===----------------------------------------------------------------------===//
129
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000130static SourceRange getRawCursorExtent(CXCursor C);
Douglas Gregor66537982010-11-17 17:14:07 +0000131static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
132
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000133
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000134RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000135 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000136}
137
Douglas Gregorb1373d02010-01-20 20:59:29 +0000138/// \brief Visit the given cursor and, if requested by the visitor,
139/// its children.
140///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000141/// \param Cursor the cursor to visit.
142///
143/// \param CheckRegionOfInterest if true, then the caller already checked that
144/// this cursor is within the region of interest.
145///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000146/// \returns true if the visitation should be aborted, false if it
147/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000148bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000149 if (clang_isInvalid(Cursor.kind))
150 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000151
Douglas Gregorb1373d02010-01-20 20:59:29 +0000152 if (clang_isDeclaration(Cursor.kind)) {
153 Decl *D = getCursorDecl(Cursor);
154 assert(D && "Invalid declaration cursor");
Argyrios Kyrtzidis65ab9072011-09-26 19:05:37 +0000155 // Ignore implicit declarations, unless it's an objc method because
156 // currently we should report implicit methods for properties when indexing.
157 if (D->isImplicit() && !isa<ObjCMethodDecl>(D))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000158 return false;
159 }
160
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000161 // If we have a range of interest, and this cursor doesn't intersect with it,
162 // we're done.
163 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000164 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000165 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000166 return false;
167 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000168
Douglas Gregorb1373d02010-01-20 20:59:29 +0000169 switch (Visitor(Cursor, Parent, ClientData)) {
170 case CXChildVisit_Break:
171 return true;
172
173 case CXChildVisit_Continue:
174 return false;
175
176 case CXChildVisit_Recurse:
177 return VisitChildren(Cursor);
178 }
179
Douglas Gregorfd643772010-01-25 16:45:46 +0000180 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000181}
182
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000183static bool visitPreprocessedEntitiesInRange(SourceRange R,
184 PreprocessingRecord &PPRec,
185 CursorVisitor &Visitor) {
186 SourceManager &SM = Visitor.getASTUnit()->getSourceManager();
187 FileID FID;
188
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +0000189 if (!Visitor.shouldVisitIncludedEntities()) {
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000190 // If the begin/end of the range lie in the same FileID, do the optimization
191 // where we skip preprocessed entities that do not come from the same FileID.
192 FID = SM.getFileID(R.getBegin());
193 if (FID != SM.getFileID(R.getEnd()))
194 FID = FileID();
195 }
196
197 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
198 Entities = PPRec.getPreprocessedEntitiesInRange(R);
199 return Visitor.visitPreprocessedEntities(Entities.first, Entities.second,
200 PPRec, FID);
201}
202
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000203void CursorVisitor::visitFileRegion() {
204 if (RegionOfInterest.isInvalid())
205 return;
206
207 ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData);
208 SourceManager &SM = Unit->getSourceManager();
209
210 std::pair<FileID, unsigned>
211 Begin = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getBegin())),
212 End = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getEnd()));
213
214 if (End.first != Begin.first) {
215 // If the end does not reside in the same file, try to recover by
216 // picking the end of the file of begin location.
217 End.first = Begin.first;
218 End.second = SM.getFileIDSize(Begin.first);
219 }
220
221 assert(Begin.first == End.first);
222 if (Begin.second > End.second)
223 return;
224
225 FileID File = Begin.first;
226 unsigned Offset = Begin.second;
227 unsigned Length = End.second - Begin.second;
228
229 if (!VisitPreprocessorLast &&
230 Unit->getPreprocessor().getPreprocessingRecord())
231 visitPreprocessedEntitiesInRegion();
232
233 visitDeclsFromFileRegion(File, Offset, Length);
234
235 if (VisitPreprocessorLast &&
236 Unit->getPreprocessor().getPreprocessingRecord())
237 visitPreprocessedEntitiesInRegion();
238}
239
240void CursorVisitor::visitDeclsFromFileRegion(FileID File,
241 unsigned Offset, unsigned Length) {
242 ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData);
243 SourceManager &SM = Unit->getSourceManager();
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000244 SourceRange Range = RegionOfInterest;
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000245
246 SmallVector<Decl *, 16> Decls;
247 Unit->findFileRegionDecls(File, Offset, Length, Decls);
248
249 // If we didn't find any file level decls for the file, try looking at the
250 // file that it was included from.
251 while (Decls.empty()) {
252 bool Invalid = false;
253 const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid);
254 if (Invalid)
255 return;
256
257 SourceLocation Outer;
258 if (SLEntry.isFile())
259 Outer = SLEntry.getFile().getIncludeLoc();
260 else
261 Outer = SLEntry.getExpansion().getExpansionLocStart();
262 if (Outer.isInvalid())
263 return;
264
265 llvm::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer);
266 Length = 0;
267 Unit->findFileRegionDecls(File, Offset, Length, Decls);
268 }
269
270 assert(!Decls.empty());
271
272 bool VisitedAtLeastOnce = false;
273 SmallVector<Decl *, 16>::iterator DIt = Decls.begin();
274 for (SmallVector<Decl *, 16>::iterator DE = Decls.end(); DIt != DE; ++DIt) {
275 Decl *D = *DIt;
276
277 // We handle forward decls via ObjCClassDecl.
278 if (ObjCInterfaceDecl *InterD = dyn_cast<ObjCInterfaceDecl>(D)) {
279 if (InterD->isForwardDecl())
280 continue;
281 // An interface that started as a forward decl may have changed location
282 // because its @interface was parsed.
283 if (InterD->isInitiallyForwardDecl() &&
284 !SM.isInFileID(SM.getFileLoc(InterD->getLocation()), File))
285 continue;
286 }
287
288 RangeComparisonResult CompRes = RangeCompare(SM, D->getSourceRange(),Range);
289 if (CompRes == RangeBefore)
290 continue;
291 if (CompRes == RangeAfter)
292 break;
293
294 assert(CompRes == RangeOverlap);
295 VisitedAtLeastOnce = true;
Argyrios Kyrtzidisba986172011-11-03 19:02:28 +0000296 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000297 break;
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000298 }
299
300 if (VisitedAtLeastOnce)
301 return;
302
303 // No Decls overlapped with the range. Move up the lexical context until there
304 // is a context that contains the range or we reach the translation unit
305 // level.
306 DeclContext *DC = DIt == Decls.begin() ? (*DIt)->getLexicalDeclContext()
307 : (*(DIt-1))->getLexicalDeclContext();
308
309 while (DC && !DC->isTranslationUnit()) {
310 Decl *D = cast<Decl>(DC);
311 SourceRange CurDeclRange = D->getSourceRange();
312 if (CurDeclRange.isInvalid())
313 break;
314
315 if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) {
Argyrios Kyrtzidisba986172011-11-03 19:02:28 +0000316 Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true);
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000317 break;
318 }
319
320 DC = D->getLexicalDeclContext();
321 }
322}
323
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000324bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
Douglas Gregor788f5a12010-03-20 00:41:21 +0000325 PreprocessingRecord &PPRec
Ted Kremeneka60ed472010-11-16 08:15:36 +0000326 = *AU->getPreprocessor().getPreprocessingRecord();
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000327 SourceManager &SM = AU->getSourceManager();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000328
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000329 if (RegionOfInterest.isValid()) {
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +0000330 SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000331 SourceLocation B = MappedRange.getBegin();
332 SourceLocation E = MappedRange.getEnd();
333
334 if (AU->isInPreambleFileID(B)) {
335 if (SM.isLoadedSourceLocation(E))
336 return visitPreprocessedEntitiesInRange(SourceRange(B, E),
337 PPRec, *this);
338
339 // Beginning of range lies in the preamble but it also extends beyond
340 // it into the main file. Split the range into 2 parts, one covering
341 // the preamble and another covering the main file. This allows subsequent
342 // calls to visitPreprocessedEntitiesInRange to accept a source range that
343 // lies in the same FileID, allowing it to skip preprocessed entities that
344 // do not come from the same FileID.
345 bool breaked =
346 visitPreprocessedEntitiesInRange(
347 SourceRange(B, AU->getEndOfPreambleFileID()),
348 PPRec, *this);
349 if (breaked) return true;
350 return visitPreprocessedEntitiesInRange(
351 SourceRange(AU->getStartOfMainFileID(), E),
352 PPRec, *this);
353 }
354
355 return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this);
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000356 }
357
Douglas Gregor788f5a12010-03-20 00:41:21 +0000358 bool OnlyLocalDecls
Douglas Gregor32038bb2010-12-21 19:07:48 +0000359 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
360
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000361 if (OnlyLocalDecls)
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000362 return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(),
363 PPRec);
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000364
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000365 return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec);
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000366}
367
368template<typename InputIterator>
369bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000370 InputIterator Last,
371 PreprocessingRecord &PPRec,
372 FileID FID) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000373 for (; First != Last; ++First) {
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000374 if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID))
375 continue;
376
377 PreprocessedEntity *PPE = *First;
378 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000379 if (Visit(MakeMacroExpansionCursor(ME, TU)))
380 return true;
381
382 continue;
383 }
384
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000385 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(PPE)) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000386 if (Visit(MakeMacroDefinitionCursor(MD, TU)))
387 return true;
388
389 continue;
390 }
391
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000392 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000393 if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
394 return true;
395
396 continue;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000397 }
398 }
399
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000400 return false;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000401}
402
Douglas Gregorb1373d02010-01-20 20:59:29 +0000403/// \brief Visit the children of the given cursor.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000404///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000405/// \returns true if the visitation should be aborted, false if it
406/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000407bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregorc314aa42011-03-02 19:17:03 +0000408 if (clang_isReference(Cursor.kind) &&
409 Cursor.kind != CXCursor_CXXBaseSpecifier) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000410 // By definition, references have no children.
411 return false;
412 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000413
414 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000415 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000416 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000417
Douglas Gregorb1373d02010-01-20 20:59:29 +0000418 if (clang_isDeclaration(Cursor.kind)) {
419 Decl *D = getCursorDecl(Cursor);
Douglas Gregor06d9b1a2011-04-14 21:41:34 +0000420 if (!D)
421 return false;
422
Ted Kremenek539311e2010-02-18 18:47:01 +0000423 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000424 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000425
Douglas Gregor06d9b1a2011-04-14 21:41:34 +0000426 if (clang_isStatement(Cursor.kind)) {
427 if (Stmt *S = getCursorStmt(Cursor))
428 return Visit(S);
429
430 return false;
431 }
432
433 if (clang_isExpression(Cursor.kind)) {
434 if (Expr *E = getCursorExpr(Cursor))
435 return Visit(E);
436
437 return false;
438 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000439
Douglas Gregorb1373d02010-01-20 20:59:29 +0000440 if (clang_isTranslationUnit(Cursor.kind)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000441 CXTranslationUnit tu = getCursorTU(Cursor);
442 ASTUnit *CXXUnit = static_cast<ASTUnit*>(tu->TUData);
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000443
444 int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
445 for (unsigned I = 0; I != 2; ++I) {
446 if (VisitOrder[I]) {
447 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
448 RegionOfInterest.isInvalid()) {
449 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
450 TLEnd = CXXUnit->top_level_end();
451 TL != TLEnd; ++TL) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000452 if (Visit(MakeCXCursor(*TL, tu, RegionOfInterest), true))
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000453 return true;
454 }
455 } else if (VisitDeclContext(
456 CXXUnit->getASTContext().getTranslationUnitDecl()))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000457 return true;
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000458 continue;
Douglas Gregor7b691f332010-01-20 21:13:59 +0000459 }
Bob Wilson3178cb62010-03-19 03:57:57 +0000460
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000461 // Walk the preprocessing record.
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000462 if (CXXUnit->getPreprocessor().getPreprocessingRecord())
463 visitPreprocessedEntitiesInRegion();
Douglas Gregor0396f462010-03-19 05:22:59 +0000464 }
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000465
Douglas Gregor7b691f332010-01-20 21:13:59 +0000466 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000467 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000468
Douglas Gregorc314aa42011-03-02 19:17:03 +0000469 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
470 if (CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
471 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
472 return Visit(BaseTSInfo->getTypeLoc());
473 }
474 }
475 }
Argyrios Kyrtzidis221d5a52011-09-13 18:49:56 +0000476
477 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
478 IBOutletCollectionAttr *A =
479 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
480 if (const ObjCInterfaceType *InterT = A->getInterface()->getAs<ObjCInterfaceType>())
481 return Visit(cxcursor::MakeCursorObjCClassRef(InterT->getInterface(),
482 A->getInterfaceLoc(), TU));
483 }
484
Douglas Gregorb1373d02010-01-20 20:59:29 +0000485 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000486 return false;
487}
488
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000489bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
Douglas Gregor13c8ccb2011-04-22 23:49:24 +0000490 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
491 if (Visit(TSInfo->getTypeLoc()))
492 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000493
Ted Kremenek664cffd2010-07-22 11:30:19 +0000494 if (Stmt *Body = B->getBody())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000495 return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest));
Ted Kremenek664cffd2010-07-22 11:30:19 +0000496
497 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000498}
499
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000500llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
501 if (RegionOfInterest.isValid()) {
Douglas Gregor66537982010-11-17 17:14:07 +0000502 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000503 if (Range.isInvalid())
504 return llvm::Optional<bool>();
Douglas Gregor66537982010-11-17 17:14:07 +0000505
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000506 switch (CompareRegionOfInterest(Range)) {
507 case RangeBefore:
508 // This declaration comes before the region of interest; skip it.
509 return llvm::Optional<bool>();
510
511 case RangeAfter:
512 // This declaration comes after the region of interest; we're done.
513 return false;
514
515 case RangeOverlap:
516 // This declaration overlaps the region of interest; visit it.
517 break;
518 }
519 }
520 return true;
521}
522
523bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
524 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
525
526 // FIXME: Eventually remove. This part of a hack to support proper
527 // iteration over all Decls contained lexically within an ObjC container.
528 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
529 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
530
531 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000532 Decl *D = *I;
533 if (D->getLexicalDeclContext() != DC)
534 continue;
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000535 CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000536 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
537 if (!V.hasValue())
538 continue;
539 if (!V.getValue())
540 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000541 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000542 return true;
543 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000544 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000545}
546
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000547bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
548 llvm_unreachable("Translation units are visited directly by Visit()");
549 return false;
550}
551
Richard Smith162e1c12011-04-15 14:24:37 +0000552bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
553 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
554 return Visit(TSInfo->getTypeLoc());
555
556 return false;
557}
558
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000559bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
560 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
561 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000562
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000563 return false;
564}
565
566bool CursorVisitor::VisitTagDecl(TagDecl *D) {
567 return VisitDeclContext(D);
568}
569
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000570bool CursorVisitor::VisitClassTemplateSpecializationDecl(
571 ClassTemplateSpecializationDecl *D) {
572 bool ShouldVisitBody = false;
573 switch (D->getSpecializationKind()) {
574 case TSK_Undeclared:
575 case TSK_ImplicitInstantiation:
576 // Nothing to visit
577 return false;
578
579 case TSK_ExplicitInstantiationDeclaration:
580 case TSK_ExplicitInstantiationDefinition:
581 break;
582
583 case TSK_ExplicitSpecialization:
584 ShouldVisitBody = true;
585 break;
586 }
587
588 // Visit the template arguments used in the specialization.
589 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
590 TypeLoc TL = SpecType->getTypeLoc();
591 if (TemplateSpecializationTypeLoc *TSTLoc
592 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
593 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
594 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
595 return true;
596 }
597 }
598
599 if (ShouldVisitBody && VisitCXXRecordDecl(D))
600 return true;
601
602 return false;
603}
604
Douglas Gregor74dbe642010-08-31 19:31:58 +0000605bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
606 ClassTemplatePartialSpecializationDecl *D) {
607 // FIXME: Visit the "outer" template parameter lists on the TagDecl
608 // before visiting these template parameters.
609 if (VisitTemplateParameters(D->getTemplateParameters()))
610 return true;
611
612 // Visit the partial specialization arguments.
613 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
614 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
615 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
616 return true;
617
618 return VisitCXXRecordDecl(D);
619}
620
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000621bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000622 // Visit the default argument.
623 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
624 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
625 if (Visit(DefArg->getTypeLoc()))
626 return true;
627
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000628 return false;
629}
630
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000631bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
632 if (Expr *Init = D->getInitExpr())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000633 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000634 return false;
635}
636
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000637bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
638 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
639 if (Visit(TSInfo->getTypeLoc()))
640 return true;
641
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000642 // Visit the nested-name-specifier, if present.
643 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
644 if (VisitNestedNameSpecifierLoc(QualifierLoc))
645 return true;
646
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000647 return false;
648}
649
Douglas Gregora67e03f2010-09-09 21:42:20 +0000650/// \brief Compare two base or member initializers based on their source order.
Sean Huntcbb67482011-01-08 20:30:50 +0000651static int CompareCXXCtorInitializers(const void* Xp, const void *Yp) {
652 CXXCtorInitializer const * const *X
653 = static_cast<CXXCtorInitializer const * const *>(Xp);
654 CXXCtorInitializer const * const *Y
655 = static_cast<CXXCtorInitializer const * const *>(Yp);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000656
657 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
658 return -1;
659 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
660 return 1;
661 else
662 return 0;
663}
664
Douglas Gregorb1373d02010-01-20 20:59:29 +0000665bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000666 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
667 // Visit the function declaration's syntactic components in the order
668 // written. This requires a bit of work.
Abramo Bagnara723df242010-12-14 22:11:44 +0000669 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
Douglas Gregor01829d32010-08-31 14:41:23 +0000670 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
671
672 // If we have a function declared directly (without the use of a typedef),
673 // visit just the return type. Otherwise, just visit the function's type
674 // now.
675 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
676 (!FTL && Visit(TL)))
677 return true;
678
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000679 // Visit the nested-name-specifier, if present.
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000680 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
681 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000682 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000683
684 // Visit the declaration name.
685 if (VisitDeclarationNameInfo(ND->getNameInfo()))
686 return true;
687
688 // FIXME: Visit explicitly-specified template arguments!
689
690 // Visit the function parameters, if we have a function type.
691 if (FTL && VisitFunctionTypeLoc(*FTL, true))
692 return true;
693
694 // FIXME: Attributes?
695 }
696
Sean Hunt10620eb2011-05-06 20:44:56 +0000697 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
Douglas Gregora67e03f2010-09-09 21:42:20 +0000698 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
699 // Find the initializers that were written in the source.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000700 SmallVector<CXXCtorInitializer *, 4> WrittenInits;
Douglas Gregora67e03f2010-09-09 21:42:20 +0000701 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
702 IEnd = Constructor->init_end();
703 I != IEnd; ++I) {
704 if (!(*I)->isWritten())
705 continue;
706
707 WrittenInits.push_back(*I);
708 }
709
710 // Sort the initializers in source order
711 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
Sean Huntcbb67482011-01-08 20:30:50 +0000712 &CompareCXXCtorInitializers);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000713
714 // Visit the initializers in source order
715 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
Sean Huntcbb67482011-01-08 20:30:50 +0000716 CXXCtorInitializer *Init = WrittenInits[I];
Francois Pichet00eb3f92010-12-04 09:14:42 +0000717 if (Init->isAnyMemberInitializer()) {
718 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
Douglas Gregora67e03f2010-09-09 21:42:20 +0000719 Init->getMemberLocation(), TU)))
720 return true;
Douglas Gregor76852c22011-11-01 01:16:03 +0000721 } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) {
722 if (Visit(TInfo->getTypeLoc()))
Douglas Gregora67e03f2010-09-09 21:42:20 +0000723 return true;
724 }
725
726 // Visit the initializer value.
727 if (Expr *Initializer = Init->getInit())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000728 if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
Douglas Gregora67e03f2010-09-09 21:42:20 +0000729 return true;
730 }
731 }
732
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000733 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
Douglas Gregora67e03f2010-09-09 21:42:20 +0000734 return true;
735 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000736
Douglas Gregorb1373d02010-01-20 20:59:29 +0000737 return false;
738}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000739
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000740bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
741 if (VisitDeclaratorDecl(D))
742 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000743
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000744 if (Expr *BitWidth = D->getBitWidth())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000745 return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000746
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000747 return false;
748}
749
750bool CursorVisitor::VisitVarDecl(VarDecl *D) {
751 if (VisitDeclaratorDecl(D))
752 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000753
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000754 if (Expr *Init = D->getInit())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000755 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000756
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000757 return false;
758}
759
Douglas Gregor84b51d72010-09-01 20:16:53 +0000760bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
761 if (VisitDeclaratorDecl(D))
762 return true;
763
764 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
765 if (Expr *DefArg = D->getDefaultArgument())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000766 return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
Douglas Gregor84b51d72010-09-01 20:16:53 +0000767
768 return false;
769}
770
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000771bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
772 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
773 // before visiting these template parameters.
774 if (VisitTemplateParameters(D->getTemplateParameters()))
775 return true;
776
777 return VisitFunctionDecl(D->getTemplatedDecl());
778}
779
Douglas Gregor39d6f072010-08-31 19:02:00 +0000780bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
781 // FIXME: Visit the "outer" template parameter lists on the TagDecl
782 // before visiting these template parameters.
783 if (VisitTemplateParameters(D->getTemplateParameters()))
784 return true;
785
786 return VisitCXXRecordDecl(D->getTemplatedDecl());
787}
788
Douglas Gregor84b51d72010-09-01 20:16:53 +0000789bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
790 if (VisitTemplateParameters(D->getTemplateParameters()))
791 return true;
792
793 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
794 VisitTemplateArgumentLoc(D->getDefaultArgument()))
795 return true;
796
797 return false;
798}
799
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000800bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000801 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
802 if (Visit(TSInfo->getTypeLoc()))
803 return true;
804
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000805 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000806 PEnd = ND->param_end();
807 P != PEnd; ++P) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000808 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000809 return true;
810 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000811
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000812 if (ND->isThisDeclarationADefinition() &&
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000813 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000814 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000815
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000816 return false;
817}
818
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000819namespace {
820 struct ContainerDeclsSort {
821 SourceManager &SM;
822 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
823 bool operator()(Decl *A, Decl *B) {
824 SourceLocation L_A = A->getLocStart();
825 SourceLocation L_B = B->getLocStart();
826 assert(L_A.isValid() && L_B.isValid());
827 return SM.isBeforeInTranslationUnit(L_A, L_B);
828 }
829 };
830}
831
Douglas Gregora59e3902010-01-21 23:27:09 +0000832bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000833 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
834 // an @implementation can lexically contain Decls that are not properly
835 // nested in the AST. When we identify such cases, we need to retrofit
836 // this nesting here.
837 if (!DI_current)
838 return VisitDeclContext(D);
839
840 // Scan the Decls that immediately come after the container
841 // in the current DeclContext. If any fall within the
842 // container's lexical region, stash them into a vector
843 // for later processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000844 SmallVector<Decl *, 24> DeclsInContainer;
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000845 SourceLocation EndLoc = D->getSourceRange().getEnd();
Ted Kremeneka60ed472010-11-16 08:15:36 +0000846 SourceManager &SM = AU->getSourceManager();
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000847 if (EndLoc.isValid()) {
848 DeclContext::decl_iterator next = *DI_current;
849 while (++next != DE_current) {
850 Decl *D_next = *next;
851 if (!D_next)
852 break;
853 SourceLocation L = D_next->getLocStart();
854 if (!L.isValid())
855 break;
856 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
857 *DI_current = next;
858 DeclsInContainer.push_back(D_next);
859 continue;
860 }
861 break;
862 }
863 }
864
865 // The common case.
866 if (DeclsInContainer.empty())
867 return VisitDeclContext(D);
868
869 // Get all the Decls in the DeclContext, and sort them with the
870 // additional ones we've collected. Then visit them.
871 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
872 I!=E; ++I) {
873 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000874 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
875 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000876 continue;
877 DeclsInContainer.push_back(subDecl);
878 }
879
880 // Now sort the Decls so that they appear in lexical order.
881 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
882 ContainerDeclsSort(SM));
883
884 // Now visit the decls.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000885 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000886 E = DeclsInContainer.end(); I != E; ++I) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000887 CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000888 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
889 if (!V.hasValue())
890 continue;
891 if (!V.getValue())
892 return false;
893 if (Visit(Cursor, true))
894 return true;
895 }
896 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000897}
898
Douglas Gregorb1373d02010-01-20 20:59:29 +0000899bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000900 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
901 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000902 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000903
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000904 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
905 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
906 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000907 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000908 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000909
Douglas Gregora59e3902010-01-21 23:27:09 +0000910 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000911}
912
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000913bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
914 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
915 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
916 E = PID->protocol_end(); I != E; ++I, ++PL)
917 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
918 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000919
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000920 return VisitObjCContainerDecl(PID);
921}
922
Ted Kremenek23173d72010-05-18 21:09:07 +0000923bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000924 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000925 return true;
926
Ted Kremenek23173d72010-05-18 21:09:07 +0000927 // FIXME: This implements a workaround with @property declarations also being
928 // installed in the DeclContext for the @interface. Eventually this code
929 // should be removed.
930 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
931 if (!CDecl || !CDecl->IsClassExtension())
932 return false;
933
934 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
935 if (!ID)
936 return false;
937
938 IdentifierInfo *PropertyId = PD->getIdentifier();
939 ObjCPropertyDecl *prevDecl =
940 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
941
942 if (!prevDecl)
943 return false;
944
945 // Visit synthesized methods since they will be skipped when visiting
946 // the @interface.
947 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000948 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000949 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
Ted Kremenek23173d72010-05-18 21:09:07 +0000950 return true;
951
952 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000953 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000954 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
Ted Kremenek23173d72010-05-18 21:09:07 +0000955 return true;
956
957 return false;
958}
959
Douglas Gregorb1373d02010-01-20 20:59:29 +0000960bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000961 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000962 if (D->getSuperClass() &&
963 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000964 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000965 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000966 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000967
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000968 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
969 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
970 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000971 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000972 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000973
Douglas Gregora59e3902010-01-21 23:27:09 +0000974 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000975}
976
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000977bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
978 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000979}
980
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000981bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +0000982 // 'ID' could be null when dealing with invalid code.
983 if (ObjCInterfaceDecl *ID = D->getClassInterface())
984 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
985 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000986
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000987 return VisitObjCImplDecl(D);
988}
989
990bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
991#if 0
992 // Issue callbacks for super class.
993 // FIXME: No source location information!
994 if (D->getSuperClass() &&
995 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000996 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000997 TU)))
998 return true;
999#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001000
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001001 return VisitObjCImplDecl(D);
1002}
1003
1004bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1005 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1006 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1007 E = D->protocol_end();
1008 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001009 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001010 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001011
1012 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001013}
1014
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001015bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00001016 if (Visit(MakeCursorObjCClassRef(D->getForwardInterfaceDecl(),
1017 D->getForwardDecl()->getLocation(), TU)))
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001018 return true;
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001019 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001020}
1021
Douglas Gregora4ffd852010-11-17 01:03:52 +00001022bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1023 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1024 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1025
1026 return false;
1027}
1028
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001029bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1030 return VisitDeclContext(D);
1031}
1032
Douglas Gregor69319002010-08-31 23:48:11 +00001033bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001034 // Visit nested-name-specifier.
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00001035 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1036 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001037 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001038
1039 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1040 D->getTargetNameLoc(), TU));
1041}
1042
Douglas Gregor7e242562010-09-01 19:52:22 +00001043bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001044 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001045 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1046 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001047 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001048 }
Douglas Gregor7e242562010-09-01 19:52:22 +00001049
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001050 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1051 return true;
1052
Douglas Gregor7e242562010-09-01 19:52:22 +00001053 return VisitDeclarationNameInfo(D->getNameInfo());
1054}
1055
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001056bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001057 // Visit nested-name-specifier.
Douglas Gregordb992412011-02-25 16:33:46 +00001058 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1059 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001060 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001061
1062 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1063 D->getIdentLocation(), TU));
1064}
1065
Douglas Gregor7e242562010-09-01 19:52:22 +00001066bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001067 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001068 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1069 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001070 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001071 }
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001072
Douglas Gregor7e242562010-09-01 19:52:22 +00001073 return VisitDeclarationNameInfo(D->getNameInfo());
1074}
1075
1076bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1077 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001078 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001079 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1080 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001081 return true;
1082
Douglas Gregor7e242562010-09-01 19:52:22 +00001083 return false;
1084}
1085
Douglas Gregor01829d32010-08-31 14:41:23 +00001086bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1087 switch (Name.getName().getNameKind()) {
1088 case clang::DeclarationName::Identifier:
1089 case clang::DeclarationName::CXXLiteralOperatorName:
1090 case clang::DeclarationName::CXXOperatorName:
1091 case clang::DeclarationName::CXXUsingDirective:
1092 return false;
1093
1094 case clang::DeclarationName::CXXConstructorName:
1095 case clang::DeclarationName::CXXDestructorName:
1096 case clang::DeclarationName::CXXConversionFunctionName:
1097 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1098 return Visit(TSInfo->getTypeLoc());
1099 return false;
1100
1101 case clang::DeclarationName::ObjCZeroArgSelector:
1102 case clang::DeclarationName::ObjCOneArgSelector:
1103 case clang::DeclarationName::ObjCMultiArgSelector:
1104 // FIXME: Per-identifier location info?
1105 return false;
1106 }
1107
1108 return false;
1109}
1110
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001111bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1112 SourceRange Range) {
1113 // FIXME: This whole routine is a hack to work around the lack of proper
1114 // source information in nested-name-specifiers (PR5791). Since we do have
1115 // a beginning source location, we can visit the first component of the
1116 // nested-name-specifier, if it's a single-token component.
1117 if (!NNS)
1118 return false;
1119
1120 // Get the first component in the nested-name-specifier.
1121 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1122 NNS = Prefix;
1123
1124 switch (NNS->getKind()) {
1125 case NestedNameSpecifier::Namespace:
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001126 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1127 TU));
1128
Douglas Gregor14aba762011-02-24 02:36:08 +00001129 case NestedNameSpecifier::NamespaceAlias:
1130 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1131 Range.getBegin(), TU));
1132
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001133 case NestedNameSpecifier::TypeSpec: {
1134 // If the type has a form where we know that the beginning of the source
1135 // range matches up with a reference cursor. Visit the appropriate reference
1136 // cursor.
John McCallf4c73712011-01-19 06:33:43 +00001137 const Type *T = NNS->getAsType();
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001138 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1139 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1140 if (const TagType *Tag = dyn_cast<TagType>(T))
1141 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1142 if (const TemplateSpecializationType *TST
1143 = dyn_cast<TemplateSpecializationType>(T))
1144 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1145 break;
1146 }
1147
1148 case NestedNameSpecifier::TypeSpecWithTemplate:
1149 case NestedNameSpecifier::Global:
1150 case NestedNameSpecifier::Identifier:
1151 break;
1152 }
1153
1154 return false;
1155}
1156
Douglas Gregordc355712011-02-25 00:36:19 +00001157bool
1158CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001159 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
Douglas Gregordc355712011-02-25 00:36:19 +00001160 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1161 Qualifiers.push_back(Qualifier);
1162
1163 while (!Qualifiers.empty()) {
1164 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1165 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1166 switch (NNS->getKind()) {
1167 case NestedNameSpecifier::Namespace:
1168 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001169 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001170 TU)))
1171 return true;
1172
1173 break;
1174
1175 case NestedNameSpecifier::NamespaceAlias:
1176 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001177 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001178 TU)))
1179 return true;
1180
1181 break;
1182
1183 case NestedNameSpecifier::TypeSpec:
1184 case NestedNameSpecifier::TypeSpecWithTemplate:
1185 if (Visit(Q.getTypeLoc()))
1186 return true;
1187
1188 break;
1189
1190 case NestedNameSpecifier::Global:
1191 case NestedNameSpecifier::Identifier:
1192 break;
1193 }
1194 }
1195
1196 return false;
1197}
1198
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001199bool CursorVisitor::VisitTemplateParameters(
1200 const TemplateParameterList *Params) {
1201 if (!Params)
1202 return false;
1203
1204 for (TemplateParameterList::const_iterator P = Params->begin(),
1205 PEnd = Params->end();
1206 P != PEnd; ++P) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001207 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001208 return true;
1209 }
1210
1211 return false;
1212}
1213
Douglas Gregor0b36e612010-08-31 20:37:03 +00001214bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1215 switch (Name.getKind()) {
1216 case TemplateName::Template:
1217 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1218
1219 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001220 // Visit the overloaded template set.
1221 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1222 return true;
1223
Douglas Gregor0b36e612010-08-31 20:37:03 +00001224 return false;
1225
1226 case TemplateName::DependentTemplate:
1227 // FIXME: Visit nested-name-specifier.
1228 return false;
1229
1230 case TemplateName::QualifiedTemplate:
1231 // FIXME: Visit nested-name-specifier.
1232 return Visit(MakeCursorTemplateRef(
1233 Name.getAsQualifiedTemplateName()->getDecl(),
1234 Loc, TU));
John McCall14606042011-06-30 08:33:18 +00001235
1236 case TemplateName::SubstTemplateTemplateParm:
1237 return Visit(MakeCursorTemplateRef(
1238 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1239 Loc, TU));
Douglas Gregor1aee05d2011-01-15 06:45:20 +00001240
1241 case TemplateName::SubstTemplateTemplateParmPack:
1242 return Visit(MakeCursorTemplateRef(
1243 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1244 Loc, TU));
Douglas Gregor0b36e612010-08-31 20:37:03 +00001245 }
1246
1247 return false;
1248}
1249
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001250bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1251 switch (TAL.getArgument().getKind()) {
1252 case TemplateArgument::Null:
1253 case TemplateArgument::Integral:
Douglas Gregor87dd6972010-12-20 16:52:59 +00001254 case TemplateArgument::Pack:
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001255 return false;
1256
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001257 case TemplateArgument::Type:
1258 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1259 return Visit(TSInfo->getTypeLoc());
1260 return false;
1261
1262 case TemplateArgument::Declaration:
1263 if (Expr *E = TAL.getSourceDeclExpression())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001264 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001265 return false;
1266
1267 case TemplateArgument::Expression:
1268 if (Expr *E = TAL.getSourceExpression())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001269 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001270 return false;
1271
1272 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001273 case TemplateArgument::TemplateExpansion:
Douglas Gregorb6744ef2011-03-02 17:09:35 +00001274 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1275 return true;
1276
Douglas Gregora7fc9012011-01-05 18:58:31 +00001277 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
Douglas Gregor0b36e612010-08-31 20:37:03 +00001278 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001279 }
1280
1281 return false;
1282}
1283
Ted Kremeneka0536d82010-05-07 01:04:29 +00001284bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1285 return VisitDeclContext(D);
1286}
1287
Douglas Gregor01829d32010-08-31 14:41:23 +00001288bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1289 return Visit(TL.getUnqualifiedLoc());
1290}
1291
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001292bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00001293 ASTContext &Context = AU->getASTContext();
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001294
1295 // Some builtin types (such as Objective-C's "id", "sel", and
1296 // "Class") have associated declarations. Create cursors for those.
1297 QualType VisitType;
John McCalle0a22d02011-10-18 21:02:43 +00001298 switch (TL.getTypePtr()->getKind()) {
John McCall2dde35b2011-10-18 22:28:37 +00001299
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001300 case BuiltinType::Void:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001301 case BuiltinType::NullPtr:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001302 case BuiltinType::Dependent:
John McCall2dde35b2011-10-18 22:28:37 +00001303#define BUILTIN_TYPE(Id, SingletonId)
1304#define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1305#define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1306#define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
1307#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
1308#include "clang/AST/BuiltinTypes.def"
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001309 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001310
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001311 case BuiltinType::ObjCId:
1312 VisitType = Context.getObjCIdType();
1313 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001314
1315 case BuiltinType::ObjCClass:
1316 VisitType = Context.getObjCClassType();
1317 break;
1318
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001319 case BuiltinType::ObjCSel:
1320 VisitType = Context.getObjCSelType();
1321 break;
1322 }
1323
1324 if (!VisitType.isNull()) {
1325 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001326 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001327 TU));
1328 }
1329
1330 return false;
1331}
1332
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001333bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
Richard Smith162e1c12011-04-15 14:24:37 +00001334 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001335}
1336
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001337bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1338 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1339}
1340
1341bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
Argyrios Kyrtzidis6f155de2011-08-25 22:24:47 +00001342 if (TL.isDefinition())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001343 return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
Argyrios Kyrtzidis6f155de2011-08-25 22:24:47 +00001344
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001345 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1346}
1347
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001348bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Chandler Carruth960d13d2011-05-01 09:53:37 +00001349 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001350}
1351
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001352bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1353 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1354 return true;
1355
John McCallc12c5bb2010-05-15 11:32:37 +00001356 return false;
1357}
1358
1359bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1360 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1361 return true;
1362
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001363 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1364 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1365 TU)))
1366 return true;
1367 }
1368
1369 return false;
1370}
1371
1372bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001373 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001374}
1375
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001376bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1377 return Visit(TL.getInnerLoc());
1378}
1379
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001380bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1381 return Visit(TL.getPointeeLoc());
1382}
1383
1384bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1385 return Visit(TL.getPointeeLoc());
1386}
1387
1388bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1389 return Visit(TL.getPointeeLoc());
1390}
1391
1392bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001393 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001394}
1395
1396bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001397 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001398}
1399
Argyrios Kyrtzidis3422fbc2011-08-15 18:44:43 +00001400bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1401 return Visit(TL.getModifiedLoc());
1402}
1403
Douglas Gregor01829d32010-08-31 14:41:23 +00001404bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1405 bool SkipResultType) {
1406 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001407 return true;
1408
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001409 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001410 if (Decl *D = TL.getArg(I))
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001411 if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001412 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001413
1414 return false;
1415}
1416
1417bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1418 if (Visit(TL.getElementLoc()))
1419 return true;
1420
1421 if (Expr *Size = TL.getSizeExpr())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001422 return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001423
1424 return false;
1425}
1426
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001427bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1428 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001429 // Visit the template name.
1430 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1431 TL.getTemplateNameLoc()))
1432 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001433
1434 // Visit the template arguments.
1435 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1436 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1437 return true;
1438
1439 return false;
1440}
1441
Douglas Gregor2332c112010-01-21 20:48:56 +00001442bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1443 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1444}
1445
1446bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1447 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1448 return Visit(TSInfo->getTypeLoc());
1449
1450 return false;
1451}
1452
Sean Huntca63c202011-05-24 22:41:36 +00001453bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1454 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1455 return Visit(TSInfo->getTypeLoc());
1456
1457 return false;
1458}
1459
Douglas Gregor2494dd02011-03-01 01:34:45 +00001460bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
1461 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1462 return true;
1463
1464 return false;
1465}
1466
Douglas Gregor94fdffa2011-03-01 20:11:18 +00001467bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1468 DependentTemplateSpecializationTypeLoc TL) {
1469 // Visit the nested-name-specifier, if there is one.
1470 if (TL.getQualifierLoc() &&
1471 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1472 return true;
1473
1474 // Visit the template arguments.
1475 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1476 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1477 return true;
1478
1479 return false;
1480}
1481
Douglas Gregor9e876872011-03-01 18:12:44 +00001482bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1483 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1484 return true;
1485
1486 return Visit(TL.getNamedTypeLoc());
1487}
1488
Douglas Gregor7536dd52010-12-20 02:24:11 +00001489bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1490 return Visit(TL.getPatternLoc());
1491}
1492
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +00001493bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1494 if (Expr *E = TL.getUnderlyingExpr())
1495 return Visit(MakeCXCursor(E, StmtParent, TU));
1496
1497 return false;
1498}
1499
1500bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1501 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1502}
1503
Eli Friedmanb001de72011-10-06 23:00:33 +00001504bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1505 return Visit(TL.getValueLoc());
1506}
1507
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +00001508#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1509bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1510 return Visit##PARENT##Loc(TL); \
1511}
1512
1513DEFAULT_TYPELOC_IMPL(Complex, Type)
1514DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1515DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1516DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1517DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
1518DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1519DEFAULT_TYPELOC_IMPL(Vector, Type)
1520DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1521DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1522DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1523DEFAULT_TYPELOC_IMPL(Record, TagType)
1524DEFAULT_TYPELOC_IMPL(Enum, TagType)
1525DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1526DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1527DEFAULT_TYPELOC_IMPL(Auto, Type)
1528
Ted Kremenek3064ef92010-08-27 21:34:58 +00001529bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001530 // Visit the nested-name-specifier, if present.
1531 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1532 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1533 return true;
1534
John McCall5e1cdac2011-10-07 06:10:15 +00001535 if (D->isCompleteDefinition()) {
Ted Kremenek3064ef92010-08-27 21:34:58 +00001536 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1537 E = D->bases_end(); I != E; ++I) {
1538 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1539 return true;
1540 }
1541 }
1542
1543 return VisitTagDecl(D);
1544}
1545
Ted Kremenek09dfa372010-02-18 05:46:33 +00001546bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001547 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1548 i != e; ++i)
1549 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001550 return true;
1551
1552 return false;
1553}
1554
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001555//===----------------------------------------------------------------------===//
1556// Data-recursive visitor methods.
1557//===----------------------------------------------------------------------===//
1558
Ted Kremenek28a71942010-11-13 00:36:47 +00001559namespace {
Ted Kremenek035dc412010-11-13 00:36:50 +00001560#define DEF_JOB(NAME, DATA, KIND)\
1561class NAME : public VisitorJob {\
1562public:\
1563 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1564 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Ted Kremenekf64d8032010-11-18 00:02:32 +00001565 DATA *get() const { return static_cast<DATA*>(data[0]); }\
Ted Kremenek035dc412010-11-13 00:36:50 +00001566};
1567
1568DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1569DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001570DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001571DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001572DEF_JOB(ExplicitTemplateArgsVisit, ASTTemplateArgumentListInfo,
Ted Kremenek60608ec2010-11-17 00:50:47 +00001573 ExplicitTemplateArgsVisitKind)
Douglas Gregor94d96292011-01-19 20:34:17 +00001574DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001575#undef DEF_JOB
1576
1577class DeclVisit : public VisitorJob {
1578public:
1579 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1580 VisitorJob(parent, VisitorJob::DeclVisitKind,
1581 d, isFirst ? (void*) 1 : (void*) 0) {}
1582 static bool classof(const VisitorJob *VJ) {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001583 return VJ->getKind() == DeclVisitKind;
Ted Kremenek035dc412010-11-13 00:36:50 +00001584 }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001585 Decl *get() const { return static_cast<Decl*>(data[0]); }
1586 bool isFirst() const { return data[1] ? true : false; }
Ted Kremenek035dc412010-11-13 00:36:50 +00001587};
Ted Kremenek035dc412010-11-13 00:36:50 +00001588class TypeLocVisit : public VisitorJob {
1589public:
1590 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1591 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1592 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1593
1594 static bool classof(const VisitorJob *VJ) {
1595 return VJ->getKind() == TypeLocVisitKind;
1596 }
1597
Ted Kremenek82f3c502010-11-15 22:23:26 +00001598 TypeLoc get() const {
Ted Kremenekf64d8032010-11-18 00:02:32 +00001599 QualType T = QualType::getFromOpaquePtr(data[0]);
1600 return TypeLoc(T, data[1]);
Ted Kremenek035dc412010-11-13 00:36:50 +00001601 }
1602};
1603
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001604class LabelRefVisit : public VisitorJob {
1605public:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001606 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1607 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001608 labelLoc.getPtrEncoding()) {}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001609
1610 static bool classof(const VisitorJob *VJ) {
1611 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1612 }
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001613 LabelDecl *get() const { return static_cast<LabelDecl*>(data[0]); }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001614 SourceLocation getLoc() const {
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001615 return SourceLocation::getFromPtrEncoding(data[1]); }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001616};
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001617
1618class NestedNameSpecifierLocVisit : public VisitorJob {
1619public:
1620 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1621 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1622 Qualifier.getNestedNameSpecifier(),
1623 Qualifier.getOpaqueData()) { }
1624
1625 static bool classof(const VisitorJob *VJ) {
1626 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1627 }
1628
1629 NestedNameSpecifierLoc get() const {
1630 return NestedNameSpecifierLoc(static_cast<NestedNameSpecifier*>(data[0]),
1631 data[1]);
1632 }
1633};
1634
Ted Kremenekf64d8032010-11-18 00:02:32 +00001635class DeclarationNameInfoVisit : public VisitorJob {
1636public:
1637 DeclarationNameInfoVisit(Stmt *S, CXCursor parent)
1638 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
1639 static bool classof(const VisitorJob *VJ) {
1640 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1641 }
1642 DeclarationNameInfo get() const {
1643 Stmt *S = static_cast<Stmt*>(data[0]);
1644 switch (S->getStmtClass()) {
1645 default:
1646 llvm_unreachable("Unhandled Stmt");
Douglas Gregorba0513d2011-10-25 01:33:02 +00001647 case clang::Stmt::MSDependentExistsStmtClass:
1648 return cast<MSDependentExistsStmt>(S)->getNameInfo();
Ted Kremenekf64d8032010-11-18 00:02:32 +00001649 case Stmt::CXXDependentScopeMemberExprClass:
1650 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1651 case Stmt::DependentScopeDeclRefExprClass:
1652 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
1653 }
1654 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001655};
Ted Kremenekcdba6592010-11-18 00:42:18 +00001656class MemberRefVisit : public VisitorJob {
1657public:
1658 MemberRefVisit(FieldDecl *D, SourceLocation L, CXCursor parent)
1659 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001660 L.getPtrEncoding()) {}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001661 static bool classof(const VisitorJob *VJ) {
1662 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1663 }
1664 FieldDecl *get() const {
1665 return static_cast<FieldDecl*>(data[0]);
1666 }
1667 SourceLocation getLoc() const {
1668 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1669 }
1670};
Ted Kremenek28a71942010-11-13 00:36:47 +00001671class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1672 VisitorWorkList &WL;
1673 CXCursor Parent;
1674public:
1675 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1676 : WL(wl), Parent(parent) {}
1677
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001678 void VisitAddrLabelExpr(AddrLabelExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001679 void VisitBlockExpr(BlockExpr *B);
Ted Kremenek28a71942010-11-13 00:36:47 +00001680 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek083c7e22010-11-13 05:38:03 +00001681 void VisitCompoundStmt(CompoundStmt *S);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001682 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
Douglas Gregorba0513d2011-10-25 01:33:02 +00001683 void VisitMSDependentExistsStmt(MSDependentExistsStmt *S);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001684 void VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001685 void VisitCXXNewExpr(CXXNewExpr *E);
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001686 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001687 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001688 void VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001689 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001690 void VisitCXXTypeidExpr(CXXTypeidExpr *E);
Ted Kremenek55b933a2010-11-17 00:50:36 +00001691 void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001692 void VisitCXXUuidofExpr(CXXUuidofExpr *E);
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001693 void VisitDeclRefExpr(DeclRefExpr *D);
Ted Kremenek035dc412010-11-13 00:36:50 +00001694 void VisitDeclStmt(DeclStmt *S);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001695 void VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001696 void VisitDesignatedInitExpr(DesignatedInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001697 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1698 void VisitForStmt(ForStmt *FS);
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001699 void VisitGotoStmt(GotoStmt *GS);
Ted Kremenek28a71942010-11-13 00:36:47 +00001700 void VisitIfStmt(IfStmt *If);
1701 void VisitInitListExpr(InitListExpr *IE);
1702 void VisitMemberExpr(MemberExpr *M);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001703 void VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001704 void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001705 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1706 void VisitOverloadExpr(OverloadExpr *E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001707 void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001708 void VisitStmt(Stmt *S);
1709 void VisitSwitchStmt(SwitchStmt *S);
1710 void VisitWhileStmt(WhileStmt *W);
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001711 void VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Francois Pichet6ad6f282010-12-07 00:08:36 +00001712 void VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E);
John Wiegley21ff2e52011-04-28 00:16:57 +00001713 void VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E);
John Wiegley55262202011-04-25 06:54:41 +00001714 void VisitExpressionTraitExpr(ExpressionTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001715 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001716 void VisitVAArgExpr(VAArgExpr *E);
Douglas Gregor94d96292011-01-19 20:34:17 +00001717 void VisitSizeOfPackExpr(SizeOfPackExpr *E);
John McCall4b9c2d22011-11-06 09:01:30 +00001718 void VisitPseudoObjectExpr(PseudoObjectExpr *E);
1719 void VisitOpaqueValueExpr(OpaqueValueExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00001720
Ted Kremenek28a71942010-11-13 00:36:47 +00001721private:
Ted Kremenekf64d8032010-11-18 00:02:32 +00001722 void AddDeclarationNameInfo(Stmt *S);
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001723 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001724 void AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001725 void AddMemberRef(FieldDecl *D, SourceLocation L);
Ted Kremenek28a71942010-11-13 00:36:47 +00001726 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001727 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001728 void AddTypeLoc(TypeSourceInfo *TI);
1729 void EnqueueChildren(Stmt *S);
1730};
1731} // end anonyous namespace
1732
Ted Kremenekf64d8032010-11-18 00:02:32 +00001733void EnqueueVisitor::AddDeclarationNameInfo(Stmt *S) {
1734 // 'S' should always be non-null, since it comes from the
1735 // statement we are visiting.
1736 WL.push_back(DeclarationNameInfoVisit(S, Parent));
1737}
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001738
1739void
1740EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1741 if (Qualifier)
1742 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
1743}
1744
Ted Kremenek28a71942010-11-13 00:36:47 +00001745void EnqueueVisitor::AddStmt(Stmt *S) {
1746 if (S)
1747 WL.push_back(StmtVisit(S, Parent));
1748}
Ted Kremenek035dc412010-11-13 00:36:50 +00001749void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001750 if (D)
Ted Kremenek035dc412010-11-13 00:36:50 +00001751 WL.push_back(DeclVisit(D, Parent, isFirst));
Ted Kremenek28a71942010-11-13 00:36:47 +00001752}
Ted Kremenek60608ec2010-11-17 00:50:47 +00001753void EnqueueVisitor::
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001754 AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001755 if (A)
1756 WL.push_back(ExplicitTemplateArgsVisit(
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001757 const_cast<ASTTemplateArgumentListInfo*>(A), Parent));
Ted Kremenek60608ec2010-11-17 00:50:47 +00001758}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001759void EnqueueVisitor::AddMemberRef(FieldDecl *D, SourceLocation L) {
1760 if (D)
1761 WL.push_back(MemberRefVisit(D, L, Parent));
1762}
Ted Kremenek28a71942010-11-13 00:36:47 +00001763void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1764 if (TI)
1765 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1766 }
1767void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001768 unsigned size = WL.size();
John McCall7502c1d2011-02-13 04:07:26 +00001769 for (Stmt::child_range Child = S->children(); Child; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001770 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001771 }
1772 if (size == WL.size())
1773 return;
1774 // Now reverse the entries we just added. This will match the DFS
1775 // ordering performed by the worklist.
1776 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1777 std::reverse(I, E);
1778}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001779void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1780 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
1781}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001782void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1783 AddDecl(B->getBlockDecl());
1784}
Ted Kremenek28a71942010-11-13 00:36:47 +00001785void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1786 EnqueueChildren(E);
1787 AddTypeLoc(E->getTypeSourceInfo());
1788}
Ted Kremenek083c7e22010-11-13 05:38:03 +00001789void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1790 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1791 E = S->body_rend(); I != E; ++I) {
1792 AddStmt(*I);
1793 }
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001794}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001795void EnqueueVisitor::
Douglas Gregorba0513d2011-10-25 01:33:02 +00001796VisitMSDependentExistsStmt(MSDependentExistsStmt *S) {
1797 AddStmt(S->getSubStmt());
1798 AddDeclarationNameInfo(S);
1799 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
1800 AddNestedNameSpecifierLoc(QualifierLoc);
1801}
1802
1803void EnqueueVisitor::
Ted Kremenekf64d8032010-11-18 00:02:32 +00001804VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
1805 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1806 AddDeclarationNameInfo(E);
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001807 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1808 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001809 if (!E->isImplicitAccess())
1810 AddStmt(E->getBase());
1811}
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001812void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1813 // Enqueue the initializer or constructor arguments.
1814 for (unsigned I = E->getNumConstructorArgs(); I > 0; --I)
1815 AddStmt(E->getConstructorArg(I-1));
1816 // Enqueue the array size, if any.
1817 AddStmt(E->getArraySize());
1818 // Enqueue the allocated type.
1819 AddTypeLoc(E->getAllocatedTypeSourceInfo());
1820 // Enqueue the placement arguments.
1821 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1822 AddStmt(E->getPlacementArg(I-1));
1823}
Ted Kremenek28a71942010-11-13 00:36:47 +00001824void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
Ted Kremenek8b8d8c92010-11-13 05:55:56 +00001825 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1826 AddStmt(CE->getArg(I-1));
Ted Kremenek28a71942010-11-13 00:36:47 +00001827 AddStmt(CE->getCallee());
1828 AddStmt(CE->getArg(0));
1829}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001830void EnqueueVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1831 // Visit the name of the type being destroyed.
1832 AddTypeLoc(E->getDestroyedTypeInfo());
1833 // Visit the scope type that looks disturbingly like the nested-name-specifier
1834 // but isn't.
1835 AddTypeLoc(E->getScopeTypeInfo());
1836 // Visit the nested-name-specifier.
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001837 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1838 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001839 // Visit base expression.
1840 AddStmt(E->getBase());
1841}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001842void EnqueueVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1843 AddTypeLoc(E->getTypeSourceInfo());
1844}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001845void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1846 EnqueueChildren(E);
1847 AddTypeLoc(E->getTypeSourceInfo());
1848}
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001849void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1850 EnqueueChildren(E);
1851 if (E->isTypeOperand())
1852 AddTypeLoc(E->getTypeOperandSourceInfo());
1853}
Ted Kremenek55b933a2010-11-17 00:50:36 +00001854
1855void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
1856 *E) {
1857 EnqueueChildren(E);
1858 AddTypeLoc(E->getTypeSourceInfo());
1859}
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001860void EnqueueVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1861 EnqueueChildren(E);
1862 if (E->isTypeOperand())
1863 AddTypeLoc(E->getTypeOperandSourceInfo());
1864}
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001865void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001866 if (DR->hasExplicitTemplateArgs()) {
1867 AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
1868 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001869 WL.push_back(DeclRefExprParts(DR, Parent));
1870}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001871void EnqueueVisitor::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
1872 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1873 AddDeclarationNameInfo(E);
Douglas Gregor00cf3cc2011-02-25 20:49:16 +00001874 AddNestedNameSpecifierLoc(E->getQualifierLoc());
Ted Kremenekf64d8032010-11-18 00:02:32 +00001875}
Ted Kremenek035dc412010-11-13 00:36:50 +00001876void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1877 unsigned size = WL.size();
1878 bool isFirst = true;
1879 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1880 D != DEnd; ++D) {
1881 AddDecl(*D, isFirst);
1882 isFirst = false;
1883 }
1884 if (size == WL.size())
1885 return;
1886 // Now reverse the entries we just added. This will match the DFS
1887 // ordering performed by the worklist.
1888 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1889 std::reverse(I, E);
1890}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001891void EnqueueVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1892 AddStmt(E->getInit());
1893 typedef DesignatedInitExpr::Designator Designator;
1894 for (DesignatedInitExpr::reverse_designators_iterator
1895 D = E->designators_rbegin(), DEnd = E->designators_rend();
1896 D != DEnd; ++D) {
1897 if (D->isFieldDesignator()) {
1898 if (FieldDecl *Field = D->getField())
1899 AddMemberRef(Field, D->getFieldLoc());
1900 continue;
1901 }
1902 if (D->isArrayDesignator()) {
1903 AddStmt(E->getArrayIndex(*D));
1904 continue;
1905 }
1906 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1907 AddStmt(E->getArrayRangeEnd(*D));
1908 AddStmt(E->getArrayRangeStart(*D));
1909 }
1910}
Ted Kremenek28a71942010-11-13 00:36:47 +00001911void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1912 EnqueueChildren(E);
1913 AddTypeLoc(E->getTypeInfoAsWritten());
1914}
1915void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1916 AddStmt(FS->getBody());
1917 AddStmt(FS->getInc());
1918 AddStmt(FS->getCond());
1919 AddDecl(FS->getConditionVariable());
1920 AddStmt(FS->getInit());
1921}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001922void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) {
1923 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
1924}
Ted Kremenek28a71942010-11-13 00:36:47 +00001925void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
1926 AddStmt(If->getElse());
1927 AddStmt(If->getThen());
1928 AddStmt(If->getCond());
1929 AddDecl(If->getConditionVariable());
1930}
1931void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
1932 // We care about the syntactic form of the initializer list, only.
1933 if (InitListExpr *Syntactic = IE->getSyntacticForm())
1934 IE = Syntactic;
1935 EnqueueChildren(IE);
1936}
1937void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
Douglas Gregor89629a72010-11-17 17:15:08 +00001938 WL.push_back(MemberExprParts(M, Parent));
1939
1940 // If the base of the member access expression is an implicit 'this', don't
1941 // visit it.
1942 // FIXME: If we ever want to show these implicit accesses, this will be
1943 // unfortunate. However, clang_getCursor() relies on this behavior.
Douglas Gregor75e85042011-03-02 21:06:53 +00001944 if (!M->isImplicitAccess())
1945 AddStmt(M->getBase());
Ted Kremenek28a71942010-11-13 00:36:47 +00001946}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001947void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1948 AddTypeLoc(E->getEncodedTypeSourceInfo());
1949}
Ted Kremenek28a71942010-11-13 00:36:47 +00001950void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
1951 EnqueueChildren(M);
1952 AddTypeLoc(M->getClassReceiverTypeInfo());
1953}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001954void EnqueueVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
1955 // Visit the components of the offsetof expression.
1956 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
1957 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
1958 const OffsetOfNode &Node = E->getComponent(I-1);
1959 switch (Node.getKind()) {
1960 case OffsetOfNode::Array:
1961 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
1962 break;
1963 case OffsetOfNode::Field:
Abramo Bagnara06dec892011-03-12 09:45:03 +00001964 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
Ted Kremenekcdba6592010-11-18 00:42:18 +00001965 break;
1966 case OffsetOfNode::Identifier:
1967 case OffsetOfNode::Base:
1968 continue;
1969 }
1970 }
1971 // Visit the type into which we're computing the offset.
1972 AddTypeLoc(E->getTypeSourceInfo());
1973}
Ted Kremenek28a71942010-11-13 00:36:47 +00001974void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001975 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
Ted Kremenek60458782010-11-12 21:34:16 +00001976 WL.push_back(OverloadExprParts(E, Parent));
1977}
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001978void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
1979 UnaryExprOrTypeTraitExpr *E) {
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001980 EnqueueChildren(E);
1981 if (E->isArgumentType())
1982 AddTypeLoc(E->getArgumentTypeInfo());
1983}
Ted Kremenek28a71942010-11-13 00:36:47 +00001984void EnqueueVisitor::VisitStmt(Stmt *S) {
1985 EnqueueChildren(S);
1986}
1987void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
1988 AddStmt(S->getBody());
1989 AddStmt(S->getCond());
1990 AddDecl(S->getConditionVariable());
1991}
Ted Kremenekfafa75a2010-11-17 00:50:39 +00001992
Ted Kremenek28a71942010-11-13 00:36:47 +00001993void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
1994 AddStmt(W->getBody());
1995 AddStmt(W->getCond());
1996 AddDecl(W->getConditionVariable());
1997}
John Wiegley21ff2e52011-04-28 00:16:57 +00001998
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001999void EnqueueVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
2000 AddTypeLoc(E->getQueriedTypeSourceInfo());
2001}
Francois Pichet6ad6f282010-12-07 00:08:36 +00002002
2003void EnqueueVisitor::VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
Francois Pichet6ad6f282010-12-07 00:08:36 +00002004 AddTypeLoc(E->getRhsTypeSourceInfo());
Francois Pichet0a03a3f2010-12-08 09:11:05 +00002005 AddTypeLoc(E->getLhsTypeSourceInfo());
Francois Pichet6ad6f282010-12-07 00:08:36 +00002006}
2007
John Wiegley21ff2e52011-04-28 00:16:57 +00002008void EnqueueVisitor::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
2009 AddTypeLoc(E->getQueriedTypeSourceInfo());
2010}
2011
John Wiegley55262202011-04-25 06:54:41 +00002012void EnqueueVisitor::VisitExpressionTraitExpr(ExpressionTraitExpr *E) {
2013 EnqueueChildren(E);
2014}
2015
Ted Kremenek28a71942010-11-13 00:36:47 +00002016void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
2017 VisitOverloadExpr(U);
2018 if (!U->isImplicitAccess())
2019 AddStmt(U->getBase());
2020}
Ted Kremenek9d3bf792010-11-17 00:50:43 +00002021void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) {
2022 AddStmt(E->getSubExpr());
2023 AddTypeLoc(E->getWrittenTypeInfo());
2024}
Douglas Gregor94d96292011-01-19 20:34:17 +00002025void EnqueueVisitor::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
2026 WL.push_back(SizeOfPackExprParts(E, Parent));
2027}
John McCall4b9c2d22011-11-06 09:01:30 +00002028void EnqueueVisitor::VisitOpaqueValueExpr(OpaqueValueExpr *E) {
2029 // If the opaque value has a source expression, just transparently
2030 // visit that. This is useful for (e.g.) pseudo-object expressions.
2031 if (Expr *SourceExpr = E->getSourceExpr())
2032 return Visit(SourceExpr);
2033 AddStmt(E);
2034}
2035void EnqueueVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *E) {
2036 // Treat the expression like its syntactic form.
2037 Visit(E->getSyntacticForm());
2038}
Ted Kremenek60458782010-11-12 21:34:16 +00002039
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002040void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002041 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002042}
2043
2044bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2045 if (RegionOfInterest.isValid()) {
2046 SourceRange Range = getRawCursorExtent(C);
2047 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2048 return false;
2049 }
2050 return true;
2051}
2052
2053bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2054 while (!WL.empty()) {
2055 // Dequeue the worklist item.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002056 VisitorJob LI = WL.back();
2057 WL.pop_back();
2058
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002059 // Set the Parent field, then back to its old value once we're done.
2060 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2061
2062 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00002063 case VisitorJob::DeclVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002064 Decl *D = cast<DeclVisit>(&LI)->get();
Ted Kremenekf1107452010-11-12 18:26:56 +00002065 if (!D)
2066 continue;
2067
2068 // For now, perform default visitation for Decls.
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002069 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2070 cast<DeclVisit>(&LI)->isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00002071 return true;
2072
2073 continue;
2074 }
Ted Kremenek60608ec2010-11-17 00:50:47 +00002075 case VisitorJob::ExplicitTemplateArgsVisitKind: {
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00002076 const ASTTemplateArgumentListInfo *ArgList =
Ted Kremenek60608ec2010-11-17 00:50:47 +00002077 cast<ExplicitTemplateArgsVisit>(&LI)->get();
2078 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2079 *ArgEnd = Arg + ArgList->NumTemplateArgs;
2080 Arg != ArgEnd; ++Arg) {
2081 if (VisitTemplateArgumentLoc(*Arg))
2082 return true;
2083 }
2084 continue;
2085 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002086 case VisitorJob::TypeLocVisitKind: {
2087 // Perform default visitation for TypeLocs.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002088 if (Visit(cast<TypeLocVisit>(&LI)->get()))
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002089 return true;
2090 continue;
2091 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002092 case VisitorJob::LabelRefVisitKind: {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002093 LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Ted Kremeneke7455012011-02-23 04:54:51 +00002094 if (LabelStmt *stmt = LS->getStmt()) {
2095 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2096 TU))) {
2097 return true;
2098 }
2099 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002100 continue;
2101 }
Ted Kremenek47695c82011-08-18 22:25:21 +00002102
Douglas Gregorf3db29f2011-02-25 18:19:59 +00002103 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2104 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2105 if (VisitNestedNameSpecifierLoc(V->get()))
2106 return true;
2107 continue;
2108 }
2109
Ted Kremenekf64d8032010-11-18 00:02:32 +00002110 case VisitorJob::DeclarationNameInfoVisitKind: {
2111 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2112 ->get()))
2113 return true;
2114 continue;
2115 }
Ted Kremenekcdba6592010-11-18 00:42:18 +00002116 case VisitorJob::MemberRefVisitKind: {
2117 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2118 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2119 return true;
2120 continue;
2121 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002122 case VisitorJob::StmtVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002123 Stmt *S = cast<StmtVisit>(&LI)->get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00002124 if (!S)
2125 continue;
2126
Ted Kremenekf1107452010-11-12 18:26:56 +00002127 // Update the current cursor.
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002128 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
Ted Kremenekcdba6592010-11-18 00:42:18 +00002129 if (!IsInRegionOfInterest(Cursor))
2130 continue;
2131 switch (Visitor(Cursor, Parent, ClientData)) {
2132 case CXChildVisit_Break: return true;
2133 case CXChildVisit_Continue: break;
2134 case CXChildVisit_Recurse:
2135 EnqueueWorkList(WL, S);
Ted Kremenek82f3c502010-11-15 22:23:26 +00002136 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002137 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00002138 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002139 }
2140 case VisitorJob::MemberExprPartsKind: {
2141 // Handle the other pieces in the MemberExpr besides the base.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002142 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002143
2144 // Visit the nested-name-specifier
Douglas Gregor40d96a62011-02-28 21:54:11 +00002145 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
2146 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002147 return true;
2148
2149 // Visit the declaration name.
2150 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2151 return true;
2152
2153 // Visit the explicitly-specified template arguments, if any.
2154 if (M->hasExplicitTemplateArgs()) {
2155 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2156 *ArgEnd = Arg + M->getNumTemplateArgs();
2157 Arg != ArgEnd; ++Arg) {
2158 if (VisitTemplateArgumentLoc(*Arg))
2159 return true;
2160 }
2161 }
2162 continue;
2163 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002164 case VisitorJob::DeclRefExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002165 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002166 // Visit nested-name-specifier, if present.
Douglas Gregor40d96a62011-02-28 21:54:11 +00002167 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
2168 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002169 return true;
2170 // Visit declaration name.
2171 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2172 return true;
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002173 continue;
2174 }
Ted Kremenek60458782010-11-12 21:34:16 +00002175 case VisitorJob::OverloadExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002176 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Ted Kremenek60458782010-11-12 21:34:16 +00002177 // Visit the nested-name-specifier.
Douglas Gregor4c9be892011-02-28 20:01:57 +00002178 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
2179 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenek60458782010-11-12 21:34:16 +00002180 return true;
2181 // Visit the declaration name.
2182 if (VisitDeclarationNameInfo(O->getNameInfo()))
2183 return true;
2184 // Visit the overloaded declaration reference.
2185 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2186 return true;
Ted Kremenek60458782010-11-12 21:34:16 +00002187 continue;
2188 }
Douglas Gregor94d96292011-01-19 20:34:17 +00002189 case VisitorJob::SizeOfPackExprPartsKind: {
2190 SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
2191 NamedDecl *Pack = E->getPack();
2192 if (isa<TemplateTypeParmDecl>(Pack)) {
2193 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
2194 E->getPackLoc(), TU)))
2195 return true;
2196
2197 continue;
2198 }
2199
2200 if (isa<TemplateTemplateParmDecl>(Pack)) {
2201 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
2202 E->getPackLoc(), TU)))
2203 return true;
2204
2205 continue;
2206 }
2207
2208 // Non-type template parameter packs and function parameter packs are
2209 // treated like DeclRefExpr cursors.
2210 continue;
2211 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002212 }
2213 }
2214 return false;
2215}
2216
Ted Kremenekcdba6592010-11-18 00:42:18 +00002217bool CursorVisitor::Visit(Stmt *S) {
Ted Kremenekd1ded662010-11-15 23:31:32 +00002218 VisitorWorkList *WL = 0;
2219 if (!WorkListFreeList.empty()) {
2220 WL = WorkListFreeList.back();
2221 WL->clear();
2222 WorkListFreeList.pop_back();
2223 }
2224 else {
2225 WL = new VisitorWorkList();
2226 WorkListCache.push_back(WL);
2227 }
2228 EnqueueWorkList(*WL, S);
2229 bool result = RunVisitorWorkList(*WL);
2230 WorkListFreeList.push_back(WL);
2231 return result;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002232}
2233
Francois Pichet48a8d142011-07-25 22:00:44 +00002234namespace {
2235typedef llvm::SmallVector<SourceRange, 4> RefNamePieces;
2236RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
2237 const DeclarationNameInfo &NI,
2238 const SourceRange &QLoc,
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00002239 const ASTTemplateArgumentListInfo *TemplateArgs = 0){
Francois Pichet48a8d142011-07-25 22:00:44 +00002240 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
2241 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
2242 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
2243
2244 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
2245
2246 RefNamePieces Pieces;
2247
2248 if (WantQualifier && QLoc.isValid())
2249 Pieces.push_back(QLoc);
2250
2251 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
2252 Pieces.push_back(NI.getLoc());
2253
2254 if (WantTemplateArgs && TemplateArgs)
2255 Pieces.push_back(SourceRange(TemplateArgs->LAngleLoc,
2256 TemplateArgs->RAngleLoc));
2257
2258 if (Kind == DeclarationName::CXXOperatorName) {
2259 Pieces.push_back(SourceLocation::getFromRawEncoding(
2260 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
2261 Pieces.push_back(SourceLocation::getFromRawEncoding(
2262 NI.getInfo().CXXOperatorName.EndOpNameLoc));
2263 }
2264
2265 if (WantSinglePiece) {
2266 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
2267 Pieces.clear();
2268 Pieces.push_back(R);
2269 }
2270
2271 return Pieces;
2272}
2273}
2274
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002275//===----------------------------------------------------------------------===//
2276// Misc. API hooks.
2277//===----------------------------------------------------------------------===//
2278
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002279static llvm::sys::Mutex EnableMultithreadingMutex;
2280static bool EnabledMultithreading;
2281
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002282extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002283CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2284 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002285 // Disable pretty stack trace functionality, which will otherwise be a very
2286 // poor citizen of the world and set up all sorts of signal handlers.
2287 llvm::DisablePrettyStackTrace = true;
2288
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002289 // We use crash recovery to make some of our APIs more reliable, implicitly
2290 // enable it.
2291 llvm::CrashRecoveryContext::Enable();
2292
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002293 // Enable support for multithreading in LLVM.
2294 {
2295 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2296 if (!EnabledMultithreading) {
2297 llvm::llvm_start_multithreaded();
2298 EnabledMultithreading = true;
2299 }
2300 }
2301
Douglas Gregora030b7c2010-01-22 20:35:53 +00002302 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002303 if (excludeDeclarationsFromPCH)
2304 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002305 if (displayDiagnostics)
2306 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002307 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002308}
2309
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002310void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002311 if (CIdx)
2312 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002313}
2314
Ted Kremenekd2427dd2011-03-18 23:05:39 +00002315void clang_toggleCrashRecovery(unsigned isEnabled) {
2316 if (isEnabled)
2317 llvm::CrashRecoveryContext::Enable();
2318 else
2319 llvm::CrashRecoveryContext::Disable();
2320}
2321
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002322CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002323 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002324 if (!CIdx)
2325 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002326
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002327 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002328 FileSystemOptions FileSystemOpts;
2329 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002330
David Blaikied6471f72011-09-25 23:23:43 +00002331 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002332 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002333 CXXIdx->getOnlyLocalDecls(),
2334 0, 0, true);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002335 return MakeCXTranslationUnit(TU);
Steve Naroff600866c2009-08-27 19:51:58 +00002336}
2337
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002338unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002339 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregorb5af8432011-08-25 22:54:01 +00002340 CXTranslationUnit_CacheCompletionResults;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002341}
2342
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002343CXTranslationUnit
2344clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2345 const char *source_filename,
2346 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002347 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002348 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002349 struct CXUnsavedFile *unsaved_files) {
Douglas Gregordca8ee82011-05-06 16:33:08 +00002350 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord |
Chandler Carruthba7537f2011-07-14 09:02:10 +00002351 CXTranslationUnit_NestedMacroExpansions;
Douglas Gregor5a430212010-07-21 18:52:53 +00002352 return clang_parseTranslationUnit(CIdx, source_filename,
2353 command_line_args, num_command_line_args,
2354 unsaved_files, num_unsaved_files,
Douglas Gregordca8ee82011-05-06 16:33:08 +00002355 Options);
Douglas Gregor5a430212010-07-21 18:52:53 +00002356}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002357
2358struct ParseTranslationUnitInfo {
2359 CXIndex CIdx;
2360 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002361 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002362 int num_command_line_args;
2363 struct CXUnsavedFile *unsaved_files;
2364 unsigned num_unsaved_files;
2365 unsigned options;
2366 CXTranslationUnit result;
2367};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002368static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002369 ParseTranslationUnitInfo *PTUI =
2370 static_cast<ParseTranslationUnitInfo*>(UserData);
2371 CXIndex CIdx = PTUI->CIdx;
2372 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002373 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002374 int num_command_line_args = PTUI->num_command_line_args;
2375 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2376 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2377 unsigned options = PTUI->options;
2378 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002379
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002380 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002381 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002382
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002383 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2384
Douglas Gregor44c181a2010-07-23 00:33:23 +00002385 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregor467dc882011-08-25 22:30:56 +00002386 // FIXME: Add a flag for modules.
2387 TranslationUnitKind TUKind
2388 = (options & CXTranslationUnit_Incomplete)? TU_Prefix : TU_Complete;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002389 bool CacheCodeCompetionResults
2390 = options & CXTranslationUnit_CacheCompletionResults;
2391
Douglas Gregor5352ac02010-01-28 00:27:43 +00002392 // Configure the diagnostics.
2393 DiagnosticOptions DiagOpts;
David Blaikied6471f72011-09-25 23:23:43 +00002394 llvm::IntrusiveRefCntPtr<DiagnosticsEngine>
Ted Kremenek25a11e12011-03-22 01:15:24 +00002395 Diags(CompilerInstance::createDiagnostics(DiagOpts, num_command_line_args,
2396 command_line_args));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002397
Ted Kremenek25a11e12011-03-22 01:15:24 +00002398 // Recover resources if we crash before exiting this function.
David Blaikied6471f72011-09-25 23:23:43 +00002399 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
2400 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00002401 DiagCleanup(Diags.getPtr());
2402
2403 llvm::OwningPtr<std::vector<ASTUnit::RemappedFile> >
2404 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2405
2406 // Recover resources if we crash before exiting this function.
2407 llvm::CrashRecoveryContextCleanupRegistrar<
2408 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2409
Douglas Gregor4db64a42010-01-23 00:14:00 +00002410 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002411 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002412 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002413 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002414 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2415 Buffer));
Douglas Gregor4db64a42010-01-23 00:14:00 +00002416 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002417
Ted Kremenek25a11e12011-03-22 01:15:24 +00002418 llvm::OwningPtr<std::vector<const char *> >
2419 Args(new std::vector<const char*>());
2420
2421 // Recover resources if we crash before exiting this method.
2422 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
2423 ArgsCleanup(Args.get());
2424
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002425 // Since the Clang C library is primarily used by batch tools dealing with
2426 // (often very broken) source code, where spell-checking can have a
2427 // significant negative impact on performance (particularly when
2428 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002429 // Only do this if we haven't found a spell-checking-related argument.
2430 bool FoundSpellCheckingArgument = false;
2431 for (int I = 0; I != num_command_line_args; ++I) {
2432 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2433 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2434 FoundSpellCheckingArgument = true;
2435 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002436 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002437 }
2438 if (!FoundSpellCheckingArgument)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002439 Args->push_back("-fno-spell-checking");
Douglas Gregorb10daed2010-10-11 16:52:23 +00002440
Ted Kremenek25a11e12011-03-22 01:15:24 +00002441 Args->insert(Args->end(), command_line_args,
2442 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002443
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002444 // The 'source_filename' argument is optional. If the caller does not
2445 // specify it then it is assumed that the source file is specified
2446 // in the actual argument list.
2447 // Put the source file after command_line_args otherwise if '-x' flag is
2448 // present it will be unused.
2449 if (source_filename)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002450 Args->push_back(source_filename);
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002451
Douglas Gregor44c181a2010-07-23 00:33:23 +00002452 // Do we need the detailed preprocessing record?
Chandler Carruthba7537f2011-07-14 09:02:10 +00002453 bool NestedMacroExpansions = false;
Douglas Gregor44c181a2010-07-23 00:33:23 +00002454 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Ted Kremenek25a11e12011-03-22 01:15:24 +00002455 Args->push_back("-Xclang");
2456 Args->push_back("-detailed-preprocessing-record");
Chandler Carruthba7537f2011-07-14 09:02:10 +00002457 NestedMacroExpansions
2458 = (options & CXTranslationUnit_NestedMacroExpansions);
Douglas Gregor44c181a2010-07-23 00:33:23 +00002459 }
2460
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002461 unsigned NumErrors = Diags->getClient()->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002462 llvm::OwningPtr<ASTUnit> Unit(
Ted Kremenek4ee99262011-03-22 20:16:19 +00002463 ASTUnit::LoadFromCommandLine(Args->size() ? &(*Args)[0] : 0
2464 /* vector::data() not portable */,
2465 Args->size() ? (&(*Args)[0] + Args->size()) :0,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002466 Diags,
2467 CXXIdx->getClangResourcesPath(),
2468 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002469 /*CaptureDiagnostics=*/true,
Ted Kremenek4ee99262011-03-22 20:16:19 +00002470 RemappedFiles->size() ? &(*RemappedFiles)[0]:0,
Ted Kremenek25a11e12011-03-22 01:15:24 +00002471 RemappedFiles->size(),
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00002472 /*RemappedFilesKeepOriginalName=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002473 PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00002474 TUKind,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002475 CacheCodeCompetionResults,
Chandler Carruthba7537f2011-07-14 09:02:10 +00002476 NestedMacroExpansions));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002477
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002478 if (NumErrors != Diags->getClient()->getNumErrors()) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002479 // Make sure to check that 'Unit' is non-NULL.
2480 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2481 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2482 DEnd = Unit->stored_diag_end();
2483 D != DEnd; ++D) {
2484 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2485 CXString Msg = clang_formatDiagnostic(&Diag,
2486 clang_defaultDiagnosticDisplayOptions());
2487 fprintf(stderr, "%s\n", clang_getCString(Msg));
2488 clang_disposeString(Msg);
2489 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002490#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002491 // On Windows, force a flush, since there may be multiple copies of
2492 // stderr and stdout in the file system, all with different buffers
2493 // but writing to the same device.
2494 fflush(stderr);
2495#endif
2496 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002497 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002498
Ted Kremeneka60ed472010-11-16 08:15:36 +00002499 PTUI->result = MakeCXTranslationUnit(Unit.take());
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002500}
2501CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2502 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002503 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002504 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002505 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002506 unsigned num_unsaved_files,
2507 unsigned options) {
2508 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002509 num_command_line_args, unsaved_files,
2510 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002511 llvm::CrashRecoveryContext CRC;
2512
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002513 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002514 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2515 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2516 fprintf(stderr, " 'command_line_args' : [");
2517 for (int i = 0; i != num_command_line_args; ++i) {
2518 if (i)
2519 fprintf(stderr, ", ");
2520 fprintf(stderr, "'%s'", command_line_args[i]);
2521 }
2522 fprintf(stderr, "],\n");
2523 fprintf(stderr, " 'unsaved_files' : [");
2524 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2525 if (i)
2526 fprintf(stderr, ", ");
2527 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2528 unsaved_files[i].Length);
2529 }
2530 fprintf(stderr, "],\n");
2531 fprintf(stderr, " 'options' : %d,\n", options);
2532 fprintf(stderr, "}\n");
2533
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002534 return 0;
Douglas Gregor6df78732011-05-05 20:27:22 +00002535 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
2536 PrintLibclangResourceUsage(PTUI.result);
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002537 }
Douglas Gregor6df78732011-05-05 20:27:22 +00002538
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002539 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002540}
2541
Douglas Gregor19998442010-08-13 15:35:05 +00002542unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2543 return CXSaveTranslationUnit_None;
2544}
2545
2546int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2547 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002548 if (!TU)
Douglas Gregor39c411f2011-07-06 16:43:36 +00002549 return CXSaveError_InvalidTU;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002550
Douglas Gregor39c411f2011-07-06 16:43:36 +00002551 CXSaveError result = static_cast<ASTUnit *>(TU->TUData)->Save(FileName);
Douglas Gregor6df78732011-05-05 20:27:22 +00002552 if (getenv("LIBCLANG_RESOURCE_USAGE"))
2553 PrintLibclangResourceUsage(TU);
2554 return result;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002555}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002556
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002557void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002558 if (CTUnit) {
2559 // If the translation unit has been marked as unsafe to free, just discard
2560 // it.
Ted Kremeneka60ed472010-11-16 08:15:36 +00002561 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002562 return;
2563
Ted Kremeneka60ed472010-11-16 08:15:36 +00002564 delete static_cast<ASTUnit *>(CTUnit->TUData);
2565 disposeCXStringPool(CTUnit->StringPool);
Ted Kremenek15322172011-11-10 08:43:12 +00002566 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002567 delete CTUnit;
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002568 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002569}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002570
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002571unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2572 return CXReparse_None;
2573}
2574
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002575struct ReparseTranslationUnitInfo {
2576 CXTranslationUnit TU;
2577 unsigned num_unsaved_files;
2578 struct CXUnsavedFile *unsaved_files;
2579 unsigned options;
2580 int result;
2581};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002582
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002583static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002584 ReparseTranslationUnitInfo *RTUI =
2585 static_cast<ReparseTranslationUnitInfo*>(UserData);
2586 CXTranslationUnit TU = RTUI->TU;
Ted Kremenek15322172011-11-10 08:43:12 +00002587
2588 // Reset the associated diagnostics.
2589 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
2590 TU->Diagnostics = 0;
2591
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002592 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2593 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2594 unsigned options = RTUI->options;
2595 (void) options;
2596 RTUI->result = 1;
2597
Douglas Gregorabc563f2010-07-19 21:46:24 +00002598 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002599 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002600
Ted Kremeneka60ed472010-11-16 08:15:36 +00002601 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor593b0c12010-09-23 18:47:53 +00002602 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002603
Ted Kremenek25a11e12011-03-22 01:15:24 +00002604 llvm::OwningPtr<std::vector<ASTUnit::RemappedFile> >
2605 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2606
2607 // Recover resources if we crash before exiting this function.
2608 llvm::CrashRecoveryContextCleanupRegistrar<
2609 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2610
Douglas Gregorabc563f2010-07-19 21:46:24 +00002611 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002612 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002613 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002614 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002615 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2616 Buffer));
Douglas Gregorabc563f2010-07-19 21:46:24 +00002617 }
2618
Ted Kremenek4ee99262011-03-22 20:16:19 +00002619 if (!CXXUnit->Reparse(RemappedFiles->size() ? &(*RemappedFiles)[0] : 0,
2620 RemappedFiles->size()))
Douglas Gregor593b0c12010-09-23 18:47:53 +00002621 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002622}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002623
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002624int clang_reparseTranslationUnit(CXTranslationUnit TU,
2625 unsigned num_unsaved_files,
2626 struct CXUnsavedFile *unsaved_files,
2627 unsigned options) {
2628 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2629 options, 0 };
Argyrios Kyrtzidis8c4b47e2011-10-28 22:54:33 +00002630
Argyrios Kyrtzidise7de9b42011-10-29 19:32:39 +00002631 if (getenv("LIBCLANG_NOTHREADS")) {
Argyrios Kyrtzidis8c4b47e2011-10-28 22:54:33 +00002632 clang_reparseTranslationUnit_Impl(&RTUI);
2633 return RTUI.result;
2634 }
2635
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002636 llvm::CrashRecoveryContext CRC;
2637
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002638 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002639 fprintf(stderr, "libclang: crash detected during reparsing\n");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002640 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002641 return 1;
Douglas Gregor6df78732011-05-05 20:27:22 +00002642 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
2643 PrintLibclangResourceUsage(TU);
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002644
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002645 return RTUI.result;
2646}
2647
Douglas Gregordf95a132010-08-09 20:45:32 +00002648
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002649CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002650 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002651 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002652
Ted Kremeneka60ed472010-11-16 08:15:36 +00002653 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002654 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002655}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002656
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002657CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002658 CXCursor Result = { CXCursor_TranslationUnit, 0, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002659 return Result;
2660}
2661
Ted Kremenekfb480492010-01-13 21:46:36 +00002662} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002663
Ted Kremenekfb480492010-01-13 21:46:36 +00002664//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002665// CXFile Operations.
2666//===----------------------------------------------------------------------===//
2667
2668extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002669CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002670 if (!SFile)
Ted Kremeneka60ed472010-11-16 08:15:36 +00002671 return createCXString((const char*)NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002672
Steve Naroff88145032009-10-27 14:35:18 +00002673 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002674 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002675}
2676
2677time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002678 if (!SFile)
2679 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002680
Steve Naroff88145032009-10-27 14:35:18 +00002681 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2682 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002683}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002684
Douglas Gregorb9790342010-01-22 21:44:22 +00002685CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2686 if (!tu)
2687 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002688
Ted Kremeneka60ed472010-11-16 08:15:36 +00002689 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002690
Douglas Gregorb9790342010-01-22 21:44:22 +00002691 FileManager &FMgr = CXXUnit->getFileManager();
Chris Lattner39b49bc2010-11-23 08:35:12 +00002692 return const_cast<FileEntry *>(FMgr.getFile(file_name));
Douglas Gregorb9790342010-01-22 21:44:22 +00002693}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002694
Douglas Gregordd3e5542011-05-04 00:14:37 +00002695unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit tu, CXFile file) {
2696 if (!tu || !file)
2697 return 0;
2698
2699 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
2700 FileEntry *FEnt = static_cast<FileEntry *>(file);
2701 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
2702 .isFileMultipleIncludeGuarded(FEnt);
2703}
2704
Ted Kremenekfb480492010-01-13 21:46:36 +00002705} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002706
Ted Kremenekfb480492010-01-13 21:46:36 +00002707//===----------------------------------------------------------------------===//
2708// CXCursor Operations.
2709//===----------------------------------------------------------------------===//
2710
Ted Kremenekfb480492010-01-13 21:46:36 +00002711static Decl *getDeclFromExpr(Stmt *E) {
Argyrios Kyrtzidisc2954612011-09-12 22:17:26 +00002712 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Douglas Gregordb1314e2010-10-01 21:11:22 +00002713 return getDeclFromExpr(CE->getSubExpr());
2714
Ted Kremenekfb480492010-01-13 21:46:36 +00002715 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2716 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002717 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2718 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002719 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2720 return ME->getMemberDecl();
2721 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2722 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002723 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
John McCall12f78a62010-12-02 01:19:52 +00002724 return PRE->isExplicitProperty() ? PRE->getExplicitProperty() : 0;
John McCall4b9c2d22011-11-06 09:01:30 +00002725 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
2726 return getDeclFromExpr(POE->getSyntacticForm());
2727 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
2728 if (Expr *Src = OVE->getSourceExpr())
2729 return getDeclFromExpr(Src);
Douglas Gregordb1314e2010-10-01 21:11:22 +00002730
Ted Kremenekfb480492010-01-13 21:46:36 +00002731 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2732 return getDeclFromExpr(CE->getCallee());
Chris Lattner5f9e2722011-07-23 10:55:15 +00002733 if (CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Douglas Gregor93798e22010-11-05 21:11:19 +00002734 if (!CE->isElidable())
2735 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002736 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2737 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002738
Douglas Gregordb1314e2010-10-01 21:11:22 +00002739 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2740 return PE->getProtocol();
Douglas Gregorc7793c72011-01-15 01:15:58 +00002741 if (SubstNonTypeTemplateParmPackExpr *NTTP
2742 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
2743 return NTTP->getParameterPack();
Douglas Gregor94d96292011-01-19 20:34:17 +00002744 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2745 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
2746 isa<ParmVarDecl>(SizeOfPack->getPack()))
2747 return SizeOfPack->getPack();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002748
Ted Kremenekfb480492010-01-13 21:46:36 +00002749 return 0;
2750}
2751
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002752static SourceLocation getLocationFromExpr(Expr *E) {
Argyrios Kyrtzidisc2954612011-09-12 22:17:26 +00002753 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
2754 return getLocationFromExpr(CE->getSubExpr());
2755
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002756 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2757 return /*FIXME:*/Msg->getLeftLoc();
2758 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2759 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002760 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2761 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002762 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2763 return Member->getMemberLoc();
2764 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2765 return Ivar->getLocation();
Douglas Gregor94d96292011-01-19 20:34:17 +00002766 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2767 return SizeOfPack->getPackLoc();
2768
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002769 return E->getLocStart();
2770}
2771
Ted Kremenekfb480492010-01-13 21:46:36 +00002772extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002773
2774unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002775 CXCursorVisitor visitor,
2776 CXClientData client_data) {
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00002777 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
2778 /*VisitPreprocessorLast=*/false);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002779 return CursorVis.VisitChildren(parent);
2780}
2781
David Chisnall3387c652010-11-03 14:12:26 +00002782#ifndef __has_feature
2783#define __has_feature(x) 0
2784#endif
2785#if __has_feature(blocks)
2786typedef enum CXChildVisitResult
2787 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2788
2789static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2790 CXClientData client_data) {
2791 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2792 return block(cursor, parent);
2793}
2794#else
2795// If we are compiled with a compiler that doesn't have native blocks support,
2796// define and call the block manually, so the
2797typedef struct _CXChildVisitResult
2798{
2799 void *isa;
2800 int flags;
2801 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002802 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2803 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00002804} *CXCursorVisitorBlock;
2805
2806static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2807 CXClientData client_data) {
2808 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2809 return block->invoke(block, cursor, parent);
2810}
2811#endif
2812
2813
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002814unsigned clang_visitChildrenWithBlock(CXCursor parent,
2815 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00002816 return clang_visitChildren(parent, visitWithBlock, block);
2817}
2818
Douglas Gregor78205d42010-01-20 21:45:58 +00002819static CXString getDeclSpelling(Decl *D) {
2820 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
Douglas Gregore3c60a72010-11-17 00:13:31 +00002821 if (!ND) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002822 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00002823 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
2824 return createCXString(Property->getIdentifier()->getName());
2825
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002826 return createCXString("");
Douglas Gregore3c60a72010-11-17 00:13:31 +00002827 }
2828
Douglas Gregor78205d42010-01-20 21:45:58 +00002829 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002830 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002831
Douglas Gregor78205d42010-01-20 21:45:58 +00002832 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2833 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2834 // and returns different names. NamedDecl returns the class name and
2835 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002836 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002837
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002838 if (isa<UsingDirectiveDecl>(D))
2839 return createCXString("");
2840
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002841 llvm::SmallString<1024> S;
2842 llvm::raw_svector_ostream os(S);
2843 ND->printName(os);
2844
2845 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002846}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002847
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002848CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002849 if (clang_isTranslationUnit(C.kind))
Ted Kremeneka60ed472010-11-16 08:15:36 +00002850 return clang_getTranslationUnitSpelling(
2851 static_cast<CXTranslationUnit>(C.data[2]));
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002852
Steve Narofff334b4e2009-09-02 18:26:48 +00002853 if (clang_isReference(C.kind)) {
2854 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002855 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002856 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002857 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002858 }
2859 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002860 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002861 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002862 }
2863 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002864 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002865 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002866 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002867 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002868 case CXCursor_CXXBaseSpecifier: {
2869 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2870 return createCXString(B->getType().getAsString());
2871 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002872 case CXCursor_TypeRef: {
2873 TypeDecl *Type = getCursorTypeRef(C).first;
2874 assert(Type && "Missing type decl");
2875
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002876 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2877 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002878 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002879 case CXCursor_TemplateRef: {
2880 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002881 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002882
2883 return createCXString(Template->getNameAsString());
2884 }
Douglas Gregor69319002010-08-31 23:48:11 +00002885
2886 case CXCursor_NamespaceRef: {
2887 NamedDecl *NS = getCursorNamespaceRef(C).first;
2888 assert(NS && "Missing namespace decl");
2889
2890 return createCXString(NS->getNameAsString());
2891 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002892
Douglas Gregora67e03f2010-09-09 21:42:20 +00002893 case CXCursor_MemberRef: {
2894 FieldDecl *Field = getCursorMemberRef(C).first;
2895 assert(Field && "Missing member decl");
2896
2897 return createCXString(Field->getNameAsString());
2898 }
2899
Douglas Gregor36897b02010-09-10 00:22:18 +00002900 case CXCursor_LabelRef: {
2901 LabelStmt *Label = getCursorLabelRef(C).first;
2902 assert(Label && "Missing label");
2903
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002904 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00002905 }
2906
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002907 case CXCursor_OverloadedDeclRef: {
2908 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2909 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2910 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2911 return createCXString(ND->getNameAsString());
2912 return createCXString("");
2913 }
2914 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2915 return createCXString(E->getName().getAsString());
2916 OverloadedTemplateStorage *Ovl
2917 = Storage.get<OverloadedTemplateStorage*>();
2918 if (Ovl->size() == 0)
2919 return createCXString("");
2920 return createCXString((*Ovl->begin())->getNameAsString());
2921 }
2922
Daniel Dunbaracca7252009-11-30 20:42:49 +00002923 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002924 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002925 }
2926 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002927
2928 if (clang_isExpression(C.kind)) {
2929 Decl *D = getDeclFromExpr(getCursorExpr(C));
2930 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002931 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002932 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002933 }
2934
Douglas Gregor36897b02010-09-10 00:22:18 +00002935 if (clang_isStatement(C.kind)) {
2936 Stmt *S = getCursorStmt(C);
2937 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002938 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00002939
2940 return createCXString("");
2941 }
2942
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00002943 if (C.kind == CXCursor_MacroExpansion)
Chandler Carruth9e5bb852011-07-14 08:20:46 +00002944 return createCXString(getCursorMacroExpansion(C)->getName()
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002945 ->getNameStart());
2946
Douglas Gregor572feb22010-03-18 18:04:21 +00002947 if (C.kind == CXCursor_MacroDefinition)
2948 return createCXString(getCursorMacroDefinition(C)->getName()
2949 ->getNameStart());
2950
Douglas Gregorecdcb882010-10-20 22:00:55 +00002951 if (C.kind == CXCursor_InclusionDirective)
2952 return createCXString(getCursorInclusionDirective(C)->getFileName());
2953
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002954 if (clang_isDeclaration(C.kind))
2955 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002956
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00002957 if (C.kind == CXCursor_AnnotateAttr) {
2958 AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
2959 return createCXString(AA->getAnnotation());
2960 }
2961
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002962 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002963}
2964
Douglas Gregor358559d2010-10-02 22:49:11 +00002965CXString clang_getCursorDisplayName(CXCursor C) {
2966 if (!clang_isDeclaration(C.kind))
2967 return clang_getCursorSpelling(C);
2968
2969 Decl *D = getCursorDecl(C);
2970 if (!D)
2971 return createCXString("");
2972
Douglas Gregor30c42402011-09-27 22:38:19 +00002973 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
Douglas Gregor358559d2010-10-02 22:49:11 +00002974 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2975 D = FunTmpl->getTemplatedDecl();
2976
2977 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
2978 llvm::SmallString<64> Str;
2979 llvm::raw_svector_ostream OS(Str);
2980 OS << Function->getNameAsString();
2981 if (Function->getPrimaryTemplate())
2982 OS << "<>";
2983 OS << "(";
2984 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
2985 if (I)
2986 OS << ", ";
2987 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
2988 }
2989
2990 if (Function->isVariadic()) {
2991 if (Function->getNumParams())
2992 OS << ", ";
2993 OS << "...";
2994 }
2995 OS << ")";
2996 return createCXString(OS.str());
2997 }
2998
2999 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
3000 llvm::SmallString<64> Str;
3001 llvm::raw_svector_ostream OS(Str);
3002 OS << ClassTemplate->getNameAsString();
3003 OS << "<";
3004 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
3005 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3006 if (I)
3007 OS << ", ";
3008
3009 NamedDecl *Param = Params->getParam(I);
3010 if (Param->getIdentifier()) {
3011 OS << Param->getIdentifier()->getName();
3012 continue;
3013 }
3014
3015 // There is no parameter name, which makes this tricky. Try to come up
3016 // with something useful that isn't too long.
3017 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3018 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
3019 else if (NonTypeTemplateParmDecl *NTTP
3020 = dyn_cast<NonTypeTemplateParmDecl>(Param))
3021 OS << NTTP->getType().getAsString(Policy);
3022 else
3023 OS << "template<...> class";
3024 }
3025
3026 OS << ">";
3027 return createCXString(OS.str());
3028 }
3029
3030 if (ClassTemplateSpecializationDecl *ClassSpec
3031 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
3032 // If the type was explicitly written, use that.
3033 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
3034 return createCXString(TSInfo->getType().getAsString(Policy));
3035
3036 llvm::SmallString<64> Str;
3037 llvm::raw_svector_ostream OS(Str);
3038 OS << ClassSpec->getNameAsString();
3039 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00003040 ClassSpec->getTemplateArgs().data(),
3041 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00003042 Policy);
3043 return createCXString(OS.str());
3044 }
3045
3046 return clang_getCursorSpelling(C);
3047}
3048
Ted Kremeneke68fff62010-02-17 00:41:32 +00003049CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00003050 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00003051 case CXCursor_FunctionDecl:
3052 return createCXString("FunctionDecl");
3053 case CXCursor_TypedefDecl:
3054 return createCXString("TypedefDecl");
3055 case CXCursor_EnumDecl:
3056 return createCXString("EnumDecl");
3057 case CXCursor_EnumConstantDecl:
3058 return createCXString("EnumConstantDecl");
3059 case CXCursor_StructDecl:
3060 return createCXString("StructDecl");
3061 case CXCursor_UnionDecl:
3062 return createCXString("UnionDecl");
3063 case CXCursor_ClassDecl:
3064 return createCXString("ClassDecl");
3065 case CXCursor_FieldDecl:
3066 return createCXString("FieldDecl");
3067 case CXCursor_VarDecl:
3068 return createCXString("VarDecl");
3069 case CXCursor_ParmDecl:
3070 return createCXString("ParmDecl");
3071 case CXCursor_ObjCInterfaceDecl:
3072 return createCXString("ObjCInterfaceDecl");
3073 case CXCursor_ObjCCategoryDecl:
3074 return createCXString("ObjCCategoryDecl");
3075 case CXCursor_ObjCProtocolDecl:
3076 return createCXString("ObjCProtocolDecl");
3077 case CXCursor_ObjCPropertyDecl:
3078 return createCXString("ObjCPropertyDecl");
3079 case CXCursor_ObjCIvarDecl:
3080 return createCXString("ObjCIvarDecl");
3081 case CXCursor_ObjCInstanceMethodDecl:
3082 return createCXString("ObjCInstanceMethodDecl");
3083 case CXCursor_ObjCClassMethodDecl:
3084 return createCXString("ObjCClassMethodDecl");
3085 case CXCursor_ObjCImplementationDecl:
3086 return createCXString("ObjCImplementationDecl");
3087 case CXCursor_ObjCCategoryImplDecl:
3088 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00003089 case CXCursor_CXXMethod:
3090 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003091 case CXCursor_UnexposedDecl:
3092 return createCXString("UnexposedDecl");
3093 case CXCursor_ObjCSuperClassRef:
3094 return createCXString("ObjCSuperClassRef");
3095 case CXCursor_ObjCProtocolRef:
3096 return createCXString("ObjCProtocolRef");
3097 case CXCursor_ObjCClassRef:
3098 return createCXString("ObjCClassRef");
3099 case CXCursor_TypeRef:
3100 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003101 case CXCursor_TemplateRef:
3102 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00003103 case CXCursor_NamespaceRef:
3104 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00003105 case CXCursor_MemberRef:
3106 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00003107 case CXCursor_LabelRef:
3108 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003109 case CXCursor_OverloadedDeclRef:
3110 return createCXString("OverloadedDeclRef");
Douglas Gregor42b29842011-10-05 19:00:14 +00003111 case CXCursor_IntegerLiteral:
3112 return createCXString("IntegerLiteral");
3113 case CXCursor_FloatingLiteral:
3114 return createCXString("FloatingLiteral");
3115 case CXCursor_ImaginaryLiteral:
3116 return createCXString("ImaginaryLiteral");
3117 case CXCursor_StringLiteral:
3118 return createCXString("StringLiteral");
3119 case CXCursor_CharacterLiteral:
3120 return createCXString("CharacterLiteral");
3121 case CXCursor_ParenExpr:
3122 return createCXString("ParenExpr");
3123 case CXCursor_UnaryOperator:
3124 return createCXString("UnaryOperator");
3125 case CXCursor_ArraySubscriptExpr:
3126 return createCXString("ArraySubscriptExpr");
3127 case CXCursor_BinaryOperator:
3128 return createCXString("BinaryOperator");
3129 case CXCursor_CompoundAssignOperator:
3130 return createCXString("CompoundAssignOperator");
3131 case CXCursor_ConditionalOperator:
3132 return createCXString("ConditionalOperator");
3133 case CXCursor_CStyleCastExpr:
3134 return createCXString("CStyleCastExpr");
3135 case CXCursor_CompoundLiteralExpr:
3136 return createCXString("CompoundLiteralExpr");
3137 case CXCursor_InitListExpr:
3138 return createCXString("InitListExpr");
3139 case CXCursor_AddrLabelExpr:
3140 return createCXString("AddrLabelExpr");
3141 case CXCursor_StmtExpr:
3142 return createCXString("StmtExpr");
3143 case CXCursor_GenericSelectionExpr:
3144 return createCXString("GenericSelectionExpr");
3145 case CXCursor_GNUNullExpr:
3146 return createCXString("GNUNullExpr");
3147 case CXCursor_CXXStaticCastExpr:
3148 return createCXString("CXXStaticCastExpr");
3149 case CXCursor_CXXDynamicCastExpr:
3150 return createCXString("CXXDynamicCastExpr");
3151 case CXCursor_CXXReinterpretCastExpr:
3152 return createCXString("CXXReinterpretCastExpr");
3153 case CXCursor_CXXConstCastExpr:
3154 return createCXString("CXXConstCastExpr");
3155 case CXCursor_CXXFunctionalCastExpr:
3156 return createCXString("CXXFunctionalCastExpr");
3157 case CXCursor_CXXTypeidExpr:
3158 return createCXString("CXXTypeidExpr");
3159 case CXCursor_CXXBoolLiteralExpr:
3160 return createCXString("CXXBoolLiteralExpr");
3161 case CXCursor_CXXNullPtrLiteralExpr:
3162 return createCXString("CXXNullPtrLiteralExpr");
3163 case CXCursor_CXXThisExpr:
3164 return createCXString("CXXThisExpr");
3165 case CXCursor_CXXThrowExpr:
3166 return createCXString("CXXThrowExpr");
3167 case CXCursor_CXXNewExpr:
3168 return createCXString("CXXNewExpr");
3169 case CXCursor_CXXDeleteExpr:
3170 return createCXString("CXXDeleteExpr");
3171 case CXCursor_UnaryExpr:
3172 return createCXString("UnaryExpr");
3173 case CXCursor_ObjCStringLiteral:
3174 return createCXString("ObjCStringLiteral");
3175 case CXCursor_ObjCEncodeExpr:
3176 return createCXString("ObjCEncodeExpr");
3177 case CXCursor_ObjCSelectorExpr:
3178 return createCXString("ObjCSelectorExpr");
3179 case CXCursor_ObjCProtocolExpr:
3180 return createCXString("ObjCProtocolExpr");
3181 case CXCursor_ObjCBridgedCastExpr:
3182 return createCXString("ObjCBridgedCastExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00003183 case CXCursor_BlockExpr:
3184 return createCXString("BlockExpr");
Douglas Gregor42b29842011-10-05 19:00:14 +00003185 case CXCursor_PackExpansionExpr:
3186 return createCXString("PackExpansionExpr");
3187 case CXCursor_SizeOfPackExpr:
3188 return createCXString("SizeOfPackExpr");
3189 case CXCursor_UnexposedExpr:
3190 return createCXString("UnexposedExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003191 case CXCursor_DeclRefExpr:
3192 return createCXString("DeclRefExpr");
3193 case CXCursor_MemberRefExpr:
3194 return createCXString("MemberRefExpr");
3195 case CXCursor_CallExpr:
3196 return createCXString("CallExpr");
3197 case CXCursor_ObjCMessageExpr:
3198 return createCXString("ObjCMessageExpr");
3199 case CXCursor_UnexposedStmt:
3200 return createCXString("UnexposedStmt");
Douglas Gregor42b29842011-10-05 19:00:14 +00003201 case CXCursor_DeclStmt:
3202 return createCXString("DeclStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00003203 case CXCursor_LabelStmt:
3204 return createCXString("LabelStmt");
Douglas Gregor42b29842011-10-05 19:00:14 +00003205 case CXCursor_CompoundStmt:
3206 return createCXString("CompoundStmt");
3207 case CXCursor_CaseStmt:
3208 return createCXString("CaseStmt");
3209 case CXCursor_DefaultStmt:
3210 return createCXString("DefaultStmt");
3211 case CXCursor_IfStmt:
3212 return createCXString("IfStmt");
3213 case CXCursor_SwitchStmt:
3214 return createCXString("SwitchStmt");
3215 case CXCursor_WhileStmt:
3216 return createCXString("WhileStmt");
3217 case CXCursor_DoStmt:
3218 return createCXString("DoStmt");
3219 case CXCursor_ForStmt:
3220 return createCXString("ForStmt");
3221 case CXCursor_GotoStmt:
3222 return createCXString("GotoStmt");
3223 case CXCursor_IndirectGotoStmt:
3224 return createCXString("IndirectGotoStmt");
3225 case CXCursor_ContinueStmt:
3226 return createCXString("ContinueStmt");
3227 case CXCursor_BreakStmt:
3228 return createCXString("BreakStmt");
3229 case CXCursor_ReturnStmt:
3230 return createCXString("ReturnStmt");
3231 case CXCursor_AsmStmt:
3232 return createCXString("AsmStmt");
3233 case CXCursor_ObjCAtTryStmt:
3234 return createCXString("ObjCAtTryStmt");
3235 case CXCursor_ObjCAtCatchStmt:
3236 return createCXString("ObjCAtCatchStmt");
3237 case CXCursor_ObjCAtFinallyStmt:
3238 return createCXString("ObjCAtFinallyStmt");
3239 case CXCursor_ObjCAtThrowStmt:
3240 return createCXString("ObjCAtThrowStmt");
3241 case CXCursor_ObjCAtSynchronizedStmt:
3242 return createCXString("ObjCAtSynchronizedStmt");
3243 case CXCursor_ObjCAutoreleasePoolStmt:
3244 return createCXString("ObjCAutoreleasePoolStmt");
3245 case CXCursor_ObjCForCollectionStmt:
3246 return createCXString("ObjCForCollectionStmt");
3247 case CXCursor_CXXCatchStmt:
3248 return createCXString("CXXCatchStmt");
3249 case CXCursor_CXXTryStmt:
3250 return createCXString("CXXTryStmt");
3251 case CXCursor_CXXForRangeStmt:
3252 return createCXString("CXXForRangeStmt");
3253 case CXCursor_SEHTryStmt:
3254 return createCXString("SEHTryStmt");
3255 case CXCursor_SEHExceptStmt:
3256 return createCXString("SEHExceptStmt");
3257 case CXCursor_SEHFinallyStmt:
3258 return createCXString("SEHFinallyStmt");
3259 case CXCursor_NullStmt:
3260 return createCXString("NullStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003261 case CXCursor_InvalidFile:
3262 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00003263 case CXCursor_InvalidCode:
3264 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003265 case CXCursor_NoDeclFound:
3266 return createCXString("NoDeclFound");
3267 case CXCursor_NotImplemented:
3268 return createCXString("NotImplemented");
3269 case CXCursor_TranslationUnit:
3270 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00003271 case CXCursor_UnexposedAttr:
3272 return createCXString("UnexposedAttr");
3273 case CXCursor_IBActionAttr:
3274 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003275 case CXCursor_IBOutletAttr:
3276 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003277 case CXCursor_IBOutletCollectionAttr:
3278 return createCXString("attribute(iboutletcollection)");
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00003279 case CXCursor_CXXFinalAttr:
3280 return createCXString("attribute(final)");
3281 case CXCursor_CXXOverrideAttr:
3282 return createCXString("attribute(override)");
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00003283 case CXCursor_AnnotateAttr:
3284 return createCXString("attribute(annotate)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003285 case CXCursor_PreprocessingDirective:
3286 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003287 case CXCursor_MacroDefinition:
3288 return createCXString("macro definition");
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003289 case CXCursor_MacroExpansion:
3290 return createCXString("macro expansion");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003291 case CXCursor_InclusionDirective:
3292 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003293 case CXCursor_Namespace:
3294 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003295 case CXCursor_LinkageSpec:
3296 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003297 case CXCursor_CXXBaseSpecifier:
3298 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003299 case CXCursor_Constructor:
3300 return createCXString("CXXConstructor");
3301 case CXCursor_Destructor:
3302 return createCXString("CXXDestructor");
3303 case CXCursor_ConversionFunction:
3304 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003305 case CXCursor_TemplateTypeParameter:
3306 return createCXString("TemplateTypeParameter");
3307 case CXCursor_NonTypeTemplateParameter:
3308 return createCXString("NonTypeTemplateParameter");
3309 case CXCursor_TemplateTemplateParameter:
3310 return createCXString("TemplateTemplateParameter");
3311 case CXCursor_FunctionTemplate:
3312 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003313 case CXCursor_ClassTemplate:
3314 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003315 case CXCursor_ClassTemplatePartialSpecialization:
3316 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003317 case CXCursor_NamespaceAlias:
3318 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003319 case CXCursor_UsingDirective:
3320 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003321 case CXCursor_UsingDeclaration:
3322 return createCXString("UsingDeclaration");
Richard Smith162e1c12011-04-15 14:24:37 +00003323 case CXCursor_TypeAliasDecl:
Douglas Gregor352697a2011-06-03 23:08:58 +00003324 return createCXString("TypeAliasDecl");
3325 case CXCursor_ObjCSynthesizeDecl:
3326 return createCXString("ObjCSynthesizeDecl");
3327 case CXCursor_ObjCDynamicDecl:
3328 return createCXString("ObjCDynamicDecl");
Argyrios Kyrtzidis2dfdb942011-09-30 17:58:23 +00003329 case CXCursor_CXXAccessSpecifier:
3330 return createCXString("CXXAccessSpecifier");
Steve Naroff89922f82009-08-31 00:59:03 +00003331 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003332
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003333 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneka60ed472010-11-16 08:15:36 +00003334 return createCXString((const char*) 0);
Steve Naroff600866c2009-08-27 19:51:58 +00003335}
Steve Naroff89922f82009-08-31 00:59:03 +00003336
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003337struct GetCursorData {
3338 SourceLocation TokenBeginLoc;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003339 bool PointsAtMacroArgExpansion;
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003340 CXCursor &BestCursor;
3341
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003342 GetCursorData(SourceManager &SM,
3343 SourceLocation tokenBegin, CXCursor &outputCursor)
3344 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
3345 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
3346 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003347};
3348
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003349static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3350 CXCursor parent,
3351 CXClientData client_data) {
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003352 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
3353 CXCursor *BestCursor = &Data->BestCursor;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003354
3355 // If we point inside a macro argument we should provide info of what the
3356 // token is so use the actual cursor, don't replace it with a macro expansion
3357 // cursor.
3358 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
3359 return CXChildVisit_Recurse;
Argyrios Kyrtzidis65ab9072011-09-26 19:05:37 +00003360
3361 if (clang_isDeclaration(cursor.kind)) {
3362 // Avoid having the implicit methods override the property decls.
3363 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(getCursorDecl(cursor)))
3364 if (MD->isImplicit())
3365 return CXChildVisit_Break;
3366 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003367
3368 if (clang_isExpression(cursor.kind) &&
3369 clang_isDeclaration(BestCursor->kind)) {
3370 Decl *D = getCursorDecl(*BestCursor);
3371
3372 // Avoid having the cursor of an expression replace the declaration cursor
3373 // when the expression source range overlaps the declaration range.
3374 // This can happen for C++ constructor expressions whose range generally
3375 // include the variable declaration, e.g.:
3376 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
3377 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
3378 D->getLocation() == Data->TokenBeginLoc)
3379 return CXChildVisit_Break;
3380 }
3381
Douglas Gregor93798e22010-11-05 21:11:19 +00003382 // If our current best cursor is the construction of a temporary object,
3383 // don't replace that cursor with a type reference, because we want
3384 // clang_getCursor() to point at the constructor.
3385 if (clang_isExpression(BestCursor->kind) &&
3386 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003387 cursor.kind == CXCursor_TypeRef) {
3388 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
3389 // as having the actual point on the type reference.
3390 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
Douglas Gregor93798e22010-11-05 21:11:19 +00003391 return CXChildVisit_Recurse;
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003392 }
Douglas Gregor93798e22010-11-05 21:11:19 +00003393
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003394 *BestCursor = cursor;
3395 return CXChildVisit_Recurse;
3396}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003397
Douglas Gregorb9790342010-01-22 21:44:22 +00003398CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3399 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003400 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003401
Ted Kremeneka60ed472010-11-16 08:15:36 +00003402 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003403 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3404
Ted Kremeneka297de22010-01-25 22:34:44 +00003405 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003406 CXCursor Result = cxcursor::getCursor(TU, SLoc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003407
Douglas Gregor40749ee2010-11-03 00:35:38 +00003408 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregor40749ee2010-11-03 00:35:38 +00003409 if (Logging) {
3410 CXFile SearchFile;
3411 unsigned SearchLine, SearchColumn;
3412 CXFile ResultFile;
3413 unsigned ResultLine, ResultColumn;
Douglas Gregor66537982010-11-17 17:14:07 +00003414 CXString SearchFileName, ResultFileName, KindSpelling, USR;
3415 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
Douglas Gregor40749ee2010-11-03 00:35:38 +00003416 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3417
Chandler Carruth20174222011-08-31 16:53:37 +00003418 clang_getExpansionLocation(Loc, &SearchFile, &SearchLine, &SearchColumn, 0);
3419 clang_getExpansionLocation(ResultLoc, &ResultFile, &ResultLine,
3420 &ResultColumn, 0);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003421 SearchFileName = clang_getFileName(SearchFile);
3422 ResultFileName = clang_getFileName(ResultFile);
3423 KindSpelling = clang_getCursorKindSpelling(Result.kind);
Douglas Gregor66537982010-11-17 17:14:07 +00003424 USR = clang_getCursorUSR(Result);
3425 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n",
Douglas Gregor40749ee2010-11-03 00:35:38 +00003426 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3427 clang_getCString(KindSpelling),
Douglas Gregor66537982010-11-17 17:14:07 +00003428 clang_getCString(ResultFileName), ResultLine, ResultColumn,
3429 clang_getCString(USR), IsDef);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003430 clang_disposeString(SearchFileName);
3431 clang_disposeString(ResultFileName);
3432 clang_disposeString(KindSpelling);
Douglas Gregor66537982010-11-17 17:14:07 +00003433 clang_disposeString(USR);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003434
3435 CXCursor Definition = clang_getCursorDefinition(Result);
3436 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
3437 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
3438 CXString DefinitionKindSpelling
3439 = clang_getCursorKindSpelling(Definition.kind);
3440 CXFile DefinitionFile;
3441 unsigned DefinitionLine, DefinitionColumn;
Chandler Carruth20174222011-08-31 16:53:37 +00003442 clang_getExpansionLocation(DefinitionLoc, &DefinitionFile,
3443 &DefinitionLine, &DefinitionColumn, 0);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003444 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
3445 fprintf(stderr, " -> %s(%s:%d:%d)\n",
3446 clang_getCString(DefinitionKindSpelling),
3447 clang_getCString(DefinitionFileName),
3448 DefinitionLine, DefinitionColumn);
3449 clang_disposeString(DefinitionFileName);
3450 clang_disposeString(DefinitionKindSpelling);
3451 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003452 }
3453
Ted Kremeneke68fff62010-02-17 00:41:32 +00003454 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003455}
3456
Ted Kremenek73885552009-11-17 19:28:59 +00003457CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003458 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003459}
3460
3461unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003462 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003463}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003464
Douglas Gregor9ce55842010-11-20 00:09:34 +00003465unsigned clang_hashCursor(CXCursor C) {
3466 unsigned Index = 0;
3467 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
3468 Index = 1;
3469
3470 return llvm::DenseMapInfo<std::pair<unsigned, void*> >::getHashValue(
3471 std::make_pair(C.kind, C.data[Index]));
3472}
3473
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003474unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003475 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3476}
3477
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003478unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003479 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3480}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003481
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003482unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003483 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3484}
3485
Douglas Gregor97b98722010-01-19 23:20:36 +00003486unsigned clang_isExpression(enum CXCursorKind K) {
3487 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3488}
3489
3490unsigned clang_isStatement(enum CXCursorKind K) {
3491 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3492}
3493
Douglas Gregor8be80e12011-07-06 03:00:34 +00003494unsigned clang_isAttribute(enum CXCursorKind K) {
3495 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
3496}
3497
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003498unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3499 return K == CXCursor_TranslationUnit;
3500}
3501
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003502unsigned clang_isPreprocessing(enum CXCursorKind K) {
3503 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3504}
3505
Ted Kremenekad6eff62010-03-08 21:17:29 +00003506unsigned clang_isUnexposed(enum CXCursorKind K) {
3507 switch (K) {
3508 case CXCursor_UnexposedDecl:
3509 case CXCursor_UnexposedExpr:
3510 case CXCursor_UnexposedStmt:
3511 case CXCursor_UnexposedAttr:
3512 return true;
3513 default:
3514 return false;
3515 }
3516}
3517
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003518CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003519 return C.kind;
3520}
3521
Douglas Gregor98258af2010-01-18 22:46:11 +00003522CXSourceLocation clang_getCursorLocation(CXCursor C) {
3523 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003524 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003525 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003526 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3527 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003528 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003529 }
3530
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003531 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003532 std::pair<ObjCProtocolDecl *, SourceLocation> P
3533 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003534 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003535 }
3536
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003537 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003538 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3539 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003540 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003541 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003542
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003543 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003544 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003545 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003546 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003547
3548 case CXCursor_TemplateRef: {
3549 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3550 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3551 }
3552
Douglas Gregor69319002010-08-31 23:48:11 +00003553 case CXCursor_NamespaceRef: {
3554 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3555 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3556 }
3557
Douglas Gregora67e03f2010-09-09 21:42:20 +00003558 case CXCursor_MemberRef: {
3559 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3560 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3561 }
3562
Ted Kremenek3064ef92010-08-27 21:34:58 +00003563 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003564 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3565 if (!BaseSpec)
3566 return clang_getNullLocation();
3567
3568 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3569 return cxloc::translateSourceLocation(getCursorContext(C),
3570 TSInfo->getTypeLoc().getBeginLoc());
3571
3572 return cxloc::translateSourceLocation(getCursorContext(C),
3573 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003574 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003575
Douglas Gregor36897b02010-09-10 00:22:18 +00003576 case CXCursor_LabelRef: {
3577 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3578 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3579 }
3580
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003581 case CXCursor_OverloadedDeclRef:
3582 return cxloc::translateSourceLocation(getCursorContext(C),
3583 getCursorOverloadedDeclRef(C).second);
3584
Douglas Gregorf46034a2010-01-18 23:41:10 +00003585 default:
3586 // FIXME: Need a way to enumerate all non-reference cases.
3587 llvm_unreachable("Missed a reference kind");
3588 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003589 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003590
3591 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003592 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003593 getLocationFromExpr(getCursorExpr(C)));
3594
Douglas Gregor36897b02010-09-10 00:22:18 +00003595 if (clang_isStatement(C.kind))
3596 return cxloc::translateSourceLocation(getCursorContext(C),
3597 getCursorStmt(C)->getLocStart());
3598
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003599 if (C.kind == CXCursor_PreprocessingDirective) {
3600 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3601 return cxloc::translateSourceLocation(getCursorContext(C), L);
3602 }
Douglas Gregor48072312010-03-18 15:23:44 +00003603
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003604 if (C.kind == CXCursor_MacroExpansion) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003605 SourceLocation L
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003606 = cxcursor::getCursorMacroExpansion(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003607 return cxloc::translateSourceLocation(getCursorContext(C), L);
3608 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003609
3610 if (C.kind == CXCursor_MacroDefinition) {
3611 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3612 return cxloc::translateSourceLocation(getCursorContext(C), L);
3613 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003614
3615 if (C.kind == CXCursor_InclusionDirective) {
3616 SourceLocation L
3617 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3618 return cxloc::translateSourceLocation(getCursorContext(C), L);
3619 }
3620
Ted Kremenek9a700d22010-05-12 06:16:13 +00003621 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003622 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003623
Douglas Gregorf46034a2010-01-18 23:41:10 +00003624 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003625 SourceLocation Loc = D->getLocation();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003626 // FIXME: Multiple variables declared in a single declaration
3627 // currently lack the information needed to correctly determine their
3628 // ranges when accounting for the type-specifier. We use context
3629 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3630 // and if so, whether it is the first decl.
3631 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3632 if (!cxcursor::isFirstInDeclGroup(C))
3633 Loc = VD->getLocation();
3634 }
3635
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003636 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003637}
Douglas Gregora7bde202010-01-19 00:34:46 +00003638
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003639} // end extern "C"
3640
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003641CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
3642 assert(TU);
3643
3644 // Guard against an invalid SourceLocation, or we may assert in one
3645 // of the following calls.
3646 if (SLoc.isInvalid())
3647 return clang_getNullCursor();
3648
3649 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
3650
3651 // Translate the given source location to make it point at the beginning of
3652 // the token under the cursor.
3653 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3654 CXXUnit->getASTContext().getLangOptions());
3655
3656 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3657 if (SLoc.isValid()) {
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003658 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003659 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
3660 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00003661 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003662 SourceLocation(SLoc));
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00003663 CursorVis.visitFileRegion();
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003664 }
3665
3666 return Result;
3667}
3668
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003669static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003670 if (clang_isReference(C.kind)) {
3671 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003672 case CXCursor_ObjCSuperClassRef:
3673 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003674
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003675 case CXCursor_ObjCProtocolRef:
3676 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003677
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003678 case CXCursor_ObjCClassRef:
3679 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003680
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003681 case CXCursor_TypeRef:
3682 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003683
3684 case CXCursor_TemplateRef:
3685 return getCursorTemplateRef(C).second;
3686
Douglas Gregor69319002010-08-31 23:48:11 +00003687 case CXCursor_NamespaceRef:
3688 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003689
3690 case CXCursor_MemberRef:
3691 return getCursorMemberRef(C).second;
3692
Ted Kremenek3064ef92010-08-27 21:34:58 +00003693 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003694 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003695
Douglas Gregor36897b02010-09-10 00:22:18 +00003696 case CXCursor_LabelRef:
3697 return getCursorLabelRef(C).second;
3698
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003699 case CXCursor_OverloadedDeclRef:
3700 return getCursorOverloadedDeclRef(C).second;
3701
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003702 default:
3703 // FIXME: Need a way to enumerate all non-reference cases.
3704 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003705 }
3706 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003707
3708 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003709 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003710
3711 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003712 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003713
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00003714 if (clang_isAttribute(C.kind))
3715 return getCursorAttr(C)->getRange();
3716
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003717 if (C.kind == CXCursor_PreprocessingDirective)
3718 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003719
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00003720 if (C.kind == CXCursor_MacroExpansion) {
3721 ASTUnit *TU = getCursorASTUnit(C);
3722 SourceRange Range = cxcursor::getCursorMacroExpansion(C)->getSourceRange();
3723 return TU->mapRangeFromPreamble(Range);
3724 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003725
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00003726 if (C.kind == CXCursor_MacroDefinition) {
3727 ASTUnit *TU = getCursorASTUnit(C);
3728 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
3729 return TU->mapRangeFromPreamble(Range);
3730 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003731
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00003732 if (C.kind == CXCursor_InclusionDirective) {
3733 ASTUnit *TU = getCursorASTUnit(C);
3734 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3735 return TU->mapRangeFromPreamble(Range);
3736 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003737
Ted Kremenek007a7c92010-11-01 23:26:51 +00003738 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3739 Decl *D = cxcursor::getCursorDecl(C);
3740 SourceRange R = D->getSourceRange();
3741 // FIXME: Multiple variables declared in a single declaration
3742 // currently lack the information needed to correctly determine their
3743 // ranges when accounting for the type-specifier. We use context
3744 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3745 // and if so, whether it is the first decl.
3746 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3747 if (!cxcursor::isFirstInDeclGroup(C))
3748 R.setBegin(VD->getLocation());
3749 }
3750 return R;
3751 }
Douglas Gregor66537982010-11-17 17:14:07 +00003752 return SourceRange();
3753}
3754
3755/// \brief Retrieves the "raw" cursor extent, which is then extended to include
3756/// the decl-specifier-seq for declarations.
3757static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
3758 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3759 Decl *D = cxcursor::getCursorDecl(C);
3760 SourceRange R = D->getSourceRange();
Douglas Gregor66537982010-11-17 17:14:07 +00003761
Douglas Gregor2494dd02011-03-01 01:34:45 +00003762 // Adjust the start of the location for declarations preceded by
3763 // declaration specifiers.
3764 SourceLocation StartLoc;
3765 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
3766 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
3767 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
3768 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
3769 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
3770 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
3771 }
3772
3773 if (StartLoc.isValid() && R.getBegin().isValid() &&
3774 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
3775 R.setBegin(StartLoc);
3776
3777 // FIXME: Multiple variables declared in a single declaration
3778 // currently lack the information needed to correctly determine their
3779 // ranges when accounting for the type-specifier. We use context
3780 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3781 // and if so, whether it is the first decl.
3782 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3783 if (!cxcursor::isFirstInDeclGroup(C))
3784 R.setBegin(VD->getLocation());
Douglas Gregor66537982010-11-17 17:14:07 +00003785 }
3786
3787 return R;
3788 }
3789
3790 return getRawCursorExtent(C);
3791}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003792
3793extern "C" {
3794
3795CXSourceRange clang_getCursorExtent(CXCursor C) {
3796 SourceRange R = getRawCursorExtent(C);
3797 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003798 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003799
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003800 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003801}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003802
3803CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003804 if (clang_isInvalid(C.kind))
3805 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003806
Ted Kremeneka60ed472010-11-16 08:15:36 +00003807 CXTranslationUnit tu = getCursorTU(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003808 if (clang_isDeclaration(C.kind)) {
3809 Decl *D = getCursorDecl(C);
3810 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003811 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003812 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003813 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003814 if (ObjCForwardProtocolDecl *Protocols
3815 = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003816 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), tu);
Chris Lattner5f9e2722011-07-23 10:55:15 +00003817 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00003818 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3819 return MakeCXCursor(Property, tu);
3820
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003821 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003822 }
3823
Douglas Gregor97b98722010-01-19 23:20:36 +00003824 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003825 Expr *E = getCursorExpr(C);
3826 Decl *D = getDeclFromExpr(E);
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003827 if (D) {
3828 CXCursor declCursor = MakeCXCursor(D, tu);
3829 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
3830 declCursor);
3831 return declCursor;
3832 }
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003833
3834 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003835 return MakeCursorOverloadedDeclRef(Ovl, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003836
Douglas Gregor97b98722010-01-19 23:20:36 +00003837 return clang_getNullCursor();
3838 }
3839
Douglas Gregor36897b02010-09-10 00:22:18 +00003840 if (clang_isStatement(C.kind)) {
3841 Stmt *S = getCursorStmt(C);
3842 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Ted Kremenek37c2e962011-03-15 23:47:49 +00003843 if (LabelDecl *label = Goto->getLabel())
3844 if (LabelStmt *labelS = label->getStmt())
3845 return MakeCXCursor(labelS, getCursorDecl(C), tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003846
3847 return clang_getNullCursor();
3848 }
3849
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003850 if (C.kind == CXCursor_MacroExpansion) {
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003851 if (MacroDefinition *Def = getCursorMacroExpansion(C)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003852 return MakeMacroDefinitionCursor(Def, tu);
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003853 }
3854
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003855 if (!clang_isReference(C.kind))
3856 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003857
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003858 switch (C.kind) {
3859 case CXCursor_ObjCSuperClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003860 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003861
3862 case CXCursor_ObjCProtocolRef: {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003863 return MakeCXCursor(getCursorObjCProtocolRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003864
3865 case CXCursor_ObjCClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003866 return MakeCXCursor(getCursorObjCClassRef(C).first, tu );
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003867
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003868 case CXCursor_TypeRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003869 return MakeCXCursor(getCursorTypeRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003870
3871 case CXCursor_TemplateRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003872 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003873
Douglas Gregor69319002010-08-31 23:48:11 +00003874 case CXCursor_NamespaceRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003875 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
Douglas Gregor69319002010-08-31 23:48:11 +00003876
Douglas Gregora67e03f2010-09-09 21:42:20 +00003877 case CXCursor_MemberRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003878 return MakeCXCursor(getCursorMemberRef(C).first, tu );
Douglas Gregora67e03f2010-09-09 21:42:20 +00003879
Ted Kremenek3064ef92010-08-27 21:34:58 +00003880 case CXCursor_CXXBaseSpecifier: {
3881 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3882 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003883 tu ));
Ted Kremenek3064ef92010-08-27 21:34:58 +00003884 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003885
Douglas Gregor36897b02010-09-10 00:22:18 +00003886 case CXCursor_LabelRef:
3887 // FIXME: We end up faking the "parent" declaration here because we
3888 // don't want to make CXCursor larger.
3889 return MakeCXCursor(getCursorLabelRef(C).first,
Ted Kremeneka60ed472010-11-16 08:15:36 +00003890 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
3891 .getTranslationUnitDecl(),
3892 tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003893
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003894 case CXCursor_OverloadedDeclRef:
3895 return C;
3896
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003897 default:
3898 // We would prefer to enumerate all non-reference cursor kinds here.
3899 llvm_unreachable("Unhandled reference cursor kind");
3900 break;
3901 }
3902 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003903
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003904 return clang_getNullCursor();
3905}
3906
Douglas Gregorb6998662010-01-19 19:34:47 +00003907CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003908 if (clang_isInvalid(C.kind))
3909 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003910
Ted Kremeneka60ed472010-11-16 08:15:36 +00003911 CXTranslationUnit TU = getCursorTU(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003912
Douglas Gregorb6998662010-01-19 19:34:47 +00003913 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003914 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003915 C = clang_getCursorReferenced(C);
3916 WasReference = true;
3917 }
3918
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003919 if (C.kind == CXCursor_MacroExpansion)
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003920 return clang_getCursorReferenced(C);
3921
Douglas Gregorb6998662010-01-19 19:34:47 +00003922 if (!clang_isDeclaration(C.kind))
3923 return clang_getNullCursor();
3924
3925 Decl *D = getCursorDecl(C);
3926 if (!D)
3927 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003928
Douglas Gregorb6998662010-01-19 19:34:47 +00003929 switch (D->getKind()) {
3930 // Declaration kinds that don't really separate the notions of
3931 // declaration and definition.
3932 case Decl::Namespace:
3933 case Decl::Typedef:
Richard Smith162e1c12011-04-15 14:24:37 +00003934 case Decl::TypeAlias:
Richard Smith3e4c6c42011-05-05 21:57:07 +00003935 case Decl::TypeAliasTemplate:
Douglas Gregorb6998662010-01-19 19:34:47 +00003936 case Decl::TemplateTypeParm:
3937 case Decl::EnumConstant:
3938 case Decl::Field:
Benjamin Kramerd9811462010-11-21 14:11:41 +00003939 case Decl::IndirectField:
Douglas Gregorb6998662010-01-19 19:34:47 +00003940 case Decl::ObjCIvar:
3941 case Decl::ObjCAtDefsField:
3942 case Decl::ImplicitParam:
3943 case Decl::ParmVar:
3944 case Decl::NonTypeTemplateParm:
3945 case Decl::TemplateTemplateParm:
3946 case Decl::ObjCCategoryImpl:
3947 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00003948 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00003949 case Decl::LinkageSpec:
3950 case Decl::ObjCPropertyImpl:
3951 case Decl::FileScopeAsm:
3952 case Decl::StaticAssert:
3953 case Decl::Block:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003954 case Decl::Label: // FIXME: Is this right??
Francois Pichetaf0f4d02011-08-14 03:52:19 +00003955 case Decl::ClassScopeFunctionSpecialization:
Douglas Gregorb6998662010-01-19 19:34:47 +00003956 return C;
3957
3958 // Declaration kinds that don't make any sense here, but are
3959 // nonetheless harmless.
3960 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00003961 break;
3962
3963 // Declaration kinds for which the definition is not resolvable.
3964 case Decl::UnresolvedUsingTypename:
3965 case Decl::UnresolvedUsingValue:
3966 break;
3967
3968 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003969 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003970 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003971
3972 case Decl::NamespaceAlias:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003973 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003974
3975 case Decl::Enum:
3976 case Decl::Record:
3977 case Decl::CXXRecord:
3978 case Decl::ClassTemplateSpecialization:
3979 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00003980 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003981 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003982 return clang_getNullCursor();
3983
3984 case Decl::Function:
3985 case Decl::CXXMethod:
3986 case Decl::CXXConstructor:
3987 case Decl::CXXDestructor:
3988 case Decl::CXXConversion: {
3989 const FunctionDecl *Def = 0;
3990 if (cast<FunctionDecl>(D)->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003991 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003992 return clang_getNullCursor();
3993 }
3994
3995 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00003996 // Ask the variable if it has a definition.
3997 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003998 return MakeCXCursor(Def, TU);
Sebastian Redl31310a22010-02-01 20:16:42 +00003999 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00004000 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004001
Douglas Gregorb6998662010-01-19 19:34:47 +00004002 case Decl::FunctionTemplate: {
4003 const FunctionDecl *Def = 0;
4004 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004005 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004006 return clang_getNullCursor();
4007 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004008
Douglas Gregorb6998662010-01-19 19:34:47 +00004009 case Decl::ClassTemplate: {
4010 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00004011 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00004012 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004013 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004014 return clang_getNullCursor();
4015 }
4016
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004017 case Decl::Using:
4018 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004019 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004020
4021 case Decl::UsingShadow:
4022 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004023 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004024 TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004025
4026 case Decl::ObjCMethod: {
4027 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
4028 if (Method->isThisDeclarationADefinition())
4029 return C;
4030
4031 // Dig out the method definition in the associated
4032 // @implementation, if we have it.
4033 // FIXME: The ASTs should make finding the definition easier.
4034 if (ObjCInterfaceDecl *Class
4035 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
4036 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
4037 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
4038 Method->isInstanceMethod()))
4039 if (Def->isThisDeclarationADefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004040 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004041
4042 return clang_getNullCursor();
4043 }
4044
4045 case Decl::ObjCCategory:
4046 if (ObjCCategoryImplDecl *Impl
4047 = cast<ObjCCategoryDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004048 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004049 return clang_getNullCursor();
4050
4051 case Decl::ObjCProtocol:
4052 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
4053 return C;
4054 return clang_getNullCursor();
4055
4056 case Decl::ObjCInterface:
4057 // There are two notions of a "definition" for an Objective-C
4058 // class: the interface and its implementation. When we resolved a
4059 // reference to an Objective-C class, produce the @interface as
4060 // the definition; when we were provided with the interface,
4061 // produce the @implementation as the definition.
4062 if (WasReference) {
4063 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
4064 return C;
4065 } else if (ObjCImplementationDecl *Impl
4066 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004067 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004068 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004069
Douglas Gregorb6998662010-01-19 19:34:47 +00004070 case Decl::ObjCProperty:
4071 // FIXME: We don't really know where to find the
4072 // ObjCPropertyImplDecls that implement this property.
4073 return clang_getNullCursor();
4074
4075 case Decl::ObjCCompatibleAlias:
4076 if (ObjCInterfaceDecl *Class
4077 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
4078 if (!Class->isForwardDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004079 return MakeCXCursor(Class, TU);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004080
Douglas Gregorb6998662010-01-19 19:34:47 +00004081 return clang_getNullCursor();
4082
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004083 case Decl::ObjCForwardProtocol:
4084 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004085 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004086
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004087 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004088 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004089 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004090
4091 case Decl::Friend:
4092 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004093 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004094 return clang_getNullCursor();
4095
4096 case Decl::FriendTemplate:
4097 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004098 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004099 return clang_getNullCursor();
4100 }
4101
4102 return clang_getNullCursor();
4103}
4104
4105unsigned clang_isCursorDefinition(CXCursor C) {
4106 if (!clang_isDeclaration(C.kind))
4107 return 0;
4108
4109 return clang_getCursorDefinition(C) == C;
4110}
4111
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004112CXCursor clang_getCanonicalCursor(CXCursor C) {
4113 if (!clang_isDeclaration(C.kind))
4114 return C;
4115
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004116 if (Decl *D = getCursorDecl(C)) {
Argyrios Kyrtzidisdebb00f2011-07-15 22:37:58 +00004117 if (ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
4118 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
4119 return MakeCXCursor(CatD, getCursorTU(C));
4120
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004121 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
4122 if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
4123 return MakeCXCursor(IFD, getCursorTU(C));
4124
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004125 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004126 }
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004127
4128 return C;
4129}
4130
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004131unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004132 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004133 return 0;
4134
4135 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
4136 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
4137 return E->getNumDecls();
4138
4139 if (OverloadedTemplateStorage *S
4140 = Storage.dyn_cast<OverloadedTemplateStorage*>())
4141 return S->size();
4142
4143 Decl *D = Storage.get<Decl*>();
4144 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00004145 return Using->shadow_size();
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00004146 if (isa<ObjCClassDecl>(D))
4147 return 1;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004148 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
4149 return Protocols->protocol_size();
4150
4151 return 0;
4152}
4153
4154CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004155 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004156 return clang_getNullCursor();
4157
4158 if (index >= clang_getNumOverloadedDecls(cursor))
4159 return clang_getNullCursor();
4160
Ted Kremeneka60ed472010-11-16 08:15:36 +00004161 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004162 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
4163 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004164 return MakeCXCursor(E->decls_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004165
4166 if (OverloadedTemplateStorage *S
4167 = Storage.dyn_cast<OverloadedTemplateStorage*>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004168 return MakeCXCursor(S->begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004169
4170 Decl *D = Storage.get<Decl*>();
4171 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
4172 // FIXME: This is, unfortunately, linear time.
4173 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
4174 std::advance(Pos, index);
Ted Kremeneka60ed472010-11-16 08:15:36 +00004175 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004176 }
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004177 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00004178 return MakeCXCursor(Classes->getForwardInterfaceDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004179 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004180 return MakeCXCursor(Protocols->protocol_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004181
4182 return clang_getNullCursor();
4183}
4184
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00004185void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00004186 const char **startBuf,
4187 const char **endBuf,
4188 unsigned *startLine,
4189 unsigned *startColumn,
4190 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00004191 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00004192 assert(getCursorDecl(C) && "CXCursor has null decl");
4193 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00004194 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
4195 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004196
Steve Naroff4ade6d62009-09-23 17:52:52 +00004197 SourceManager &SM = FD->getASTContext().getSourceManager();
4198 *startBuf = SM.getCharacterData(Body->getLBracLoc());
4199 *endBuf = SM.getCharacterData(Body->getRBracLoc());
4200 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
4201 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
4202 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
4203 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
4204}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004205
Douglas Gregor430d7a12011-07-25 17:48:11 +00004206
4207CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
4208 unsigned PieceIndex) {
4209 RefNamePieces Pieces;
4210
4211 switch (C.kind) {
4212 case CXCursor_MemberRefExpr:
4213 if (MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
4214 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
4215 E->getQualifierLoc().getSourceRange());
4216 break;
4217
4218 case CXCursor_DeclRefExpr:
4219 if (DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C)))
4220 Pieces = buildPieces(NameFlags, false, E->getNameInfo(),
4221 E->getQualifierLoc().getSourceRange(),
4222 E->getExplicitTemplateArgsOpt());
4223 break;
4224
4225 case CXCursor_CallExpr:
4226 if (CXXOperatorCallExpr *OCE =
4227 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
4228 Expr *Callee = OCE->getCallee();
4229 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
4230 Callee = ICE->getSubExpr();
4231
4232 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
4233 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
4234 DRE->getQualifierLoc().getSourceRange());
4235 }
4236 break;
4237
4238 default:
4239 break;
4240 }
4241
4242 if (Pieces.empty()) {
4243 if (PieceIndex == 0)
4244 return clang_getCursorExtent(C);
4245 } else if (PieceIndex < Pieces.size()) {
4246 SourceRange R = Pieces[PieceIndex];
4247 if (R.isValid())
4248 return cxloc::translateSourceRange(getCursorContext(C), R);
4249 }
4250
4251 return clang_getNullRange();
4252}
4253
Douglas Gregor0a812cf2010-02-18 23:07:20 +00004254void clang_enableStackTraces(void) {
4255 llvm::sys::PrintStackTraceOnErrorSignal();
4256}
4257
Daniel Dunbar995aaf92010-11-04 01:26:29 +00004258void clang_executeOnThread(void (*fn)(void*), void *user_data,
4259 unsigned stack_size) {
4260 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
4261}
4262
Ted Kremenekfb480492010-01-13 21:46:36 +00004263} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00004264
Ted Kremenekfb480492010-01-13 21:46:36 +00004265//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004266// Token-based Operations.
4267//===----------------------------------------------------------------------===//
4268
4269/* CXToken layout:
4270 * int_data[0]: a CXTokenKind
4271 * int_data[1]: starting token location
4272 * int_data[2]: token length
4273 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004274 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004275 * otherwise unused.
4276 */
4277extern "C" {
4278
4279CXTokenKind clang_getTokenKind(CXToken CXTok) {
4280 return static_cast<CXTokenKind>(CXTok.int_data[0]);
4281}
4282
4283CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
4284 switch (clang_getTokenKind(CXTok)) {
4285 case CXToken_Identifier:
4286 case CXToken_Keyword:
4287 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004288 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
4289 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004290
4291 case CXToken_Literal: {
4292 // We have stashed the starting pointer in the ptr_data field. Use it.
4293 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Chris Lattner5f9e2722011-07-23 10:55:15 +00004294 return createCXString(StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004295 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004296
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004297 case CXToken_Punctuation:
4298 case CXToken_Comment:
4299 break;
4300 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004301
4302 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004303 // deconstructing the source location.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004304 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004305 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004306 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004307
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004308 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
4309 std::pair<FileID, unsigned> LocInfo
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004310 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00004311 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004312 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004313 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
4314 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00004315 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004316
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004317 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004318}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004319
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004320CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004321 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004322 if (!CXXUnit)
4323 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004324
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004325 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
4326 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4327}
4328
4329CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004330 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor5352ac02010-01-28 00:27:43 +00004331 if (!CXXUnit)
4332 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004333
4334 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004335 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4336}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004337
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004338static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
4339 SmallVectorImpl<CXToken> &CXTokens) {
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004340 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4341 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004342 = SourceMgr.getDecomposedLoc(Range.getBegin());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004343 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004344 = SourceMgr.getDecomposedLoc(Range.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004345
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004346 // Cannot tokenize across files.
4347 if (BeginLocInfo.first != EndLocInfo.first)
4348 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004349
4350 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004351 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004352 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004353 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00004354 if (Invalid)
4355 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00004356
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004357 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4358 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004359 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004360 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004361
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004362 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004363 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004364 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00004365 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004366 do {
4367 // Lex the next token
4368 Lex.LexFromRawLexer(Tok);
4369 if (Tok.is(tok::eof))
4370 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004371
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004372 // Initialize the CXToken.
4373 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004374
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004375 // - Common fields
4376 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
4377 CXTok.int_data[2] = Tok.getLength();
4378 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004379
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004380 // - Kind-specific fields
4381 if (Tok.isLiteral()) {
4382 CXTok.int_data[0] = CXToken_Literal;
4383 CXTok.ptr_data = (void *)Tok.getLiteralData();
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004384 } else if (Tok.is(tok::raw_identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00004385 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004386 IdentifierInfo *II
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004387 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004388
David Chisnall096428b2010-10-13 21:44:48 +00004389 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004390 CXTok.int_data[0] = CXToken_Keyword;
4391 }
4392 else {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004393 CXTok.int_data[0] = Tok.is(tok::identifier)
4394 ? CXToken_Identifier
4395 : CXToken_Keyword;
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004396 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004397 CXTok.ptr_data = II;
4398 } else if (Tok.is(tok::comment)) {
4399 CXTok.int_data[0] = CXToken_Comment;
4400 CXTok.ptr_data = 0;
4401 } else {
4402 CXTok.int_data[0] = CXToken_Punctuation;
4403 CXTok.ptr_data = 0;
4404 }
4405 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00004406 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004407 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004408}
4409
4410void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
4411 CXToken **Tokens, unsigned *NumTokens) {
4412 if (Tokens)
4413 *Tokens = 0;
4414 if (NumTokens)
4415 *NumTokens = 0;
4416
4417 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4418 if (!CXXUnit || !Tokens || !NumTokens)
4419 return;
4420
4421 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4422
4423 SourceRange R = cxloc::translateCXSourceRange(Range);
4424 if (R.isInvalid())
4425 return;
4426
4427 SmallVector<CXToken, 32> CXTokens;
4428 getTokens(CXXUnit, R, CXTokens);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004429
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004430 if (CXTokens.empty())
4431 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004432
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004433 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
4434 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
4435 *NumTokens = CXTokens.size();
4436}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004437
Ted Kremenek6db61092010-05-05 00:55:15 +00004438void clang_disposeTokens(CXTranslationUnit TU,
4439 CXToken *Tokens, unsigned NumTokens) {
4440 free(Tokens);
4441}
4442
4443} // end: extern "C"
4444
4445//===----------------------------------------------------------------------===//
4446// Token annotation APIs.
4447//===----------------------------------------------------------------------===//
4448
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004449typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004450static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4451 CXCursor parent,
4452 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00004453namespace {
4454class AnnotateTokensWorker {
4455 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004456 CXToken *Tokens;
4457 CXCursor *Cursors;
4458 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004459 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00004460 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004461 CursorVisitor AnnotateVis;
4462 SourceManager &SrcMgr;
Douglas Gregorf5251602011-03-08 17:10:18 +00004463 bool HasContextSensitiveKeywords;
4464
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004465 bool MoreTokens() const { return TokIdx < NumTokens; }
4466 unsigned NextToken() const { return TokIdx; }
4467 void AdvanceToken() { ++TokIdx; }
4468 SourceLocation GetTokenLoc(unsigned tokI) {
4469 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4470 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004471 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004472 return Tokens[tokI].int_data[3] != 0;
4473 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004474 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004475 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[3]);
4476 }
4477
4478 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004479 void annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
4480 SourceRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004481
Ted Kremenek6db61092010-05-05 00:55:15 +00004482public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00004483 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004484 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004485 CXTranslationUnit tu, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00004486 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00004487 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004488 AnnotateVis(tu,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00004489 AnnotateTokensVisitor, this,
4490 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00004491 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00004492 RegionOfInterest),
Douglas Gregorf5251602011-03-08 17:10:18 +00004493 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()),
4494 HasContextSensitiveKeywords(false) { }
Ted Kremenek11949cb2010-05-05 00:55:17 +00004495
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004496 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00004497 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004498 void AnnotateTokens(CXCursor parent);
Ted Kremenekab979612010-11-11 08:05:23 +00004499 void AnnotateTokens() {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004500 AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getTU()));
Ted Kremenekab979612010-11-11 08:05:23 +00004501 }
Douglas Gregorf5251602011-03-08 17:10:18 +00004502
4503 /// \brief Determine whether the annotator saw any cursors that have
4504 /// context-sensitive keywords.
4505 bool hasContextSensitiveKeywords() const {
4506 return HasContextSensitiveKeywords;
4507 }
Ted Kremenek6db61092010-05-05 00:55:15 +00004508};
4509}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004510
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004511void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
4512 // Walk the AST within the region of interest, annotating tokens
4513 // along the way.
4514 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00004515
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004516 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4517 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004518 if (Pos != Annotated.end() &&
4519 (clang_isInvalid(Cursors[I].kind) ||
4520 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004521 Cursors[I] = Pos->second;
4522 }
4523
4524 // Finish up annotating any tokens left.
4525 if (!MoreTokens())
4526 return;
4527
4528 const CXCursor &C = clang_getNullCursor();
4529 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
4530 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4531 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004532 }
4533}
4534
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004535/// \brief It annotates and advances tokens with a cursor until the comparison
4536//// between the cursor location and the source range is the same as
4537/// \arg compResult.
4538///
4539/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
4540/// Pass RangeOverlap to annotate tokens inside a range.
4541void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
4542 RangeComparisonResult compResult,
4543 SourceRange range) {
4544 while (MoreTokens()) {
4545 const unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004546 if (isFunctionMacroToken(I))
4547 return annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004548
4549 SourceLocation TokLoc = GetTokenLoc(I);
4550 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4551 Cursors[I] = updateC;
4552 AdvanceToken();
4553 continue;
4554 }
4555 break;
4556 }
4557}
4558
4559/// \brief Special annotation handling for macro argument tokens.
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004560void AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
4561 CXCursor updateC,
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004562 RangeComparisonResult compResult,
4563 SourceRange range) {
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004564 assert(MoreTokens());
4565 assert(isFunctionMacroToken(NextToken()) &&
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004566 "Should be called only for macro arg tokens");
4567
4568 // This works differently than annotateAndAdvanceTokens; because expanded
4569 // macro arguments can have arbitrary translation-unit source order, we do not
4570 // advance the token index one by one until a token fails the range test.
4571 // We only advance once past all of the macro arg tokens if all of them
4572 // pass the range test. If one of them fails we keep the token index pointing
4573 // at the start of the macro arg tokens so that the failing token will be
4574 // annotated by a subsequent annotation try.
4575
4576 bool atLeastOneCompFail = false;
4577
4578 unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004579 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
4580 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004581 if (TokLoc.isFileID())
4582 continue; // not macro arg token, it's parens or comma.
4583 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4584 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
4585 Cursors[I] = updateC;
4586 } else
4587 atLeastOneCompFail = true;
4588 }
4589
4590 if (!atLeastOneCompFail)
4591 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
4592}
4593
Ted Kremenek6db61092010-05-05 00:55:15 +00004594enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004595AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004596 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004597 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004598 if (cursorRange.isInvalid())
4599 return CXChildVisit_Recurse;
Douglas Gregorf5251602011-03-08 17:10:18 +00004600
4601 if (!HasContextSensitiveKeywords) {
4602 // Objective-C properties can have context-sensitive keywords.
4603 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
4604 if (ObjCPropertyDecl *Property
4605 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
4606 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
4607 }
4608 // Objective-C methods can have context-sensitive keywords.
4609 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
4610 cursor.kind == CXCursor_ObjCClassMethodDecl) {
4611 if (ObjCMethodDecl *Method
4612 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
4613 if (Method->getObjCDeclQualifier())
4614 HasContextSensitiveKeywords = true;
4615 else {
4616 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
4617 PEnd = Method->param_end();
4618 P != PEnd; ++P) {
4619 if ((*P)->getObjCDeclQualifier()) {
4620 HasContextSensitiveKeywords = true;
4621 break;
4622 }
4623 }
4624 }
4625 }
4626 }
4627 // C++ methods can have context-sensitive keywords.
4628 else if (cursor.kind == CXCursor_CXXMethod) {
4629 if (CXXMethodDecl *Method
4630 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
4631 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
4632 HasContextSensitiveKeywords = true;
4633 }
4634 }
4635 // C++ classes can have context-sensitive keywords.
4636 else if (cursor.kind == CXCursor_StructDecl ||
4637 cursor.kind == CXCursor_ClassDecl ||
4638 cursor.kind == CXCursor_ClassTemplate ||
4639 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
4640 if (Decl *D = getCursorDecl(cursor))
4641 if (D->hasAttr<FinalAttr>())
4642 HasContextSensitiveKeywords = true;
4643 }
4644 }
4645
Douglas Gregor4419b672010-10-21 06:10:04 +00004646 if (clang_isPreprocessing(cursor.kind)) {
Chandler Carruthcea731a2011-07-14 16:07:57 +00004647 // For macro expansions, just note where the beginning of the macro
4648 // expansion occurs.
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004649 if (cursor.kind == CXCursor_MacroExpansion) {
Douglas Gregor4419b672010-10-21 06:10:04 +00004650 Annotated[Loc.int_data] = cursor;
4651 return CXChildVisit_Recurse;
4652 }
4653
Douglas Gregor4419b672010-10-21 06:10:04 +00004654 // Items in the preprocessing record are kept separate from items in
4655 // declarations, so we keep a separate token index.
4656 unsigned SavedTokIdx = TokIdx;
4657 TokIdx = PreprocessingTokIdx;
4658
4659 // Skip tokens up until we catch up to the beginning of the preprocessing
4660 // entry.
4661 while (MoreTokens()) {
4662 const unsigned I = NextToken();
4663 SourceLocation TokLoc = GetTokenLoc(I);
4664 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4665 case RangeBefore:
4666 AdvanceToken();
4667 continue;
4668 case RangeAfter:
4669 case RangeOverlap:
4670 break;
4671 }
4672 break;
4673 }
4674
4675 // Look at all of the tokens within this range.
4676 while (MoreTokens()) {
4677 const unsigned I = NextToken();
4678 SourceLocation TokLoc = GetTokenLoc(I);
4679 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4680 case RangeBefore:
David Blaikieb219cfc2011-09-23 05:06:16 +00004681 llvm_unreachable("Infeasible");
Douglas Gregor4419b672010-10-21 06:10:04 +00004682 case RangeAfter:
4683 break;
4684 case RangeOverlap:
4685 Cursors[I] = cursor;
4686 AdvanceToken();
4687 continue;
4688 }
4689 break;
4690 }
4691
4692 // Save the preprocessing token index; restore the non-preprocessing
4693 // token index.
4694 PreprocessingTokIdx = TokIdx;
4695 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004696 return CXChildVisit_Recurse;
4697 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004698
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004699 if (cursorRange.isInvalid())
4700 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004701
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004702 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4703
Ted Kremeneka333c662010-05-12 05:29:33 +00004704 // Adjust the annotated range based specific declarations.
4705 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4706 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004707 Decl *D = cxcursor::getCursorDecl(cursor);
Douglas Gregor2494dd02011-03-01 01:34:45 +00004708
4709 SourceLocation StartLoc;
Ted Kremenek23173d72010-05-18 21:09:07 +00004710 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00004711 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
4712 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
4713 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
4714 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
4715 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
Ted Kremeneka333c662010-05-12 05:29:33 +00004716 }
Douglas Gregor2494dd02011-03-01 01:34:45 +00004717
4718 if (StartLoc.isValid() && L.isValid() &&
4719 SrcMgr.isBeforeInTranslationUnit(StartLoc, L))
4720 cursorRange.setBegin(StartLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004721 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004722
Ted Kremenek3f404602010-08-14 01:14:06 +00004723 // If the location of the cursor occurs within a macro instantiation, record
4724 // the spelling location of the cursor in our annotation map. We can then
4725 // paper over the token labelings during a post-processing step to try and
4726 // get cursor mappings for tokens that are the *arguments* of a macro
4727 // instantiation.
4728 if (L.isMacroID()) {
4729 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4730 // Only invalidate the old annotation if it isn't part of a preprocessing
4731 // directive. Here we assume that the default construction of CXCursor
4732 // results in CXCursor.kind being an initialized value (i.e., 0). If
4733 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004734
Ted Kremenek3f404602010-08-14 01:14:06 +00004735 CXCursor &oldC = Annotated[rawEncoding];
4736 if (!clang_isPreprocessing(oldC.kind))
4737 oldC = cursor;
4738 }
4739
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004740 const enum CXCursorKind K = clang_getCursorKind(parent);
4741 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004742 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4743 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004744
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004745 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004746
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00004747 // Avoid having the cursor of an expression "overwrite" the annotation of the
4748 // variable declaration that it belongs to.
4749 // This can happen for C++ constructor expressions whose range generally
4750 // include the variable declaration, e.g.:
4751 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
4752 if (clang_isExpression(cursorK)) {
4753 Expr *E = getCursorExpr(cursor);
Argyrios Kyrtzidis8ccac3d2011-06-29 22:20:07 +00004754 if (Decl *D = getCursorParentDecl(cursor)) {
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00004755 const unsigned I = NextToken();
4756 if (E->getLocStart().isValid() && D->getLocation().isValid() &&
4757 E->getLocStart() == D->getLocation() &&
4758 E->getLocStart() == GetTokenLoc(I)) {
4759 Cursors[I] = updateC;
4760 AdvanceToken();
4761 }
4762 }
4763 }
4764
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004765 // Visit children to get their cursor information.
4766 const unsigned BeforeChildren = NextToken();
4767 VisitChildren(cursor);
4768 const unsigned AfterChildren = NextToken();
4769
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004770 // Scan the tokens that are at the end of the cursor, but are not captured
4771 // but the child cursors.
4772 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
Ted Kremenek6db61092010-05-05 00:55:15 +00004773
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004774 // Scan the tokens that are at the beginning of the cursor, but are not
4775 // capture by the child cursors.
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004776 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4777 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4778 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004779
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004780 Cursors[I] = cursor;
4781 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004782
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004783 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004784}
4785
Ted Kremenek6db61092010-05-05 00:55:15 +00004786static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4787 CXCursor parent,
4788 CXClientData client_data) {
4789 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4790}
4791
Ted Kremenek6628a612011-03-18 22:51:30 +00004792namespace {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004793
4794/// \brief Uses the macro expansions in the preprocessing record to find
4795/// and mark tokens that are macro arguments. This info is used by the
4796/// AnnotateTokensWorker.
4797class MarkMacroArgTokensVisitor {
4798 SourceManager &SM;
4799 CXToken *Tokens;
4800 unsigned NumTokens;
4801 unsigned CurIdx;
4802
4803public:
4804 MarkMacroArgTokensVisitor(SourceManager &SM,
4805 CXToken *tokens, unsigned numTokens)
4806 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
4807
4808 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
4809 if (cursor.kind != CXCursor_MacroExpansion)
4810 return CXChildVisit_Continue;
4811
4812 SourceRange macroRange = getCursorMacroExpansion(cursor)->getSourceRange();
4813 if (macroRange.getBegin() == macroRange.getEnd())
4814 return CXChildVisit_Continue; // it's not a function macro.
4815
4816 for (; CurIdx < NumTokens; ++CurIdx) {
4817 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
4818 macroRange.getBegin()))
4819 break;
4820 }
4821
4822 if (CurIdx == NumTokens)
4823 return CXChildVisit_Break;
4824
4825 for (; CurIdx < NumTokens; ++CurIdx) {
4826 SourceLocation tokLoc = getTokenLoc(CurIdx);
4827 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
4828 break;
4829
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004830 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004831 }
4832
4833 if (CurIdx == NumTokens)
4834 return CXChildVisit_Break;
4835
4836 return CXChildVisit_Continue;
4837 }
4838
4839private:
4840 SourceLocation getTokenLoc(unsigned tokI) {
4841 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4842 }
4843
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004844 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004845 // The third field is reserved and currently not used. Use it here
4846 // to mark macro arg expanded tokens with their expanded locations.
4847 Tokens[tokI].int_data[3] = loc.getRawEncoding();
4848 }
4849};
4850
4851} // end anonymous namespace
4852
4853static CXChildVisitResult
4854MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
4855 CXClientData client_data) {
4856 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
4857 parent);
4858}
4859
4860namespace {
Ted Kremenek6628a612011-03-18 22:51:30 +00004861 struct clang_annotateTokens_Data {
4862 CXTranslationUnit TU;
4863 ASTUnit *CXXUnit;
4864 CXToken *Tokens;
4865 unsigned NumTokens;
4866 CXCursor *Cursors;
4867 };
4868}
4869
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004870static void annotatePreprocessorTokens(CXTranslationUnit TU,
4871 SourceRange RegionOfInterest,
4872 AnnotateTokensData &Annotated) {
4873 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4874
4875 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4876 std::pair<FileID, unsigned> BeginLocInfo
4877 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4878 std::pair<FileID, unsigned> EndLocInfo
4879 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
4880
4881 if (BeginLocInfo.first != EndLocInfo.first)
4882 return;
4883
4884 StringRef Buffer;
4885 bool Invalid = false;
4886 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
4887 if (Buffer.empty() || Invalid)
4888 return;
4889
4890 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4891 CXXUnit->getASTContext().getLangOptions(),
4892 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
4893 Buffer.end());
4894 Lex.SetCommentRetentionState(true);
4895
4896 // Lex tokens in raw mode until we hit the end of the range, to avoid
4897 // entering #includes or expanding macros.
4898 while (true) {
4899 Token Tok;
4900 Lex.LexFromRawLexer(Tok);
4901
4902 reprocess:
4903 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4904 // We have found a preprocessing directive. Gobble it up so that we
4905 // don't see it while preprocessing these tokens later, but keep track
4906 // of all of the token locations inside this preprocessing directive so
4907 // that we can annotate them appropriately.
4908 //
4909 // FIXME: Some simple tests here could identify macro definitions and
4910 // #undefs, to provide specific cursor kinds for those.
4911 SmallVector<SourceLocation, 32> Locations;
4912 do {
4913 Locations.push_back(Tok.getLocation());
4914 Lex.LexFromRawLexer(Tok);
4915 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
4916
4917 using namespace cxcursor;
4918 CXCursor Cursor
4919 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4920 Locations.back()),
4921 TU);
4922 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4923 Annotated[Locations[I].getRawEncoding()] = Cursor;
4924 }
4925
4926 if (Tok.isAtStartOfLine())
4927 goto reprocess;
4928
4929 continue;
4930 }
4931
4932 if (Tok.is(tok::eof))
4933 break;
4934 }
4935}
4936
Ted Kremenekab979612010-11-11 08:05:23 +00004937// This gets run a separate thread to avoid stack blowout.
Ted Kremenek6628a612011-03-18 22:51:30 +00004938static void clang_annotateTokensImpl(void *UserData) {
4939 CXTranslationUnit TU = ((clang_annotateTokens_Data*)UserData)->TU;
4940 ASTUnit *CXXUnit = ((clang_annotateTokens_Data*)UserData)->CXXUnit;
4941 CXToken *Tokens = ((clang_annotateTokens_Data*)UserData)->Tokens;
4942 const unsigned NumTokens = ((clang_annotateTokens_Data*)UserData)->NumTokens;
4943 CXCursor *Cursors = ((clang_annotateTokens_Data*)UserData)->Cursors;
4944
4945 // Determine the region of interest, which contains all of the tokens.
4946 SourceRange RegionOfInterest;
4947 RegionOfInterest.setBegin(
4948 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
4949 RegionOfInterest.setEnd(
4950 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
4951 Tokens[NumTokens-1])));
4952
4953 // A mapping from the source locations found when re-lexing or traversing the
4954 // region of interest to the corresponding cursors.
4955 AnnotateTokensData Annotated;
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004956
Ted Kremenek6628a612011-03-18 22:51:30 +00004957 // Relex the tokens within the source range to look for preprocessing
4958 // directives.
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004959 annotatePreprocessorTokens(TU, RegionOfInterest, Annotated);
Ted Kremenek6628a612011-03-18 22:51:30 +00004960
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004961 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
4962 // Search and mark tokens that are macro argument expansions.
4963 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
4964 Tokens, NumTokens);
4965 CursorVisitor MacroArgMarker(TU,
4966 MarkMacroArgTokensVisitorDelegate, &Visitor,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00004967 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00004968 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00004969 RegionOfInterest);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004970 MacroArgMarker.visitPreprocessedEntitiesInRegion();
4971 }
4972
Ted Kremenek6628a612011-03-18 22:51:30 +00004973 // Annotate all of the source locations in the region of interest that map to
4974 // a specific cursor.
4975 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
4976 TU, RegionOfInterest);
4977
4978 // FIXME: We use a ridiculous stack size here because the data-recursion
4979 // algorithm uses a large stack frame than the non-data recursive version,
4980 // and AnnotationTokensWorker currently transforms the data-recursion
4981 // algorithm back into a traditional recursion by explicitly calling
4982 // VisitChildren(). We will need to remove this explicit recursive call.
4983 W.AnnotateTokens();
4984
4985 // If we ran into any entities that involve context-sensitive keywords,
4986 // take another pass through the tokens to mark them as such.
4987 if (W.hasContextSensitiveKeywords()) {
4988 for (unsigned I = 0; I != NumTokens; ++I) {
4989 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
4990 continue;
4991
4992 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
4993 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
4994 if (ObjCPropertyDecl *Property
4995 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
4996 if (Property->getPropertyAttributesAsWritten() != 0 &&
4997 llvm::StringSwitch<bool>(II->getName())
4998 .Case("readonly", true)
4999 .Case("assign", true)
John McCallf85e1932011-06-15 23:02:42 +00005000 .Case("unsafe_unretained", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00005001 .Case("readwrite", true)
5002 .Case("retain", true)
5003 .Case("copy", true)
5004 .Case("nonatomic", true)
5005 .Case("atomic", true)
5006 .Case("getter", true)
5007 .Case("setter", true)
John McCallf85e1932011-06-15 23:02:42 +00005008 .Case("strong", true)
5009 .Case("weak", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00005010 .Default(false))
5011 Tokens[I].int_data[0] = CXToken_Keyword;
5012 }
5013 continue;
5014 }
5015
5016 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
5017 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
5018 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5019 if (llvm::StringSwitch<bool>(II->getName())
5020 .Case("in", true)
5021 .Case("out", true)
5022 .Case("inout", true)
5023 .Case("oneway", true)
5024 .Case("bycopy", true)
5025 .Case("byref", true)
5026 .Default(false))
5027 Tokens[I].int_data[0] = CXToken_Keyword;
5028 continue;
5029 }
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00005030
5031 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
5032 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
5033 Tokens[I].int_data[0] = CXToken_Keyword;
Ted Kremenek6628a612011-03-18 22:51:30 +00005034 continue;
5035 }
5036 }
5037 }
Ted Kremenekab979612010-11-11 08:05:23 +00005038}
5039
Ted Kremenek6db61092010-05-05 00:55:15 +00005040extern "C" {
5041
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005042void clang_annotateTokens(CXTranslationUnit TU,
5043 CXToken *Tokens, unsigned NumTokens,
5044 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005045
5046 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005047 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005048
Douglas Gregor4419b672010-10-21 06:10:04 +00005049 // Any token we don't specifically annotate will have a NULL cursor.
5050 CXCursor C = clang_getNullCursor();
5051 for (unsigned I = 0; I != NumTokens; ++I)
5052 Cursors[I] = C;
5053
Ted Kremeneka60ed472010-11-16 08:15:36 +00005054 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor4419b672010-10-21 06:10:04 +00005055 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005056 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005057
Douglas Gregorbdf60622010-03-05 21:16:25 +00005058 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenek6628a612011-03-18 22:51:30 +00005059
5060 clang_annotateTokens_Data data = { TU, CXXUnit, Tokens, NumTokens, Cursors };
Ted Kremenekab979612010-11-11 08:05:23 +00005061 llvm::CrashRecoveryContext CRC;
Ted Kremenek6628a612011-03-18 22:51:30 +00005062 if (!RunSafely(CRC, clang_annotateTokensImpl, &data,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005063 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00005064 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
5065 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005066}
Ted Kremenek6628a612011-03-18 22:51:30 +00005067
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005068} // end: extern "C"
5069
5070//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00005071// Operations for querying linkage of a cursor.
5072//===----------------------------------------------------------------------===//
5073
5074extern "C" {
5075CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00005076 if (!clang_isDeclaration(cursor.kind))
5077 return CXLinkage_Invalid;
5078
Ted Kremenek16b42592010-03-03 06:36:57 +00005079 Decl *D = cxcursor::getCursorDecl(cursor);
5080 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
5081 switch (ND->getLinkage()) {
5082 case NoLinkage: return CXLinkage_NoLinkage;
5083 case InternalLinkage: return CXLinkage_Internal;
5084 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
5085 case ExternalLinkage: return CXLinkage_External;
5086 };
5087
5088 return CXLinkage_Invalid;
5089}
5090} // end: extern "C"
5091
5092//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005093// Operations for querying language of a cursor.
5094//===----------------------------------------------------------------------===//
5095
5096static CXLanguageKind getDeclLanguage(const Decl *D) {
5097 switch (D->getKind()) {
5098 default:
5099 break;
5100 case Decl::ImplicitParam:
5101 case Decl::ObjCAtDefsField:
5102 case Decl::ObjCCategory:
5103 case Decl::ObjCCategoryImpl:
5104 case Decl::ObjCClass:
5105 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005106 case Decl::ObjCForwardProtocol:
5107 case Decl::ObjCImplementation:
5108 case Decl::ObjCInterface:
5109 case Decl::ObjCIvar:
5110 case Decl::ObjCMethod:
5111 case Decl::ObjCProperty:
5112 case Decl::ObjCPropertyImpl:
5113 case Decl::ObjCProtocol:
5114 return CXLanguage_ObjC;
5115 case Decl::CXXConstructor:
5116 case Decl::CXXConversion:
5117 case Decl::CXXDestructor:
5118 case Decl::CXXMethod:
5119 case Decl::CXXRecord:
5120 case Decl::ClassTemplate:
5121 case Decl::ClassTemplatePartialSpecialization:
5122 case Decl::ClassTemplateSpecialization:
5123 case Decl::Friend:
5124 case Decl::FriendTemplate:
5125 case Decl::FunctionTemplate:
5126 case Decl::LinkageSpec:
5127 case Decl::Namespace:
5128 case Decl::NamespaceAlias:
5129 case Decl::NonTypeTemplateParm:
5130 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005131 case Decl::TemplateTemplateParm:
5132 case Decl::TemplateTypeParm:
5133 case Decl::UnresolvedUsingTypename:
5134 case Decl::UnresolvedUsingValue:
5135 case Decl::Using:
5136 case Decl::UsingDirective:
5137 case Decl::UsingShadow:
5138 return CXLanguage_CPlusPlus;
5139 }
5140
5141 return CXLanguage_C;
5142}
5143
5144extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00005145
5146enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
5147 if (clang_isDeclaration(cursor.kind))
5148 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005149 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Douglas Gregor58ddb602010-08-23 23:00:57 +00005150 return CXAvailability_Available;
5151
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005152 switch (D->getAvailability()) {
5153 case AR_Available:
5154 case AR_NotYetIntroduced:
5155 return CXAvailability_Available;
5156
5157 case AR_Deprecated:
Douglas Gregor58ddb602010-08-23 23:00:57 +00005158 return CXAvailability_Deprecated;
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005159
5160 case AR_Unavailable:
5161 return CXAvailability_NotAvailable;
5162 }
Douglas Gregor58ddb602010-08-23 23:00:57 +00005163 }
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005164
Douglas Gregor58ddb602010-08-23 23:00:57 +00005165 return CXAvailability_Available;
5166}
5167
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005168CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
5169 if (clang_isDeclaration(cursor.kind))
5170 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
5171
5172 return CXLanguage_Invalid;
5173}
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005174
5175 /// \brief If the given cursor is the "templated" declaration
5176 /// descibing a class or function template, return the class or
5177 /// function template.
5178static Decl *maybeGetTemplateCursor(Decl *D) {
5179 if (!D)
5180 return 0;
5181
5182 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
5183 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
5184 return FunTmpl;
5185
5186 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
5187 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
5188 return ClassTmpl;
5189
5190 return D;
5191}
5192
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005193CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
5194 if (clang_isDeclaration(cursor.kind)) {
5195 if (Decl *D = getCursorDecl(cursor)) {
5196 DeclContext *DC = D->getDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005197 if (!DC)
5198 return clang_getNullCursor();
5199
5200 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5201 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005202 }
5203 }
5204
5205 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
5206 if (Decl *D = getCursorDecl(cursor))
Ted Kremeneka60ed472010-11-16 08:15:36 +00005207 return MakeCXCursor(D, getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005208 }
5209
5210 return clang_getNullCursor();
5211}
5212
5213CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
5214 if (clang_isDeclaration(cursor.kind)) {
5215 if (Decl *D = getCursorDecl(cursor)) {
5216 DeclContext *DC = D->getLexicalDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005217 if (!DC)
5218 return clang_getNullCursor();
5219
5220 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5221 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005222 }
5223 }
5224
5225 // FIXME: Note that we can't easily compute the lexical context of a
5226 // statement or expression, so we return nothing.
5227 return clang_getNullCursor();
5228}
5229
Douglas Gregor9f592342010-10-01 20:25:15 +00005230void clang_getOverriddenCursors(CXCursor cursor,
5231 CXCursor **overridden,
5232 unsigned *num_overridden) {
5233 if (overridden)
5234 *overridden = 0;
5235 if (num_overridden)
5236 *num_overridden = 0;
5237 if (!overridden || !num_overridden)
5238 return;
5239
Argyrios Kyrtzidisb11be042011-10-06 07:00:46 +00005240 SmallVector<CXCursor, 8> Overridden;
5241 cxcursor::getOverriddenCursors(cursor, Overridden);
Douglas Gregor9f592342010-10-01 20:25:15 +00005242
Ted Kremenek24077122011-11-14 23:51:37 +00005243 // Don't allocate memory if we have no overriden cursors.
5244 if (Overridden.size() == 0)
5245 return;
5246
Argyrios Kyrtzidisb11be042011-10-06 07:00:46 +00005247 *num_overridden = Overridden.size();
5248 *overridden = new CXCursor [Overridden.size()];
5249 std::copy(Overridden.begin(), Overridden.end(), *overridden);
Douglas Gregor9f592342010-10-01 20:25:15 +00005250}
5251
5252void clang_disposeOverriddenCursors(CXCursor *overridden) {
5253 delete [] overridden;
5254}
5255
Douglas Gregorecdcb882010-10-20 22:00:55 +00005256CXFile clang_getIncludedFile(CXCursor cursor) {
5257 if (cursor.kind != CXCursor_InclusionDirective)
5258 return 0;
5259
5260 InclusionDirective *ID = getCursorInclusionDirective(cursor);
5261 return (void *)ID->getFile();
5262}
5263
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005264} // end: extern "C"
5265
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005266
5267//===----------------------------------------------------------------------===//
5268// C++ AST instrospection.
5269//===----------------------------------------------------------------------===//
5270
5271extern "C" {
5272unsigned clang_CXXMethod_isStatic(CXCursor C) {
5273 if (!clang_isDeclaration(C.kind))
5274 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00005275
5276 CXXMethodDecl *Method = 0;
5277 Decl *D = cxcursor::getCursorDecl(C);
5278 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5279 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5280 else
5281 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5282 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00005283}
Ted Kremenekb12903e2010-05-18 22:32:15 +00005284
Douglas Gregor211924b2011-05-12 15:17:24 +00005285unsigned clang_CXXMethod_isVirtual(CXCursor C) {
5286 if (!clang_isDeclaration(C.kind))
5287 return 0;
5288
5289 CXXMethodDecl *Method = 0;
5290 Decl *D = cxcursor::getCursorDecl(C);
5291 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5292 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5293 else
5294 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5295 return (Method && Method->isVirtual()) ? 1 : 0;
5296}
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005297} // end: extern "C"
5298
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005299//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00005300// Attribute introspection.
5301//===----------------------------------------------------------------------===//
5302
5303extern "C" {
5304CXType clang_getIBOutletCollectionType(CXCursor C) {
5305 if (C.kind != CXCursor_IBOutletCollectionAttr)
Ted Kremeneka60ed472010-11-16 08:15:36 +00005306 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005307
5308 IBOutletCollectionAttr *A =
5309 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
5310
Argyrios Kyrtzidis18aa2ff2011-09-13 18:49:52 +00005311 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005312}
5313} // end: extern "C"
5314
5315//===----------------------------------------------------------------------===//
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005316// Inspecting memory usage.
5317//===----------------------------------------------------------------------===//
5318
Ted Kremenekf7870022011-04-20 16:41:07 +00005319typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005320
Ted Kremenekf7870022011-04-20 16:41:07 +00005321static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
5322 enum CXTUResourceUsageKind k,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005323 unsigned long amount) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005324 CXTUResourceUsageEntry entry = { k, amount };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005325 entries.push_back(entry);
5326}
5327
5328extern "C" {
5329
Ted Kremenekf7870022011-04-20 16:41:07 +00005330const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005331 const char *str = "";
5332 switch (kind) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005333 case CXTUResourceUsage_AST:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005334 str = "ASTContext: expressions, declarations, and types";
5335 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005336 case CXTUResourceUsage_Identifiers:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005337 str = "ASTContext: identifiers";
5338 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005339 case CXTUResourceUsage_Selectors:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005340 str = "ASTContext: selectors";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005341 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005342 case CXTUResourceUsage_GlobalCompletionResults:
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005343 str = "Code completion: cached global results";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005344 break;
Ted Kremenek457aaf02011-04-28 04:10:31 +00005345 case CXTUResourceUsage_SourceManagerContentCache:
5346 str = "SourceManager: content cache allocator";
5347 break;
Ted Kremenekba29bd22011-04-28 04:53:38 +00005348 case CXTUResourceUsage_AST_SideTables:
5349 str = "ASTContext: side tables";
5350 break;
Ted Kremenekf61b8312011-04-28 20:36:42 +00005351 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
5352 str = "SourceManager: malloc'ed memory buffers";
5353 break;
5354 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
5355 str = "SourceManager: mmap'ed memory buffers";
5356 break;
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005357 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
5358 str = "ExternalASTSource: malloc'ed memory buffers";
5359 break;
5360 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
5361 str = "ExternalASTSource: mmap'ed memory buffers";
5362 break;
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005363 case CXTUResourceUsage_Preprocessor:
5364 str = "Preprocessor: malloc'ed memory";
5365 break;
5366 case CXTUResourceUsage_PreprocessingRecord:
5367 str = "Preprocessor: PreprocessingRecord";
5368 break;
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005369 case CXTUResourceUsage_SourceManager_DataStructures:
5370 str = "SourceManager: data structures and tables";
5371 break;
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005372 case CXTUResourceUsage_Preprocessor_HeaderSearch:
5373 str = "Preprocessor: header search tables";
5374 break;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005375 }
5376 return str;
5377}
5378
Ted Kremenekf7870022011-04-20 16:41:07 +00005379CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005380 if (!TU) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005381 CXTUResourceUsage usage = { (void*) 0, 0, 0 };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005382 return usage;
5383 }
5384
5385 ASTUnit *astUnit = static_cast<ASTUnit*>(TU->TUData);
5386 llvm::OwningPtr<MemUsageEntries> entries(new MemUsageEntries());
5387 ASTContext &astContext = astUnit->getASTContext();
5388
5389 // How much memory is used by AST nodes and types?
Ted Kremenekf7870022011-04-20 16:41:07 +00005390 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005391 (unsigned long) astContext.getASTAllocatedMemory());
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005392
5393 // How much memory is used by identifiers?
Ted Kremenekf7870022011-04-20 16:41:07 +00005394 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005395 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
5396
5397 // How much memory is used for selectors?
Ted Kremenekf7870022011-04-20 16:41:07 +00005398 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005399 (unsigned long) astContext.Selectors.getTotalMemory());
5400
Ted Kremenekba29bd22011-04-28 04:53:38 +00005401 // How much memory is used by ASTContext's side tables?
5402 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
5403 (unsigned long) astContext.getSideTableAllocatedMemory());
5404
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005405 // How much memory is used for caching global code completion results?
5406 unsigned long completionBytes = 0;
5407 if (GlobalCodeCompletionAllocator *completionAllocator =
5408 astUnit->getCachedCompletionAllocator().getPtr()) {
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005409 completionBytes = completionAllocator->getTotalMemory();
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005410 }
Ted Kremenek457aaf02011-04-28 04:10:31 +00005411 createCXTUResourceUsageEntry(*entries,
5412 CXTUResourceUsage_GlobalCompletionResults,
5413 completionBytes);
5414
5415 // How much memory is being used by SourceManager's content cache?
5416 createCXTUResourceUsageEntry(*entries,
5417 CXTUResourceUsage_SourceManagerContentCache,
5418 (unsigned long) astContext.getSourceManager().getContentCacheSize());
Ted Kremenekf61b8312011-04-28 20:36:42 +00005419
5420 // How much memory is being used by the MemoryBuffer's in SourceManager?
5421 const SourceManager::MemoryBufferSizes &srcBufs =
5422 astUnit->getSourceManager().getMemoryBufferSizes();
5423
5424 createCXTUResourceUsageEntry(*entries,
5425 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
5426 (unsigned long) srcBufs.malloc_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005427 createCXTUResourceUsageEntry(*entries,
Ted Kremenekf61b8312011-04-28 20:36:42 +00005428 CXTUResourceUsage_SourceManager_Membuffer_MMap,
5429 (unsigned long) srcBufs.mmap_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005430 createCXTUResourceUsageEntry(*entries,
5431 CXTUResourceUsage_SourceManager_DataStructures,
5432 (unsigned long) astContext.getSourceManager()
5433 .getDataStructureSizes());
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005434
5435 // How much memory is being used by the ExternalASTSource?
5436 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
5437 const ExternalASTSource::MemoryBufferSizes &sizes =
5438 esrc->getMemoryBufferSizes();
5439
5440 createCXTUResourceUsageEntry(*entries,
5441 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
5442 (unsigned long) sizes.malloc_bytes);
5443 createCXTUResourceUsageEntry(*entries,
5444 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
5445 (unsigned long) sizes.mmap_bytes);
5446 }
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005447
5448 // How much memory is being used by the Preprocessor?
5449 Preprocessor &pp = astUnit->getPreprocessor();
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005450 createCXTUResourceUsageEntry(*entries,
5451 CXTUResourceUsage_Preprocessor,
Argyrios Kyrtzidisc5c5e922011-06-29 22:20:04 +00005452 pp.getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005453
5454 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
5455 createCXTUResourceUsageEntry(*entries,
5456 CXTUResourceUsage_PreprocessingRecord,
5457 pRec->getTotalMemory());
5458 }
5459
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005460 createCXTUResourceUsageEntry(*entries,
5461 CXTUResourceUsage_Preprocessor_HeaderSearch,
5462 pp.getHeaderSearchInfo().getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005463
Ted Kremenekf7870022011-04-20 16:41:07 +00005464 CXTUResourceUsage usage = { (void*) entries.get(),
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005465 (unsigned) entries->size(),
5466 entries->size() ? &(*entries)[0] : 0 };
5467 entries.take();
5468 return usage;
5469}
5470
Ted Kremenekf7870022011-04-20 16:41:07 +00005471void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005472 if (usage.data)
5473 delete (MemUsageEntries*) usage.data;
5474}
5475
5476} // end extern "C"
5477
Douglas Gregor6df78732011-05-05 20:27:22 +00005478void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
5479 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
5480 for (unsigned I = 0; I != Usage.numEntries; ++I)
5481 fprintf(stderr, " %s: %lu\n",
5482 clang_getTUResourceUsageName(Usage.entries[I].kind),
5483 Usage.entries[I].amount);
5484
5485 clang_disposeCXTUResourceUsage(Usage);
5486}
5487
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005488//===----------------------------------------------------------------------===//
Ted Kremenek04bb7162010-01-22 22:44:15 +00005489// Misc. utility functions.
5490//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00005491
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00005492/// Default to using an 8 MB stack size on "safety" threads.
5493static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005494
5495namespace clang {
5496
5497bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005498 void (*Fn)(void*), void *UserData,
5499 unsigned Size) {
5500 if (!Size)
5501 Size = GetSafetyThreadStackSize();
5502 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005503 return CRC.RunSafelyOnThread(Fn, UserData, Size);
5504 return CRC.RunSafely(Fn, UserData);
5505}
5506
5507unsigned GetSafetyThreadStackSize() {
5508 return SafetyStackThreadSize;
5509}
5510
5511void SetSafetyThreadStackSize(unsigned Value) {
5512 SafetyStackThreadSize = Value;
5513}
5514
5515}
5516
Ted Kremenek04bb7162010-01-22 22:44:15 +00005517extern "C" {
5518
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00005519CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00005520 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00005521}
5522
5523} // end: extern "C"
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005524